每个部分有一个计数器,并在部分标题中打印总数

每个部分有一个计数器,并在部分标题中打印总数

我正在尝试为每个部分设置一个单独的计数器(就像在第二个答案中所做的那样如何读取每个部分的计数器值),但我想在部分标题中打印计数器的最终值(就像使用 totcount 包所做的那样)。

例子:

\documentclass{article}
\begin{document}

\section{First section}
\incrementCounter{2}%We increment the section counter
\incrementCounter{1}
%section counter has value 3

\section{Second section}
\incrementCounter{1}
%section counter has value 1
\end{document}

应该显示

1 First section 3
2 Second section 1

答案1

以下内容根据您在问题中提到的糟糕的答案并用途而定totcount

如果您取消\pagestyle{headings}注释该调用或以其他方式使用标题受 约束的类\MakeUppercase,则需要最新的 LaTeX 内核,例如LaTeX2e <2022-06-01> patch level 1(这是 的\l_text_case_exclude_arg_tl)。

\documentclass{article}
\usepackage{etoolbox}
\usepackage{totcount}
% \usepackage{lipsum}             % for the dummy text

\makeatletter

\newcommand*{\ocalexIncr}[2]{%
  \edef\ocalex@ctrname{ocalex@#1@ctr@\number\value{section}}%
  \@ifundefined{c@\ocalex@ctrname}
    {\newcounter{\ocalex@ctrname}%
     \expandafter\regtotcounter\expandafter{\ocalex@ctrname}%
    }{}%
  \addtocounter{\ocalex@ctrname}{\numexpr (#2) - 1\relax}%
  \refstepcounter{\ocalex@ctrname}%
  %(\csuse{the\ocalex@ctrname})% uncomment to show the current counter value
}

\newcommand*{\mytotal}[1]{%
  \protect\total{ocalex@#1@ctr@\number\value{section}}%
}

% Redefinition: automatically append “\nobreakspace \mytotal{foo}” to
% numbered \section titles.
\NewCommandCopy{\ocalex@orig@section}{\section}

\ExplSyntaxOn
\RenewDocumentCommand \section { s O{#3} m }
  {
    \IfBooleanTF{#1}
      % No automatic addition for unnumbered sections
      { \ocalex@orig@section* {#3} }
      {
        \ocalex@orig@section
          [ { #2\nobreakspace \mytotal{foo} } ]
          {   #3\nobreakspace \mytotal{foo} }
      }
  }

% This is for \pagestyle{headings} and requires a recent LaTeX format
\tl_if_in:NnF \l_text_case_exclude_arg_tl { \total }
  { \tl_put_right:Nn \l_text_case_exclude_arg_tl { \total } }
\ExplSyntaxOff

\makeatother

% As many such counters as you want. 'foo' is used in \incrementCounter and in
% the above redefinition of \section, in order to comply with the document
% markup from the question.
\newcommand*{\incrementCounter}{\ocalexIncr{foo}}

% \pagestyle{headings}       % this works

\begin{document}

\tableofcontents             % this also works

% That would have been a reasonable syntax, but the question doesn't want it.
% \section{First section~\mytotal{foo}}
\section{First section}
\incrementCounter{2}
\incrementCounter{1}
% \lipsum[1-10]               % uncomment to test with \pagestyle{headings}

\section{Second section}
\incrementCounter{1}
% \lipsum[1-3]                % uncomment to test with \pagestyle{headings}

\end{document}

在此处输入图片描述

相关内容