我只是想要一个包含代码的枚举列表,但结果却有问题:
理想情况下,我会将代码块缩进并从与项目标签相同的水平位置开始。这是我的代码:
\documentclass[10pt]{article}
\usepackage[a4paper, total={18cm, 25cm}]{geometry}
\usepackage[utf8]{inputenc}
\usepackage{fontspec}
\usepackage{enumitem}
\usepackage{xcolor}
\usepackage{listings}
\usepackage{multicol}
\usepackage{xpatch}
\usepackage{realboxes}
\definecolor{mygray}{rgb}{0.9,0.9,0.9}
\lstset{
language=c,
breaklines=true,
keepspaces=true,
backgroundcolor=\color{mygray},
frame=single,
framerule=0pt,
framextopmargin=3ex,
framexbottommargin=3ex,
framexleftmargin=1em,
xleftmargin={\dimexpr 1em+3pt},
linewidth={\dimexpr \linewidth-3pt}
}
\begin{document}
\begin{multicols}{2}
\begin{enumerate}[label=(\roman*)]
\item\begin{lstlisting}
#include <stdio.h>
int main() {
printf("Hello World!");
}
\end{lstlisting}
\item\begin{lstlisting}[language=lisp]
(defun make-hanoi (from-tower aux-tower to-tower)
(list from-tower aux-tower to-tower))
;; Select I'th tower of HANOI
(defun hanoi-tower (hanoi i)
(nth (1- i) hanoi))
\end{lstlisting}
\end{enumerate}
\end{multicols}
\end{document}
答案1
您需要做一些调整:
- 发出一些使其
\item
完成工作的事情,例如\mbox{}
; - 添加负垂直空间来掩盖你的踪迹;
- 修复
xleftmargin
; - 修复
linewidth
。
\documentclass[10pt]{article}
\usepackage[a4paper, total={18cm, 25cm}]{geometry}
\usepackage[utf8]{inputenc}
\usepackage{fontspec}
\usepackage{enumitem}
\usepackage{xcolor}
\usepackage{listings}
\usepackage{multicol}
\usepackage{xpatch}
\usepackage{realboxes}
\definecolor{mygray}{rgb}{0.9,0.9,0.9}
\lstnewenvironment{itemlisting}[1][]
{%
\mbox{}
\vspace*{-\baselineskip}
\lstset{
xleftmargin=\leftmargin,
linewidth=\linewidth,
#1
}%
}
{}
\lstset{
language=c,
breaklines=true,
keepspaces=true,
backgroundcolor=\color{mygray},
frame=single,
framerule=0pt,
framextopmargin=3ex,
framexbottommargin=3ex,
framexleftmargin=1em,
xleftmargin=\dimexpr 1em+3pt\relax,
linewidth=\dimexpr \linewidth-3pt\relax
}
\begin{document}
\begin{multicols}{2}
\begin{enumerate}[label=(\roman*)]
\item \begin{itemlisting}
#include <stdio.h>
int main() {
printf("Hello World!");
}
\end{itemlisting}
\item\begin{itemlisting}[language=lisp]
(defun make-hanoi (from-tower aux-tower to-tower)
(list from-tower aux-tower to-tower))
;; Select I'th tower of HANOI
(defun hanoi-tower (hanoi i)
(nth (1- i) hanoi))
\end{itemlisting}
\end{enumerate}
\end{multicols}
\end{document}
我留下了错误的分页符来显示可能存在的问题:显然,listings
将框架中列表上方的空间视为一个良好的分页点;恐怕您必须手动调整错误的分页符。