[Tex/LaTex] LaTeX conditional expression

conditionals

I would like to be able to set a flag at the beginning of the main flag (say output) that tells if I want to produce a paper document or an electronic document.

Then I should check this flag to define or not empty pages, hypperref, oneside or twosides, etc.

How could I do that ?

Best Answer

There are many ways.

Plain LaTeX

Perhaps the most canonical is:

\newif\ifpaper

Then either

\papertrue % or
\paperfalse

These set \ifpaper to be equal to \iftrue and \iffalse respectively. Therefore to use it:

\ifpaper
  % using paper
\else
  % electronic
\fi

However, using these primitive conditionals can lead to unexpected problems if you're not entirely familiar with the way TeX processes them, and the following solutions are recommended.


etoolbox

A more user-friendly and modern approach is taken by etoolbox, where you'd write instead

\newtoggle{paper}

which is set with either

\toggletrue{paper}
\togglefalse{paper}

And to use it:

\iftoggle{paper}{%
  % using paper
}{%
  % electronic
}

Why do I say this is more friendly? You'll never run into troubles with nesting, for which LaTeX's \newif conditions can sometimes be a bit of a pain to deal with.

etoolbox also supports boolean expressions such as

\ifboolexpr { togl {paper} and togl {pdf} } {true} {false}

which can also be combined with various testing functions also provided by that package (and others):

\ifboolexpr { togl {paper} or test {\ifdef{\foo}} } {true} {false}

expl3

Finally, for package writers (not really document authors): expl3 as part of LaTeX3 provides booleans that can be used in all sorts of interesting ways. For basic use, they look like this:

\bool_new:N \l_tmpa_bool

\bool_set_true:N \l_tmpa_bool
\bool_set_false:N \l_tmpa_bool

\bool_if:NTF \l_tmpa_bool {true} {false}
\bool_if:NT \l_tmpa_bool {true}
\bool_if:NF \l_tmpa_bool {false}

You can use boolean logic as follows:

\bool_if:nTF { ( \l_tmpa_bool || \l_tmpb_bool ) && !( \l_tmpc_bool ) } {true} {false}

Everything is expandable and lazy evaluation is used to avoid performing tests that don't need to be checked.

You can also combine boolean variables above with conditional functions such as \cs_if_eq_p:NN (‘are two control sequences equal?’) which can be tested in exactly the same way:

\bool_if:nTF { \l_tmpa_bool && \cs_if_eq_p:NN \foo \bar } {true} {false}

The overlap between etoolbox and expl3 here is rather pronounced; I think of the difference between the two as the separation between document authors (for etoolbox) and package writers (for expl3). But it's purely a matter of taste, when it comes down to it.

Related Question