# xstring functions in section/paragraph headers

In the following example,

\documentclass{article}
\usepackage{xstring}
\newcommand\foo[1]{\StrSubstitute{#1}{love}{hate}}

\begin{document}
\section*{\foo{I love Mondays}}
\end{document}


if I remove the * from \section* the code stops compiling.

1. What is the trick that makes \section* work ok with \StrSubstitute but not \section?
2. Is there a workaround to include the command \foo in a \section header too?
-

## 2 Answers

Remember, section headings are also used for the table of contents, thus expanded and written to the .toc file. Use \protect to prevent the early expansion of \foo:

\section{\protect\foo{I love Mondays}}


Alternatively use the optional argument to fix it:

\section[]{\foo{I love Mondays}}


Have a look at Fragile and Robust commands for explanation.

You can define the command to be robust, avoiding such problems from the beginning:

\DeclareRobustCommand\foo[1]{\StrSubstitute{#1}{love}{hate}}

-
thanks for the answer (and Herbert, too); but I still do not get why the same syntax works with \section*. Moreover, is there a way to modify either \section or \foo so that I can use the second syntax without a \protect or an optional argument? – Federico Poloni Jan 19 '11 at 21:05
@Federico: \section* doesn't create a table of contents entry, that's why id doesn't expand \foo writing it to the .toc file which causes the problem. You can make it robust by \DeclareRobustCommand. I'll edit my answer to add that. – Stefan Kottwitz Jan 19 '11 at 21:09

it is a moving argument:

  \section{\protect\foo{I love Mondays}}

-