Como prefixar e quebrar o texto da linha de título em um ToC (para capítulos) na classe do livro?

Como prefixar e quebrar o texto da linha de título em um ToC (para capítulos) na classe do livro?

Estou procurando uma maneira de incluir o texto "Capítulo" como um prefixo para a numeração do capítulo em um ToC para uma classe de livro E fazer com que o título do capítulo seja colocado na borda mais à esquerda na listagem do ToC. Estou construindo isso em um recurso comum, atualmente em duas partes, uma como o arquivo de classe apenas com pacotes e a outra como um arquivo .tex de configurações que está \input no preâmbulo. Eu tentei duas abordagens diferentes no arquivo de configurações. O primeiro abaixo não captura o patch necessário corretamente.

\documentclass{book}

\usepackage{xpatch}
\usepackage{hyperref}

\makeatletter
\xpatchcmd{\@chapter}
    {\addcontentsline{toc}{chapter}{\numberline {#1}}}
    {\addcontentsline{toc}{chapter}{\numberline {Chapter~\thechapter{}.~#1}}}
    {\typeout{Success}}
    {\typeout{Failed!}}
\makeatother

\begin{document}

\tableofcontents

\chapter{This is First}

Some day this will work.

\chapter{This is Second}

Perhaps soon!

\end{document}

Esta segunda abordagem coloca a palavra Capítulo no ToC, mas o texto no título mais longo do Capítulo 2 não é quebrado conforme exigido na linha do ToC.

\documentclass{book}

\usepackage{tocloft}

\begin{document}

\newlength{\tocchapwidth}
\settowidth{\tocchapwidth}{\chaptername\ }
\addtolength{\cftchapnumwidth}{\tocchapwidth}
\renewcommand{\cftchappresnum}{\chaptername\ }
\renewcommand{\cftchapaftersnum}{.}
\renewcommand{\cftchapaftersnumb}{~}
\renewcommand{\cftchapdotsep}{\cftdotsep}

\tableofcontents

\chapter{This is First}

Some day this will work.

\chapter{This is Second, a Rather Long and Windy Road Leading to a Door Going to Nowhere Fast}

Perhaps soon!

\end{document}

Esta é uma tentativa de atender aos requisitos de formatação de um documento de tese/dissertação. Atualmente temos uma solução alternativa - digitamos o título do capítulo incluindo o prefixo, por exemplo \chapter{Capítulo 2.~Este é o segundo ...} (e suprimimos as saídas do número do capítulo no ToC usando o pacote titlesec).

Além disso, embora eu não o inclua no segundo exemplo, o documento requer o pacote hyperref. Deduzo de uma postagem separada que talvez eu precise corrigir o comando do capítulo Hy@..., mas mesmo minhas tentativas de fazer isso falharam.

Não estou familiarizado o suficiente com o LaTeX3, mas ficarei feliz em incorporar tais modificações. Finalmente, espero que qualquer opção oferecida funcione prontamente no Overleaf, onde um grande contingente daqueles que usarão o pacote provavelmente farão o seu trabalho.

Responder1

Existem vários problemas com sua primeira abordagem.

Em primeiro lugar, mesmo a definição original de book.clsnão possui:

\addcontentsline{toc}{chapter}{\numberline {#1}}

na definição de \@chapter, mas:

\addcontentsline{toc}{chapter}{\protect\numberline{\thechapter}#1}

Portanto, falta \protectum argumento correto \numberlinee o primeiro argumento de \@chapteré usado sem colchetes.

O segundo problema é que depois de carregar hyperrefa definição das \@chapteralterações. Então o patch deve serantescarregando hyperref.

BTW: Para ver a definição original, basta adicionar \show\@chapterbefore \xpatchcmd. Isso produzirá a definição atual antes de aplicar o patch \@chapterno logarquivo -.

O terceiro problema é que a substituição:

\addcontentsline{toc}{chapter}{\protect\numberline {Chapter~\thechapter{}.~#1}}

Colocaria não apenas Chapter~<number>.no argumento do número, mas também no título. Então deveria ser pelo menos:

\addcontentsline{toc}{chapter}{\numberline {Chapter~\thechapter{}.}#1}

Mas para esta definição também seria necessária uma mudança de \l@chapterpara aumentar o espaço reservado para o número. Talvez, em vez disso, você não queira reservar espaço numérico e, em vez disso, goste de usar:

\addcontentsline{toc}{chapter}{Chapter~\thechapter{}.~#1}

Então com:

\documentclass{book}

\usepackage{xpatch}

\makeatletter
\xpatchcmd{\@chapter}
  {\addcontentsline{toc}{chapter}{\protect\numberline{\thechapter}#1}}
  {\addcontentsline{toc}{chapter}{Chapter~\thechapter{}.~#1}}
  {\typeout{Success}}
  {\typeout{Failed!}}
\makeatother

\usepackage{hyperref}

\begin{document}

\tableofcontents

\chapter{This is First}

Some day this will work.

\chapter{This is Second}

Perhaps soon!

\end{document}

você obtém:

Capítulo 1. Este é o…

A alternativa de usar Chapter <number>.como argumento \numberlineseria, por exemplo:

\documentclass{book}

\usepackage{xpatch}

\makeatletter
\xpatchcmd{\@chapter}
  {\addcontentsline{toc}{chapter}{\protect\numberline{\thechapter}#1}}
  {\addcontentsline{toc}{chapter}{\protect\numberline{Chapter~\thechapter{}.}#1}}
  {\typeout{\string\@chapter\space patch success}}
  {\typeout{\string\@chapter\space patch failed!}}
\xpatchcmd{\l@chapter}
  {\setlength\@tempdima{1.5em}}
  {\setlength\@tempdima{6em}}% increase reserved number width
  {\typeout{\string\l@chapter\space patch success}}
  {\typeout{\string\l@chapter\space patch failed!}}
\makeatother

\usepackage{hyperref}

\begin{document}

\tableofcontents

\chapter{This is First}

Some day this will work.

\chapter{This is Second}

Perhaps soon!

\end{document}

O resultado para entradas de uma linha é semelhante à primeira sugestão. Para ver a diferença, tente entradas com mais de uma linha, por exemplo

\chapter{This is Second Chapter with very long Titel Needing more than one
  Line in the Table of Contents}

Então, IMHO, esta segunda abordagem minha é o que você deseja.


Seu problema com sua segunda abordagem é que você não leva em consideração o ponto .e o espaço após o número ao aumentar . Aqui está uma possível correção de sua configuração:~\cftchapnumwidth

\documentclass{book}

\usepackage{tocloft}

\begin{document}

\newlength{\tocchapwidth}
\renewcommand{\cftchappresnum}{\chaptername\ }
\settowidth{\tocchapwidth}{\cftchappresnum}
\renewcommand{\cftchapaftersnum}{.~}
\newlength{\tocchapafternumwidth}
\settowidth{\tocchapafternumwidth}{\cftchapaftersnum}
\addtolength{\cftchapnumwidth}{\tocchapwidth}
\addtolength{\cftchapnumwidth}{\tocchapafternumwidth}
\renewcommand{\cftchapdotsep}{\cftdotsep}

\tableofcontents

\chapter{This is First}

Some day this will work.

\chapter{This is Second, a Rather Long and Windy Road Leading to a Door Going to Nowhere Fast}

Perhaps soon!

\end{document}

usando tocloft

Mas se você analisar atentamente essa sugestão, ela ainda não estará correta, porque você está medindo o texto na fonte do documento atual e não na fonte usada nas entradas do capítulo. Portanto, o código anterior apenas parece estar correto, mas não está. Para um código correto você deve levar \cftchapfontem consideração ao medir as larguras do texto. (E agora você não precisa aumentar a largura também pelo espaço, se a largura do número sem o prefixo Chaptere o postfix .já fosse suficiente). Então um código melhor seria algo como:

\documentclass{book}

\usepackage{tocloft}

\newlength{\tocchapwidth}
\newlength{\tocchapafternumwidth}
\renewcommand{\cftchappresnum}{\chaptername\ }
\renewcommand{\cftchapaftersnum}{.}
\renewcommand{\cftchapdotsep}{\cftdotsep}
\AtBeginDocument{% final font setup is done in \begin{document} so we delay all text measuring
  \settowidth{\tocchapwidth}{\cftchapfont\cftchappresnum}%
  \settowidth{\tocchapafternumwidth}{\cftchapfont\cftchapaftersnum}%
  \addtolength{\cftchapnumwidth}{\tocchapwidth}%
  \addtolength{\cftchapnumwidth}{\tocchapafternumwidth}%
}

\begin{document}
\tableofcontents

\chapter{This is First}

Some day this will work.

\chapter{This is Second, a Rather Long and Windy Road Leading to a Door Going to Nowhere Fast}

Perhaps soon!

\end{document}

O problema do apêndice

Nota: Ambos os exemplos não são adequados para documentos com apêndice, pois neste caso Chapternão seria o termo correto no apêndice.

tocloftSeria fácil fazer a sugestão recomendada sem ser adequada para documentos com apêndice. Você só precisa substituir o codificado Chapterpor \@chapappe aumentar a largura:

\documentclass{book}

\usepackage{xpatch}

\makeatletter
\xpatchcmd{\@chapter}
  {\addcontentsline{toc}{chapter}{\protect\numberline{\thechapter}#1}}
  {\addcontentsline{toc}{chapter}{\protect\numberline{\@chapapp~\thechapter{}.}#1}}
  {\typeout{\string\@chapter\space patch success}}
  {\typeout{\string\@chapter\space patch failed!}}
\xpatchcmd{\l@chapter}
  {\setlength\@tempdima{1.5em}}
  {\setlength\@tempdima{7em}}% increase reserved number width
  {\typeout{\string\l@chapter\space patch success}}
  {\typeout{\string\l@chapter\space patch failed!}}
\makeatother

\usepackage{hyperref}

\begin{document}

\tableofcontents

\chapter{This is First}

Some day this will work.

\chapter{This is Second}

Perhaps soon!

\appendix
\chapter{This is a Rather Long and Windy Road Leading to a Door Going
  to Nowhere Fast}

\end{document}

Para a tocloftsolução você poderia usar algo como:

\documentclass{book}

\usepackage{tocloft}

\newlength{\tocchapwidth}
\newlength{\tocappwidth}
\newlength{\tocchapafternumwidth}
\renewcommand{\cftchappresnum}{\chaptername\ }
\renewcommand{\cftchapaftersnum}{.}
\renewcommand{\cftchapdotsep}{\cftdotsep}
\AtBeginDocument{%
  \settowidth{\tocchapwidth}{\cftchapfont\chaptername}%
  \settowidth{\tocappwidth}{\cftchapfont\appendixname}%
  \ifdim\tocappwidth>\tocchapwidth
    \addtolength{\cftchapnumwidth}{\tocappwidth}%
  \else
    \addtolength{\cftchapnumwidth}{\tocchapwidth}%
  \fi
  \settowidth{\tocchapafternumwidth}{\cftchapfont\cftchapaftersnum}%
  \addtolength{\cftchapnumwidth}{\tocchapafternumwidth}%
}
\AddToHook{cmd/appendix/after}{%
  \addtocontents{toc}{%
    \protect\renewcommand{\protect\cftchappresnum}{\protect\appendixname{} }%
  }%
}
\begin{document}
\tableofcontents

\chapter{This is First}

Some day this will work.

\chapter{This is Second, a Rather Long and Windy Road Leading to a Door Going to Nowhere Fast}

Perhaps soon!

\appendix
\chapter{A Rather Long Appendix Heading and Windy Road Leading to a Door Going to Nowhere Fast}


\end{document}

informação relacionada