
假設您有一個文檔,您想在開頭提及有多少個部分。例如,這樣的事情:
\documentclass{article}
\begin{document}
Abstract\\There are ... sections in this document.
\section{Section 1}
\section{Section 2}
\section{Section 3}
\end{document}
這裡...將是一個巨集(或其他東西),表示有 3 個部分。
不幸的是,我找不到一種方法來在最後評估該巨集(它報告 3)。
在這個例子中,我想知道最後有多少節。可能有一個使用計數器(以某種方式)的解決方案,但我真的在尋找一個可以對巨集的評估順序產生一些影響的解決方案。
答案1
您可以使用\AtEndDocument
(並\AtBeginDocument
在第一次運行時設定巨集):
\documentclass{article}
\makeatletter
\AtEndDocument{
\write\@auxout{\string\gdef\string\previousrunsections{\thesection}}%
}
\AtBeginDocument{%
\ifcsname previousrunsections\endcsname
\else
\gdef\previousrunsections{??}%
\fi
}
\makeatother
\begin{document}
Abstract
\noindent There are \previousrunsections{} sections in this document.
\section{Section 1}
\section{Section 2}
\section{Section 3}
\end{document}
至少運行兩次後,您將獲得:
如果您需要更多控制,該軟體包etoolbox
為您提供了很多鉤子。
答案2
您可以使用 來將總數放在任意位置totcount
。
\documentclass{article}
\usepackage{totcount}
\regtotcounter{section}
\begin{document}
\title{Title}
\author{Ömer}
\maketitle
\begin{abstract}
This is the abstract.
There are \total{section} sections in this document.
\end{abstract}
\section{Section 1}
\section{Section 2}
\section{Section 3}
\end{document}
答案3
這使用xyz
aux 檔案來保存資訊。
\documentclass{article}
\newcommand\addxyzline[1]{\addtocontents {xyz}{#1}}
\makeatletter
\newcommand\writexyz{\@starttoc{xyz}}
\makeatother
\begin{document}
%\tableofcontents% CAN UNCOMMMENT TO SEE THAT toc WORKS FINE
\noindent Abstract\\There are \writexyz sections in this document.
\section{Introduction}
\section{Next}
\section{Third}
\addxyzline{\thesection}
\end{document}
編譯後,該.xyz
檔案包含(在本例中)數字3
,並且該.aux
檔案包含
\relax
\@writefile{toc}{\contentsline {section}{\numberline {1}Introduction}{1}\protected@file@percent }
\@writefile{toc}{\contentsline {section}{\numberline {2}Next}{1}\protected@file@percent }
\@writefile{toc}{\contentsline {section}{\numberline {3}Third}{1}\protected@file@percent }
\@writefile{xyz}{3}
輸出如下:
注意:無論輸入檔案的名稱如何,給定的版本都有效。如果您不喜歡使用 toc 方法,您可以將其硬連接到您的文件名稱,而不是定義
\newcommand\writexyz{\input junk.xyz }
在這種情況下,文件必須是junk.tex。