Como contar o número total de seções dentro de um capítulo?

Como contar o número total de seções dentro de um capítulo?

Como se pode contar o número total de seçõesdentro decada capítulo?

Estou tentando usar o totcountpacote, mas ele retorna o número total de seções dodurarcapítulo, não o número total de seções doatualcapítulo.

No MWE seguinte, o comportamento desejado seria reportar 3 seções para o primeiro capítulo e 1 seção para o segundo e último capítulo.

totcountrelata apenas 1 seção (o valor do contador do último capítulo).

\documentclass[12pt]{book}

\usepackage{totcount}
\regtotcounter{section}

\begin{document}
\chapter*{First Chapter}

The total number of sections in this chapter should be 3.

The totcount package reports: \total{section}

\section{First Section}
First text

\section{Second Section}
Second text

\section{Third Section}
Third text

\chapter*{Last Chapter}

The total number of sections in this chapter should be 1.

The totcount package reports: \total{section}

\section{First and only section}
Section text

\end{document}

Como contar o número total de seções dentro de cada capítulo?

Nota: totcountreporta 0 seções se estiver usando \section*, veja o comentário de Sigur.

Responder1

EditarA versão antecipada de saber antecipadamente os números das seções por capítulo está no final desta postagem. Requer duas execuções de compilação.

Esta questão levou a um novo pacote cntperchapque está disponível em sua versão 0.2 no CTAN desde 05/09/2015

Isso usa o assoccntpacote (cujo autor eu acidentalmente conheço muito bem ;-))

Ele associa um contador totalsectionsao sectioncontador - cada vez que o sectioncontador é aumentado, o totalsectionscontador também aumenta.

No entanto, não há redefinição automática para \chapter*uso. Neste caso, isso pode ser feito automaticamente acrescentando algum código ao \chapteruso \xpretocmddo xpatchpacote

ObservaçãoO autor assoccntrealmente deveria incorporar isso em seu pacote ;-)

\documentclass[12pt]{book}
\usepackage{assoccnt}

\usepackage{xpatch}
\newcounter{totalsections}[chapter] % Does not work with `chapter*`

% Automatically provide for resetting of the section counter each time 
%`\chapter` or `\chapter*` is used -- in this setup this is requested.
\xpretocmd{\chapter}{\setcounter{totalsections}{0}}{}{}


\DeclareAssociatedCounters{section}{totalsections}

\begin{document}
\chapter*{First Chapter}

The total number of sections in this chapter should be 3.



\section{First Section}
First text

\section{Second Section}
Second text

\section{Third Section}
Third text

There \number\value{totalsections} sections in this chapter

\chapter*{Last Chapter}


\section{First and only section}
Section text

There \number\value{totalsections} sections in this chapter


\end{document}

EditarAlguma versão nova, que usa uma contagem de seções por capítulo (requer duas execuções para ter sucesso).

Explicação: Cada vez que um novo capítulo é usado, o número acumulado de seções é gravado em um arquivo externo, \jobname.seccntabreviadamente foo.seccnt. Este arquivo é lido novamente na próxima execução de compilação do latex e os valores são armazenados em uma etoolboxlista. A macro \GetTotalSectionCounteravançará por esta lista até estar na posição correta e então imprimirá o número de seções deste capítulo, mesmo à frente. (A macro deveria ser expansível, acho que é esse o caso)

No momento, é necessário remover manualmente o foo.seccntarquivo caso tenha havido alterações no número de capítulos/seções.

Vou tentar contornar essa desvantagem.

\documentclass{book}

\usepackage{ifthen}
\usepackage{assoccnt}

\usepackage{xpatch}

\usepackage{pgffor} % Only for quick usage of a lot of sections, demo only

\newwrite\seccountfile%

\newread\seccountinfile%

\listgadd{\seccountlist}{}% Initialize an empty list


\newcounter{currentchapter}
\newcounter{totalsections}
\newcounter{togglecounter}

\DeclareAssociatedCounters{section}{totalsections}


\newcommand{\getsectioncountnumbers}{%
  \setcounter{togglecounter}{0}%  
  \whiledo {\value{togglecounter} < 1}{%
    \read\seccountinfile to \gandalf%
    \ifeof\seccountinfile%
    \stepcounter{togglecounter}%
    \else%
    \listxadd{\seccountlist}{\gandalf}%
    \fi%
  }%
}


\xpretocmd{\chapter}{%
  \stepcounter{currentchapter}%
  \immediate\write\seccountfile{%
    \number\value{totalsections}%
  }%
  \setcounter{totalsections}{0}
}{}{}

