在巨集定義中使用 \StrSubstitute

在巨集定義中使用 \StrSubstitute

我想建立一個宏,用於排版參數\emph並使用該名稱建立標籤。我的名字包含下劃線,所以我嘗試\StrSubstitutexstring包中使用:

\documentclass{article}

\usepackage{xstring}

\newcommand{\tactic}[1]{
\label{\StrSubstitute{#1}{\_}{}}
\emph{#1}
}

\begin{document}

\tactic{EXISTS_TAC}

\end{document}

但我得到

! Use of \@xs@StrSubstitute@@ doesn't match its definition.
\kernel@ifnextchar ...d@d =#1\def \reserved@a {#2}
\def \reserved@b {#3}\futu... l.12 
\tactic{EXISTS_TAC}

我怎樣才能解決這個問題?

答案1

實際上,您遇到了相反的問題:諸如此類的輸入\emph{EXISTS_TAC}會引發錯誤,而這\label{EXISTS_TAC}是完全安全的。

\documentclass{article}

\usepackage{xstring}

\newcommand{\tactic}[1]{%
  \emph{\noexpandarg\StrSubstitute{#1}{_}{\_}}\label{#1}%
}

\begin{document}

\tactic{EXISTS_TAC}

It was on page~\pageref{EXISTS_TAC}

\end{document}

在此輸入影像描述

答案2

這是一個基於 LuaLaTeX 的解決方案。

在此輸入影像描述

\documentclass{article}
\usepackage{luacode} % for 'luacode' env. and '\luastringN' macro
\begin{luacode}
function tactic ( s ) 
   tex.sprint ( "\\label{"..s.."}" )
   tex.sprint ( "\\emph{\\detokenize{"..s.."}}" )
end
\end{luacode}
\newcommand\tactic[1]{\directlua{tactic(\luastringN{#1})}}

\begin{document}
\tactic{EXISTS_TAC} \quad \tactic{_^&@$<>}
\end{document}

答案3

您不需要從引用標籤的名稱中刪除下劃線,但如果您堅持這樣做:

\documentclass{article}

\usepackage{xstring}
\usepackage{textcomp}

\newcommand{\tactic}[1]{%
  \begingroup
  \let\textunderscore=\relax
  \StrSubstitute{#1}{_}{\textunderscore}[\mytemp]%
  \expandafter\endgroup
  \expandafter\emph
  \expandafter{\mytemp}%
  \begingroup
  \StrSubstitute{#1}{_}{}[\mytemp]%
  \expandafter\endgroup
  \expandafter\label
  \expandafter{\mytemp}%
}%

\begin{document}

\tactic{EXISTS_TAC}  \pageref{EXISTSTAC}

\end{document}

在此輸入影像描述

請注意,如果使用超引用-package\label不會為超連結放置錨點,並且您的\tactic- 命令在任何情況下都不會更改任何計數器 via ,因此透過 or引用\refstepcounter標籤將導致引用切片的上級項目。將提供對應命令輸出發生的頁面的頁碼。\ref\nameref\autoref\pageref\tactic

相關內容