最後に式/マクロを評価する

最後に式/マクロを評価する

冒頭にセクションがいくつあるかを示したい文書があるとします。たとえば、次のようになります。

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

少なくとも 2 回実行すると、次の結果が得られます。

ここに画像の説明を入力してください

より高度な制御が必要な場合、パッケージetoolboxには多くのフックが用意されています。

PD:\\通常のテキストの行や段落の終了には使用しないでください

答え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 である必要があります。

関連情報