数据结构:定义仅在某一类型的环境中有效的命令或环境

数据结构:定义仅在某一类型的环境中有效的命令或环境

我想要编写 LaTeX 文档生成脚本,因此我需要使用数据结构来组织信息。例如:

  • 人:
    • 姓名
    • 电话
    • 地址

我知道在 LaTeX 中你可以创建新的命令和环境,例如:

\newenvironment{Person}{\bigskip\noindent}{\bigskip}
\begin{Person}\end{Person}

如果你愿意的话,可以将命令/环境作为 OO 属性:

\newcommand{\Name}[1]{My name is #1}
\Name{John Doe}

\newcommand{Phone}[1]{Phone: #1}
\Phone{555-123-3221}

\newcommand{Address}[1]{Address: #1}
\Address{1234 My Street}

有没有一种方法可以实现 OO 风格的 1) 作用域和 2) 重载?也就是说,

\begin{Person}\Name{Joey}\end{Person}

是有效的(问题 1),但是这不是:

This is outside the Person environment, \Name{Silly}!

我希望这些命令只在我选择的环境中起作用。

对于问题#2,如果我写(使用另一个名为Species的新环境):

\begin{Species}\Name{E. Coli}\end{Species}

我不希望它打印与 Person 的 Name 相同的输出。这在 LaTeX 中可行吗?

答案1

是的,这是可能的,但我不建议根据上下文使用相同的命令执行非常不同的任务。

\newcommand{\Name}[1]{Do something with #1} % default action
\newcommand{\SpeciesName}[1]{Do something else with #1}

\newenvironment{Species}
 {<something at the opening>%
  \let\Name\SpeciesName
  <something else at the opening>}
 {<something at the end>}

您还可以使\SpeciesName不(容易访问):

\newcommand{\Name}[1]{Do something with #1}

\makeatletter
\newcommand{\Species@Name}[1]{Do something else with #1}

\newenvironment{Species}
 {<something at the opening>%
  \let\Name\Species@Name
  <something else at the opening>}
 {<something at the end>}
\makeatother

如果你想禁止\Name在环境中使用 except Species,请使用

\makeatletter
\newcommand{\Name}[1]{%
  \@latex@error{\noexpand\Name used in a wrong place}
    {You dummy! How many times should I tell you?}%
}
\makeatother

为“默认定义”。

相关内容