Evaluate expression/macro at the end

You can put the total number wherever you want by using 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}

enter image description here


You can use \AtEndDocument (and \AtBeginDocument to set the macro in the first run):

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

After at least two runs, you get:

enter image description here

If you need more control, the package etoolbox gives you a lot of hooks.

PD: don't use \\ to end lines or paragraphs in normal text!


This uses an xyz aux file to save the information.

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

Upon compilation, the .xyz file contains, in this case, the number 3, and the .aux file contains

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

The output is thus:

enter image description here

Note: the given version works regardless of the name of your input file. If you prefer not working with the toc approach, you could have hardwired it to your document name, instead defining

\newcommand\writexyz{\input junk.xyz }

where in this case the document must be junk.tex.

Tags:

Macros