I am writing a book and hope to create automatic labels for every Chapters and Sections in the form \label{AutoChap:"ChapTitle")
and \label{AutoSec:SecTitle)
. Learning from "Automatic" section labeling?, I have got a small progress as showed in my WME.
\documentclass{memoir}
\usepackage{letltxmacro}
\LetLtxMacro{\oldsection}{\section}
\renewcommand{\section}[2][]{\oldsection[#1]{#2}\index{#1}\label{sec:#1}}
\LetLtxMacro{\oldchapter}{\chapter}
\renewcommand{\chapter}[2][]{\oldchapter[#1]{#2}\index{#1}\label{chap:#1}}
\begin{document}
\chapter[ABC]{ABC}
\section[One]{One}
\section{Two}
\section*[Three]{Three}
Test reference \ref{chap:ABC}
Test reference \ref{chap:XYZ}
Test reference \ref{sec:One}
Test reference \ref{sec:Two}
\chapter{DEF}
\chapter*[XYZ]{XYZ}
\end{document}
However, there are still 2 problems:
-
This code requires an assigned name ([]) for each Chapter and Section. For example, in my WME, it is working for Chapter ABC, Section One, but not for Chapter DEF, Section Two. Almost (but not all) my Chapters and Sections have not been assigned any Name, then I am seeking for a solution which could be working for both situations (assigning or not).
-
It causes error for starred Chapters and Sections, for example Chapter XYZ or Section Three in my example. (And as a result, it creates troubles to my table of contents or Bibliography…) .
Please kindly advise me any possible solution for getting auto label without such problems. Many thanks.
EDIT. I have also tried the other suggestion (as showed below) in the same thread, "Automatic" section labeling?, which is:
\let\orisectionmark\sectionmark
\renewcommand\sectionmark[1]{\label{autosection::\thesection}\orisectionmark{#1}}
It might be better working for Section label, but still can not apply the same idea for Chapters' label. Please kindly help me.
Best Answer
I don't recommend using label names generated from chapter or section names, since those
However, the main reason the code from the O.P. does not work is
memoir
's 'weird' 2nd optional argument for the\chapter
and\section
macros.This can be catched easily with
xparse
and\RenewDocumentCommand
. I've have provided for an\@currentlabel
approach that defaults to the chapter or section title for starred macros.This approach works with
hyperref
as well.