如何忽略或标记环境和命令之外的内容

如何忽略或标记环境和命令之外的内容

在 LaTeX 文档的前言中,命令被处理,但所有导致输出的内容都会导致错误Missing \begin{document}

\documentclass{article}
This leads to an error.
\begin{document}
\end{document}

tikzpicture环境中,所有不能解释为 tikz 命令的内容都会被忽略。

\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
  Something that is ignored
  \node {A};
  Something that is ignored
\end{tikzpicture}
\end{document}

问题:在专用环境中,实现类似效果的最简单方法是什么?例如,文档

\documentclass{article}
\newenvironment{IgnoreOrFlagUnknownStuff}{}{}% ??? to be defined
\newenvironment{A}{\paragraph{A:}}{}
\newcommand\B[1]{\paragraph{B:} #1\par}
\begin{document}
\begin{IgnoreOrFlagUnknownStuff}
  Something to ignore or to complain about.
  \begin{A}
    This is OK.
  \end{A}
  Something to ignore or to complain about.
  \B{This is also OK.}
  Something to ignore or to complain about.
\end{IgnoreOrFlagUnknownStuff}
\end{document}

应该抱怨这些Something to ignore句子或者忽略它们,同时处理其余部分。

答案1

根据 Enrico 的评论,可以通过切换到 来抑制输出\nullfont

\newenvironment{IgnoreUnknownStuff}{\nullfont}{}

这将生成类似Missing character: There is no S in font nullfont!日志文件中的警告,可以通过设置来抑制这些警告\tracinglostchars=0。被忽略的内容可能仍会导致额外的垂直和水平空间,可能是因为进入和离开 hmode 并在行尾添加空格,因此被忽略的内容不会完全不可见。

要对忽略的内容发出错误消息(就像 LaTeX 格式对前言中的字符所做的那样),可以使用\everypar在进入 hmode 时通过设置来生成错误\everypar{\ErrorUnknownStuff}。必须确保在预期出现忽略字符时 TeX 处于 vmode 中;请注意\par以下命令。

\newenvironment{FlagUnknownStuff}%
  {\everypar{\ErrorUnknownStuff}%
   \nullfont
   \par
   \tracinglostchars=0
  }{}
\newcommand\ErrorUnknownStuff{\GenericError{}{Unknown Stuff}{}{}}
% Commands and environments that may appear in the environment
\newenvironment{A}{\normalfont\paragraph{A:}}{\par}
\newcommand\B[1]{{\normalfont\paragraph{B:} #1\par}}
\newcommand\C[1]{{\everypar{}\normalfont #1\par}}

\everypar在进入 hmode 之前必须通过 还原\everypar{}。上面的定义\paragraph将隐式执行此操作,但 的定义\C必须明确执行此操作。

左图是下面代码的结果。环境中的四条忽略和抱怨行均会发出错误FlagUnknownStuff。右图是删除所有要忽略的行时的输出;请注意间距的差异。

在此处输入图片描述 在此处输入图片描述

\documentclass{article}
\newenvironment{IgnoreUnknownStuff}{\nullfont}{}
\newenvironment{FlagUnknownStuff}%
  {\everypar{\ErrorUnknownStuff}%
   \nullfont
   \par
   \tracinglostchars=0
  }{}
\newcommand\ErrorUnknownStuff{\GenericError{}{Unknown Stuff}{}{}}
% Commands and environments that may appear in the environment
\newenvironment{A}{\normalfont\paragraph{A:}}{\par}
\newcommand\B[1]{{\normalfont\paragraph{B:} #1\par}}
\newcommand\C[1]{{\everypar{}\normalfont #1\par}}
\begin{document}
Before.
\begin{IgnoreUnknownStuff}
  Something to ignore.
  \begin{A}
    This is OK.
  \end{A}
  Something to ignore.
  \B{This is also OK.}%
  Something to ignore.
  \C{This also.}
  Something to ignore.
\end{IgnoreUnknownStuff}
In-between.
\begin{FlagUnknownStuff}
  Something to ignore and to complain about.
  \begin{A}
    This is OK.
  \end{A}
  Something to ignore and to complain about.
  \B{This is also OK.}
  Something to ignore and to complain about.
  \C{This also.}
  Something to ignore and to complain about.
\end{FlagUnknownStuff}
After.
\end{document}

相关内容