Đánh giá biểu thức / macro ở cuối
Giả sử bạn có một tài liệu mà bạn muốn đề cập đến có bao nhiêu phần trong đầu. Ví dụ, một cái gì đó như thế này:
\documentclass{article}
\begin{document}
Abstract\\There are ... sections in this document.
\section{Section 1}
\section{Section 2}
\section{Section 3}
\end{document}
Đây ... sẽ là một macro (hoặc một cái gì đó khác) nói rằng có 3 phần.
Thật không may, tôi không thể tìm ra cách để đánh giá macro đó ở cuối (nơi nó báo cáo 3).
Trong ví dụ này, tôi muốn biết số phần cuối cùng. Có thể có một giải pháp sử dụng bộ đếm (theo một cách nào đó), nhưng tôi thực sự đang tìm kiếm một giải pháp mà tôi có thể có một số ảnh hưởng đến thứ tự đánh giá của các macro.
Trả lời
Bạn có thể sử dụng \AtEndDocument(và \AtBeginDocumentđể đặt macro trong lần chạy đầu tiê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}
Sau ít nhất hai lần chạy, bạn nhận được:
Nếu bạn cần kiểm soát nhiều hơn, gói etoolboxcung cấp cho bạn rất nhiều móc.
PD: không sử dụng \\để kết thúc dòng hoặc đoạn văn trong văn bản bình thường !
Bạn có thể đặt tổng số bất cứ nơi nào bạn muốn bằng cách sử dụng 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}
Điều này sử dụng xyztệp aux để lưu thông tin.
\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}
Khi biên dịch, .xyztrong trường hợp này, tệp chứa số 3và .auxtệp chứa
\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}
Kết quả đầu ra là:
Lưu ý: phiên bản đã cho hoạt động bất kể tên tệp đầu vào của bạn. Nếu bạn không muốn làm việc với cách tiếp cận toc, bạn có thể đã cố định nó thành tên tài liệu của mình, thay vào đó xác định
\newcommand\writexyz{\input junk.xyz }
trong trường hợp này tài liệu phải là junk.tex.