%20en%20la%20clase%20de%20libro%3F%20.png)
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.cls
no tiene:
\addcontentsline{toc}{chapter}{\numberline {#1}}
en la definición de \@chapter
, pero:
\addcontentsline{toc}{chapter}{\protect\numberline{\thechapter}#1}
Entonces falta un \protect
argumento y el correcto \numberline
y el primer argumento de \@chapter
se usa sin llaves.
El segundo problema es que después de cargar hyperref
la definición de \@chapter
cambios. Entonces el parche debe serantescargando hyperref
.
Por cierto: para ver la definición original, simplemente agregue \show\@chapter
antes \xpatchcmd
. Esto generará la definición actual antes de aplicar el parche \@chapter
en el log
archivo.
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@chapter
para 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:
La alternativa con el uso Chapter <number>.
como argumento de \numberline
serí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}
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 \cftchapfont
cuenta 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 Chapter
y 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 Chapter
no sería el término correcto en el apéndice.
tocloft
Sería fácil hacer la sugerencia recomendada sin documentos adecuados con apéndice. Sólo necesita reemplazar el código fijo Chapter
y \@chapapp
aumentar 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 tocloft
solució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}