如何编写带有变体的定义?

如何编写带有变体的定义?

在 TeX 中我可以定义,例如

\def\1#1 is #2.{#1 & is & #2.\\}

\def\2#1 has #2.{#1 & has & #2.\\}

使用方便 \1 Jim Jones is a fictional character.\2 Tim Smith has two brothers.

这给出了表格的三列:Jim Jones,是虚构人物。第二种情况类似。

我可以根据 is/has 写一个定义吗?这样我就可以写

\3 Jim Jones is a fictional character.\3 Tim Smith has two brothers.

获得先前的结果?

使用 Lua 或 expl3 的解决方案是可以的,但我希望纯 TeX 的解决方案也是可行的。

答案1

一种listofitems方法。此外,listofitems还可用于 Plain TeX。

\documentclass{article}
\usepackage{listofitems}
\def\variant#1.{%
  \setsepchar{is||has}%
  \greadlist*\varinput{#1}
  \varinput[1] & \varinputsep[1] & \varinput[2].
}
\begin{document}
\begin{tabular}{|c|c|c|}
\variant Jim Jones is a fictional character.\\
\variant Tim Smith has two brothers.
\end{tabular}
\end{document}

在此处输入图片描述

在纯 TeX 中同样可以完成

\input listofitems
\def\variant#1.{%
  \setsepchar{is||has}%
  \greadlist*\varinput{#1}
  \varinput[1] \& \varinputsep[1] \& \varinput[2].
}
\variant Jim Jones is a fictional character.

\variant Tim Smith has two brothers.

\bye

答案2

\replacestrings可以使用 OPmac 中的宏:

%from OPmac code:
\bgroup \catcode`!=3 \catcode`?=3
\gdef\replacestrings#1#2{\long\def\replacestringsA##1#1{\def\tmpb{##1}\replacestringsB}%
   \long\def\replacestringsB##1#1{\ifx!##1\relax \else\addto\tmpb{#2##1}%
      \expandafter\replacestringsB\fi}%     improved version <May 2016> inspired 
   \expandafter\replacestringsA\tmpb?#1!#1% 
   \long\def\replacestringsA##1?{\def\tmpb{##1}}\expandafter\replacestringsA\tmpb
}
\egroup
\long\def\addto#1#2{\expandafter\def\expandafter#1\expandafter{#1#2}}

%variant definition:
\def\variant #1.{\def\tmpb{#1}%
  \replacestrings{ is }{ \tabsep is \tabsep }%
  \replacestrings{ has }{ \tabsep has \tabsep }%
  \tmpb
}
\def\tabsep{&}

%% test:
\halign{#\hfil\vrule\strut\ &#\hfil\vrule\ &# \hfil\cr
%
  \variant Jim Jones is a fictional character. \cr
  \variant Tim Smith has two brothers. \cr
}

\end

答案3

expl3当然是有了。;-)

\input expl3-generic

\ExplSyntaxOn

\cs_new_protected:Npn \3 #1.
 {
  \tl_set:Nx \l_tmpa_tl { \tl_trim_spaces:n { #1 } }
  \regex_replace_once:nnN { \s*(is|has)\s* } { \cT\& \1 \cT\& } \l_tmpa_tl
  \l_tmpa_tl. \cr
 }

\ExplSyntaxOff

\halign{#\hfil&\ \hfil#\hfil\ &# \hfil\cr
  \3 Jim Jones is a fictional character and is funny.
  \3 Tim Smith has two brothers.
}

\bye

在此处输入图片描述

相关内容