为 % 创建别名(用于注释的宏)

为 % 创建别名(用于注释的宏)

我想定义一个宏,用于为特定行组合打开/关闭注释;但是,我不确定如何绑定%到宏的输出。这可能吗?

例如我想定义\tlc临时行注释)类似\newcommand{\tlc}{%}这样的

line 1
\tlc line 2
\tlc line 3
line 4
line 5
\tlc line 6

会注释掉第 2、3 和 6 行,并且将宏重新定义为类似\newcommand{\tlc}{}会打印所有行的内容。

答案1

有时我会像这样在评论和不评论之间切换:

\documentclass{article}

\begin{document}

\catcode`\^^A=14 % catcode 14 = comment
% now stuff behind ^^A is comment:
line 1
^^Aline 2
^^Aline 3
line 4
line 5
^^Aline 6
^^A\csname @firstofone\endcsname{%
^^A  Line7%
^^A}%

\catcode`\^^A=9 % catcode 9 = ignore
% now stuff behind ^^A is processed:
line 1
^^Aline 2
^^Aline 3
line 4
line 5
^^Aline 6
^^A\csname @firstofone\endcsname{%
^^A  Line7%
^^A}%

\end{document}

^^A是 TeX 的^^符号,用于表示在 TeX 引擎的内部字符表示方案中代码点编号为 1 的 SOH 字符,在传统 TeX 中为 ASCII,在 LuaTeX 和 XeTeX 中为 unicode。

您可以在需要切换注释/不注释的代码中使用任何未使用的字符。这样做时,不要忘记在以通常方式使用它之前将字符的类别代码重置为其通常值,例如,

\documentclass{article}

\begin{document}

\catcode`\X=14 % catcode 14 = comment
% now stuff behind X is comment:
line 1
Xline 2
Xline 3
line 4
line 5
Xline 6
X\csname @firstofone\endcsname{%
X  Line7%
X}%

\catcode`\X=9 % catcode 9 = ignore
% now stuff behind X is processed:
line 1
Xline 2
Xline 3
line 4
line 5
Xline 6
X\csname @firstofone\endcsname{%
X  Line7%
X}%

% Make sure the catcode of X is reset to its usual value
% before resorting to using X as letter.
\catcode`\X=11

\end{document}


使用假设的宏\tlc或包提供的环境评论注释掉的内容需要进行处理才能删除。

使用通过切换 catcode 来切换注释/不注释的方法,注释掉的内容根本不会被标记/处理。
因此,对于后一种方法,括号平衡并不重要。
并且后一种方法也可用于注释掉属于⟨定义文本⟩宏。

即,这确实!!!不是!!!工作:

\documentclass{article}
\usepackage{comment}
%\includecomment{mycomment}
\excludecomment{mycomment}

\newcommand\mymacro{%
  This in any case is part of the definition text.
  \begin{mycomment}
  This is part of the definition text only if mycomment is included.
  \end{mycomment}
}%
[...]
\begin{document}
[...]
\end{document}

这确实有效:

\documentclass{article}
%\catcode`\^^A=9
\catcode`\^^A=14

\newcommand\mymacro{%
  This in any case is part of the definition text.
  ^^AThis is part of the definition text only if SOH has catcode 9.
}%
[...]
\begin{document}
[...]
\end{document}

答案2

我看不出有什么特别的使用方法,但你可以通过定义获取行末之间的任何内容来%获得所需的输出,而不对其进行任何操作。这是一个完整的示例,其中的定义基于@egreg 的回答\tlc\tlc\tlc这里

\documentclass{article}
\def\tlc{\begingroup\catcode`\^^M=12 \xtlc}
{\catcode`\^^M=12 %
    \gdef\xtlc#1^^M{\endgroup}%
}
%\newcommand*{\tlc}{}
\begin{document}
line 1
\tlc line 2
\tlc line 3
line 4
line 5
\tlc line 6
\end{document}

这输出

如果删除 的定义\tlc并将其替换为注释行\newcommand*{\tlc}{},则输出如下。

话虽如此,我不建议这样做:通常定义这样的奇异命令需要真正了解你在做什么。我不确定这个特定命令可能出错的所有情况,但例如,如果你{在以 开头的行上放置一个单独的(如@frougon 所建议的)\tlc,就会引发错误。我不会对其他意外行为感到惊讶,尤其是考虑到@egreg 上面的评论。

我倾向于使用更标准的语法。例如,您可以定义\tlc一个强制参数,并根据是否需要注释行来打印它。例如

\newcommand*{\tlc}[1]{#1}

或者

\newcommand*{\tlc}[1]{}

您还可以使用评论包,提供一个内容被注释掉的环境。

相关内容