Best practice to implement a boolean macro argument?
You can use a *-variant:
\usepackage{xparse}
\NewDocumentCommand{\showcase}{s}{%
Show a sentence.%
\IfBooleanT{#1}{ And a little more if asked to.}%
}
Now \showcase
will produce the short version and \showcase*
the long one. Just change \IfBooleanT
into \IfBooleanF
for the reverse. There's also \IfBooleanTF
that accepts two texts.
The variant indicator can be different: if you say
\NewDocumentCommand{\showcase}{t+}{...}
then the variant will be \showcase+
.
The "classical" method
Using "pure LaTeX" one can say
\makeatletter
\newcommand{\showcase}{%
\@ifstar
{\@showcase{ And a little more if asked to.}}
{\@showcase{}}%
}
\newcommand{\@showcase}[1]{Show a sentence.#1}
\makeatother
This version of \showcase
would be fragile and \DeclareRobustCommand
would be needed for defining it in case it's supposed to appear in moving arguments (or it should be preceded by \protect
). So two macros must be defined (three in case \DeclareRobustCommand
is used), instead of the only one with xparse
.
In this case, to be honest, a simpler method would work:
\makeatletter
\newcommand{\showcase}{Show a sentence.%
\@ifstar{ And a little more if asked to.}{}}
\makeatother
because you don't want to grab arguments. But this would fail if you want something like
\showcase{b}
\showcase*{b}
to produce
Show b sentence.
Show b sentence. And a little more if asked to.
respectively. You'll have to do with the auxiliary macro:
\makeatletter
\newcommand{\showcase}{%
\@ifstar
{\@showcase{ And a little more if asked to.}}
{\@showcase{}}%
}
\newcommand{\@showcase}[2]{Show #2 sentence.#1}
\makeatother
To work properly, \@ifstar{...}{...}
must be last in a replacement text.
With xparse
you'd do
\NewDocumentCommand{\showcase}{sm}{%
Show #2 sentence.%
\IfBooleanT{#1}{ And a little more if asked to.}%
}
Other methods
There are other packages that allow for defining macros with variants, for instance suffix
:
\usepackage{suffix}
\newcommand{\showcase}{Show a sentence.}
\WithSuffix\def\showcase*{%
\csname\NoSuffixName\showcase\endcsname{} And a little more if asked to.}
The syntax is not very friendly in either case.
You can try this:
\documentclass{minimal}
\newif\ifextra
\newcommand\showcase[1][1]{Show a sentence.
\ifnum#1=1 \extratrue\else\extrafalse\fi
\ifextra And a little more if asked to. \fi}
\begin{document}
\showcase[0] \\
\showcase[1]
\end{document}
I have used 1 as true and any other number as false for providing a condensed syntax.
As noted in the comments, if the switch \ifextra
is not used outside a macro you can drop it.
\documentclass{minimal}
\newif\ifextra
\newcommand\showcase[1][0]{Show a sentence.
\ifnum#1=1 And a little more if asked to. \fi}
\begin{document}
\showcase\\
\showcase[1]
\end{document}