3

I want to trim the chapter titles in toc up to first dot.

\documentclass{book}
\usepackage{xstring}

\newcommand{\chap}[1]{%
    \chapter[\StrBefore{#1}{.}]{#1}
}
\begin{document}
\chap{Some title. Very long}

Foo Bar

\end{document}

Unfortunately this doesn't work - what am I missing here? (Xe)LaTeX gives me:

Chapter 1.
! Use of \@chapter doesn't match its definition.
\@ifnextchar ... \reserved@d =#1\def \reserved@a {
                                               #2}\def \reserved@b {#3}\f...
l.8 \chap{Some title. Very long}
5

The optional argument to \chapter should not contain unprotected assignments.

\documentclass{book}
\usepackage{xstring}

\newcommand{\chap}[1]{%
    \chapter[\protect\StrBefore{#1}{.}]{#1}%
}
\begin{document}
\chap{Some title. Very long}

Foo Bar

\end{document}

Alternatively, and preferably in my opinion,

\documentclass{book}
\usepackage{xstring}

\newcommand{\chap}[1]{%
    \StrBefore{#1}{.}[\chapterstart]%
    \expandafter\chapter\expandafter[\chapterstart]{#1}%
}
\begin{document}
\tableofcontents
\chap{Some title. Very long}

Foo Bar

\end{document}

Perhaps the two \expandafter commands are not necessary, but this ensures we never rely on a particular value of \chapterstart. With this we don't clutter the auxiliary files with \StrBefore.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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