4

Say I have a variable that contains some non-plain text, for instance \def\var{Caro \textit{et al.}}, and I want to make a substring substitution of Caro for \underline{Caro}. If I try to follow the recipe from Replacing a substring, this will fail:

\documentclass{minimal}
\usepackage{xstring}
\def\ReplaceStr#1{%
  \IfSubStr{#1}{Caro}{%
    \StrSubstitute{#1}{Caro}{\underline{Caro}}}{#1}}

\begin{document}

\def\var{Caro \textit{et al.}}

\ReplaceStr{\var}

\end{document}

If I remove the formatting from the variable definition, i.e. \def\var{Caro et al.}, then it works:

\documentclass{minimal}
\usepackage{xstring}
\def\ReplaceStr#1{%
  \IfSubStr{#1}{Caro}{%
    \StrSubstitute{#1}{Caro}{\underline{Caro}}}{#1}}

\begin{document}

\def\var{Caro et al.}

\ReplaceStr{\var}

\end{document}

Unfortunately, in my actual case I have no way to directly modify the formatting that \var comes with since it's generated through a series of commands. How can I either:

  • Remove all formatting from \var (i.e. make it "plain text") before I do the substring replacement
  • Make the string replacement act correctly on formatted text

For the curious, my actual \var comes from a biblatex call: \def\var{\citename{somebibitem}{author}}.

Miguel
  • 717

1 Answers1

5

You have to be careful with expansion; by default xstring performs full expansion and \textit doesn't survive it.

\documentclass{article}
\usepackage{xstring}

\newcommand\replacecaro[1]{%
  \begingroup\expandarg
  \IfSubStr{#1}{Caro}{\StrSubstitute{#1}{Caro}{\underline{Caro}}}{#1}%
  \endgroup
}

\begin{document}

\newcommand{\var}{Caro \textit{et al.}}

\replacecaro{\var}

\end{document}

enter image description here

Don't use \def in LaTeX unless you know precisely why you need it.

egreg
  • 1,121,712
  • Thanks, this does work for my simplification of the problem, but unfortunately does not work for my actual problem where the definition of \var is actually \newcommand{\var}{\citename{caro_2015}{author}} and caro_2015 is a bibitem where M. A. Caro is the outcome of \citename{caro_2015}{author}. I will accept your answer but help on this more complicated scenario would be appreciated. – Miguel Sep 22 '15 at 11:31
  • @Miguel Much more information is needed for the full scenario. In a new question with all the details. But I think you can already find something about the problem on the site: http://tex.stackexchange.com/search?q=highlight+author – egreg Sep 22 '15 at 11:36
  • Thanks again. I have seen most of those answers already but I don't like the most common solution of directly editing the bibfile. I will keep researching a bit and post another question if I don't manage what I want. – Miguel Sep 22 '15 at 11:39
  • @Miguel The solutions within biblatex seem more effective. – egreg Sep 22 '15 at 11:42
  • I finally gave up and ended up writing a small bash sed command to generate a temporary bib file from my master bib file with the correct formatting... – Miguel Sep 22 '15 at 13:23