测试 \author{} 宏是否为空

测试 \author{} 宏是否为空

我必须检查\author{}宏是否为空,因为如果设置了此条件,输出应该改变。

作者为空的情况有两种:

  • \author{}
  • \author{}文档中没有命令。

我尝试使用\ifdefempty{\macro}{<true>}{<false>}命令etoolbox,它对于类似的自定义宏很有效\def\testmacro{foo},但对于\author总是会导致false

我如何测试作者是否已设置,然后根据此检查的结果修改输出?(检查应按命令工作\ifdefempty

答案1

如果您重新定义用户命令\author和内部命令\@author,您可以让它们执行您想要的操作。您可以以可测试的方式设置它们。下面是一个简单的示例,在注释中进行了解释。

\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}

相关内容