# \thesection (and related) must be fragile?

I think the answer to my question lies somewhere in this thread, but I can't quite find it, and it seems to me that I'm asking the reverse of the question first posed in that thread. In any case...

I've been trying to redefine \thesection (and related \the... sectioning commands) to produce alternative ordinals for my sections. If I use \renewcommand, things work out just fine. If I try to use \DeclareRobustCommand or any of the command declarators in the xparse package, I run into problems with the table of contents.

So this first question is, do I have to use \renewcommand here, because \thesection needs to be fragile? That doesn't quite make sense to me, as the ordinal shows up correctly in the document proper. It's just the table of contents that get's a bit messy.

The second question would be, if I don't have to use \renewcommand, how would I go about using, say, \RenewDocumentCommand. Normally, I'd be perfectly happy to just use what works, but I have plans down the future to do some more tricky things with \thesection (that is allowing me to parse an ordinal style string, like the one enumerate provides for enumerated lists -- something I already have working, and should just be able to plug in.)

A MWE to illustrate (have to comment out one of the lines in the preamble):

\documentclass{article}

\DeclareRobustCommand{\thesection}{\Alph{section}}% does not work in toc
\renewcommand{\thesection}{\Alph{section}}% works always

\begin{document}
\tableofcontents
\section{Section One}
\section{Section Two}
\section{Section Red}
\section{Section Blue}
\end{document}

-

We are not talking exactly about 'fragile' macros here, but about expandable ones, and it is necessary that \the... are expandable. The reason is that when the TOC is written, robust macros are placed in the .toc file 'as is' whereas expandable ones are expanded. In the .toc file, you want to save the numbers for sections, etc., and not the marker \thesection, etc.

If you want to use xparse for these definitions, you'll need to use \DeclareExpandableDocumentCommand. The name is pretty long as these are rare: the syntax is identical to \RenewDocumentCommand. Note that you need to only use expandable arguments here for everything to work: as a test, make sure that doing

\edef\test{\thesection}\show\test


gives the expected results.

-

\thesection isn't necessarily fragile, but simple expandable when defined with \newcommand. It is written to the .aux and .toc file and should then fully expand to the current section number, otherwise the ToC and labels etc. will break. You might not want to define it to something complex for this reasons.

If \thesection would be fragile the writing to the above mentioned would also break. Not any non-robust is automatically fragile, only if it contains code which must be executed by the TeX stomach and is therefore not fully expandable.

-