如何在LaTeX中创建类似于\title的命令?

20

我正在编写一个LaTeX文档类,并希望它是通用的。在这个文档类中,我重新定义了\maketitle命令以显示自定义标题页,并在此处显示一些信息,例如标题、作者等,以及其他一些信息。下面是我如何显示标题:

{\LARGE{\bf \@title}}\\

我想创建一个类似于 \title\author 的新命令,我该如何做到这一点?


这可能更适合于LaTeX SE。 - Someone
1
有趣的是,在LaTeX SE首次提出之前3周,以及公共测试版发布之前2个半月,就有人问过这个问题:https://tex.meta.stackexchange.com/questions/3175/when-was-the-tex-latex-site-at-stack-exchange-founded - Kjir
那对我来说绝对是一个糟糕的时刻。 - Someone
2个回答

25

如果你查看 latex.ltx,你可以看到 \title 的定义如下:

\def\title#1{\gdef\@title{#1}}
\def\@title{\@latex@error{No \noexpand\title given}\@ehc}

这些是低级别的TeX命令。 \title 是一种重新定义 \@title 的命令,使其扩展为给定给 \title 的参数。在更现代的LaTeX命令中,您自己的定义可能如下所示:

\newcommand\foo[1]{\renewcommand\@foo{#1}}
\newcommand\@foo{\@latex@error{No \noexpand\foo given}\@ehc}

最好使用 \PackageError\ClassError 来显示错误信息。或者,如果您想让 \foo 是可选的并且默认为空:

\newcommand\foo[1]{\renewcommand\@foo{#1}}
\newcommand\@foo{}

如果这不在一个包内,你需要把它放在\makeatletter\makeatother之间,因为有@符号。


你能解释一下这段代码的每一部分是在做什么吗?例如,为什么有两行声明,为什么有包含 \renewcommand\@foo{#1} \newcommand\foo[1]{}等内容?同时,为什么需要放在 \makeatletter \makeatother之间?这些东西是什么,它们有什么作用? 抱歉,我只是想更好地理解这个代码。 - Ekanshdeep Gupta
1
好的,我明白了。我会把我的解释留在这里以备后用。请查看 https://tex.stackexchange.com/questions/8351/what-do-makeatletter-and-makeatother-do,了解 \makeatletter\makeatother 的说明。我们所做的是默认定义 \@foo 抛出一个错误消息,除非它被 \foo 的声明覆盖掉。 \foo 然后将 \@foo 命令更新为我们给出的任何参数(通过 \foo {blah blah} 等)。然后在 \@maketitle 中,我们可以像使用 \@title\@date 等一样使用 \@foo - Ekanshdeep Gupta

9

这里是我在thesis.cls类中使用的一个示例命令。它定义了一个名为\university的新命令,该命令的作用与\title\author命令相同,其默认值为“no university”。如果我在导言部分不使用\university命令,则将使用默认值。

\def\@university{no university}
\newcommand{\university}[1]{
  \def\@university{#1}
}

然后,在 \maketitle 命令中,您可以添加如下内容:

\newcommand{\maketitle}{
  {\LARGE{\bf \@title}}\\
  {\small{\@university}}\\
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接