我正在尝试在 lstlisting 环境中在两行之间添加空格。
\begin{lstlisting}[language=Python, frame=single]
def foo():
# I need extra vertical space here
return x
\end{lstlisting}
以下跳过在列表后添加空格,跳过或者空间增加了空间,但破坏了框架,如下所示。
和跳行在第一行上方给出了不想要的边距,(即定义 foo()),如下所示。
\begin{lstlisting}[language=Python, frame=single, lineskip = 3em]
def foo():
return x
\end{lstlisting}
答案1
您可以使用tcolorbox
和escapechar
:
\documentclass{article}
\usepackage[most]{tcolorbox}
\tcbuselibrary{xparse,listings}
\NewTCBListing{framedlisting}{O{}}
{%
boxrule=0.4pt,
colback=white,
colframe=black,
sharp corners,
listing only,
listing options={#1},
}
\begin{document}
\begin{framedlisting}[language=Python,escapechar=$]
def foo(): $\vspace{3\baselineskip}$
return x
\end{framedlisting}
\end{document}
答案2
只需在您想要额外空间的行之间添加空行即可解决您的问题。(在逐字逐句环境中,空行并不意味着段落开始,而是->空行):
\documentclass[a4paper,10pt]{article}
\usepackage[utf8]{inputenc}
\usepackage{listings}
%opening
\title{}
\author{}
\begin{document}
\begin{lstlisting}[language=Python, frame=single]
def foo():
# I need extra vertical space here
return x
\end{lstlisting}
\end{document}
输出:
编辑(使用 tikz 的解决方案):
\documentclass[a4paper,10pt]{article}
\usepackage[utf8]{inputenc}
\usepackage{listings}
\usepackage{tikz}
\usetikzlibrary{calc}
%opening
\title{}
\author{}
\def\tikzmark#1{\tikz[overlay, remember picture]\coordinate(#1);}
\lstnewenvironment{frlstlisting}[1][]{\noindent\tikzmark{A}\lstset{#1}}
{\hspace{\fill}\tikzmark{B}%
\tikz[overlay,remember picture] \draw[very thick] ([xshift=-3.7pt,yshift=-7.6pt]A)rectangle([xshift=4.2pt, yshift=14.pt]B);}
\begin{document}
\begin{frlstlisting}[language={Python},escapeinside={/@}{@/}]
def foo():
/@\vspace{20pt}@/
return x
\end{frlstlisting}
\begin{frlstlisting}[language={Python},escapeinside={/@}{@/}]
def foo():
/@\vspace{70pt}@/
return x
\end{frlstlisting}
\end{document}
输出:
框架在那里,带有框架选项(手动设置空间后)