我看到过使用
\def\afterelse#1\else#2\fi{\fi#1}
TeX 似乎很乐意接受这一点。但是在采用第一个分支时,TeX 不是期望\else
而不是吗\fi
?也就是说,以下不是第一个分支的正确语法吗?TeX 也接受了这一点。
\def\afterelse#1\else#2\fi{\else#1}
编辑
感谢 Egreg。跟踪\if
显示了正在发生的事情。
\def\loggingallstuff{%
\tracinggroups\@ne\tracingifs\@ne\loggingall\tracingassigns\@ne
}
\def\afterelse#1\else#2\fi{\fi#1}
{\loggingallstuff
%\edef\x{\iftrue\afterelse T\else F\fi}
\edef\x{\iftrue T\else F\fi}
% \edef\x{\iffalse T\else F\fi}
}
% \iftrue
{\edef}
{\iftrue: (level 1) entered on line 23}
{true}
{\else: \iftrue (level 1) entered on line 23}
{\fi: \iftrue (level 1) entered on line 23}
{changing \x=undefined}
{into \x=macro:->T}
% \iffalse:
{\edef}
{\iffalse: (level 1) entered on line 24}
{false}
{\else: \iffalse (level 1) entered on line 24}
{\fi: \iffalse (level 1) entered on line 24}
{changing \x=undefined}
{into \x=macro:->F}
以下是我发现的一个有趣的案例:
\documentclass{article}
\usepackage{pgfkeys}
\makeatletter
\def\pgfkeysafterfi#1\fi{\fi#1}
%\def\pgfkeysafterelsei#1\else#2\fi{\fi#1}
\def\pgfkeysafterelsei#1\else#2\fi{\else#1} % wrong but gives no error.
\def\pgfkeysifkeydef#1#2#3{%
\ifcsname pgfk@#1/.@cmd\endcsname
\pgfkeysafterelsei{#2}\else\pgfkeysafterfi{#3}\fi
}
\pgfkeys{%
/handlers/.if definable/.code 2 args={
\pgfkeysifkeydef{\pgfkeyscurrentpath}{%
\@latexerr{Oops, key '\pgfkeyscurrentpath' already exists}
{You aren't in trouble here!}%
}{%
\pgfkeys{\pgfkeyscurrentpath/.default=#1,\pgfkeyscurrentpath/.code=#2}%
}%
}%
}
\pgfkeys{
/fam/.is family,/fam/.cd,
keya/.if definable=\relax\@empty,
keya/.if definable=\@empty{\def\x##1{##1*#1}},
}
\makeatother
\begin{document}
x
\end{document}
答案1
让我们使用\iftrue
和\iffalse
来测试会发生什么,假设定义
\def\afterelse#1\else#2\fi{\fi#1}
\iftrue
\iftrue\afterelse T\else F\fi
变成
\afterelse T\else F\fi
下一个扩展是
\fi T
\iffalse
\iffalse\afterelse T\else F\fi
变成
F\fi
并且的展开式\fi
为空。
重要的是,当采用“真”分支时,只有测试被删除,而\else
当采用“假”分支时,所有测试(包括测试)都将被删除。这可以在以下交互式会话中看到:
This is TeX, Version 3.1415926 (TeX Live 2011)
**\relax
*\toks0=\expandafter{\iftrue T\else F\fi}
*\showthe\toks0
> T\else F\fi .
<*> \showthe\toks0
?
*\toks0=\expandafter{\iffalse T\else F\fi}
*\showthe\toks0
> F\fi .
<*> \showthe\toks0
代码
\def\afterelse#1\else#2\fi{\else#1}
是不正确的,如以下交互式会话所示
This is TeX, Version 3.1415926 (TeX Live 2011)
**\relax
*\def\afterelse#1\else#2\fi{\else#1}
*\iftrue\afterelse T\else F\fi
*
(Please type a command or say `\end')
*\bye
! Incomplete \iftrue; all text was ignored after line 0.
<inserted text>
\fi
<to be read again>
\bye
<*> \bye