# Sectioning command that automatically creates label

I'm trying to define a custom section command that will also define a corresponding label after a bit of preparsing. Specifically, I want the command to define a section with the given name, and then define a label with the name lower-cased and having spaces replaced with dashes.

So far I've come up with the following:

\NewDocumentCommand\startSection{m}
{
\section{#1}\label{\lowercase{\StrSubstitute{#1}{ }{-}}}
}


Which uses the xstring and xparse packages, but this yields an error:

! Argument of \@sect has an extra }.


After a bit of playing around I would get:

! Missing \endcsname inserted


around the \lowercase command.

I seem to be missing some essential knowledge about how labels work, so does anyone have a good suggestion?

-
create a complete example –  Herbert Aug 30 '11 at 7:52

\usepackage{xstring}
\newcommand{\startSection}[1]{%
\lowercase{\def\templabel{#1}}%
\StrSubstitute{\templabel}{ }{-}[\templabel]
\section{#1}\label{\templabel}}


The \StrSubstitute and \lowercase commands are not expandable, so your \label doesn't find anything good for it. You have to \lowercase first, then to \StrSubstitute and finally feed the string to \label.

However, it's just an exercise: this command will probably break if accented letters or commands are in the section title.

-
Thanks, this works, and yes, that did strike me, also because it's not uncommon for my LaTeX section headings to have nested commands, etc. –  oleks Aug 30 '11 at 8:54
Use a package such as showkeys during document preparation: it shows labels in the margin or next to the referenced object. At a later stage it can be disabled, for the final revision, when labels are not important any more. –  egreg Aug 30 '11 at 8:59
Perhaps this macro could be expanded to use the syntax of \section[short title]{long title with macros}. You probably don't want the label names to be too long at any rate. –  doncherry Jan 10 '12 at 11:55
@doncherry I wouldn't recommend using such an automatism. It can be handy only if section titles are short. –  egreg Jan 10 '12 at 12:03