9

Leaving blank line break simple macro but % terminating it fixes it. What's going on? I know one is supposed to use %, but I can't have any blank lines in the macro without it complaining. A blank line essentially terminates the macro and TeX complains about a mixing }. Using etoolbox also produces the same problem so it seems it is an issue with xparse.

Is there any way to fix xparse package so I don't have to litter my code with %s?

\documentclass{book}

\usepackage{xparse, ifthen, etoolbox}


\NewDocumentCommand\iftb{m m G{\relax}}{\ifthenelse{\boolean{#1}}{#2}{#3}}

%\NewDocumentCommand\iftb{m m G{\relax}}{\ifbool{#1}{#2}{#3}}
\newboolean{A}\setboolean{A}{true}
\newboolean{B}\setboolean{B}{true}


\begin{document}

\iftb{A}{%
% <- remove all text on this line breaks macro (keep blank line)
    \iftb{B}{%
        asdffdsasdff
        % <- same here
        asdf
    }
}

End
\end{document}

1 Answer 1

12

Macros defined with \NewDocumentCommand by default don't accept \par (or empty lines, which is the same) in their arguments.

You can overcome this behavior by adding + in front of an argument specifier that can possibly contain a \par:

\NewDocumentCommand\iftb{m +m +G{\relax}}{\ifthenelse{\boolean{#1}}{#2}{#3}}

or

\NewDocumentCommand\iftb{m +m +G{\relax}}{\ifbool{#1}{#2}{#3}}

The macros on which \ifthenelse and \ifbool are built already accept \par.


The question why \par is not accepted in macro arguments comes from the fact that this is the default behavior for macros, as Knuth imagined them.

A macro defined with

\def\macro#1{...}

doesn't accept \par in its argument. Knuth thought that this can catch the common error of forgetting the closing brace and wanted to avoid that such a mistake could lead to reading in all the current file looking for the closing brace.

However a macro definition can be prefixed by \long: so

\long\def\macro#1{...}

allows empty lines in the argument of \macro.

LaTeX's \newcommand is of course built on \def and by default prefixes it with \long; the *-form \newcommand* doesn't.

The function \NewDocumentCommand (also \DeclareDocumentCommand, but the New variety should be preferred, for it provides a check against redefinitions) take the \newcommand* approach, but in a slightly different way: each argument can be declared "long" or not (by default it isn't), while with \newcommand and \newcommand* all arguments are treated equal.

3
  • Thanks, can you explain why, by default, \par and empty lines are not accepted? Commented Jul 22, 2012 at 22:50
  • 3
    @AbstractDissonance It is a feature built in to TeX at the most primitive level so that (in a latex context) a typo like \documentclass{article with no closing } stops at the first paragraph not the end of the document. Commented Jul 22, 2012 at 22:57
  • Awesome. We learn everyday. Commented Jul 19, 2023 at 0:15

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .