该命令来自问题相当于 \show,用于在文档中显示 LaTeX 代码标准\meaning
正确地指出命令未定义,
\documentclass{article}
\makeatletter
\newcommand\meaningbody[1]{%
{\ttfamily
\expandafter\strip@prefix\meaning#1}%
}
\makeatother
\begin{document}
\meaningbody\sectio
\end{document}
但是\meaningbody
当命令未定义时会引发错误:
! Argument of \strip@prefix has an extra }.
<inserted text>
\par
l.12 \meaningbody\sectio
然后我尝试了这个来修复:
\documentclass{article}
\makeatletter
\newcommand{\meaningbody}[1]
{%
{\ttfamily
\ifdefined#1
\expandafter\strip@prefix\meaning#1
\else
Command #1 undefined.
\fi}%
}
\makeatother
\begin{document}
\meaningbody\sectio
\end{document}
但还是会出错:
! Undefined control sequence.
<argument> \sectio
l.17 \meaningbody\sectio
相关问题:
答案1
您正在将未定义的命令放入消息中,用于\string
使其安全。
\documentclass{article}
\makeatletter
\newcommand{\meaningbody}[1]
{%
{\ttfamily
\ifdefined#1%
\expandafter\strip@prefix\meaning#1%
\else
Command \string#1 undefined.%
\fi}%
}
\makeatother
\begin{document}
\meaningbody\sectio
\end{document}
一个更完整的版本,可以处理原语以及宏和未定义的命令,以便@egreg最终可以找到\box
\documentclass{article}
\makeatletter
\def\mystripprefix#1>#2{%
\ifx\relax#2%
#1 (not macro)%
\else
\expandafter\zaplessrelax\expandafter#2%
\fi}
\def\zaplessrelax#1>\relax{#1}
\newcommand{\meaningbody}[1]
{%
{\ttfamily
\ifdefined#1%
\expandafter\mystripprefix\meaning#1>\relax
\else
Command \string#1 undefined.%
\fi}%
}
\makeatother
\begin{document}
A \meaningbody\sectio
B \meaningbody\section
C \meaningbody\box
\end{document}
答案2
这是一个相当通用的版本,可以显示有关宏的更多信息,并且不会被其他控制序列所阻塞。可以添加一个测试参数是否是单个控制序列。
\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentCommand{\meaningbody}{m}
{
\texttt
{
\egreg_meaning_body:N #1
}
}
\cs_new:Nn \egreg_meaning_body:N
{
\cs_if_exist:NTF #1
{
\__egreg_meaning_body:N #1
}
{
Command~\token_to_str:N #1~undefined
}
}
\cs_new:Nn \__egreg_meaning_body:N
{
\token_if_macro:NTF #1
{
Command~\token_to_str:N #1~is~a~macro;~
\str_if_eq_x:nnTF { \token_get_prefix_spec:N #1 } { }
{
no prefix;~
}
{
prefix:~\token_get_prefix_spec:N #1;~
}
parameter~text:~\token_get_arg_spec:N #1;~
replacement~text:~\token_get_replacement_spec:N #1.
}
{
Command~\token_to_str:N #1~means~\token_to_meaning:N #1
}
}
\ExplSyntaxOff
\begin{document}
\raggedright
\meaningbody\sectio
\meaningbody\mbox
\newcommand*\foo[1]{Whatever #1}
\meaningbody\foo
\meaningbody\box
\meaningbody\alpha
\end{document}