我的 verbatim 环境是自动生成的。因此,有些环境的第一行是空的 - 但不是全部。是否可以重新定义 verbatim 环境并强制其删除第一个空行(如果存在)?我应该补充说我必须使用 verbatim 而不是其他包。这是一个示例
\documentclass{article}
\usepackage{verbatim}
\begin{document}
First line is empty in verb.
\begin{verbatim}
Empty line above.
3rd line.
\end{verbatim}
First line is not empty.
\begin{verbatim}
Empty line above?
3 line.
\end{verbatim}
\end{document}
答案1
使用verbatim
检查第一行是否为空:
\documentclass{article}
\usepackage{verbatim}
\makeatletter
\newif\iffirstlinecheck
\renewcommand{\verbatim@processline}{%
\iffirstlinecheck
\if\relax\the\verbatim@line\relax
\else
\the\verbatim@line\par
\fi
\global\firstlinecheckfalse
\else
\the\verbatim@line\par
\fi
}
\edef\verbatim{\global\noexpand\firstlinechecktrue\unexpanded\expandafter{\verbatim}}
\makeatother
\begin{document}
First line is empty in verb.
\begin{verbatim}
Empty line above.
3rd line.
\end{verbatim}
First line is not empty.
\begin{verbatim}
Empty line above?
3 line.
\end{verbatim}
\end{document}
否则,使用更加可定制的fancyvrb
,如果第一行为空,则发出负间距:
\documentclass{article}
\usepackage{fancyvrb}
\newif\iffirstlinecheck
\renewenvironment{verbatim}
{\VerbatimEnvironment\global\firstlinechecktrue
\renewcommand\FancyVerbFormatLine[1]{%
\iffirstlinecheck
\if\relax\detokenize{##1}\relax
\aftergroup\aftergroup\aftergroup\cancelline
\fi
\global\firstlinecheckfalse
\fi
##1%
}%
\begin{Verbatim}%
}
{\end{Verbatim}}
\def\cancelline{\vspace{-\baselineskip}}
\begin{document}
First line is empty in verb.
\begin{verbatim}
Empty line above.
3rd line.
\end{verbatim}
First line is not empty.
\begin{verbatim}
Empty line above?
3 line.
\end{verbatim}
\end{document}
答案2
verbatim
来自的环境逐字包裹逐行收集要排版的材料,并将其放入名为 的标记寄存器中\verbatim@line
。到达行尾时,该标记寄存器的内容将由内部宏 排版\verbatim@processline
。
因此,解决这个问题的方法是首先将的定义复制/保存为\verbatim@processline
另一个控制序列,然后重新定义以将自身设置为已保存的定义,并且仅当其不为空时才\verbatim@processline
排版其内容。\verbatim@line
\verbatim@line
将 设置\verbatim@processline
为已保存的定义发生在环境打开的本地范围内verbatim
。因此,verbatim
环境的其他实例不会受到影响。将 设置\verbatim@processline
为已保存的定义发生在\verbatim@processline
第一次执行时,即在处理环境主体的第一行时。因此,检查行是否为空在任何情况下都只会影响环境主体的第一行:
\documentclass{article}
\usepackage{verbatim}
\makeatletter
\newcommand\savedverbatim@processline{}%
\let\savedverbatim@processline=\verbatim@processline
\renewcommand{\verbatim@processline}{%
\let\verbatim@processline=\savedverbatim@processline
\if\relax\the\verbatim@line\relax
\else
\the\verbatim@line\par
\fi
}%
\makeatother
\begin{document}
The first line of \verb|verbatim|'s body is not empty.
\begin{verbatim}
First Line
Second Line
Third Line
\end{verbatim}
The first line of \verb|verbatim|'s body is empty.
\begin{verbatim}
Second line.
Third line.
\end{verbatim}
Both the first and the second line of \verb|verbatim|'s body are empty.\\
Only the first empty line will be removed.
\begin{verbatim}
Third line.
\end{verbatim}
\end{document}