好的,让我们来看看你的(第一个)重新定义,看看发生了什么:
1 \@ifundefined{comment}{}{% only do this if the comment environment has been defined
2 \renewenvironment{comment}[1]% redefining a 'comment' environment with one mandatory argument
3 {\begingroup\marginpar{\bgroup#1\egroup}}% put the mandatory argument inside a marginpar
4 {\endgroup}}% close the environment
下面是 LaTeX 是如何考虑你告诉它的内容的:
\begin{comment}{xyzzy}% <-- note the mandatory argument (runs line 3)
This is the contents of the environment.
\end{comment}% <-- this is where LaTeX runs line 4
请注意,这xyzzy
是强制性参数 ( #1
)。环境的内容(“ This is the
...”)插入到第 3 行和第 4 行之间。
如果您在文档中写下以下内容:
\begin{comment}% <-- missing mandatory argument
This is the contents of the environment.
\end{comment}
然后 LaTeX 会将第一个标记作为强制参数。在这种情况下,第一个标记是T
环境内容的第一个字符。所以这封信T
将被放在页边距,其余的文本将显示在一个正常的段落中。
好的,所以要实现我们想要的,comment
环境不需要任何参数。我们要做的是创建一个盒子,将环境的内容放入该盒子,然后将该盒子放在边距。
在我们开始之前,如果您将这段代码包含在文档的序言中,您需要将其全部包装起来\makeatletter
,\makeatother
因为我们将使用@
名称中带有 at 符号 ( ) 的命令。
首先,让我们创建一个盒子来存储材料:
\newsavebox{\marginbox}% contains the contents of the comment environment
接下来,我们将开始定义comment
环境。我们将环境开始和结束命令设置为\relax
. 这样我们的\newenvironment
命令就可以保证工作。
\let\comment\relax% removes and previous definition of \begin{comment}
\let\endcomment\relax% removes any previous definition of \end{comment}
有了这个,我们可以定义我们的新comment
环境:
\newenvironment{comment}{%
\begin{lrbox}{\marginbox}% store the contents of the environment in a box named \marginbox
\begin{minipage}{\marginparwidth}% create a box with the same width as the marginpar width
\footnotesize% set any font or other style changes you'd like
}{% the following lines are for the \end{comment} command
\end{minipage}% close the minipage
\end{lrbox}% close the box
\marginpar{\usebox{\marginbox}}% typeset the box in the margin
}
现在,在您的文档中,您可以键入:
\begin{comment}
This is a comment that gets printed in the margin.
\end{comment}
因此,为了便于复制和粘贴,完整的文档如下所示:
\documentclass{article}
\makeatletter
\newsavebox{\marginbox}% contains the contents of the comment environment
\let\comment\relax% removes and previous definition of \begin{comment}
\let\endcomment\relax% removes any previous definition of \end{comment}
\newenvironment{comment}{%
\begin{lrbox}{\marginbox}% store the contents of the environment in a box named \marginbox
\begin{minipage}{\marginparwidth}% create a box with the same width as the marginpar width
\footnotesize% set any font or other style changes you'd like
}{% the following lines are for the \end{comment} command
\end{minipage}% close the minipage
\end{lrbox}% close the box
\marginpar{\usebox{\marginbox}}% typeset the box in the margin
}
\makeatother
\usepackage{lipsum}% just provides some filler text
\begin{document}
Hello, world!
\begin{comment}
This is a comment that gets printed in the margin.
\end{comment}
\lipsum
\end{document}