4

This is a follow-up to the question Cross-referencing in multiple chapters. Following the answer to this question, I am using the following macros:

\newcommand*\maybechapter[1]{%   
 % Tests if current chapter is equal to the chapter number of label)
 \ifnum\value{chapter}=0#1\relax
     % Print nothing if so
 \else
     % Set 'chapter' locally (=> no \setcounter) to the label chapter and
     % print it in the usual format followed by a dot
     {\value{chapter}=#1\relax\thechapter.}%
 \fi
}
\renewcommand*\thesection{%
    \protect\maybechapter{\arabic{chapter}}\arabic{section}%
}

This works as expected for references but in the Table of contents, section numbers are now all preceded by their chapter numbers:

I The first chapter
    I.1 The first section of the first chapter

but I would like to get something like

I The first chapter
    1 The first section of the first chapter

How should I modify \maybechapter to get this result?

J.-E. Pin
  • 619

1 Answers1

4

I'd modify the answer there in a couple of points:

\documentclass{book}

\renewcommand*\thechapter{\Roman{chapter}}

\renewcommand*\thesection{%
    \maybechapter{\arabic{chapter}}\arabic{section}%
}

% Maybe print the chapter number
\protected\def\maybechapter#1{%
   % Tests if current chapter is equal to the chapter number of label)
   \ifnum\value{chapter}=0#1
   \else
     \uppercase\expandafter{\romannumeral#1}.%
   \fi
}

% Test document:
\begin{document}

\begingroup
\def\maybechapter#1{}
\tableofcontents
\endgroup

\chapter{One}

\section{S1}\label{S1}

Here's a reference to Section~\ref{S1},
one to Section~\ref{S2}, and one to
Section~\ref{S3}.

\section{S2}\label{S2}

Text

\chapter{Two}

\section{S3}\label{S3}

\end{document}

Using \protected\def ensures \maybechapter is never expanded in a write operation; since entries for the TOC undergo two write operations, one \protect isn't sufficient.

For the TOC I locally disable the \maybechapter command, so that it gobbles its argument.

enter image description here

egreg
  • 1,121,712