Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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?
share|improve this question
add comment

2 Answers

up vote 5 down vote accepted

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}}
share|improve this answer
    
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
2  
@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
add comment

it is a moving argument:

  \section{\protect\foo{I love Mondays}}
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.