我需要一个宏来查看其以前的用法并比较第一个参数,然后如果这些参数相同则打印附加文本。
例如
\mycommand{Michael}{Hello, John}
Michael and John shake hands.
\mycommand{Michael}{How are you today?}\\
\mycommand{John}{I'm good, how are you, Michael?}\\
\mycommand{Michael}{Good, thank you.}
将会打印类似这样的内容:
迈克尔:你好,约翰。
迈克尔和约翰握手。
迈克尔(再次):你今天好吗?
约翰:我很好,你好吗,迈克尔?
迈克尔:很好,谢谢你。
我最初以为我可以使用\renewcommand{\charactername}{#1}
宏定义中的类似功能,但需要对其进行扩展才能进行比较。有什么想法吗?
编辑
@egreg 在下面回答了一个首先有效的解决方案。如果您需要重置存储的参数(在我的示例中是字符名称),则可以使用\gdef\dialogue@remember{}
。
答案1
存储前一位发言者的发言:
\documentclass{article}
\usepackage{pdftexcmds} % for engine cross-compatibility
\makeatletter
\newcommand{\mycommand}[2]{%
#1\ifnum\pdf@strcmp{\mycommand@remember}{#1}=\z@ ~(again)\fi
\gdef\mycommand@remember{#1}%
: #2%
}
\def\mycommand@remember{} % initialize
\makeatother
\setlength{\parindent}{0pt} % just for the example
\begin{document}
\mycommand{Michael}{Hello, John}
Michael and John shake hands.
\mycommand{Michael}{How are you today?}
\mycommand{John}{I'm good, how are you, Michael?}
\mycommand{Michael}{Good, thank you.}
\end{document}
扩展版本中,主命令有一个 * 变体,可以清除记住的字符。
\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentCommand{\dialogue}{smm}
{
\IfBooleanT { #1 } { \str_gclear:N \g__experimenthouse_speaker_str }
\experimenthouse_dialogue:nn { #2 } { #3 }
}
\str_new:N \g__experimenthouse_speaker_str
\cs_new_protected:Nn \experimenthouse_dialogue:nn
{
#1 % speaker
\str_if_eq:VnT \g__experimenthouse_speaker_str { #1 } { ~(again) }
\str_gset:Nx \g__experimenthouse_speaker_str { \tl_to_str:n { #1 } }
:~#2
}
\ExplSyntaxOff
\setlength{\parindent}{0pt} % just for the example
\begin{document}
\dialogue{Michael}{Hello, John}
Michael and John shake hands.
\dialogue{Michael}{How are you today?}
\dialogue{John}{I'm fine, how are you, Michael?}
\dialogue{Michael}{Fine, thank you.}
\dialogue{Michael}{Fine, thank you.}
\dialogue*{Michael}{Fine, thank you.}
\end{document}