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}

1 Answer 1

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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .