9

I'm trying to typeset an article. In the preamble, I defined these two things:

\newcommand{\leftexp}[2]{{\vphantom{#2}}^{#1}{#2}}

\newcommand{\hr}{\leftexp{*}{\mathbb{R}}}

However, when I try to use $\hr$ in a section, as in:

\section{Constructing $\hr$}

I get an error:

Incomplete `\iffalse`; all text was ignored after line 1.

Any idea what could be causing this? Everything works just fine if I don't have the $\hr$ in the section (e.g. It typesets just fine if I have \section{Constructing $\mathbb{R}$}, say).

Joseph Wright
  • 259,911
  • 34
  • 706
  • 1,036
FPP
  • 667
  • 2
    Since the argument of \section "moves", protecting it seems to solve your problem: \newcommand{\hr}{\protect\leftexp{*}{\mathbb{R}}}, or just using \protect\hr in your sectional header. – Werner Feb 01 '12 at 23:19

2 Answers2

15

It'll be a fragile command, and \section is a moving argument, so use \protect or declare it with \DeclareRobustCommand

enter image description here

\documentclass{article}

\usepackage{amsmath,amssymb}

\newcommand{\leftexp}[2]{{\vphantom{#2}}^{#1}{#2}}

\newcommand{\hr}{\leftexp{*}{\mathbb{R}}}

\DeclareRobustCommand{\leftexpB}[2]{{\vphantom{#2}}^{#1}{#2}}
\DeclareRobustCommand{\hrB}{\leftexpB{*}{\mathbb{R}}}

\begin{document}

\tableofcontents

\section{Constructing $\protect\hr$}

aa

\section{Constructing $\hrB$}

aa


\end{document} 
David Carlisle
  • 757,742
  • 1
    Thanks a lot. I'm just learning these things, so may I ask what exactly is a "moving argument" and a "fragile command"? Alternatively, what does \protect do? – FPP Feb 01 '12 at 23:22
  • 5
    Ah, the honest answer is a "moving argument" is any argument in which things go wrong sometimes. A fragile command is a command that goes wrong in a moving argument, and \protect normally does nothing but in each such command it is locally defined to do whatever necessary to fix the problem. This case is typical, the heading is typeset as the section head, but also perhaps written to the toc file and/or used at a different font size in a page head. \protect holds the command unexpanded so it is written to the toc file unexpanded and only expanded when the toc is read back in. – David Carlisle Feb 01 '12 at 23:26
  • 1
    See also http://tex.stackexchange.com/questions/4736/what-is-the-difference-between-fragile-and-robust-commands – Joseph Wright Feb 02 '12 at 17:21
5

You got the (in)famous "fragile command in moving argument" problem. The stuff in \section is written into table of contents, which breaks things.

The following works:

\newcommand{\leftexp}[2]{{\protect\vphantom{#2}}^{#1}{#2}}
\newcommand{\hr}{\leftexp{*}{\mathbb{R}}}
Boris
  • 38,129