我想根據某些條件在目錄的章節標題前面添加一些文字。例如(這不起作用):
\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」嗎
- ETC。
答案1
由於\@chapapp
是明確使用的,\cftchappresnum
如果根本沒有有關名稱更改的信息,僅重新定義它是不夠的,因為 是ToC
在寫入時有關\@chapapp
更改的信息已被遺忘;-)
最好將此資訊寫入ToC
, with \addtocontents{toc}{\protect\renewcommand{...}}
(請參閱程式碼中的相關行。
\appendixname
與其擺弄 the或的明確單詞,\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}