LaTeX“变量”- \@varname

LaTeX“变量”- \@varname

我目前正在编写我的第一个文档类文件(个性化简历类),我想更好地了解我到底在做什么。所以,现在我正在设置允许将值分配给变量的命令(不确定这是否真的是我应该使用的词),通过如下结构:

\newcommand{\institution}[1]{\def\@institution{#1}}
\newcommand{\datesattended}[1]{\def\@datesattended{#1}}
\newcommand{\degree}[1]{\def\@degree{#1}}

因此,在 .tex 文件中,用户可以使用命令\institution{University of Whatever}将字符串“University of Whatever”保存到\@institution,然后稍后通过另一个命令在类文件中调用该命令。

所有这些都按我想要的方式工作,但现在我希望创建一些条件表达式来控制输出。例如,我有一个命令\education,当在文档中调用时,它将根据用户已经输入的机构名称、就读日期、学位信息等来格式化简历的教育部分。我希望能够在类文件中进行设置,以检查这些\@variable变量是否已定义,然后根据已定义和空值对输出进行不同的格式化。

首先,我认为我的问题很大一部分在于我实际上并不理解这些\@variable定义是什么,或者我可以用它们做什么。

我想要实现的完整示例如下(在 LaTeX/pseudo 中):

\newcommand{\showeducation}{%
    \@institutionname -- \@degree
    if \@datesattended is defined:
        \newline \@datesattended
    clear \@institutionname, \@datesattended, \@degree
}

因此,如果\@datesattended已定义,格式将发生改变以适应它。否则,命令将直接忽略它,打印给定的信息。

答案1

命令没有什么特别之处\@variable。它们只是宏,用于存储内容而不是执行其他操作。因此,可以使用 \ifdefined(e-TeX) 原语来测试是否已定义。

\documentclass[11pt,a4paper]{article}


\makeatletter

\newcommand{\@institutionname}{Ministry of Silly Walks}
\newcommand{\@degree}{Minster of Silly Walks}

%\newcommand{\@datesattended}{1969}


\newcommand{\showeducation}{%
    \@institutionname\ -- \@degree
    \ifdefined\@datesattended 
        \newline \@datesattended  % Please use some 'better' setup here
        \else
     \let\@institutionname\relax
     \let\@datesattended\relax 
     \let\@degree\relax
     \fi
}

\makeatother


\begin{document}

\showeducation   % Date should not be printed

\makeatletter
\newcommand{\@datesattended}{1969}
\makeatother

\showeducation % Now it should be printed, but the rest is \relax`ed


\end{document}

编辑\ifdef使用frometoolbox包也可以实现同样的效果

答案2

也许比\newcommand[1]...使用 toks 寄存器更好:

\newtoks\institution  \newtoks\datesattended  \newtoks\degree

如果用户说

\institution{Ministry of Silly Walks}

然后您可以在宏中使用该值:

\the\institution

如果需要测试,“变量”的值是否已经设置,您可以执行以下操作:

\if\relax\the\degree\relax The degree isn't set.\else The degree is set.\fi

相关内容