Условно добавить текст к названию главы в оглавлении

Условно добавить текст к названию главы в оглавлении

Я хочу добавить текст к заголовкам глав в TOC в соответствии с определенными условиями. Например (это не работает):

\documentclass[letterpaper,openany,oneside]{book}
\usepackage[spanish]{babel}
\usepackage[utf8]{inputenc}
\usepackage{tocloft}

% If the chapter is an appendix, print "Apéndice", else "Capítulo".
\makeatletter
\renewcommand\cftchappresnum{
\ifx\@chapapp\appendixname
Apéndice\
\else 
Capítulo\
\fi
 }
\makeatother

\renewcommand\cftchapaftersnumb{\newline}
\renewcommand\cftchapleader{\cftdotfill{4}}
\renewcommand\cftchappagefont{\normalfont}
\setlength{\cftchapnumwidth}{0em}

\begin{document}    
\tableofcontents
\mainmatter
\chapter{First chapter}
  \section{First section}
  \chapter{Another chapter}
  \section{this is yet another section} 
\appendix
\chapter{First Appendix}
\end{document} 

Я знаюэто дубликат, но я хочу знать, возможно ли что-то подобное, потому что мне нужно проверить ряд условий. А именно:

  • Это первая глава оглавления?
  • Это название эквивалентно "foo"?
  • И т. д.

решение1

Поскольку \@chapappявно используется, простого переопределения его в \cftchappresnumнедостаточно, если вообще нет информации об изменении имени, поскольку он ToCнаписан в то время, когда информация об \@chapappизменении канула в Лету ;-)

Эту информацию лучше записать в ToC, \addtocontents{toc}{\protect\renewcommand{...}}(см. соответствующую строку в коде.

Вместо того чтобы возиться с явными словами для \appendixnameили , \chapternameгораздо лучше позволить babelзаботиться об изменении, если только у вас нет очень конкретных идей относительно названий, отклоняющихся от babelнастроек для этого языка.

Если babelвнести изменения, код будет работать для любого определенного языка.

\documentclass[letterpaper,openany,oneside]{book}


\usepackage[utf8]{inputenc}
\usepackage[spanish]{babel}

\usepackage{tocloft}

\usepackage{xpatch}


% If the chapter is an appendix, print "Apéndice", else "Capítulo".
\makeatletter
\DeclareRobustCommand{\gettherightprefix}{
  \renewcommand{\cftchappresnum}{%
    \@chapapp~%
  }
}
\AtBeginDocument{%
  \addtocontents{toc}{\gettherightprefix}% Just use the protected version of this instead of a lot of \protect statements
}
\xpretocmd\appendix{%
  % Inform the ToC that `\@chapapp` is `\appendixname now
  \addtocontents{toc}{\protect\renewcommand{\protect\@chapapp}{\protect\appendixname}}
}{\typeout{Success}}{\typeout{Failure}}

\makeatother

\renewcommand\cftchapaftersnumb{\newline}
\renewcommand\cftchapleader{\cftdotfill{4}}
\renewcommand\cftchappagefont{\normalfont}
\setlength{\cftchapnumwidth}{0em}

\begin{document} 
\tableofcontents
\mainmatter
\chapter{First chapter}
  \section{First section}
  \chapter{Another chapter}
  \section{this is yet another section} 
\appendix
\chapter{First Appendix}
\end{document} 

введите описание изображения здесь

Связанный контент