[Tex/LaTex] Test if \author{} macro is empty

conditionalsetoolboxmacros

I have to check if the \author{} macro is empty because the output should change if this condition is set.

There are two ways the author can be empty:

  • \author{}
  • No \author{} command in the document.

I tried with the \ifdefempty{\macro}{<true>}{<false>} command of etoolbox, which works fine for self defined macros like \def\testmacro{foo}, but for \author it always results on false.

How could I test if an author is set and then modify the output based on the result of this check? (The check should work as the \ifdefempty command)

Best Answer

If you redefine the user command \author and the internal command \@author, you can make them do what you want them to. You can set them up in a way that you can test. A simple example is below, explained in the comments.

\documentclass{article}
\makeatletter % make it safe to use \@author

% Make \author do what you want it to: set a value for \@author
\renewcommand{\author}[1]{\def\@author{#1}}

% Create a test for whether author is present (non-empty)
\newif\ifauthor
\authorfalse % Set default value of conditional to false
\def\@author{} % Set default value of \@author to empty

% Create a command to check if \@author is empty and set the
% \ifauthor conditional accordingly, for use in other commands
\newcommand{\authorcheck}{%
    \ifx\@author\empty
    \authorfalse
    \else
    \authortrue
    \fi
}

% A sample command that would use this value to print the author, 
% if non-empty, or "Anonymous" instead
\newcommand{\printauthor}{%
    \authorcheck
    AUTHOR: \ifauthor\@author\else Anonymous\fi\par
}
\makeatother % We're done using @ now

% \author{Me} % Uncomment to test
\title{This}

\begin{document}
\printauthor
\end{document}
Related Question