Sunday, October 6, 2013

LaTeX Tip: How to define variable like \subtitle{...} which can be used from the preamble

Quite often when working with LaTeX, it is quite convenient to be able to define things like subtitles and/or other extra fields to be included in the title section, as per the screenshot below:


Now, before we go any further, I should mention that I am aware of the existence of ready-made custom document classes out there in the wild which often provide the necessary bits and pieces already. But, for argument sake, let's say that we want to keep things lightweight (i.e. fewer deps on external packages) or want to know how to do this in future should the need arise.




A First Attempt - (NOT RECOMMENDED)
An initial attempt at doing this may look something like this...

In your articleTitle.sty file (or some other include):

\newcommand{\subtitle}{}         % 1) How the "field" gets defined
...
{\large \textit{\subtitle}}      % 2) How it gets displayed


In your document, you'd then have to do:

\renewcommand{\subtitle}{My new subtitle text}


Comments:
As can be seen, while this approach is functional, it is not exactly that syntactically nice, especially since we cannot use this subtitle field in a "native" way like we can with the regular \title and \author fields.

Second Attempt - (RECOMMENDED)
After a lot of searching, I finally stumbled across the following gem by inspecting the sources for one of the document classes in the KOMA-Script package, which provides this field.

In your articleTitle.sty file:

% 1) To define the subtitle field...
\newcommand*{\subtitle}[1]{\gdef\@subtitle{#1}}
\newcommand*{\@subtitle}{}%

...

% 2) To use the subtitle field...
{\large \textit{\@subtitle}}


In your document, you can then do:

\subtitle{My new subtitle text}


Comments:
Although this method is more work to define, using it is much easier than our first solution. Namely, in the style file, you can simply use \@subtitle, which closely matches the syntax used for grabbing the values for the builtin \title and \author fields (\@title and \@author respectively).

Similarly, setting the subtitle text in your preamble is a lot easier (i.e. implementation details are hidden away).

Do also note that this little pattern can be extended to be used for any other field you may want to define. So, for instance, if you wanted to define a "\authoremail" field, simply change "subtitle" to "authoremail" in the snippets above.

No comments:

Post a Comment