Skip to content

Boolean in LaTeX macros

June 28, 2013

Much like in the statistical environment R, it is possible to make custom functions (or “macros”) in LaTeX. This is done using the

\newcommand{commandname}[number_of_arguments]{definition}

command, where commandname and definition are replaced with a name (e.g. \mysubscript) and a definition, respectively, and number_of_arguments can be provided or not. For example see my previous post on subscripts.

What do you do if you want to control the behaviour of that macro? Say you want the command to do one of two things, print Fig or Figs for instance.

One way to accomplish this is to use the etoolbox package:

\usepackage{etoolbox}
\newcommand{\fig}[1]{
\ifblank{#1}{Fig.}{Figs.}
}
\begin{document}
\fig{} is singular, while \fig{1} is plural.
\end{document}

All this does is checks to see if there is an argument (#1) and prints its second argument if not (spaces or blank), or its third argument if there is something.

Hope this helps someone!

[UPDATE] A better method seems to be to use the following

\makeatletter
\def\fig{\@ifnextchar[{\@with}{\@without}}
\def\@with{Figs.}
\def\@without{Fig.}
\makeatother

otherwise it sometimes adds in extra space for no apparent (to me) reason. I’m not sure what the \makeatletter and \makeatother lines are about, but the other parts define a command called \fig which if defined as “if the next character is a [ do \@with else do \@without“.  \@with and \@without are then defined separately.

 

Advertisements

From → Uncategorized

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: