Evaluar expresión / macro al final
Suponga que tiene un documento en el que desea mencionar cuántas secciones hay al principio. Por ejemplo, algo como esto:
\documentclass{article}
\begin{document}
Abstract\\There are ... sections in this document.
\section{Section 1}
\section{Section 2}
\section{Section 3}
\end{document}
Aquí ... sería una macro (o algo más) que dice que hay 3 secciones.
Desafortunadamente, no pude encontrar una manera de evaluar esa macro al final (donde informa 3).
En este ejemplo, quiero saber la cantidad de secciones al final. Puede haber una solución usando contadores (de alguna manera), pero realmente estoy buscando una solución en la que pueda tener alguna influencia en el orden de evaluación de las macros.
Respuestas
Puede usar \AtEndDocument(y \AtBeginDocumentpara configurar la macro en la primera ejecución):
\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}
Después de al menos dos carreras, obtienes:
Si necesita más control, el paquete etoolboxle ofrece muchos ganchos.
PD: ¡no utilices \\para terminar líneas o párrafos en texto normal !
Puede poner el número total donde quiera usando 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}
Esto usa un xyzarchivo auxiliar para guardar la información.
\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}
Tras la compilación, el .xyzarchivo contiene, en este caso, el número 3y el .auxarchivo contiene
\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}
La salida es así:
Nota: la versión dada funciona independientemente del nombre de su archivo de entrada. Si prefiere no trabajar con el enfoque toc, podría haberlo conectado al nombre de su documento, en lugar de definir
\newcommand\writexyz{\input junk.xyz }
donde en este caso el documento debe ser junk.tex.