\makeatletter
\newcounter{tempcount@a}
\newcommand{\@getsectiontotalcounter}[1]{%
  \setcounter{tempcount@a}{0}%
  \renewcommand*{\do}[1]{%
    \ifnumequal{\value{#1}}{\value{tempcount@a}}{%
      ##1\listbreak%
    }{%
      \stepcounter{tempcount@a}%
    }%  
  }%    
  \dolistloop{\seccountlist}%
}   


\newcommand{\GetSectionTotalCounter}[1][currentchapter]{%
  \ifdef{\seccountlist}{%
    \@getsectiontotalcounter{#1}%
    }{}%
}

\makeatother


\AtBeginDocument{%
  \IfFileExists{\jobname.seccnt}{%
    % Open for reading
    \immediate\openin\seccountinfile=\jobname.seccnt%
    \getsectioncountnumbers%
  }{%
    % Open for writing
    \immediate\openout\seccountfile=\jobname.seccnt%
  }%
}



\AtEndDocument{% 
  \immediate\write\seccountfile{%
    \number\value{totalsections}%
  }%
  \immediate\closeout\seccountfile%
}




\begin{document}

\chapter*{First}
This chapter will have \GetSectionTotalCounter sections
\section{First}
\section{Second}

\chapter*{Second}
This chapter will have \GetSectionTotalCounter sections
\section{First}
\section{Second}
\section{Third}
\section{Fourth}


% Now a really large chapter
\chapter*{Third}
This chapter will have \GetSectionTotalCounter sections

\foreach \x in {1,...,100} {%
\section{\x}
}

\end{document}

EditarEsta é a versão sem exclusão explícita do foo.seccntarquivo

Usei a addtocontentsabordagem para permitir LaTeXgravar os números das seções em um arquivo separado, assim como é feito com o tocmaterial relacionado. O foo.seccnté então tratado como um toc falso, lido antes (e os valores armazenados temporariamente) reescritos na execução.

\documentclass{book}

\usepackage{ifthen}
\usepackage{assoccnt}
\usepackage{xpatch}
\usepackage{pgffor}

\listgadd{\seccountlist}{}% Initialize an empty list

\newcounter{currentchapter}
\newcounter{totalsections}
\newcounter{togglecounter}

\DeclareAssociatedCounters{section}{totalsections}


\makeatletter
\newcommand{\getsectioncountnumbers}{%
  \setcounter{togglecounter}{0}%  
  \whiledo {\value{togglecounter} < 1}{%
    \read\tf@seccnt to \seccountnumberfromfile%
    \ifeof\tf@seccnt
    \stepcounter{togglecounter}%
    \else%
    \listxadd{\seccountlist}{\seccountnumberfromfile}%
    \fi%
  }%
}


\xpretocmd{\chapter}{%
  \stepcounter{currentchapter}%
  \addtocontents{seccnt}{%
    \number\value{totalsections}%
  }%
  \setcounter{totalsections}{0}
}{}{}

\newcounter{tempcount@a}
\newcommand{\@getsectiontotalcounter}[1]{%
  \setcounter{tempcount@a}{0}%
  \renewcommand*{\do}[1]{%
    \ifnumequal{\value{#1}}{\value{tempcount@a}}{%
      ##1\listbreak%
    }{%
      \stepcounter{tempcount@a}%
    }%  
  }%    
  \dolistloop{\seccountlist}%
}   

\newcommand{\GetSectionTotalCounter}[1][currentchapter]{%
  \ifdef{\seccountlist}{%
    \@getsectiontotalcounter{#1}%
  }{}%
}

% This is a modified version from \@starttoc, being defined latex.ltx
\def\@startfaketoc#1{%
  \begingroup
  % Generate the file handle first
  \expandafter\newwrite\csname tf@#1\endcsname%
  \makeatletter
  % Read first before deleting it
  \ifcsdef{tf@#1}{%
    \IfFileExists{\jobname.#1}{%
    \immediate\openin\csname tf@#1\endcsname \jobname.#1\relax
    \getsectioncountnumbers%
    }{}
  }{%
    \typeout{No section count numbers so far}
  }%
  \if@filesw
  % Write only if not `\nofiles` is specified
  \immediate\openout \csname tf@#1\endcsname \jobname.#1\relax
  \fi
  \@nobreakfalse
  \endgroup%
}


\AtBeginDocument{%
  \@startfaketoc{seccnt}
}



\AtEndDocument{%
  % Write the last section count to the file
  \addtocontents{seccnt}{%
    \number\value{totalsections}%
  }%
}
\makeatother




\begin{document}
\tableofcontents

\chapter*{First}
This chapter will have \GetSectionTotalCounter sections
\section{First}
\section{Second}

\chapter*{Second}
This chapter will have \GetSectionTotalCounter sections
\section{First}
\section{Second}
\section{Third}
\section{Fourth}



% Now a really large chapter
\chapter*{Third}
This chapter will have \GetSectionTotalCounter sections

\foreach \x in {1,...,100} {%
\section{\x}
}

\chapter{Fourth}
This chapter will have \GetSectionTotalCounter sections

\section{A single section}


\end{document}

EditarO OP gsl notou algum erro neste código. Eu poderia rastrear o fato de que ele já \@startfaketoctenta ler o foo.seccntarquivo externo na primeira execução. Isso falha, é claro, já que tal arquivo não existe se ele tiver sido excluído ou se o documento for compilado pela primeira vez.

informação relacionada