上下文相关宏:向后看?

上下文相关宏:向后看?

我尝试根据宏是否遵循特定字符/文本来对其进行微调。例如,

This is it! \great! Wait, what is \great?

应该成为

This is it! Grrreeeaaat! Wait, what is great?

因为第一次出现\great是在感叹号之后,第二次出现在句子中间。

所以我想我需要类似向后看但除了 之外什么也找不到\lastbox。有没有类似\pastlet补充的东西\futurelet,可以检查下一个字符,即向前看?

答案1

使用当前空间因子代码。我还加载amsthm

\documentclass{article}

% not needed if amsthm is loaded
\def\frenchspacing{\sfcode`\.1006\sfcode`\?1005\sfcode`\!1004%
  \sfcode`\:1003\sfcode`\;1002\sfcode`\,1001 }
%%%

\makeatletter
\newcommand{\afterbigpunctornot}{%
  \ifnum\spacefactor>\sfcode`:
    \expandafter\@firstoftwo
  \else
    \expandafter\@secondoftwo
  \fi
}
\makeatother

\newcommand{\great}{\afterbigpunctornot{G}{g}reat}

\begin{document}

This is it. \great! Wait, what is \great?

This is it! \great! Wait, what is \great?

This is it? \great! Wait, what is \great?

This is it, \great! Wait, what is \great?

This is it; \great! Wait, what is \great?

This is it: \great! Wait, what is \great?

\frenchspacing

This is it. \great! Wait, what is \great?

This is it! \great! Wait, what is \great?

This is it? \great! Wait, what is \great?

This is it, \great! Wait, what is \great?

This is it; \great! Wait, what is \great?

This is it: \great! Wait, what is \great?

\end{document}

在此处输入图片描述

这个想法是,在所有非“大”标点符号中,冒号的空间因子代码最高。我们必须重新定义,\frenchspacing因为默认定义只是将所有空间因子代码设置为 1000。

如果只需要在感叹号后面进行更改,我们必须将其空间因子代码设置为唯一的代码。

\documentclass{article}

% not needed if amsthm is loaded
\sfcode`!=\numexpr\sfcode`!+1\relax

\def\frenchspacing{\sfcode`\.1006\sfcode`\?1005\sfcode`\!1004%
  \sfcode`\:1003\sfcode`\;1002\sfcode`\,1001 }
%%%

\makeatletter
\newcommand{\afterexclamation}{%
  \ifnum\spacefactor=\sfcode`!
    \expandafter\@firstoftwo
  \else
    \expandafter\@secondoftwo
  \fi
}
\makeatother

\newcommand{\great}{\afterexclamation{Grrrr}{g}reat}

\begin{document}

This is it! \great! Wait, what is \great?

This is it. \great! Wait, what is \great?

This is it? \great! Wait, what is \great?

This is it, \great! Wait, what is \great?

This is it; \great! Wait, what is \great?

This is it: \great! Wait, what is \great?

\frenchspacing

This is it! \great! Wait, what is \great?

This is it. \great! Wait, what is \great?

This is it? \great! Wait, what is \great?

This is it, \great! Wait, what is \great?

This is it; \great! Wait, what is \great?

This is it: \great! Wait, what is \great?

\end{document}

在此处输入图片描述

答案2

\documentclass[10pt]{report}
 \sfcode`\!=1001
 \newcommand\great{\ifnum\spacefactor=1001 Grrreeeaaat\else great\fi}
 \begin{document}
 This is it! \great! Wait, what is \great?
 \end{document}

在此处输入图片描述

也可以看看检测宏中句子开头的大写字母

相关内容