[Tex/LaTex] Understanding \@ifnextchar

conditionalslatex-basemacros

I understand the definitions of the \makeatletter and \makeatother commands and also \def and \newcommand somewhat. But, explained in a simple way, what is happening in the following line?

\@ifnextchar[ \@myitem{\@noitemargtrue\@myitem[\@itemlabel]}}

Of Gonzalo Medina's answer at:

Forcing new line after item number in enumerate environment

Best Answer

\@ifnextchar is a LaTeX conditional that peeks ahead at the following character. So, \@ifnextchar[ looks ahead to see if the following character in the input stream is a [ (opening left bracket). If this is true, then it executes the immediately following token, otherwise, it skips it and executes the token following that.

The first token, executed upon a true evaluation of \@ifnextchar[ is \@myitem. If the evaluation is false, it executes {\@noitemargtrue\@myitem[\@itemlabel]}} - the following group or "token", which also calls \@myitem now with an optional argument set [\@itemlabel]. Before calling \@myitem, the boolean \if@noitemarg is set to true (\@noitemargtrue).

The general idea behind this expression is to condition on whether an optional argument is supplied or not, and therefore avoid an error if you pass arguments to a macro where the parameter text does not match what is given. Using the above example, \@mymacro is defined using

\def\@myitem[#1]{<replacement text>}

Since this uses \def for the definition, the "optional" argument is actually not optional, but required. That's why the above usage is necessary. A more conventional way of conditioning is supplied using

\newcommand{\@myitem}[1][<arg>]{<replacement text>}

where <arg> specifies the value of the optional argument if it is not explicitly specified. xparse provides similar conditioning that, for the upper-level user, might be more intuitive.