如何编写一个忽略开始和结束之间所写内容的环境?

如何编写一个忽略开始和结束之间所写内容的环境?

我正在编写一个可选使用该pythontex包的包。该pythontex包定义了一个环境pycode,允许您在之前执行 Python 代码\begin{document}。据我所知,将pycode环境放在宏中是不可能的,所以无论用户是否想使用 Pythontex,我都必须将其放入,并在用户不想使用它的情况下定义或重新定义它。在这种情况下,我必须以一种忽略环境中编写的所有代码的方式定义它,并且可以将其放入序言中(或者更确切地说,可以在加载我的包时执行)。

梅威瑟:

\RequirePackage{etoolbox}
\RequirePackage{xstring}
\RequirePackage{letltxmacro}

\newcommand{\@pythonbool}{false} %This tells us whether the python option is enabled or not.
\newcommand{\@pycodedefined}{false} %This tells us whether the environment pycode is defined at the loading of this style file or not.

\DeclareOption{python}{
\renewcommand{\@pythonbool}{true}
}

\ProcessOptions\relax

\expandafter\ifstrequal\expandafter{\@pythonbool}{false}{
\ifcsmacro{pycode}{
    \renewcommand{\@pycodedefined}{true}
    \LetLtxMacro{\@oldpy}{\pycode}
    \LetLtxMacro{\@oldendpy}{\endpycode}
    \renewenvironment{pycode}{}{} % If pycode is defined (because Pythontex is used), but the package should not use python, this will completely disregard anything in a pycode environment. We will correctly redefine pycode after the code to be disregarded. This is neccessary because we can't put the pycode environment inside a conditional. Arguably, we could also let the code execute, since it doesn't print anything, and so will not change the output, but this is cleaner since we avoid possible naming conflicts. I don't know if it also makes python run less often, which would be a plus too.
}{
    \newenvironment{pycode}{}{} % If pycode is undefined (because Pythontex isn't used), this prevents errors upon Latex encountering the pycode environment, which we otherwise can't, since we can't simply put the pycode environment  into a conditional.
}
}{ \RequirePackage{pythontex}
}

\begin{pycode}
some code
\end{pycode}

\expandafter\ifstrequal\expandafter{\@pycodedefined}{true}{
    \LetLtxMacro{\pycode}{\@oldpy}
    \LetLtxMacro{\endpycode}{\@oldendpy}}{}

我感兴趣的具体点是如何阻止我的新环境定义尝试打印代码部分。

编辑:执行此操作的最佳方法似乎是使用一个命令告诉 Latex 忽略它与其对应方之间的所有内容,但我不知道如何定义它。

答案1

您可以定义一个名为的包选项nopython,并在序言中提供以下代码。

\usepackage{comment}
\DeclareOption{nopython}{\excludecomment{pycode}}

请注意软件包用户指南中指出的语法要求:

[环境的] 打开和关闭命令应该出现在一行上。没有起始空格,后面没有任何内容。

将此语法要求应用到您的文档中,这意味着所有\begin{pycode}\end{pycode}指令必须出现在它们自己的行上,没有任何起始空格。


完整的 MWE,它考虑到 OP 使用文档scrartcl类别的新信息:

\documentclass{scrartcl} 
\usepackage{pythontex} % comment this line out if **not** using PythonTeX
\makeatletter
\AtBeginDocument{\@ifpackageloaded{pythontex}{}{%
  \usepackage{comment} 
  \excludecomment{pycode}}}
\makeatother

\begin{document} 
\begin{pycode} 
Some code. 
\end{pycode} 
Some text. 
\end{document}

相关内容