¿Cómo anteponer y ajustar el texto de la línea de título en una ToC (para capítulos) en la clase de libro?

¿Cómo anteponer y ajustar el texto de la línea de título en una ToC (para capítulos) en la clase de libro?

Estoy buscando una manera de incluir el texto "Capítulo" como prefijo de la numeración de capítulos en un ToC para una clase de libro Y hacer que el título del capítulo se ajuste al borde más izquierdo en la lista de ToC. Estoy integrando esto en un recurso común, actualmente en dos partes, una como archivo de clase solo con paquetes y la otra como un archivo .tex de configuración que está en \input en el preámbulo. Probé dos enfoques diferentes dentro del archivo de configuración. El primero a continuación no captura correctamente el parche requerido.

\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}

Este segundo enfoque coloca la palabra Capítulo en su lugar en la ToC, pero el texto en el título más largo del Capítulo 2 no se ajusta como se requiere en la línea de la 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}

Este es un intento de cumplir con los requisitos de formato de un documento de tesis/disertación. Actualmente tenemos una solución burda: escribimos el título del capítulo incluyendo el prefijo, por ejemplo \chapter{Capítulo 2.~Este es el segundo...} (y suprimimos las salidas del número de capítulo en el ToC usando el paquete titlesec).

Además, aunque no lo incluyo en el segundo ejemplo, el documento requiere el paquete hyperref. De una publicación separada deduzco que podría necesitar parchear el comando del capítulo Hy@..., pero incluso mis intentos de hacerlo fallaron.

No estoy lo suficientemente familiarizado con LaTeX3, pero estaré encantado de incorporar dichas modificaciones. Finalmente, espero que cualquier opción que se ofrezca funcione lo suficientemente bien para Overleaf, donde un gran contingente de quienes usarán el paquete probablemente harán su trabajo.

Respuesta1

Hay varios problemas con su primer enfoque.

En primer lugar, incluso la definición original de book.clsno tiene:

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

en la definición de \@chapter, pero:

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

Entonces falta un \protectargumento y el correcto \numberliney el primer argumento de \@chapterse usa sin llaves.

El segundo problema es que después de cargar hyperrefla definición de \@chaptercambios. Entonces el parche debe serantescargando hyperref.

Por cierto: para ver la definición original, simplemente agregue \show\@chapterantes \xpatchcmd. Esto generará la definición actual antes de aplicar el parche \@chapteren el logarchivo.

El tercer problema es que el reemplazo:

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

Pondría no sólo Chapter~<number>.el argumento numérico sino también el título. Entonces debería ser al menos:

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

Pero para esta definición también necesitarías un cambio de \l@chapterpara aumentar el espacio reservado para el número. Quizás en lugar de eso no quieras reservar espacio numérico y en su lugar te guste usar:

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

Entonces con:

\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}

usted obtiene:

Capítulo 1. Este es el…

La alternativa con el uso Chapter <number>.como argumento de \numberlinesería, por ejemplo:

\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}

El resultado para entradas de una línea es similar a la primera sugerencia. Para ver una diferencia, pruebe con entradas con más de una línea, por ejemplo

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

Entonces, en mi humilde opinión, este segundo enfoque mío es lo que quieres.


Su problema con su segundo enfoque es que no tiene en cuenta el punto .y el espacio ~después del número al aumentar \cftchapnumwidth. Aquí una posible corrección de su configuración:

\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

Pero si analiza detenidamente esta sugerencia, todavía no es correcta, porque está midiendo el texto en la fuente del documento actual, no en la fuente utilizada para las entradas del capítulo. Entonces el código anterior sólo parece ser correcto, pero no lo es. Para obtener un código correcto, debe tener en \cftchapfontcuenta al medir el ancho del texto. (Y ahora no es necesario aumentar el ancho también en espacios, si el ancho del número sin el prefijo Chaptery el sufijo .ya era suficiente). Entonces un mejor código sería 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}

El problema del apéndice

Nota: Ambos ejemplos no son adecuados para documentos con apéndice, porque en este caso Chapterno sería el término correcto en el apéndice.

tocloftSería fácil hacer la sugerencia recomendada sin documentos adecuados con apéndice. Sólo necesita reemplazar el código fijo Chaptery \@chapappaumentar el ancho:

\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 la tocloftsolución podrías 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}

información relacionada