% -*- coding: utf-8; time-stamp-format: "%02d-%02m-%:y at %02H:%02M:%02S %Z" -*-
% N.B.: this dtx file is NOT for use with \DocInput. The latex source of the
% user manual is not prefixed with percent signs.
%<*none>
\def\etocdtxtimestamp {Time-stamp: <17-11-2022 at 23:14:36 CET>}%
%</none>
%<*!readme>
%%
%% Package: etoc
%% Version: 1.09g (DEVELOPMENT)
%% License: LPPL 1.3c
%% Copyright (C) 2012-2022 Jean-Francois Burnol
%%                         <jfbu at free dot fr>
%</!readme>
%<*none>
\def\etocpkgdate        {2022/11/17}
\def\etocdocdate        {2022/11/17}
\def\etocpkgversion     {1.09g}
\def\etocpkgdescription {Completely customisable TOCs (JFB)}
%% German translation was last udpated on April 2015 and all new material
%% was included since in English.  During 2020/2021/2022 emerged a still
%% unresolved texdoc problem which always displays etoc-DE.pdf preferentially.
%% On 2022/08/26, decision is made to stop shipping this etoc-DE.pdf.
%% The dtx gets purged from its soure as well.
%% Not sure if I will make pdf available for download from some web site,
%% but this can always be done if requests emerge; but I hesitate for
%% the location.
% Definition of \etocLicense
% --------------------------
\begingroup
    \long\def\firstofone #1{#1}\catcode1=14\catcode2=0
    \catcode`\%=12\catcode`\_=12\endlinechar13\catcode13=13 ^^A
    \catcode32=13\catcode`\\=12^^Brelax^^A
^^Bfirstofone{^^Bendgroup^^Bdef^^BetocLicense^^A
{% Package: etoc
% Version: 1.09g
% License: LPPL 1.3c
% Copyright (C) 2012-2022 Jean-Francois Burnol <jfbu at free dot fr>
%
%     This Work may be distributed and/or modified under the
%     conditions of the LaTeX Project Public License, in its
%     version 1.3c. This version of this license is in
%          http://www.latex-project.org/lppl/lppl-1-3c.txt
%     and the latest version of this license is in
%          http://www.latex-project.org/lppl.txt
%     and version 1.3 or later is part of all distributions of
%     LaTeX version 2005/12/01 or later.
%
% The Author of this Work is:
% Jean-Francois Burnol <jfbu at free dot fr>
%
% This Work consists of the main source file etoc.dtx and the derived
% files etoc.sty, etoc.tex, etoc.pdf, etoc.dvi, README.md.
%
% Running etex (or latex or pdflatex) on etoc.dtx extracts etoc.sty,
% etoc.tex and README.md. See README.md for further instructions.
}}%
\bgroup\catcode2 0 \catcode`\\ 12 ^^Biffalse
%</none>
%<*readme>
<!-- -->

    Source:  etoc.dtx (1.09g)
    Author:  Jean-Francois Burnol
    Info:    Completely customisable TOCs
    License: LPPL 1.3c
    Copyright (C) 2012-2022 Jean-Francois Burnol.
    <jfbu at free dot fr>

ABSTRACT
========

The etoc package gives to the user complete control on how the entries
of the table of contents should be constituted from the *name*,
*number*, and *page number* of each sectioning unit. This goes via the
definition of *line styles* for each sectioning level used in the
document. The package provides its own custom line styles. Simpler
ones are given as examples in the documentation. The simplest usage
will be to take advantage of the layout facilities of packages dealing
with list environments.

Regarding the *global toc display*, etoc provides pre-defined styles
based on a multi-column format, with, optionally, a ruled title or
framed contents.

The `\tableofcontents` command may be used arbitrarily many times and
it has a variant `\localtableofcontents` which prints tables of
contents 'local' to the current surrounding document unit. An
extension of the `\label/\ref` syntax allows to reproduce (with
another layout) a local table of contents defined somewhere else in
the document.

Via *depth tags*, one gets an even finer control for each table of
contents of which sectioning units it should, or not, display.

The formatting inherited (and possibly customized by other packages)
from the document class will be used when in compatibility mode.

The assignment of levels to the sectioning units can be changed at any
time, and etoc can thus be used in a quite general manner to create
custom ''lists of'', additionally to the tables of contents related to
the document sectioning units. No auxiliary file is used additionally
to the standard `.toc` file.

INSTALLATION
============

To extract the package (.sty) and driver (.tex) files from etoc.dtx,
execute `etex etoc.dtx`.

It is also possible to execute latex or pdflatex directly on etoc.dtx.

To produce etoc.pdf one can run pdflatex directly on etoc.dtx or on
the file etoc.tex which was extracted from `etex etoc.dtx` step.

Options can be set in etoc.tex:

- scrartcl class options (paper size, font size, ...)
- with or without source code,
- with dvipdfmx or with latex+dvips or pdflatex.

Since release 1.08h pdflatex is the default in etoc.tex (prior it
was latex+dvipdfmx as it produces smaller PDFs) in order to allow
inclusion via the use of package `attachfile` of about 25 code
samples as file attachment annotations.

Installation:

    etoc.sty    -> TDS:tex/latex/etoc/etoc.sty
    etoc.dtx    -> TDS:source/latex/etoc/etoc.dtx
    etoc.pdf    -> TDS:doc/latex/etoc/etoc.pdf
    README.md   -> TDS:doc/latex/etoc/README.md

The other files may be discarded.

LICENSE
=======

This Work may be distributed and/or modified under the
conditions of the LaTeX Project Public License, in its
version 1.3c. This version of this license is in

> <http://www.latex-project.org/lppl/lppl-1-3c.txt>

and the latest version of this license is in

> <http://www.latex-project.org/lppl.txt>

and version 1.3 or later is part of all distributions of
LaTeX version 2005/12/01 or later.

The Author of this Work is Jean-Francois Burnol <jfbu at free dot fr>

This Work consists of the main source file etoc.dtx and the derived files
etoc.sty, etoc.tex, etoc.pdf, etoc.dvi.

RECENT CHANGES
==============

1.09g \[2022/11/17\]
--------------------

Compatibility hotfix with recent hyperref `7.00u` of `2022-11-13`.
Thanks to Denis Bitouzé for signaling the breakage to the author.

1.09f \[2022/08/30\]
--------------------

No more shipping of a German translation of the documentation, as
it was last updated in April 2015.

(etoc.pdf) User level commands hyperlink from their code source
definitions to their descriptions in the documentation part.  Macros
used in the code source hyperlink to where they first got defined
there.

Wrap the `\etocpartname` (from etoc's package provided toc line style)
together with the part number in a potential common hyperlink.

Try to sync the emulation of the global display style with KOMA-script
`v3.37` (in particular regarding the `noparskipfake` KOMA toc feature).

Improve documentation of some aspects under `memoir` class.

Remove the `\nonumberline` token, even though empty, from the meaning of
`\etocthename` (KOMA-script classes).

Add `\etocimmediatedepthtag.toc` to work around problems related to
`\include` (see user doc).  Thanks to Norman Ramsey who reported the problem
and proposed a work-around in July 2016.  Apologies for the somewhat longish
delay in incorporating it...

Also add `\etocimmediatesettocdepth.toc`.

Also add `\etocimmediatetoccontentsline` and its starred variant.

Also add `\etocimmediatesetlocaltop.toc`.

Fix an obscure bug (see source code comments) in the `\etocsetlocaltop.toc`
mechanism.

1.09e \[2021/09/23\]
--------------------

Needed (if etoc is used without hyperref) updates to
internal macros to prepare for the upcoming LaTeX November
2021 change to `\contentsline`.

Related updates to the user macro `\etoctoccontentsline`.

1.09d \[2021/07/13\]
--------------------

Some minor synching with tableof 1.4c.

Add `\etockeeporiginaltableofcontents` to provide a work-around to a
compatibility issue with listings's `\lstlistoflistings`, which abuses
`\tableofcontents` for doing something unrelated to the actual contents.
Thanks to Denis Bitouzé for report.

Usage: `\usepackage{etoc}\etockeeporiginaltableofcontents`, then
however you must employ `\etoctableofcontents`, not `\tableofcontents`.

1.09c \[2020/05/15\]
--------------------

Syncs with KOMA-script deprecation of `\iftocfeature`.
%</readme>
%<*tex>-------------------------------------------------------------------------
%% run pdflatex thrice on this file etoc.tex to produce the documentation
%% etoc.pdf, with source code included.
%%
\chardef\Withdvipdfmx 0 % replace 0 by 1 for using latex+dvipdfmx
\chardef\NoSourceCode 0 % replace 0 by 1 for the doc *without* the source code
\NeedsTeXFormat{LaTeX2e}
\ProvidesFile {etoc.tex}[Driver for etoc documentation]%
\PassOptionsToClass   {a4paper,fontsize=11pt,twoside}{scrartcl}
\PassOptionsToPackage {ngerman,english}{babel}
\input etoc.dtx
%%% Local Variables:
%%% mode: latex
%%% End:
%</tex>-------------------------------------------------------------------------
%<*none>------------------------------------------------------------------------
^^Bfi^^Begroup
%
\chardef\noetex 0
\ifx\numexpr\undefined\chardef\noetex 1 \fi
\ifnum\noetex=1 \chardef\extractfiles 0 % extract files, then stop
\else
    \ifx\ProvidesFile\undefined
      \chardef\extractfiles 0 % etex etc.. on etoc.dtx, only file extraction.
    \else % latex/pdflatex on etoc.tex or on etoc.dtx
      \ifx\Withdvipdfmx\undefined
        % latex/pdflatex run is on etoc.dtx
        \chardef\extractfiles 1 % 1 = extract files and typeset manual, 2 = only typeset
        \chardef\Withdvipdfmx 0 % 0 = pdflatex or latex+dvips, 1 = dvipdfmx
        \chardef\NoSourceCode 1 % 0 =  include source code, 1 = do not
        \NeedsTeXFormat {LaTeX2e}%
        \PassOptionsToClass   {a4paper,fontsize=11pt,twoside}{scrartcl}%
        \PassOptionsToPackage {ngerman,english}{babel}%
      \else % latex run is on etoc.tex
        \chardef\extractfiles 2 % do not extract files, only typeset
      \fi
      \ProvidesFile{etoc.dtx}%
        [etoc source and documentation (\etocdtxtimestamp)]%
    \fi
\fi
\ifnum\extractfiles<2 % extract files
\def\MessageDeFin{\newlinechar10 \let\Msg\message
\Msg{********************************************************************^^J}%
\Msg{*^^J}%
\Msg{* To finish the installation you have to move the following^^J}%
\Msg{* file into a directory searched by TeX:^^J}%
\Msg{*^^J}%
\Msg{*\space\space\space\space etoc.sty^^J}%
\Msg{*^^J}%
\Msg{* To produce the documentation with source code included run pdflatex^^J}%
\Msg{* thrice on file etoc.tex^^J}%
\Msg{*^^J}%
\Msg{* Happy TeXing!^^J}%
\Msg{*^^J}%
\Msg{********************************************************************^^J}%
}%
\begingroup
    \input docstrip.tex
    \askforoverwritefalse
    \generate{\nopreamble\nopostamble
    \file{README.md}{\from{etoc.dtx}{readme}}%
    \usepostamble\defaultpostamble
    \file{etoc.tex}{\from{etoc.dtx}{tex}}%
    \usepreamble\defaultpreamble
    \file{etoc.sty}{\from{etoc.dtx}{package}}}%
\endgroup
\fi % end of file extraction (from etex/latex/pdflatex run on etoc.dtx)
\ifnum\noetex=1 % warning for README.md
    \expandafter\def\expandafter\MessageDeFin\expandafter 
{\MessageDeFin
\Msg{* warning: to get correct utf-8 encoded README.md ^^J}%
\Msg{* do etex etoc.dtx and not as here tex etoc.dtx   ^^J}%
\Msg{********************************************************************^^J}}%
\fi
\ifnum\extractfiles=0 % tex/etex/xetex/etc on etoc.dtx, files extracted, stop
      \MessageDeFin\expandafter\end
\fi
% From this point on, run is necessarily with e-TeX.
% Check if \MessageDeFin got defined, if yes put it at end of run.
\ifdefined\MessageDeFin\AtEndDocument{\MessageDeFin}\fi
%-------------------------------------------------------------------------------
% START OF USER MANUAL TEX SOURCE
\documentclass[abstract]{scrartcl}

\makeatletter
%%% START OF CUSTOM doc.sty LOADING (May 21, 2022 in xint.dtx)
%%% (August 26, 2022 here, comments trimmed)
%
% For some legacy reason (because I started like this and it
% worked to my satisfaction) I had used scrdoc.cls all those
% years, without in fact needing most of its features.
%
% It loads ltxdoc class, from which again I need very little.  On
% testing May 20, 2022 the upcoming LaTeX 2022-06-01 I had some
% problems with ltxdoc not having suitable interface for rolling
% back to doc=V2.
%
% ...
%
% Thus it turns out I need very little of doc.sty, and almost
% nothing of ltxdoc.cls and scrdoc.cls.
%
% (maybe provisory, try to see if usage of cross-hyperlinking
%  as in sourcexint.pdf makes sense here for rendering of
%  implementation part - loading time of etoc.pdf in viewer
%  in increased, though. 2022/08/26)
%
% Let's load the doc=V2 version to avoid having to work around
% hypdoc loading interfering with my use of hyperref.
\ifdefined\IfFormatAtLeastTF
  \IfFormatAtLeastTF{2022/06/01}%
  {%
    \IfFileExists{doc-2021-06-01.sty}%
     {\usepackage{doc}[=v2]}%
% Why on earth do I lose my time doing this?
     {\GenericError
          {(etoc build doc)\@spaces}%
          {etoc build error: %
      Your LaTeX installation seems to be broken, format is\MessageBreak
      2022-06-01 or later but `doc' package in its `v2' version\MessageBreak
      seems to not be available. \space Will try with `doc' but if\MessageBreak
      its `v3' is used there will be an option clash error\MessageBreak
      regarding hyperref.}%
          {}%
          {Please make sure `doc' package matches your LaTeX format.}%
      \usepackage{doc}%
     }%
  }%
  {\usepackage{doc}}%
\else
\usepackage{doc}
\fi
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% MACROS OF doc.sty WILL BE HACKED (2022/06/06) FOR THE IMPLEMENTATION PART
%
% First we want to turn CodelineNo into a real LaTeX counter
% This will spare defining an extra counter for the hyperlinks with \hyperref
\begingroup\let\newcount\@gobble\@definecounter{CodelineNo}\endgroup
% Let's now reenact the doc.sty default for \theCodeLineNo
\def\theCodelineNo{\reset@font\scriptsize\arabic{CodelineNo}}
% But as we will reset CodelineNo at each style file we need some unique id
\def\theHCodelineNo{\the\value{section}.\the\value{CodelineNo}}
% This is all for now.
% The further hacks are to be found after the \StopEventually (i.e. a few
% thousands lines down from here if you don't have access to the private
% sources, which is probably the case if you are not the author).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% As explained above I was formerly using scrdoc hence ltxdoc indirectly.
% Let's emulate here the little I appear to need from ltxdoc.cls and
% srcdoc.cls.
%
\AtBeginDocument{\MakeShortVerb{\|}}
\DeclareFontShape{OT1}{cmtt}{bx}{n}{<-> ssub * cmtt/m/n}{}
\DeclareFontFamily{OMS}{cmtt}{\skewchar\font 48}  % '60
\DeclareFontShape{OMS}{cmtt}{m}{n}{<-> ssub * cmsy/m/n}{}
\DeclareFontShape{OMS}{cmtt}{bx}{n}{<-> ssub * cmsy/b/n}{}
\DeclareFontShape{OT1}{cmss}{m}{it}{<->ssub*cmss/m/sl}{}
\ifnum\NoSourceCode=1
  \OnlyDescription
\fi
\CodelineNumbered
\EnableCrossrefs  % but this will be hacked
% \setcounter{StandardModuleDepth}{1} % we don't use this mechanism currently
\def\cmd#1{\cs{\expandafter\cmd@to@cs\string#1}}
\def\cmd@to@cs#1#2{\char\number`#2\relax}
% Here I am loading doc=v2 but formerly I was using ltxdoc via scrdoc
% which I dropped at release 1.4l (2022-05-29) and without much
% thinking I had kept this.
\DeclareRobustCommand\cs[1]{\texttt{\bslash#1}}
% As I may have the * active, or macro names with _ or ^, I should
% add \detokenize.  But see below for a redefinition anyhow.
%
% More urgent is that I am also using hyperref and this definition gives wrong
% bookmarks if \cs is used in section titles.  As I had very very few usags of
% \cs in the whole of xint.dtx, it took me a while to realize the problem
% here.  Turns out that doc=v3 by default loads hypdoc which includes this
% configuation for hyperref compatibility:
\AtBeginDocument{%
\pdfstringdefDisableCommands{\def\cs#1{\textbackslash\detokenize{#1}}}%
}%
% As I have not loaded hyperref yet I must delay it to AtBeginDocument.
%%%%%%%%
%% This is xint.dtx only stuff, not used here
%% % Late May, early June 2022 I added to my custom \verb automated detection
%% % of potential hyperlinks.  So I decided to replace \cs ltxdoc definition
%% % by suitable \verb usage.  It is not important to be efficient here,
%% % I can leave some \expandafter, in fact there are a handful of uses.
%% \DeclareRobustCommand\cs[1]{\expandafter\verb\expandafter~\bslash#1~}
%% % As my \verb does a verbatimizing \scantokens  I don't need to worry
%% % here about active characters but I need in the PDF string, hence
%% % the \detokenize above.
%%%%%%%%
\providecommand\marg[1]{%
  {\ttfamily\char`\{}\meta{#1}{\ttfamily\char`\}}}
\providecommand\oarg[1]{%
  {\ttfamily[}\meta{#1}{\ttfamily]}}
\providecommand\parg[1]{%
  {\ttfamily(}\meta{#1}{\ttfamily)}}
% \@addtoreset{CodelineNo}{part}% No need for this here
% \def\partname{File}% \partname is "fixed" somewhere further down anyhow
% No need for this, anyhow I don't build the indices
% \gdef\codeline@wrindex#1{\if@filesw
%       \begingroup
%         \let\protect\noexpand
%         \immediate\write\@indexfile
%             {\string\indexentry{#1}%
%             {\filesep\number\c@CodelineNo}}%
%       \endgroup\fi}
% \let\filesep\@empty

% There is very little we seem to need from the scrdoc extras: page geometry
% is set by geometry package and a4paper option from xint.tex file.  So it
% seems I only need the hologo loading:
\usepackage{hologo}
\DeclareRobustCommand*{\eTeX}{\hologo{eTeX}}%
\DeclareRobustCommand*{\LuaTeX}{\hologo{LuaTeX}}%
%
\makeatother
%%% end of ltxdoc+srcdoc emulation from June 2022 xint.dtx,
%%% copied over almost verbatim to etoc.dtx on 2022/08/26.
%%% See after \StopEventually for doc.sty hacks.

\usepackage{ifpdf}
\ifpdf\chardef\Withdvipdfmx 0 \fi

\makeatletter
\ifnum\Withdvipdfmx=1
   \@for\@tempa:=hyperref,bookmark,graphicx,xcolor,pict2e\do
            {\PassOptionsToPackage{dvipdfmx}\@tempa}
   %
   \PassOptionsToPackage{dvipdfm}{geometry}
   \PassOptionsToPackage{bookmarks=true}{hyperref}
   \PassOptionsToPackage{dvipdfmx-outline-open}{hyperref}
   \PassOptionsToPackage{dvipdfmx-outline-open}{bookmark}
   %
   \def\pgfsysdriver{pgfsys-dvipdfm.def}
\else
   \PassOptionsToPackage{bookmarks=true}{hyperref}
\fi
\makeatother

\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[hscale=0.66,vscale=0.75]{geometry}
\pagestyle{headings}
% \usepackage{layout}

% January 2014. work-around a bug in KOMA 3.12 (December 2013):
\makeatletter
\def\buggysectionmark #1{% KOMA 3.12 as released to CTAN December 2013
    \if@twoside\expandafter\markboth\else\expandafter\markright\fi
    {\MakeMarkcase{\ifnumbered{section}{\sectionmarkformat\fi}{}#1}}{}}
\ifx\buggysectionmark\sectionmark
\def\sectionmark #1{%
    \if@twoside\expandafter\markboth\else\expandafter\markright\fi
    {\MakeMarkcase{\ifnumbered{section}{\sectionmarkformat}{}#1}}{}}
\fi
\makeatother

\makeatletter
% 2013/03/07. 
% This macro allows to conveniently center a line inside a paragraph and still
% use therein \verb or other commands changing catcodes.
% Note: \centerline in LaTeX still uses \hsize and not \linewidth/\columnwidth
    \def\@centeredline {\hbox to \linewidth
                        \bgroup \hss \bgroup
                        \aftergroup\centeredline@ }
    \newcommand*\centeredline {%
      \ifhmode
        \\\relax
        \def\centeredline@{\hss\egroup\hskip\z@skip}%
      \else
        \def\centeredline@{\hss\egroup}%
      \fi
      \afterassignment\@centeredline
      \let\next=}

% pour maintenir les % en début de ligne dans les blocs verbatim
%

   \let\original@check@percent\check@percent
   \let\check@percent\relax
\makeatother


% pour les environnements verbatim
% uniformisé finalement, avec quelques exceptions, pour dtx du 3 déc 2013
\def\MacroFont{\ttfamily\small\hyphenchar\font45 \baselineskip11pt\relax}

% ATTENTION: (avec doc.sty ou les classes scrdoc ou ltxdoc)
%
% - l'environnement macrocode se fait avec \macro@font qui est le
% \MacroFont du \begin{document}.
%
% - les environnements verbatim utilisent le \MacroFont courant.
%
% - \verb utilise un \ttfamily !! et non pas \verbatim@font que l'on
% peut customiser.
%
% - (9 mars 2015) il ne faut PAS commencer des macrocode directement après
% un \section, il faut un paragraphe (par exemple un \indent\par)

%----
% better \verb pour doc.
% 12 octobre 2013, importé de xint.dtx
% je rajoute pour { afin que truc{machin puisse avoir hyphénation
% retire \leavemmode, pas nécessaire pour emploi ici

% NOTE 9 mars 2015. J'ai depuis une version plus aboutie dans xint.dtx
% mais je laisse ici tel quel.

\def\MicroFont{\ttfamily\hyphenchar\font45 }
% modif de \do@noligs: \char`#1} --> \char`#1 }
\makeatletter 
\def\do@noligs #1%
{%
    \catcode `#1\active 
    \begingroup \lccode `\~=`#1\relax 
    \lowercase {\endgroup \def ~{\kern \z@ \char `#1 }}%
}% 
\def\dobackslash
{%
    \catcode92 \active 
    \begingroup \lccode `\~=92\relax 
    \lowercase {\endgroup \def ~{\kern \z@ \char 92 }}%
}% 
\def\dobraces
{%
    \catcode123 \active 
    \begingroup \lccode `\~=123\relax 
    \lowercase {\endgroup \def ~{\hskip \z@\@plus.1pt\@minus.1pt
                                 \char 123 }}%
    \catcode125 \active 
    \begingroup \lccode `\~=125\relax 
    \lowercase {\endgroup \def ~{\char 125 \hskip \z@\@plus.1pt\@minus.1pt }}%
}% 
\def\verb 
{%
  \relax \ifmmode\hbox\else\leavevmode\null\fi
  \bgroup \MicroFont
  \let\do\do@noligs  \verbatim@nolig@list
  \let\do\@makeother \dospecials 
  \catcode32 10 
  \dobackslash \dobraces \makestarlowast 
  \@jfverb 
}% 
\def\@jfverb #1{\catcode`#1\active
                \lccode`\~`#1\lowercase{\def~{\egroup\unskip}}}%
% (\unskip ajouté le 14 octobre)
% \lowast est défini plus loin
\begingroup
   \lccode`\~=`\*
\lowercase{%
\endgroup
\def\makestarlowast {\catcode`\*\active\let~\lowast}}%
\makeatother
%
\usepackage{txfonts}

% m'occuper de la taille de txtt:
% au passage je supprime le \hyphenchar \font\m@ne

% avril 2013
% ATTENTION ATTENTION ATTENTION Un changement de taille comme \small semble
% déclencher (peut-être) la relecture de t1txtt.fd et quoi qu'il en soit le
% \hyphenchar est REMIS à -1 !

% update: 13 octobre 2013 
% et pourtant tailles sont ok, donc au moins cette information est
% maintenue je ne sais donc pas exactement ce qui se passe.

% (2015/11/12: je soupçonne presque un bug de conception de NFSS mais je n'ai
% jamais eu ni le temps ni l'envie de regarder de plus près)

\DeclareFontFamily{T1}{txtt}{\hyphenchar\font 45\relax}
\DeclareFontShape{T1}{txtt}{m}{n}{  %medium
     <->s*[.96] t1xtt%
}{}
\DeclareFontShape{T1}{txtt}{m}{sc}{ %cap & small cap
     <->s*[.96] t1xttsc%
}{}
\DeclareFontShape{T1}{txtt}{m}{sl}{ %slanted
     <->s*[.96] t1xttsl%
}{}
\DeclareFontShape{T1}{txtt}{m}{it}{ %italic
     <->ssub * txtt/m/sl%
}{}
\DeclareFontShape{T1}{txtt}{m}{ui}{     %unslanted italic
     <->ssub * txtt/m/sl%
}{}
\DeclareFontShape{T1}{txtt}{bx}{n}{ %bold extended
     <->t1xbtt%
}{}
\DeclareFontShape{T1}{txtt}{bx}{sc}{    %bold extended cap & small cap
     <->t1xbttsc%
}{}
\DeclareFontShape{T1}{txtt}{bx}{sl}{    %bold extended slanted
     <->t1xbttsl%
}{}
\DeclareFontShape{T1}{txtt}{bx}{it}{    %bold extended italic
     <->ssub * txtt/bx/sl%
}{}
\DeclareFontShape{T1}{txtt}{bx}{ui}{    %bold extended unslanted italic
     <->ssub * txtt/bx/sl%
}{}
\DeclareFontShape{T1}{txtt}{b}{n}{  %bold
     <->ssub * txtt/bx/n%
}{}
\DeclareFontShape{T1}{txtt}{b}{sc}{ %bold cap & small cap
     <->ssub * txtt/bx/sc%
}{}
\DeclareFontShape{T1}{txtt}{b}{sl}{ %bold slanted
     <->ssub * txtt/bx/sl%
}{}
\DeclareFontShape{T1}{txtt}{b}{it}{     %bold italic
     <->ssub * txtt/bx/it%
}{}
\DeclareFontShape{T1}{txtt}{b}{ui}{     %bold unslanted italic
     <->ssub * txtt/bx/ui%
}{}

\usepackage{xspace}
% added svgnames 2022/08/26 on occasion of transfer from xint colouring scheme
\usepackage[dvipsnames,svgnames]{xcolor}
\usepackage{graphicx}
\usepackage[inline]{enumitem}
\usepackage{array}
\usepackage{longtable}

\definecolor{joli}{RGB}{225,95,0}
\definecolor{JOLI}{RGB}{225,95,0}
\definecolor{BLUE}{RGB}{0,0,255}
\colorlet{niceone}{green!35!blue!75}

\usepackage {babel} % ngerman and english options have been passed to babel
\AtBeginDocument {
%% ATTENTION à ce que fait la classe scrdoc: File/Datei pour \partname !!!
%% Je l'avais oublié pour 1.08 lorsque je suis passé à ngerman. (obsolète)
%% Attention aussi au fait qu'il faut faire le \renewcommand\partname
%% ET le mettre dans les \captions...
%% 
  \renewcommand\partname{Part}%
  \addto\captionsenglish {\renewcommand\partname{Part}}
}

\usepackage{tikz}
\usetikzlibrary{trees}    % added for "cyclic" grow function 2013/03/02

% Temporaire 16 avril 2015 pour release etoc 1.08e :
%
% \usepackage{etex}
%
% car erreur de compilation avec la pre-release 2015 de TeXLive à cause d'un
% missing \locbox avec forest 2014/03/07 1.05.
%
% Dû au fait que etoolbox 2015/03/19 v2.1d ne charge plus etex lorsqu'il
% détecte le nouveau format LaTeX 2015/01/01 qui a été diffusé sur CTAN aux
% alentours de 2015/03/31 et qui est intégré à TeXLive 2015.
%
% Note 12 mai 2015: la version 2015/05/04 1.06 de forest fait maintenant
% explicitement \RequirePackage {etex}. Il y a un nouveau package elocalloc de
% David Carlisle, donc forest devrait plutôt tester si \locbox est défini
% après avoir chargé etoolbox et sinon faire \RequirePackage {elocalloc}.
\usepackage{forest}[2015/05/04]
%
% switched from tikz-qtree to forest 2013/09/09
% No problem with hyperlinks then, contrarily to tikz-qtree.

% NOTE: (12 octobre 2013)
%  - si compilation pour dvipdfmx, les arbres dans le dvi visualisés par xdvi
%  montrent correctement les textes, mais rien au point de vue graphique,
%  - si compilation pour dvips, l'arbre fait par forest est tout empilé, celui
%  fait par tikz sans forest est presque correct, les labels débordent.
% Dans les deux cas, le résultat final dans le pdf est bon.
% grosso modo dans l'état actuel le pdf fait 250K (dvipdfmx), 340K (pdflatex) et
% 1M pour dvips+ps2pdf.

% 9 octobre 2013, je me décide à ne plus utiliser hidelinks, mais il est tout de
% même ajouté au .toc

% 12 mars 2015, pour 1.08a, see http://tex.stackexchange.com/a/232584/4686
\usetikzlibrary{mindmap} 

\usepackage{hyperref}% I had used [pdfencoding=pdfdoc] until 1.09f
\hypersetup{%
linktoc=all,%      why is the important stuff
%% bookmarksdepth=3,% (not needeed anymore now, 1.07g)
breaklinks=true,%
colorlinks,%   
linkcolor=RoyalBlue,% Orchid
urlcolor=OliveGreen,%
pdfauthor={Jean-François Burnol},% on peut y aller maintenant avec ç en 2022...
pdftitle={The etoc package},%
pdfsubject={Tables of contents with LaTeX},%
pdfkeywords={LaTeX, table of contents},%
pdfstartview=FitH,%
pdfpagemode=UseOutlines}

% added usage of package bookmark 2013/10/10
\usepackage{bookmark} 

\usepackage{framed}
\usepackage{varioref}

\usepackage{etoc}  % loads multicol
% for etoc's own default line styles. <1.08b had \partname by default but this
% does not work well with babel+frenchb hence the default is now simply Part.
% Here we can use \partname as we do (did) the documentation for English or German.
% Careful with the customization of \partname done by scrdoc class! (obsolete remark)
\renewcommand{\etocpartname}{\partname}
% see the \AtBeginDocument with \addto\captionsngerman etc...


%--------
% 10 octobre 2013:
\AtBeginDocument{\addtocontents{toc}{\protect\hypersetup{hidelinks}}}
% mieux que de passer hidelinks comme option à hyperref.
% Comme toutes les tocs sont faites dans un groupe, c'est très
% bien. (et j'utilise \etocaftertitlehook pour autre chose)

%--------
% add-ons for the new section `surprising uses of etoc' (2013/01/24)
\newcounter{visibletoc}
\renewcommand{\etocaftertitlehook}
   {\stepcounter{visibletoc}%
    \phantomsection
    \etoctoccontentsline{visibletoc}{\thevisibletoc}}
\etocsetlevel{visibletoc}{6}
%--------
% add-ons for the `fancy TOC' (2013/01/25)
% supprimé 2019/03/09
    % \newcounter{dummypart}
    % \newcounter{dummychapter}
    % \newcounter{dummysection}
    % \etocsetlevel{dummypart}{6}
    % \etocsetlevel{dummychapter}{6}
    % \etocsetlevel{dummysection}{6}
%--------
% for "Another compatibility mode"  (2013/02/21):
% attention au 5 qui est hard-coded 
% (pour 1.07f c'était 3, maintenant 5 pour 1.07g; et 4 maintenant pour 1.07h...)
% (et pour 1.07i.. à nouveau 3 faudra vraiment que je change cela)
% et maintenant =4 pour version de la doc du 28 avril 2014... faudra vraiment qu
% je mette un mécanisme plus robuste pour cette TOC.
% ATTENTION AUSSI AUX CODES VERBATIM
% màj pour 1.08k: \etocsavedsectiontocline etc...
\makeatletter
\newcommand*{\MyQuasiStandardTOC}[1]{%
  \begingroup
  \etocsetstyle{section}{}
    {\ifnum\etocthenumber=4 % <- check this if new sections added to user manual
      \etocsetstyle{subsection}
        {\par\nopagebreak\begingroup
         \leftskip1.5em \rightskip\@tocrmarg
         \parfillskip \@flushglue 
         \parindent 0pt
         \normalfont\normalsize\rmfamily\itshape
         \etocskipfirstprefix}
        {\allowbreak\,--\,}
        {\etocname\ \textup{(\etocnumber)}}
        {.\par\endgroup}%
     \else
        \etocsetstyle{subsection}{}{}
        {\etocsavedsubsectiontocline{\numberline{\etocnumber}\etocname}{\etocpage}}{}%
     \fi} 
    {\etocsavedsectiontocline
      {\numberline{{\color{cyan}\etocthenumber}}\etocname}{\etocpage}}
    {}%
  \etocstandarddisplaystyle
  \etocsetnexttocdepth {2}%
  \tableofcontents #1
  \endgroup}
\makeatother
%--------
% Statistics on sections and subsections in a part \thispartstats:
% 2 mars 2013
% cette version utilise des box, plutôt que des macros.
% mais on ne peut plus alors changer de police etc...

% 11 octobre 2013, je retire les \color{teal}.

\newsavebox\firstnamei
\newsavebox\firstnumberi
\newsavebox\lastnamei
\newsavebox\lastnumberi
\newsavebox\firstnameii
\newsavebox\firstnumberii
\newsavebox\lastnameii
\newsavebox\lastnumberii
\newcounter{mycounti}
\newcounter{mycountii}

\newcommand*{\thispartstatsauxi}{}
\newcommand*{\thispartstatsauxii}{}
\newcommand*{\oldtocdepth}{}

\newcommand*{\thispartstats}{%
  \setcounter{mycounti}{0}%
  \setcounter{mycountii}{0}%
  \def\thispartstatsauxi{%
         \sbox{\firstnamei}{\etocname}%
         \sbox{\firstnumberi}{\etocnumber}%
         \def\thispartstatsauxi{}}%
  \def\thispartstatsauxii{%
         \sbox{\firstnameii}{\etocname}%
         \sbox{\firstnumberii}{\etocnumber}%
         \def\thispartstatsauxii{}}%
  \begingroup
  \etocsetstyle{subsection}
    {}
    {}
    {\thispartstatsauxii
     \stepcounter{mycountii}%
     \sbox{\lastnameii}{\etocname}%
     \sbox{\lastnumberii}{\etocnumber}}
    {}
  \etocsetstyle{section}
    {}
    {}
    {\thispartstatsauxi
     \stepcounter{mycounti}%
     \sbox{\lastnamei}{\etocname}%
     \sbox{\lastnumberi}{\etocnumber}}
    {Here are some statistics for this part: it contains \arabic{mycounti}
      section\ifnum\value{mycounti}>1 s\fi{} and
      \arabic{mycountii} subsection\ifnum\value{mycountii}>1 s\fi. The name of
     the first section is 
     ``\unhbox\firstnamei{}'' and the corresponding number is 
     ``\unhbox\firstnumberi''. The name of the last section is 
     ``\unhbox\lastnamei{}'' and its number is
     ``\unhbox\lastnumberi''. 
     \ifnum\value{mycountii}>0 The name of
     the first subsection is 
     ``\unhbox\firstnameii{}'' and the corresponding number is 
     ``\unhbox\firstnumberii''. The name of the last subsection is 
     ``\unhbox\lastnameii{}'' and its number is
     ``\unhbox\lastnumberii''.\fi }
  \etocinline 
% october 10, 2013. 
  \etocsetnexttocdepth {2}%
  \etocsettocstyle {\pdfbookmark[1]{Statistics}{\thepart.STATS}}{}
  \localtableofcontents
  \endgroup
}
%%
% pour les TOC à la TikZ
\newtoks\treetok
\newtoks\parttok
\newtoks\sectiontok
\newtoks\subsectiontok
\newtoks\tmptok

\newcommand*\appendtotok[2]{% #1=toks variable, #2=macro, expands once #2
  #1\expandafter\expandafter\expandafter{\expandafter\the\expandafter #1#2}}

% 12 et 13 mars 2015 pour la mind map de title page
% pour les Mindmap avec branch color
\def\appendpart #1#2#3{% 
   \edef\tmpstuff {\the#1 child [branch color = #3]{\the#2}}%
   #1\expandafter {\tmpstuff }%
}
% for 1.09f mind map on title page
\def\prependpart #1#2#3{% 
   \edef\tmpstuff {child [branch color = #3]{\the#2} \the#1}%
   #1\expandafter {\tmpstuff }%
}

% Vendredi 13 mars 2015 à 18:10:40
% POUR LA TOC DE TITLE PAGE
\usepackage{eso-pic}
\usepackage{picture}

\newcommand\etoc{%
        \texorpdfstring{{\color{joli}\ttfamily\bfseries etoc}}{etoc}\xspace}

\DeclareRobustCommand\csa [1] {{\ttfamily\hyphenchar\font45 \char`\\ #1}}

\DeclareRobustCommand\csb [1] 
                {\hyperref[#1] {\ttfamily\hyphenchar\font45 \char`\\ #1}}

\newcommand\cshyp[1]{\texorpdfstring{\csa{#1}}{\textbackslash #1}}

\newcommand\csbhyp[1]{\texorpdfstring{\csa{#1}}{\textbackslash #1}}

\newcommand\toc{\csa{tableofcontents}\xspace}
\newcommand\localtoc{\csa{localtableofcontents}\xspace}
\newcommand\localtocwrdp{\csa{localtableofcontentswithrelativedepth}\xspace}

\newcommand\lowast{\raisebox{-.25\height}{*}}
\newcommand\starit[1]{\csa{#1\lowast}}
\newcommand\staritb[1]{\csb{#1}\lowast}

\hyphenation{
table-of-con-tents
local-table-of-con-tents
local-table-of-con-tents-with-rel-a-tive-depth
}

\hyphenation{toc-depth sec-num-depth con-tents-line}

\hyphenation{etoc-stan-dard-lines
etoc-de-fault-lines
etoc-toc-lines
etoc-set-style
etoc-name
etoc-page
etoc-skip-first-pre-fix
etoc-num-ber
etoc-if-first
etoc-x-if-first
etoc-if-num-bered
etoc-x-if-num-bered
etoc-if-was-empty
etoc-x-if-was-empty
etoc-checks-empti-ness
etoc-no-toc-if-no-toc
etoc-the-name
etoc-the-num-ber
etoc-the-page
etoc-link
etoc-the-linked-name
etoc-the-linked-num-ber
etoc-the-linked-page
etoc-the-link
etoc-set-level
etoc-set-toc-depth
etoc-set-next-toc-depth
etoc-set-toc-depth
etoc-obey-toc-toc-depth
etoc-ig-nore-toc-depth
etoc-depth-tag
etoc-set-tag-depth
etoc-obey-depth-tags
etoc-ig-nore-depth-tags
etoc-toc-con-tents-line
etoc-set-local-top
etoc-stan-dard-dis-playstyle
etoc-ar-ti-cle-style
etoc-book-style
etoc-set-toc-style
etoc-mul-ti-col-style
etoc-mul-ti-col
etoc-lo-cal-mul-ti-col
etoc-toc-style
etoc-toc-style-with-marks
etoc-toc-style-with-marks-nouc
etoc-ruled-style
etoc-ruled
etoc-lo-cal-ruled
etoc-framed-style
etoc-framed
etoc-lo-cal-framed
etoc-in-line
etoc-af-ter-ti-tle-hook
etoc-af-ter-con-tents-hook
etoc-af-ter-toc-hook
etoc-skip-first-pre-fix
etoc-only-on-first
}

\hyphenation{ 
etoc-font-mi-nus-two 
etoc-font-mi-nus-one 
etoc-font-zero 
etoc-font-one 
etoc-font-two 
etoc-font-three 
etoc-sep-mi-nus-two 
etoc-sep-mi-nus-one 
etoc-sep-zero 
etoc-sep-one 
etoc-sep-two 
etoc-sep-three 
etoc-mi-nus-two-left-mar-gin 
etoc-mi-nus-two-right-mar-gin 
etoc-mi-nus-one-left-mar-gin 
etoc-mi-nus-one-right-mar-gin 
etoc-base-line-spread-mi-nus-two 
etoc-base-line-spread-mi-nus-one 
etoc-base-line-spread-zero 
etoc-base-line-spread-one 
etoc-base-line-spread-two 
etoc-base-line-spread-three 
etoc-toc-line-lead-ers 
etoc-ab-brev-page-name 
etoc-part-name 
etoc-book-name 
etoc-above-toc-skip 
etoc-be-low-toc-skip 
etoc-column-sep 
etoc-mul-ti-col-sep 
etoc-mul-ti-col-pre-tol-er-ance 
etoc-mul-ti-col-tol-er-ance 
etoc-de-fault-nb-col 
etoc-in-ner-top-sep 
etoc-top-rule 
etoc-top-rule-col-or-cmd 
etoc-in-ner-left-sep 
etoc-in-ner-right-sep 
etoc-in-ner-bot-tom-sep 
etoc-left-rule 
etoc-right-rule 
etoc-bot-tom-rule 
etoc-left-rule-col-or-cmd 
etoc-right-rule-col-or-cmd 
etoc-bot-tom-rule-col-or-cmd 
etoc-bkg-col-or-cmd 
etoc-framed-mp-hook
etoc-keep-orig-i-nal-table-of-con-tents
etoc-im-me-di-ate-set-toc-dep-th
etoc-im-me-di-ate-depth-tag
etoc-im-me-di-ate-toc-con-tents-line
etoc-im-me-di-ate-set-local-top
}

\hyphenation{next-toc-with-tags}
% removed, 2022/08/26
% \frenchspacing

\renewcommand\familydefault\sfdefault

% for illustration only. Not to be recommended in general.
\setcounter{secnumdepth}{4}

% Vendredi 16 septembre 2016
% pour rendre accessibles les exemples
% Fait package filecontentsdef le Samedi 17.
\usepackage{filecontentsdef}

%\ifnum\Withdvipdfmx=1
%% I have an issue that with \thesubsection or \the\value{section} in code
%% snippet filename, the file is not correctly attached, it appears in the pdf
%% interface but with a wrong filename and one can not obtain the file from
%% the pdf (tested on Acrobat Reader 11 Vendredi 16 septembre 2016).
%  \usepackage[dvipdfmx]{attachfile2}
%\else
  \usepackage{attachfile}% no op with dvipdfmx
%\fi
% 
\def\CEST{+02'00'}\def\CET{+01'00'}
\def\ExtractDateStamp #1<#2-#3-#4 at #5:#6:#7 #8>%
    {D:#4#3#2#5#6#7\csname#8\endcsname}
\edef\DateForSamples {\expandafter\ExtractDateStamp\etocdtxtimestamp}
\attachfilesetup{icon=Paperclip, mimetype=application/x-tex, appearance=false,
     author={Jean-François Burnol}, date=\DateForSamples}% print=false ? 
% attention Paperclip pas PaperClip !!

\begin{document}%\layout
\rmfamily
\thispagestyle{empty}

% START ENGLISH VERSION
\bookmark[named=FirstPage,level=1]{Title page}

\begingroup
\newcount\tikznumberofcurrentgrandchild
\newcount\tikzdeltaofcurrentgrandchild
%\newcount\tikzoffset
% copié de http://tex.stackexchange.com/a/232914
% THIS WAS NOT USED FOR 1.08a--1.09e RELEASES AND IS NOW AGAIN USED AT 1.09f,
% BUT IS MANUALLY ADJUSTED TO HANDLE ESPECIALLY THE "Surprising" 
% (now rather "Examples") AND "Tip" PARTS
% AND FALL-BACK FOR THEM TO CIRCULAR GROWTH FUNCTION
% hence stuff is hard-coded and interacts with other hard-coded things
% further down; in particular with the configuration of depth tags,
% here all sections are included (except the first two, "Foreword" and "License",
% which are not in any part).
% But etoc documentation is not likely to receive new sections soon.
\def\tikzmycustomgrowth {%
    \pgftransformreset
    \ifnum\tikztreelevel=1
        \pgftransformrotate{-65.4545+((\pgfkeysvalueof{/tikz/sibling angle})*(1+\tikznumberofcurrentchild)}%
        \pgftransformxshift{\the\tikzleveldistance}%
    \fi
    \ifnum\tikztreelevel=2
    % hard-coded section numbers for branching
      \if1\ifnum\tikznumberofcurrentgrandchild>2
          \ifnum\tikznumberofcurrentgrandchild<6  0%
            \else
          \ifnum\tikznumberofcurrentgrandchild>21
          \ifnum\tikznumberofcurrentgrandchild<28 0%
            \else
          \ifnum\tikznumberofcurrentgrandchild>51
          \ifnum\tikznumberofcurrentgrandchild<58 0%
          \fi\fi\fi\fi\fi\fi
         1%
% le "9+" choisi manuellement jusqu'à obtenir quelque chose de bien
        \pgfmathsetmacro\tikzoffsetofcurrentchild{(\tikzsiblingdistance)*(7+\tikznumberofcurrentgrandchild
          +\tikzdeltaofcurrentgrandchild)}%
        \ifdim\tikzoffsetofcurrentchild pt<\tikzlevelheight
            \pgftransformxshift{\tikzlevelwidth/2}
            \pgftransformyshift{-\tikzlevelheight/2+\tikzoffsetofcurrentchild}
        \else
        \pgfmathsetmacro\tikzoffsetofcurrentchild{\tikzoffsetofcurrentchild-\tikzlevelheight}%
        \ifdim\tikzoffsetofcurrentchild pt<\tikzlevelwidth
            \pgftransformxshift{\tikzlevelwidth/2-\tikzoffsetofcurrentchild}
            \pgftransformyshift{\tikzlevelheight/2}
        \else
        \pgfmathsetmacro\tikzoffsetofcurrentchild{\tikzoffsetofcurrentchild-\tikzlevelwidth}%
        \ifdim\tikzoffsetofcurrentchild pt<\tikzlevelheight
            \pgftransformxshift{-\tikzlevelwidth/2}
            \pgftransformyshift{\tikzlevelheight/2-\tikzoffsetofcurrentchild}
        \else
        \pgfmathsetmacro\tikzoffsetofcurrentchild{\tikzoffsetofcurrentchild-\tikzlevelheight}%
        \ifdim\tikzoffsetofcurrentchild pt<\tikzlevelwidth

            \pgftransformxshift{-\tikzlevelwidth/2+\tikzoffsetofcurrentchild}
            \pgftransformyshift{-\tikzlevelheight/2}
        \else
        \pgfmathsetmacro\tikzoffsetofcurrentchild{\tikzoffsetofcurrentchild-\tikzlevelwidth}%
        %\ifdim\tikzoffsetofcurrentchild pt<\tikzlevelheight
            \pgftransformxshift{\tikzlevelwidth/2}
            \pgftransformyshift{-\tikzlevelheight/2+\tikzoffsetofcurrentchild}
        %\fi
        \fi\fi\fi\fi
      \else
      % NEW BRANCH ADDED AT 1.09f
        \ifnum\tikznumberofcurrentgrandchild<6
          \tikzset{level distance=8cm}% TikZ est tout de même assez génial dans l'interface
        \fi
        \pgftransformrotate {\ifnum\tikznumberofcurrentgrandchild<6 -12
                             \else\ifnum\tikznumberofcurrentgrandchild<28 180
                             \else0\fi\fi +
                             \pgfkeysvalueof{/tikz/sibling angle}*\tikznumberofcurrentgrandchild}%
        \pgftransformxshift {\the\tikzleveldistance}%
        \ifnum\tikznumberofcurrentgrandchild=5
          \global\advance\tikzdeltaofcurrentgrandchild by-3
        \fi
        \ifnum\tikznumberofcurrentgrandchild=27
          \global\advance\tikzdeltaofcurrentgrandchild by-6
        \fi
        \ifnum\tikznumberofcurrentgrandchild=57
          \global\advance\tikzdeltaofcurrentgrandchild by-6
        \fi
      \fi
      \global\advance\tikznumberofcurrentgrandchild by1
    \fi
}

%version circulaire utilisée avec les version 1.08a--1.09e du manuel.
% \def\tikzmycustomgrowth {%
%   \pgftransformreset
%   \ifnum\tikztreelevel=1
%     \pgftransformrotate {126+(\pgfkeysvalueof{/tikz/sibling angle})*(\tikznumberofcurrentchild-1)}%
%   \fi
%   \ifnum\tikztreelevel=2
%     \pgftransformrotate {(\pgfkeysvalueof{/tikz/sibling angle})*(2+\tikznumberofcurrentgrandchild)}%
%     \global\advance\tikznumberofcurrentgrandchild by 1
%  \fi
%  \pgftransformxshift {\the\tikzleveldistance}%
% }

\newcounter{partco}
% 1,2,3,4,5,... -> 1,2,3,1,2,3,1,2,3
\def\pseudomodthree #1{\numexpr #1 + 3 - 3*((#1+1)/3)\relax}

% For etoc.toctree file was used to test the Mind map separately
%\newwrite\TOCasTree

\newbox\TitlePageMindmapTOC


\etocsetstyle{part}
  {\etocskipfirstprefix}
  {\ifcase\pseudomodthree{\value{partco}}%
   \or  \appendpart\treetok\parttok {teal!30}%   first (60 avant 1.09f)
   \or  \appendpart\treetok\parttok {yellow!80}% second
   \else\appendpart\treetok\parttok {green!50}%  third
   \fi
   }
  {\stepcounter{partco}%
   \edef\treenode{node
                  {\noexpand\textbf{\etocifnumbered{\unexpanded\expandafter{\etocthelinkednumber}.}{}
                   \unexpanded\expandafter{\etocthelinkedname}}}}%
%****  Cette remarque est obsolète depuis 1.09f et la partie pour le foreword
% grosse astuce: la première Partie ne sera pas embêtée par les trois sections
% avant car ce qu'elles auront mis dans \parttok va être effacé.
%****
   \parttok\expandafter{\treenode}}
  {% 1.09f prepends...
   \ifcase\pseudomodthree{\value{partco}}%
   \or  \prependpart\treetok\parttok {teal!30}%   first (60 avant 1.09f)
   \or  \prependpart\treetok\parttok {yellow!80}% second
   \else\prependpart\treetok\parttok {green!50}%  third
   \fi
   }

\etocsetstyle{section}
  {}
  {}
  {% define the section node
   \edef\childnode{child {node
       {\noexpand\itshape\noexpand\bfseries
        \unexpanded\expandafter{\etocthelinkedname}\hfil\break
         p. \unexpanded\expandafter{\etocthelinkedpage}}}
                        }%
   \appendtotok\parttok\childnode 
   }
  {}

\etocsetnexttocdepth{section}

% title page toc
% 1.09f uses a prepend for last part so we need to delay
% start of tree construction in \treetok
\treetok{}
\makeatletter
\etocsettocstyle
  {\setcounter{partco}{0}%
   }
  {%
   \toks@{\node [root concept]{\normalfont{The \etoc package}\par {\normalsize\textsc
    {Jean-François Burnol}\par \ttfamily jfbu (at) free (dot) fr}\par
    {\normalsize Package version:\par \etocpkgversion{} (\etocpkgdate )\par}}%
   }%
   \global\treetok\expandafter\expandafter\expandafter{\expandafter\the\expandafter\toks@\the\treetok;}%
  }

% depth tags for title page toc
\etocsettagdepth {preamble}{section}
\etocsettagdepth {overview}{section}
\etocsettagdepth {arbitrarily}{section}
\etocsettagdepth {examples}{section}
\etocsettagdepth {surprising}{section}
\etocsettagdepth {linestyles}{section}
\etocsettagdepth {globalcmds}{section}
\etocsettagdepth {custom}{section}
\etocsettagdepth {tips}{section}
\etocsettagdepth {etocandworld}{section}
\etocsettagdepth {code}{all}

% fill in the \treetok
\etocinline\tableofcontents\label{toc:mindmaptitlepage}

% \immediate\openout\TOCasTree=\jobname.toctree
% \immediate\write\TOCasTree{\the\treetok}%


\tikzset {branch color/.style={concept color=#1!white,
                               every child/.append style={concept color=#1!white!30!white,
                                                          opacity=0.3, text opacity=1},
                             },
% ajout pour version de 1.08g
          level width/.store in=\tikzlevelwidth,
          level height/.store in=\tikzlevelheight
         }%

\global
\setbox\TitlePageMindmapTOC\hbox {%
\resizebox{\dimexpr\paperwidth-1cm\relax}!{%
\begin{tikzpicture}[mindmap,
                    text width=2cm,
                    align = flush center,
% pour 1.09 je reviens à version circulaire simplifiée
% pour 1.09f je reviens à version rectangulaire
                    growth function=\tikzmycustomgrowth,
                    nodes={concept},
                    concept color=orange!60,
                    % root concept/.append style={font=\huge, text width = 6cm},
                    root concept/.append style={font=\Large, text width = 5cm},
                    % level 1/.append style={level distance=7cm, sibling
                    level 1/.append style={level distance=6cm,
                                           sibling angle=360/11},% une partie de plus
                    % level 1 concept/.append style={font=\Large, text width = 3cm},
                    % ancienne version circulaire
                    % level 2/.append style={level distance=12.5cm, sibling angle=360/39},% 
% % distance par rapport au CENTRE ! (avec le code tel qu'en ce moment)
% 39 hard coded mais je pourrais aussi le calculer
%
        % pour version rectangulaire, par tâtonnements:
        % réactivée pour 1.09f (étonnamment, juste quelques petits ajustements, mais ça
        % a tout de même pris pas mal de temps...)
        level 2/.append style={level width=21cm,
                               level height=30cm,
                               sibling distance=2.21cm,% ajusté à la
                                                       % main... dépend de ce qui qu'on conserve par
                                                       % les depth tags...
                               % 1.09f pour essayer certaines parties en circulaire
                               level distance=10cm,% DISTANCE DEPUIS LE CENTRE !
                               sibling angle=12,% ajusté manuellement
                               },
        level 2 concept/.append style={text width=2cm},
                   ]
\the\treetok
\end{tikzpicture}%
}%
}% end of \hbox
\endgroup% fin de la défintion de la mind map pour la page de titre

\noindent\null

% On l'envoie au shipout
\AddToShipoutPictureFG*{\put(.5\paperwidth,.5\paperheight)
                        {\makebox(0,0){\box\TitlePageMindmapTOC}}}

\clearpage

\etocdepthtag.toc {preamble}

%----
% MAIN TOC
%
\etocsettocdepth {subsubsection}
\etoctoclines
\etocmarkboth\contentsname
\etocmulticolstyle[1]
     {\noindent 
      \bfseries\Large
      \leaders\hrule height1pt\hfill
      \MakeUppercase{Table of Contents}\let\thefootnote\empty
 \footnote{Documentation (\etocdocdate) generated from the source file
  with timestamp ``\etocdtxtimestamp''.}\setcounter{footnote}{0}%
}

\pdfbookmark[1]{Table of contents}{MAINTOC}%
      
\begin{framed}
  Starting with |1.08h|, about 25 code samples (especially the longer
  ones) are incorporated into the PDF file (thanks to \textsc{Scott
    Pakin}'s \href{http://www.ctan.org/pkg/attachfile}{attachfile}
  package) as \emph{file attachement annotations}. Each file is represented
  by an icon after the verbatim rendering of the corresponding code.
  Clicking suitably on the icon will open a dialog to open or save the
  file contents. This is much better than copy-paste which loses
  indentation. There is also in some viewer a \emph{Comment pane} which can
  be opened on the right side of the main window and which provides a
  convenient clickable list of all these \emph{attachments annotations}.

  PDF viewers unable to make these attachments accessible to the
  user may replace the clickable icons by some blank space.
\end{framed}
% https://helpx.adobe.com/acrobat/using/comments.html

\begingroup
  \etocsetlevel{subsection}{3}
  \etocsetlevel{subsubsection}{6}
  \tableofcontents \label{toc:main}
\endgroup

% ATTENTION Vendredi 09 septembre 2016 à 21:46:51
\clearpage

% refactoring 2022/08/30 via ajout de ce \part* et déplacement de l'abstract
% pour avoir une TOC mindmap plus complète
\part*{\etoc}
\addcontentsline{toc}{part}{\etoc}

\phantomsection\addcontentsline{toc}{section}{\abstractname}

\begin{abstract}
  The \etoc package gives to the user complete control on how
  the entries of the table of contents should be constituted
  from the \emph{name}, \emph{number}, and \emph{page number}
  of each sectioning unit. This goes via the definition of
  \emph{line styles} for each sectioning level used in the
  document. The package provides its own custom line styles.
  Simpler ones are given as examples in the documentation. The
  simplest usage will be to take advantage of the layout facilities
  of packages dealing with list environments.
  
  Regarding the \emph{global toc display}, \etoc provides pre-defined styles
  based on a multi-column format, with, optionally, a ruled title or framed
  contents.

  The \csa{tableofcontents} command may be used arbitrarily many times%
%
\footnote{Except if \texttt{\string\etockeeporiginaltableofcontents}
  (\textcolor{Green}{\bfseries New with 1.09d}) is issued in the preamble
  after package loading. Then the macro \texttt{\string\etoctableofcontents},
  not \texttt{\string\tableofcontents}, must be used if the \etoc features
  are to apply to the global TOC. This was added to fix a compatiblity issue
  with \texttt{listings}'s \texttt{\string\lstlistoflistings}, as it needs the
  \texttt{\string\tableofcontents} macro to keep its original meaning.}
%
 and it
  has a variant \csa{localtableofcontents} which prints tables of contents
  `local' to the current surrounding document unit. An extension of the
  \csa{label}/\csa{ref} syntax allows to reproduce (with another layout) a local
  table of contents defined somewhere else in the document.

  Via ``depth tags'', one gets an even finer control for each table of contents
  of which sectioning units it should, or not, display.

  The formatting inherited (and possibly customized by other
  packages) from the document class will be used when in
  \emph{compatibility mode}.

  The assignment of levels to the sectioning units can be changed at any
  time, and \etoc can thus be used in a quite general manner to
  create custom ``lists of'', additionally to the tables of contents
  related to the document sectioning units. No auxiliary file is used
  additionally to the standard |.toc| file.
\end{abstract}

\section{Foreword}

Popular packages dealing with TOCs include |tocloft|, |titletoc|
and |minitoc|. Why another one? I started \etoc
for my own use, and found out only later about these mentioned
packages.

As is well explained in the |tocloft| package documentation,
the standard \LaTeX{} layout for the Table of Contents is
buried in the class definitions. In particular, most of the
lengths therein are hardcoded, and the only way for the user
to change them is to recopy the class definitions into the
document and then change them to obtain what is desired
(within suitable \csa{makeatletter} and \csa{makeatother}).
The more reasonable alternative is to use a dedicated package such as
|tocloft| or to use another flexible document class.

However, although now things are hopefully not hard-coded, one
still has to go through the package or class interface. This
means one has to memorize a (possibly large) number of macros
which will serve only to this task, and one will always be
constrained to customizing one initially given layout.

The spirit of \etoc is something else. The user will deal with
the \emph{name}, the \emph{number} and the \emph{page number}
corresponding to each document sectional division (and
found in a line of the |.toc| file) in a completely arbitrary
manner: they are made available via the \csb{etocname},
\csb{etocnumber}, and \csb{etocpage} commands. 

\etoc appears to be (at least partially) compatible with the
|article|, |book|, |report|, |scrartcl|, |scrbook|, |scrreprt| and
|memoir| classes. 

\section{License}

\begingroup\ttfamily\small\hyphenchar\font -1
           \parindent0pt 
           \obeyspaces\obeylines %
\etocLicense\endgroup


\clearpage

\etocsettocdepth {subsection}

\etocdepthtag.toc{overview}

\part{Overview}\label{part:overview}

\thispartstats

\invisiblelocaltableofcontents \label{toc:overview}

\section{Do I need to be a geek to use \etoc?}

Not quite. The simplest way is to use |enumerate| environments,
with the customizing facilities of packages such as
|enumitem|,\footnote{\url{http://ctan.org/pkg/enumitem}} to
display the data fetched by \etoc from the |.toc| file. The data
consists of the \emph{name} (\csb{etocname}), \emph{number}
(\csb{etocnumber}), and \emph{page number} (\csb{etocpage}) as
extracted
% \footnote{although \LaTeX{} has been promoted as
%   separating contents from form, there are some areas where its
%   real implementation is very far from this ideal. And the |.toc|
%   file is a case in point; not to mention the hard-coded
%   dimensions, with use of the @ sign,
%   in the macros responsible for constructing the typeset table of
%   contents.} 
from the |.toc| file.

This is
illustrated \hyperref[toc:a]{at the start} of
\autoref{part:linestyles}. More
sophisticated examples would use more sophisticated |enumitem|
options. One may say then that again the user has to memorize some
customizing! indeed, but the syntax and option names to memorize
are in no way related only to matters of tables of contents, hence
an economy of use of the poor brain.

% People who
% know the internals of \LaTeX2e well (which is not my case) could
% happily use directly a |\list| command;  

Next in ease of use, perhaps, is the method explained
\hyperref[sec:firstexample]{later in this part}
(\autoref{sec:firstexample}). For this some knowledge of |\leftskip|,
|\rightskip|, etc... is necessary. And a slight elaboration of this
method, whose code is to be found in \autoref{ssec:tocwithdepthtags},
allows to mimick very well, if so desired, the standard looks. An even
closer emulation of the |book| class design is now included in this
documentation as \autoref{sec:thirdexample}.

As will be amply illustrated in this manual, \etoc is quite
versatile (especially as it allows to re-define at any point in
the document the hierarchy of sectioning units) and one can
achieve surprising effects with it: \autoref{part:surprising} is
devoted to this, and some more is to be found in
\autoref{part:tipsandtricks}.

\begin{framed}
\setcounter{mycounti}{0}%
  \etocinline
\etocsetlevel{part}{1}
\etocsetlevel{chapter}{1}
\etocsetlevel{visibletoc}{0}
\etocsetstyle{visibletoc}
    {}
    {\stepcounter{mycounti}}
    {}
    {}
\etocsettocstyle{}{}
\etocsetnexttocdepth{0}
\tableofcontents
A very important aspect of \etoc is that it is geared towards making many TOCs
in the same document, \emph{using only one} |.toc| \emph{file}! The present
documentation contains \arabic{mycounti} visible tables of contents (and a few
invisible ones) and uses only one |.toc| file!\footnotemark{} So one should
think 
twice before adding manually extra commands to the |.toc| file (see
\autoref{sec:addingtotoc}).
\end{framed}

\footnotetext{and the counting itself has been achieved by a table of contents
  which was inserted in the framed paragraph! \dots the technique for this kind
  of effect will be explained later.}


\subsection{Limitations in the use of list environments for
  tables of contents}
\label{ssec:limitations}

There are some limitations to the use of list environments
for typesetting TOCs. One of them is intrinsic to the scope
limitations created by the groups associated to the
environments: the |.toc| file
may contain, besides the information to be typeset in the
TOCs, some other commands, such as language changing
commands, which do not expect to see their scope limited in
this way inside a group (\LaTeX's environments create scope limiting groups).

Therefore the built-in ``line styles'' proposed by \etoc as an example
(and which are illustrated\footnote{with a twist, subsections having
  been downgraded to the subsubsection style\dots} by the
\hyperref[toc:main]{main table of contents} in this document) do not
make use of environments. Actually, in this user manual, only the
\hyperref[toc:a]{table of contents} at the start of
\autoref{part:linestyles}, the \autoref{toc:allsubsections} (which is a
TOC!) and examples from \autoref{etocthelink} have their line
styles expressed in terms of enumerate or itemize environments.

\section{Line styles and toc display style}

A distinction shall be made between the \emph{line styles},
\emph{i.e.} the way the name, number and page numbers are
used at each level, and the \emph{toc display style} (for
lack of a better name) which tells how the title should be
set, whether an entry in the |.toc| file should be made,
whether the contents should be typeset with multiple columns,
etc... the latter is governed by the command
\csb{etocsettocstyle} (or some higher-level commands) and the
former by the command \csb{etocsetstyle}.


\subsection{\csbhyp{etocsetstyle} for the line styles}

The command to inform \etoc of what to do with \csb{etocname}, \csb{etocnumber},
and \csb{etocpage} is called \csb{etocsetstyle}. It has five mandatory
arguments. The first one is the name of the sectional unit: a priori known names
are |book|, |part|, |chapter|, |section|, |subsection|, |subsubsection|,
|paragraph|, and |subparagraph|, and any other name can be declared and assigned
to a (numeric) level via the \csb{etocsetlevel} command.\footnote{under the
  \texttt{memoir} class, \etoc knows \texttt{appendix} as a sectioning
  name.} 

The four other arguments of \csb{etocsetstyle} specify: 1) \emph{what to do when
  this level is first encountered, down from a more general one,} then 2) \& 3)
(two arguments, a `prefix' and a `contents') \emph{what to do when a new entry
  of that type is found,} and 4) \emph{the last argument is the code to execute
  when a division unit of higher importance is again hit upon.}

\subsection{\csbhyp{etocsettocstyle} for the toc display}

The \csb{etocsettocstyle} command allows to specify what
should be done before and after the line entries of the TOC
are typeset, and in particular how the title should be
printed. It has two arguments, the first one is executed
before the TOC contents (typically it will print
``Contents'' and define suitable marks for the page headings) and
the second is executed after the TOC contents.

\etoc provides four (customizable) higher level toc styles:
\csb{etocmulticolstyle}, \csb{etoctocstyle},
\csb{etocruledstyle}, and \csb{etocframedstyle}. All use the
|multicol| package with a default of two columns
(single-column mode is obtained with the optional argument |[1]|).

These commands must be followed either by \toc or \localtoc.

\subsection{Compatibility mode}\label{subs:compat}
\label{etoctoclines}
\label{etocstandardlines}

Both for the ``line styles'' and the ``toc display style'', it is
possible to switch into a compatibility mode which uses the
defaults from the
document class.\footnote{for the ``toc display style''
  \etoc checks if it knows the class, and if not defaults to
  the |article| class layout. It will also check if
  \texttt{tocloft} has customized the TOC title.} 
This is activated by:\\
\makebox[5.2cm][l]{\csb{etocstandardlines}}
 |% `line entries' as without \usepackage{etoc}|\\
\makebox[5.2cm][l]{\csb{etocstandarddisplaystyle}}
 |% `toc display'  as without \usepackage{etoc}|


If the command \csb{etocsetstyle} has \emph{not been used in the
preamble} the package will be at |\begin{document}| in this
  compatibility mode: hence just adding \csa{usepackage\{etoc\}}
  should hopefully not change anything to the look of a
  previously existing document, under the |article|, |book|,
  |report|, |scrartcl|, |scrbook|, |scrreprt| and |memoir|
  classes.

  Any use of \csb{etocsetstyle} in the \emph{preamble or body} of
  the document turns off from that point on the compatibility mode
  for line styles, but maintains the compatibility mode for the
  TOC title. One re-activates the compatibility mode for line
  styles with \csb{etocstandardlines}; and 
  \csb{etoctoclines} will re-activate the line styles as defined
  with the help of \csb{etocsetstyle}, if their scope was not
  limited to a group or environment.

  The command \csb{etocdefaultlines} resets the line styles as
  pre-defined internally by \etoc and described in
  \autoref{etocdefaultlines}.

Even if \csb{etocsetstyle} has been used, the global display style
remains initially as defined by the document class (or the
|tocloft| package); one needs to use the command
\csb{etocsettocstyle} or its variants to exit from this
compatibility mode at the ``toc display style'' level. It will be
re-activated if use if made of \csb{etocstandarddisplaystyle}.

See further \autoref{sec:anothercompat}.

\section{A first example}
\label{sec:firstexample}

Let us present a first example of specification for line styles.
Immediately after the start of \autoref{part:overview} we inserted in the
source file:
\centeredline{|\invisiblelocaltableofcontents \label{toc:overview}|} This
sets-up the label |toc:overview|, and we can use it at any location in the
document: \centeredline{|\tableofcontents \ref{toc:overview}|} And as we used
|\invisible...|,\footnote{this is a shortcut for setting temporarily the
  |tocdepth| to |-3|, which has the effect to tell \etoc not to print the TOC,
  and not even the heading.} the local TOC will exist only through its clones
elsewhere in the document. 

\begin{filecontentsdef}{etocsnippet-\the\value{section}.tex}{\foo}
\begingroup\parindent 0pt \parfillskip 0pt \leftskip 0cm \rightskip 1cm
\etocsetstyle {section}
              {}
              {\leavevmode\leftskip 0cm\relax}
              {\bfseries\normalsize\makebox[.5cm][l]{\etocnumber.}%
               \etocname\nobreak\hfill\nobreak
               \rlap{\makebox[1cm]{\mdseries\etocpage}}\par}
              {}
\etocsetstyle {subsection}
              {}
              {\leavevmode\leftskip .5cm\relax }
              {\mdseries\normalsize\makebox[1cm][l]{\etocnumber}%
               \etocname\nobreak\hfill\nobreak
               \rlap{\makebox[1cm]{\etocpage}}\par}
              {}
\etocsetstyle {subsubsection}
              {}
              {\leavevmode\leftskip 1.5cm\relax }
              {\mdseries\normalsize\makebox[1cm][l]{\etocnumber}%
               \etocname\nobreak\hfill\nobreak
               \rlap{\makebox[1cm]{\etocpage}}\par}
              {}
\etocruledstyle[1]{\bfseries \Large My first \etoc: TOC of
  \autoref{part:overview} (\nameref{part:overview})}
\tableofcontents \ref {toc:overview}
\endgroup
\end{filecontentsdef}

\filecontentsexec\foo

We could have used the line styles defined by \etoc, with
\csb{etocdefaultlines}, or the default document class styles with
\csb{etocstandardlines}, but we were a bit more ambitious here and wanted to
design our own. The technique is a simple one: each heading is in its own
paragraph, which may extend on multiple lines; it is responsible for setting
its own |\leftskip|.

This is a simple design which does not make provisions for page breaks
which should be discouraged in-between a section and a subsection
etc\dots{} as we only used it for the table of contents of this part, thus
with sections as top levels, there was no need to specify a style for
parts too (we defined a subsubsection line style but as it turns
out there are no subsubsections in this part). The two commands used are
\csb{etocsetstyle} for specifying the line styles, and
\csb{etocruledstyle} for the TOC global style.

The |\rightskip| is shared by all, and creates space where the page
numbers get printed. For an elaboration of this technique see the next
\autoref{sec:secondexample} as well as \autoref{ssec:tocwithdepthtags}
which provides a TOC with parts and paragraphs. Both allow multi-line
headings and employ a technique for putting page numbers in the right margin
which was inspired from what \LaTeX2e's |\@dottedtocline| macro does.

Here is how it was produced:

\filecontentsprint\foo
\attachfile[description={demo \the\value{section}}]{etocsnippet-\the\value{section}.tex}


\section{A second example}
\label{sec:secondexample}

This second example displays only the contents from
\autoref{part:linestyles} and \autoref{part:globalcmds}. This selection
is done via the technique of \emph{depth tags}, described in
\autoref{etocsettagdepth} and \autoref{ssec:tocwithdepthtags}. Its
layout is a bit like the one of the \hyperref[toc:main]{main document
  TOC}, although the line styles are coded very differently.

\begin{filecontentsdef}{etocsnippet-\the\value{section}.tex}{\foo}
\begingroup
\newcommand*{\DotsAndPage}
{\nobreak\leaders\hbox{\bfseries\normalsize\hbox to .75ex {\hss.\hss}}%
         \hfill\nobreak
         \makebox[\rightskip][r]{\bfseries\normalsize\etocpage}\par}

\etocsetstyle {part}
{\parindent 0pt
 \nobreak
 \etocskipfirstprefix}
{\pagebreak[3]\bigskip}
{\large\rmfamily\bfseries\scshape\centering
 \etocifnumbered{Part \etocnumber{} -- }{}\etocname\par}
{}

\etocsetstyle {section}
{\leftskip 0pt \rightskip .75cm \parfillskip-\rightskip
 \nobreak\medskip
 \etocskipfirstprefix}
{\leftskip 0pt \rightskip .75cm \parfillskip-\rightskip
 \pagebreak[1]\smallskip}
{\normalsize\rmfamily\bfseries\scshape
 \etocnumber. \etocname\DotsAndPage }
{\parfillskip 0pt plus 1fil\relax }

\etocsetstyle {subsection}
{\leftskip1cm\rightskip .75cm \parfillskip 0pt plus 1fil\relax 
 \nobreak\smallskip}
{}
{\footnotesize\sffamily\mdseries\itshape
 \etocname{} (\etocnumber, p. \etocpage). }
{\par\medskip}

\etocsettagdepth {preamble}   {none}
%\etocsettagdepth {overview}   {none}% not needed explicitely, keeps value
%\etocsettagdepth {arbitrarily}{none}
%\etocsettagdepth {examples}   {none}
%\etocsettagdepth {surprising} {none}
\etocsettagdepth {linestyles} {subsection}
\etocsettagdepth {globalcmds} {subsection}
\etocsettagdepth {custom}     {none}
%\etocsettagdepth {tips}       {none}
%\etocsettagdepth {etocandworld}{none}
%\etocsettagdepth {code}       {none}

\etocsettocstyle {\centering\LARGE\textsc{\contentsname}\par\nobreak\medskip}{}
\etocsetnexttocdepth {subsection}
\tableofcontents
\endgroup
\end{filecontentsdef}
\filecontentsexec\foo

The code:
\filecontentsprint\foo
\attachfile[description={demo \the\value{section}}]{etocsnippet-\the\value{section}.tex}

\section{A Beautiful Thesis example}

Here is a relatively  simple example of use of the package
functionalities. 
Let us set up some line styles. We choose a style for sections and
sub-sections which would be suitable for, respectively, sections and
sub-sections in an average length memoir. The line style specifications have
some redundancy for clarity, and do not care about what to do at possible page
breaks. Also, they do not worry about potential multi-column use.

\begin{filecontentsdef}{etocsnippet-\the\value{section}.tex}{\foo}
\begingroup % we start a group to keep the style changes local
\newlength{\tocleftmargin}    \setlength{\tocleftmargin}{5cm}
\newlength{\tocrightmargin}   \setlength{\tocrightmargin}{1cm}

\etocsetstyle{section}              % will pretend to be a Chapter
{\addvspace{1ex}\parfillskip0pt
 \leftskip\tocleftmargin            % (already done in title)
 \rightskip\the\tocrightmargin plus 1fil
 \parindent0pt\color{cyan}}         % (already done)
{\bfseries\LARGE\upshape\addvspace{1ex}\leavevmode}
{\llap{Chapter\hspace{.5em}{\etocnumber}\hspace{.75cm}}\etocname
 \hfill\makebox[-\tocrightmargin][l]{\makebox[0pt]{\etocpage}}\par}
{}

\etocsetstyle{subsection}           % will pretend to be a Section
{}
{\mdseries\large\addvspace{.5ex}\leavevmode}
{\llap{\etocnumber\hspace{.75cm}}\textit{\etocname}%
 \hfill\makebox[-\tocrightmargin][l]{\makebox[0pt]{\etocpage}}\par}
{}

\def\tmptitle{My Beautiful Thesis}
\etocsettocstyle{\color{cyan}\parindent0pt \leftskip\tocleftmargin
  \leavevmode\leaders\hrule height 1pt\hfill\ 
  \huge\textit{\tmptitle}\par}{\bigskip}

\tableofcontents \ref{toc:overview}
\endgroup
\end{filecontentsdef}

\filecontentsexec\foo

\filecontentsprint\foo
\attachfile[description={demo \the\value{section}}]{etocsnippet-\the\value{section}.tex}


\section{Linked list of the main package commands}


% 2022/08/29
% bataille avec multicols et LaTeX (j'ai essayé quote
% avec un \leftmargin négatif mais n'a pas donné résultat
% espéré)

% mais comme il se trouve qu'il y a la place on va passer en deux, pas
% trois colonnes, donc je laisse tomber le parshape!

% 2022/08/30
% Je sépare les macros les plus essentielles pour les mettre en avant

\begin{framed}\multicolsep0pt\relax
  \begin{multicols}{3}\parindent0pt\relax
\flushleft
    \csb{tableofcontents}\par
    (optional \csa{ref} or \csa{label})\par
    \csb{localtableofcontents}\par\columnbreak
    \csb{etocsettocstyle}\par
    \mbox{}\par
    \csb{etocsetnexttocdepth}\par\columnbreak
\flushright
    \makebox[\widthof{\csa{etocnumber}}][l]{\csb{etocname}}\par
% \llap does not trigger horizontal mode?
    \noindent
    \llap{\csb{etocsetstyle}
% \smash is not \long!
    \smash{$\left\{\parbox{0pt}{\mbox{}\endgraf
                                %\mbox{}\endgraf
                                \mbox{}\endgraf
                                \mbox{}\endgraf
                                \mbox{}\endgraf}\right.$}
    }%
    \csb{etocnumber}\par
    \makebox[\widthof{\csa{etocnumber}}][l]{\csb{etocpage}}\par
  \end{multicols}
\end{framed}

%\parshape 1 -1.5cm \dimexpr\linewidth+3cm\relax
%\begin{minipage}{\dimexpr\linewidth+3cm\relax}
\begin{multicols}{2}\parindent0pt\relax
  \csb{etocaftercontentshook}\par
  \csb{etocaftertitlehook}\par
  \csb{etocaftertochook}\par
  \csb{etocbeforetitlehook}\par
  \csb{etocdefaultlines}\par
  \csb{etocdepthtag.toc}\par
  \csb{etocdisplay}\par
  \csb{etocframedstyle}\par
  \csb{etocframed}\par
  \csb{etociffirst}\par
  \csb{etocifnumbered}\par
  \csb{etocignoredepthtags}\par
  \csb{etocignoretoctocdepth}\par
  \csb{etocimmediatedepthtag.toc}\par
  \csb{etocimmediatesettocdepth.toc}\par
  \csb{etocimmediatetoccontentsline}\par
  \csb{etocimmediatesetlocaltop.toc}\par
  \csb{etocinline}\par
  \csb{etoclink}\par
  \csb{etoclocalframed}\par
  \csb{etoclocaltop}\par
  \csb{etoclocalmulticol}\par
  \csb{etoclocalruled}\par
  \csb{etocmulticolstyle}\par
  \csb{etocmulticol}\par
  \csb{etocname}\par
  \csb{etocnumber}\par
  \csb{etocobeydepthtags}\par\columnbreak
\flushright
  \csb{etocobeytoctocdepth}\par
  \csb{etocpage}\par
  \csb{etocruledstyle}\par
  \csb{etocruled}\par
  \csb{etocsetlevel}\par
  \csb{etocsetlocaltop.toc}\par
  \csb{etocsetnexttocdepth}\par
  \csb{etocsetstyle}\par
  \csb{etocsettagdepth}\par
  \csb{etocsettocdepth}\par
  \csb{etocsettocdepth.toc}\par
  \csb{etocsettocstyle}\par
  \csb{etocskipfirstprefix}\par
  \csb{etocstandarddisplaystyle}\par
  \csb{etocstandardlines}\par
  \csb{etocthelinkedname}\par
  \csb{etocthelinkednumber}\par
  \csb{etocthelinkedpage}\par
  \csb{etocthelink}\par
  \csb{etocthename}\par
  \csb{etocthenumber}\par
  \csb{etocthepage}\par
  \csb{etoctoccontentsline}\par
  \csb{etoctoclines}\par
  \csb{localtableofcontents}\par
  \mbox{}\llap{\csb{localtableofcontentswithrelativedepth}}\par
  \csb{tableofcontents}\par
%\vspace{5\baselineskip}\hrule height 0pt
\end{multicols}
%\end{minipage}\par

The above is not an exhaustive list of all the package user commands, although
for legacy arbitrary reasons some of the more obscure commands are included
here.

\clearpage
% 15 octobre, je teste les tags
\etocdepthtag.toc {arbitrarily}

\part{Arbitrarily many TOCs, and local ones too}
% 13 octobre, ceci était une section avant

\thispartstats

\etocsettocstyle{}{}
\etocstandardlines
\localtableofcontents

\section{The \toc, \localtoc and \localtocwrdp commands}
\label{tableofcontents}
\label{localtableofcontents}
\label{localtableofcontentswithrelativedepth}

\begin{description}
\item[\toc] can be used arbitrarily many times in the document. Styling either
  globally the TOC or its individual entries is customizable at any time in the document.
\item[\localtoc] will print local tables of
contents: \emph{i.e.} all sections and sub-units inside a
given chapter, or all subsubsections and lower inside a given
subsection, etc... (see also \csb{etocsetnexttocdepth}).%
%
\footnote{As is explained in \autoref{sec:labeling} the syntax allows to
  create somewhere a local table of contents and to display it at some other
  location either before or after its origin.}%
\textsuperscript{,}%
\footnote{As is explained in \autoref{sec:tocdepth} \etoc allows at anytime to
  locally redefine the numeric levels associated to named ones, which brings
  great flexibility to achieve special effects, all done using only a single
  auxiliary file, the standard |.toc| file.}
%
\item[\localtocwrdp\marg{number}] can be used to override the document or
  current tocdepth setting (see \autoref{sec:tocdepth} for a discussion of
  tocdepth) to become relative to where the local TOC originates. For example,
  assuming the default numeric level assignments to standard sectioning units
\begin{verbatim}
\section{This is a section}
\localtableofcontentswithrelativedepth{+2}
\end{verbatim}
  will create a local table of contents taking into account the subsections
  and subsubsections inside this section, independently of what is the value
  of the |tocdepth| counter at this position in the document. If the numeric
  argument had been |3|, the local TOC would have displayed also paragraphs.
  If the section had been a chapter, and again for a relative tocdepth of |2|,
  the taken into account levels would have been sections and subsections.%
%
\footnote{The situation may be more complex, as the |.toc| file itself may
  well contain \texttt{\string\setcounter\{tocdepth\}\{...\}} commands. This
  is not recommended pratice with \etoc. See the discussion of
  \csb{etocsettocdepth.toc} and \csb{etocdepthtag.toc} for more on this.}
\end{description}

The macro \localtocwrdp is \textbf{new with |1.09|}.%
%
\footnote{Thanks to Tony \textsc{Roberts} for feature request.}
%

\section{Labeling and reusing elsewhere}
\label{sec:labeling}

\etoc allows the labeling of a TOC with (for example)
\csa{label\{toc:A\}} and will redisplay it elsewhere when
told \csa{tableofcontents}\csa{ref\{toc:A\}}. The actual
layout (title inclusive) used for the cloned TOC will be
decided locally. The line styles and toc display style
(including the title) will be the current ones and the
current value of the |tocdepth| counter is obeyed. As an
example the table of contents of 
\autoref{part:custom} is in a \hyperref[toc:d]{float} which appears
\vpageref{toc:d}. 
\begin{filecontentsdef}{etocsnippet-\the\value{section}.tex}{\foo}
\begin{figure}[ht!]
  \centering
  \begingroup
  \etocstandardlines 
  \renewcommand{\etocbkgcolorcmd}{\color{green!5}}
  \renewcommand{\etocbelowtocskip}{0pt\relax}
  \fboxsep1ex 
  \etocframedstyle [1]{\fbox{\makebox[.5\linewidth]{\etocfontminusone
        \hyperref[toc:c]{I am from far away}}}}
  \tableofcontents \label{toc:d} \ref{toc:c}
  \endgroup
\end{figure}
\end{filecontentsdef}
\filecontentsexec\foo

We used this: \filecontentsprint\foo
\attachfile[description={demo \the\value{section}}]{etocsnippet-\the\value{section}.tex} In the above example, not
only did we use |\ref{toc:c}| to print here the distant (local) table of
contents which has been labeled |toc:c| but we added a (possibly confusing)
|\label{toc:d}|.  This is done for the down-to-earth reason of being able
to use, as we did in the previous paragraph, |\vpageref{toc:d}|.
But if one wants to clone
again the original local table of contents, one must reference its original
label: \toc|\ref{toc:c}|.%
%
\footnote{Why does this author always give
complicated examples rather than down-to-earth ones?}
%
This original local table of contents is to be found \vpageref{toc:c}.

\section{A powerful functionality of \etoc: the
  re-assignment of levels with \csbhyp{etocsetlevel}}
\label{sec:tocdepth}

The intrinsic levels manipulated by \etoc are numeric: from
|-2| (which corresponds to |book| in the |memoir| class)
down (from the big to the small)
to |5| (|subparagraph|). But the assignment of a numeric level
to a given name can be modified at any time with the command
\csb{etocsetlevel}\marg{level\_name}\marg{number}. In conjunction
with the use of the \LaTeX{} |tocdepth| counter, this has
powerful applications: \meta{level\_name} does not have to
coincide with an actual document sectioning command, and \etoc
can be used to print arbitrary ``lists of things'', using no
other auxiliary file than the |.toc| file. This is
explained further in \autoref{part:surprising}.

\begin{framed}
  It is often said that in the standard classes, the sectioning
  level of |\part| is |0| in the classes not having a |\chapter|
  command, and |-1| in classes having a |\chapter| command. This
  is \emph{correct} for what regards the \emph{automatic
    numbering}, as is governed by the value of the |secnumdepth|
  counter; but it is \emph{wrong} for what regards the effect of
  the |tocdepth| counter: setting the |tocdepth| to |-1| in the
  |article| class just before |\tableofcontents| does \emph{not}
  prevent Parts from appearing in the Table of Contents. One has
  to set it to |-2| for that, whether in the |article| or in the
  |book| class.

  The canonical levels, a priori known to \etoc, are those of
  relevance to the \textbf{|tocdepth|} counter in the standard
  classes and are recapitulated in this table: \centeredline{
    \fbox{\begin{tabular}{rc}
        (|memoir| class) book&-2\\ part&-1\\ chapter&0 \\
        section&1\\ subsection&2 \\
        subsubsection&3 \\ paragraph&4 \\ subparagraph& 5
    \end{tabular}}}

\smallskip With \etoc, the user can easily print a local table of
contents inside a given subsection, where subsubsections will be
printed in the style of sections, paragraphs in the style of
subsections, and subparagraphs in the style of subsubsections, if
so desired. One can also decide to set everything to be at the level
|6| (never displayed by \etoc), except for example
paragraphs, promoted to be at level |1|, and then one obtains a nice
table of contents of all the paragraphs from the document! 
(|tocdepth| at least |1|)\footnotemark
\end{framed}

\footnotetext{and one should naturally not print this TOC of paragraphs in
  compatibility mode, which would insist on inserting a gigantic left
  margin.}

\section{The \csbhyp{etocsettocdepth} and \csbhyp{etocsetnexttocdepth} commands}
\label{etocsettocdepth}
\label{etocsetnexttocdepth}

The |tocdepth| counter has no bearing on what gets written to the |.toc| file;
its action is only on the actual typesetting of the table of
contents.\footnote{In the standard classes (at least), it also influences the
  \csa{listoftables} and \csa{listoffigures}, via \csa{@dottedtocline}.} In the
standard classes there is only one |\tableofcontents| possible, whereas with
\etoc, arbitrarily many are allowed, so one may change |tocdepth| to the
appropriate value (which decides the finest sectioning level displayed) again
and again each time a table of contents needs to be typeset.

\etoc provides \csb {etocsettocdepth}\marg{level} whose mandatory argument is
either 
numeric (from |-3| to |5|) or a division name such as |subsection| or
|subsubsection| or any name previously declared to \etoc with
\csb{etocsetlevel} (the keywords |all| and |none| are recognized, although not
corresponding to a document division). 
This does the appropriate |\setcounter{tocdepth}{numeric_level}|.

As is explained in the next subsection, |tocdepth| is used by |hyperref|, and
one must take steps to prevent its changes from influencing the bookmarks, too.
So, \etoc has \csb {etocsetnexttocdepth}\marg{level} whose influence ceases
immediately after the next table of contents. Thus, |\invisibletableofcontents|
is essentially |\etocsetnexttocdepth{none}\tableofcontents|.

The simplest course is thus to have after |\begin{document}| and before the
  first |\tableofcontents| a single instance of the \csb{etocsettocdepth}
  command, with argument the deepest level (or most commonly used deepest level)
  among the tables of contents of the document, and to use locally,
  where needed, \csb{etocsetnexttocdepth} before |\tableofcontents| or
  |\localtableofcontents|.

\begin{framed}
  It is possible to use \csb{etocsettocdepth} inside the first argument of
  \csb{etocsettocstyle} (possibly in conjunction with checking the
  \csb{etoclocaltop} value, \emph{which however will be up-to-date there only if
  \csb{etocchecksemptiness} was executed}). There is no worry then about
  possible impact on hyperref bookmarks later on, because \etoc always resets
  the |tocdepth| counter after typesetting a TOC to the value it had before
  it.

  Since |1.09| the macro \csb{etocsetnexttocdepth} works also if located in
  first argument of \csb{etocsettocstyle}, but there is no reason to use it
  there as \csb{etocsettocdepth} has no durable effet on the |tocdepth|
  counter if executed there.

  Check \csb{localtableofcontentswithrelativedepth} for a simpler way to
  control the depth of local tables of contents. This has the advantage of
  working reliably whether or not the \csb{etocchecksemptiness} is used.
\end{framed}

\subsection{The hyperref option \emph{bookmarksdepth}}
\label{ssec:bookmarksdepth}

When modifying the counter |tocdepth| for the purposes of
multiple uses of \toc or \localtoc, one should be aware that
package |hyperref| by default takes into account the
\emph{current} value of the |tocdepth| counter to decide
whether the |pdf| file will contain a bookmark corresponding
to sectioning commands encountered in the source file. Thus,
one typically needs to reset |tocdepth| to its previous
value after having temporarily modified it for a given table of
contents.

Or, there is the \emph{bookmarksdepth=n} option of package
|hyperref|, with \emph{n} the desired document bookmarks
maximal depth, which can be numeric or the name of a level known to
|hyperref|. This documentation previously passed |bookmarksdepth=3| as
option to |hyperref|, so even if |tocdepth| was left to |1|
by inadvertance after printing a certain table of contents 
this did not modify the bookmark tree of the |pdf| file. Now that
\csb{etocsetnexttocdepth} has been added to the package, we have used it
systematically and there was no need for  |bookmarksdepth=3| anymore.

\section[The command \csbhyp{etocsettocdepth.toc}]{The command
  \csbhyp{etocsettocdepth.toc} and
  \csbhyp{etocimmediatesettocdepth.toc}}
\label{etocsettocdepth.toc}
\label{etocimmediatesettocdepth.toc}

This command \csb{etocsettocdepth.toc} implements some functionality of
|tocvsec2|\footnote{\url{http://ctan.org/pkg/tocvsec2}. I thank Denis \textsc{Bitouzé} for drawing
  my attention to the incompatibility of this package with \etoc.}, a package
which however was incompatible with \etoc (it can still be used for its
|secnumdepth|-related commands, but its |toc|-related activities will get
canceled by \etoc) and more-or-less designed for a single table of contents.

The action of \csb{etocsettocdepth.toc} is totally different than the one of
\csb{etocsettocdepth}. Rather than modifying the |tocdepth| counter immediately,
it adds a line to the |.toc| file which, when executed inside a table of
contents will enact this change. 

The command \csb{etocsettocdepth.toc}, like
\csb{etocsettocdepth}, accepts both numeric and named
arguments. In the case of a named argument, the actual numeric
value to be used is not yet decided at the time the |.toc|
file is created; it will be the value currently specified for
the named level at the time each table of contents (not having
done |\etocignoretoctocdepth|) is typeset. 

The |tocdepth| counter will never be set to a value finer than its initial value
at the start of the table of contents: so adding commands
\csb{etocsettocdepth.toc} in the document is a way to \emph{restrict} locally
the depth of the table of contents. For example to prevent inclusion in the
tables of contents of the sub-sub-sections of a given chapter.

This
{\fbox{gets executed in ALL tables of contents.}}

Also \csb{etocimmediatesettocdepth.toc} is provided.  For explanations,
refer to the discussion of \csb{etocimmediatedepthtag.toc} in the
next section.

\subsection{The commands \csbhyp{etocobeytoctocdepth} and \csbhyp{etocignoretoctocdepth}}
\label{etocobeytoctocdepth}
\label{etocignoretoctocdepth}


So \csb{etocignoretoctocdepth} is provided to cancel the
\csb{etocsettocdepth.toc} mechanism when
needed; and \csb{etocobeytoctocdepth} will
re-activate it. The package does initially \csb{etocobeytoctocdepth}.

\section[The commands \csbhyp{etocdepthtag.toc} and \csbhyp{etocsettagdepth}]{The commands
  \csbhyp{etocdepthtag.toc}, \csbhyp{etocimmediatedepthtag.toc} and
  \csbhyp{etocsettagdepth}}
\label{etocdepthtag.toc}
\label{etocimmediatedepthtag.toc}
\label{etocsettagdepth}

% As mentioned above, when the argument to  \csb{etocsettocdepth.toc} isn't
% numeric but a named level the actual numeric level used is decided at the time
% the TOC gets typeset, thus with the \emph{shuffling abilities of \etoc}, one may
% obtain a very flexible control in the following way: one first declares with
% \csb{etocsetlevel} some
% dummy named level, say |partIII|, assigning it the invisible numeric level |6|.
% Then before the actual third |\part| command in the source one inserts
% \csb{etocsettocdepth.toc}|{partIII}|. At the location where the effect should
% cease one inserts in the source \csb{etocsettocdepth.toc}|{all}|. It is now
% possible to specify, each time one wants to typeset a TOC, what will be the
% finest level for the entries originating in the third part: one just has to do
% \csb{etocsetlevel}|{partIII}{1}| for example. This will limit to sections
% (if |tocdepth| was at least at that level at the time \toc is encountered).

% This method has some limitations:
% \begin{enumerate*}[label={(\roman*)}]
%   \item the second argument to \csb{etocsetlevel} must be numeric,
%   \item it can not be set to |-3| (which would be necessary if one wanted to
%     exclude an entire Book from a TOC in a |memoir| document with multiple such
%     Books \dots admittedly a possibly rare case!),
%   \item it is a bit of a hack as |partIII| is not a real division unit, but just
%     a \emph{tag}.
% \end{enumerate*} 

Release |1.07h| has a command \csb{etocdepthtag.toc} which
allows to control dynamically the which contents end up included in the
displayed TOCs (this documentation also decribed formerly a way
using \csb{etocsettocdepth.toc} with some dummy level name, which got
then set via \csb{etocsetlevel} according to what was locally needed,
but it was too hacky and I am not sure if it was understandable).

It is used as \csb{etocdepthtag.toc}\marg{tag\_name}, where the
\meta{tag\_name} is anything, and this will put the tag in the |.toc|
file. When typesetting a TOC, one issues a series of commands
\csb{etocsettagdepth}\marg{tag\_name}\marg{level} where the
\meta{level} may be either numeric (from |-3| to |5|) or the name of a
division unit known to \etoc, or |none| or |all|. The effect of the tag
inside the |.toc| file will then be to set the |tocdepth| counter to
the desired value, in real time (this can not get finer than the
initial value of |tocdepth| at the start of the TOC).

The added flexibility is thus that \csb{etocsetlevel} has not been used in a
kind of hacky way, that one may use named level depths, and the
keywords |none| and |all|.

As usual, once the tag depths have been set, they remain in effect until getting
redefined or seeing their scope expire via the closing of a group or of a
surrounding 
environment. For an example, see \autoref{ssec:tocwithdepthtags}.

When using \csb{etocdepthtag.toc} in combination with \LaTeX's |\include|,
data may not end up in the |.toc| file in the correct order.  For example in
this situation:
\begin{verbatim}
  \clearpage % or anything ending up causing its presence here right before
             % the \etocdepthtag.toc
  \etocdepthtag.toc{sometag}
  \include{some file containing sections}
\end{verbatim}
The tag will end up in the |.toc| file \emph{after} all section headings from
the included file.  The cause is that \LaTeX\ inserts immediately in the
main auxiliary file a command to input the auxiliary file of the included file
(which in turn, contains instructions to add data to the |.toc| file).  But
\csb{etocdepthtag.toc} does not internally use such immediateness, as it uses
the same interface as |\section| and alike commands when they want to write
extra data to the |.toc| file.

So%
%
\footnote{Thanks to Norman \textsc{Ramsey} who reported this problem, together
  with a fix, in July\dots 2016.  Sorry for long delay before updating
  \etoc six years later\dots}
%
|1.09f| adds \csb{etocimmediatedepthtag.toc} which will force the tag to be written
immediately to the |.toc| file (well, rather immediately to the |.aux| file,
so before the inclusion of the auxiliary file of the included file).

One should not use this variant systematically.  For example if your document
looks like:
\begin{verbatim}
\clearpage

\section{bbbb}

Some text

\etocdepthtag.toc{sometag}
\etocimmediatedepthtag.toc{someimmediatetag}
\section{cccc}

Some text

\end{document}
\end{verbatim}
then the |someimmediatetag| will end up being inserted in |.toc| file
\emph{before} the |bbbb| section.  This is because \LaTeX's |\section|
uses a \emph{delayed} write, not an \emph{immediate} one.  And
\csb{etocdepthtag.toc} wisely uses a \emph{delayed} write.

As it seems very hard programmatically to identify automatically if the
\emph{immediate} variant of \csb{etocdepthtag.toc} should be used, the package
provides two separate commands and it is up to user to make the correct
choice.


\subsection{The commands \csbhyp{etocobeydepthtags} and \csbhyp{etocignoredepthtags}}
\label{etocobeydepthtags}
\label{etocignoredepthtags}


After \csb{etocignoredepthtags}, the |.toc| depth tags are ignored (but
\csb{etocdepthtag.toc} still works). The package does initially
\csb{etocobeydepthtags} which makes \etoc react to the found tags in the
|.toc| file. 

\section{The commands \csbhyp{etocglobaldefs} and \csbhyp{etoclocaldefs}}
\label{etocglobaldefs}
\label{etoclocaldefs}

In \LaTeX{} the meaning of a command defined via |\newcommand\foo{...}| inside
an environment (or group) vanishes from \TeX's memory on exit from this
environment (or group). At times however it is needed to make definitions with
global scope, for this \TeX{} has the primitive prefix |\global|.

By default \etoc's definitions of \csb{etocname} etc... are local. This causes
problems in certain contexts such as TOC as tables (\autoref{sec:tocastable}, \autoref{ssec:tocastableold}) and also
with |enumitem| \emph{inline} variants of its standard environments, because
the command |\item| then closes a group (see \autoref{etocthelink}).

After \csb{etocglobaldefs}, \etoc will make its definitions of \csb{etocname}
etc... have global scope. For normal use this is not necessary. It does not hurt
either to activate it systematically. 

To return to the default, use \csb{etoclocaldefs}. Note that both
\csb{etocglobaldefs} and \csb{etoclocaldefs} actions are local to the
environment or group where they are used.


\section{Not displayed empty TOCs}

\subsection{The \csbhyp{etocchecksemptiness} command}
\label{etocchecksemptiness}
\label{etocdoesnotcheckemptiness}

The user needs to issue \csb{etocchecksemptiness} to tell \etoc to check whether
local tables of contents are empty and in case of emptiness to print nothing
at all.\footnote{Thanks to Paul Gaborit who asked for
such a feature.} This
can be useful to authors of \LaTeX{} classes who for example wish to have a
|\chapter| command doing systematically a \localtoc, or for
people producing files via automatic conversions and some of those might have
sectioning commands and others not.

«Emptiness» means that no \csa{contentsline} command would get executed within
the scope of the local table of contents --- empty line styles by themselves do
not make the TOC empty. \etoc always executes the \csb{etocaftertochook}
command; and the test for emptiness itself executes everything else found in
the |.toc| file. See \autoref{sec:addingtotoc} in this context.
\begin{enumerate}
\item the \csb{etocifwasempty} command discussed below can be used from inside
\csb{etocaftertochook}, and even from inside \csb{etocbeforetitlehook}.
\item there is also \csb{etocdoesnotcheckemptiness} (since |1.08i|.)
\end{enumerate}

The suppression of the heading (more precisely of the toc display style
elements) may be effective only for the final \LaTeX{} runs. For example in
the situation of a \toc|\ref{foo}| where the label |foo| is
not yet recognized, the heading (but not the contents) is printed and the TOC
is declared non-empty. Or, if one adds a \localtoc to a document, on the next
run, the test for emptiness will in fact apply to the next one, and the last
local TOC of the document will have its contents temporarily unknown to \etoc,
hence will be declared non empty, and the heading will be printed.

For a finalized document compiled with initially no auxiliary files, the first
\LaTeX{} run will declare all local TOCs non empty and print for each of them a
heading (and no contents naturally). The second \LaTeX{} run will then
correctly decide which local TOC is empty or not.

\subsection{The \csbhyp{etocnotocifnotoc} command}
\label{etocnotocifnotoc}

The user can then extend the emptiness-checking to the global TOCs with
\csb{etocnotocifnotoc}. May I respectfully give the advice then to rather do
none of |\usepackage{etoc}| nor \toc ? |;-)|. Well, there is always the case
of batch conversions of documents having or not sectioning units.

\subsection{The \csbhyp{etocifwasempty} command}
\label{etocifwasempty}
\label{etocxifwasempty}

The command \csb{etocifwasempty}\marg{YES}\marg{NO} executes \meta{YES} if
the previous TOC was found to be empty and \meta{NO} if its was not so. This
may serve to act appropriately after a truly empty TOC. If
\csb{etocchecksemptiness} has not been issued, this conditional always
executes the \meta{NO} branch.

This command is robust, and \csb{etocxifwasempty} is its expandable
version.

\fbox{Do not forget the second argument: at least an empty pair of braces |{}|
  must be present.}

This conditional may wrongly say that the local TOC is empty or not empty
until \LaTeX{} compilations stabilize. But if it says that a local TOC is
empty, this does mean that \etoc considered the just encountered local table
of contents to be empty (for that run) and thus printed nothing (not even a
|\par|).

% pas traduit
\section{The \csbhyp{etoclocaltop} command}
\label{etoclocaltop}

\textbf{New with 1.09 (2019/03/09)}.

Within either the TOC style
(\csb{etocsettocstyle}) or the local title styles (\csb{etocsetstyle}), the
control sequence \csb{etoclocaltop} is made equivalent for the duration of
\csb{localtableofcontents} to a numeric (self-delimiting) denotation of the
current top level.

Thus: it will in numeric contexts (|\ifnum|, |\ifcase|, ...) represent zero
for a local TOC corresponding to chapter, or one if in a section, or two if in
a subsection, etc..., assuming of course here that the default levels are
obeyed (see \autoref{sec:tocdepth}).

\begin{framed}
  \csb{etoclocaltop} from inside the TOC heading (first argument of
  \csb{etocsettocstyle}) has the correct value \emph{only under
    \csb{etocchecksemptiness} regime}. Special circumstances correspond to
  some special values:
  \begin{description}[nolistsep]
  \item[|-3|] (|-\thr@@|)\newline
    signals that \etoc considers the local TOC to be
    ``unknown''; this happens at the last local TOC, for the first \LaTeX\ run
    after adding a new \localtoc to the document. In doubt, \etoc assumes the
    TOC will prove non empty, hence it prints (independently of whether the
    check for emptiness was activated or not) the heading as specified by
    \csb{etocsettocstyle}. Thus, check if \csb{etoclocaltop} gives |-3| as a
    a \meta{number} to detect that situation from within the first argument of
    \csb{etocsettocstyle}, if desired.
  \item[|-1000|](|-\@m|)\newline  is in case of a \localtoc
    being considered ``known'' (although it may still refer to the data in the
    |.toc| file from the previous run) but without the check for emptiness
    having been executed.
  \item[|-10000|](|-\@M|)\newline  is the value when accessed from the title
    of a global TOCs.
  \end{description}
\end{framed}
\begin{framed}
  When executed from within a local table of contents \textbf{line styles}
  (\csb{etocsetstyle}), \csb{etoclocaltop} always will hold the correct value,
  whether or not the emptiness check was executed.

  For a global table of contents however, it will always keep the value |-3|.
\end{framed}

Attention! \cs{etoclocaltop} is only to be queried; modifying it is strictly
forbidden and falls under the most rigorous prosecution allowed by federal
law.

\section{Adding commands to the \texorpdfstring{\texttt{.toc}}{.toc} file}
\label{sec:addingtotoc}

We described above \csb{etocsettocdepth.toc} and \csb{etocdepthtag.toc} which
both insert commands inside the |.toc| file. An even more general mechanism of
adding ``action tags'' to the |.toc| file could be envisioned, but this would
just be a wrapper for direct use of |\addtocontents{toc}{\something}|.

One should be cautious when adding in this way
things
to the |.toc| file. For example, inserting
\csa{addtocontents}|{toc}{\string\clearpage}|
just
before a \csa{part} to fix the problem when some part entry (in
the table of contents) is isolated at the bottom of one page,
will cause problems with multiple TOCs: this \csa{clearpage}
will be executed by \etoc each time a \toc or \localtoc
command is encountered! The more prudent thing is to do
rather: {\csa{addtocontents}|{toc}{\string\myclearpage}|,}
to have a |\let\myclearpage\relax| at the top level of the
document and  to use where needed something like:
\begin{verbatim}
\let\myclearpage\clearpage
\tableofcontents
\let\myclearpage\relax
\end{verbatim}
The |memoir| class has the command \csa{settocdepth} which
writes a \csa{changetoc\-depth} command inside the |.toc| file.
This will impact the typesetting by \etoc of \emph{all} tables
of contents, with (possibly) unexpected results: imagine the
document has \csa{settocdepth}|{chapter}| at some point to
avoid having the sections from subsequent chapters be listed
in the main table of contents. Then a local table of contents
in one of these chapters will print a title but will be
without any entry. 

As the |memoir| class by itself allows multiple\toc
  these issues already arise there,
  independently of \etoc, see page 170 of the |memoir|
  manual.

For this specific issue, the commands \csb{etocsettocdepth.toc},
\csb{etocignoretoctocdepth} and \csb{etocobeytoctocdepth} are the way to go; or
their variants \csb{etocdepthtag.toc} and \csb{etocsettagdepth}.

As an aside, any |\setcounter{tocdepth}{n}| command added directly to the |.toc|
file sees its effect (since release |1.07g|) canceled at the end of each table
of contents, which automatically does a |\setcounter{tocdepth}{previous_value}|
with the value active on entering the table of contents.

\subsection{The hyperref option \emph{hidelinks}}\label{ssec:hidelinks}

The colored links (and also the rectangle links) are a bit
annoying when used in tables of contents, especially when
the document uses \etoc and has plenty of them! One may wish
for having colored links, \emph{except} for those within
table of contents!
Indeed, why would things in TOCs need to be either framed in
rectangles or colored, when the user \emph{already expects
  them to be links}?

I use the following trick:  either in the preamble using
|\AtBeginDocument|, or right after |\begin{document}|, I
  have the command
  \centeredline{|\addtocontents{toc}{\protect\hypersetup{hidelinks}}|}

  \begin{framed}
    All TOCs typeset by \etoc have their contents done
    within a group (as if enclosed in an environment). So
    the command \csa{hypersetup}|{hidelinks}| will be
    executed by \emph{each} TOC, but its effect will be
    limited to that TOC. 
  \end{framed}

  I found out experimentally that the option |hidelinks| could
  indeed be set many times with |\hypersetup| (this is not the
  case of all |hyperref| options).


\clearpage
\etocdepthtag.toc {examples}
\part{Examples}\label{part:examples}

\thispartstats %% (pas de sous-section)

\etocstandardlines
\etocsettocstyle {}{\medskip}
\localtableofcontents

We present some additional examples. To understand all code snippets in detail,
one will possibly need to have first browsed through \autoref{part:linestyles}
and \autoref{part:globalcmds}.

\section{Testing the compatibility mode}

As a further example we now print the local table of contents
of \autoref{part:globalcmds}. First we will test the compatibility mode.\footnote{the
present document uses the |scrartcl| class, and we check here that
the \etoc compatibility mode does respect the customizing done via the
class commands.}   The original was invisibly defined with a label at the
beginning of \autoref{part:globalcmds}.
\begin{verbatim}
\begingroup % to keep in particular toc=left with local effect
\KOMAoptions{toc=left}
\etocstandarddisplaystyle % necessary for the display to obey toc=left
\etocstandardlines
\tableofcontents \ref{toc:globalcmds}
\endgroup
\end{verbatim}
\begingroup
\KOMAoptions{toc=left}
\etocstandarddisplaystyle
\etocstandardlines
\tableofcontents \ref{toc:globalcmds}
\endgroup

\section{Another compatibility mode}\label{sec:anothercompat}

As explained in \autoref{subs:compat}, the commands
\csb{etocstandardlines} and \csb{etocstandarddisplaystyle} tell \etoc to,
essentially, act as an observer. The document class layout for the table of
contents is then perfectly obeyed. There is no way to customize this standard
layout (change fonts, margins, vertical spacings, etc...) from within the
package. For this, use some package dedicated to this task; because \etoc either
is (temporarily perhaps) in compatibility mode with no customization on its part
possible, or the user has specified the layout in \csb{etocsetstyle} commands
(and \csb{etocsettocstyle}) and is (supposedly...) in complete control.

Well, there is actually an alternative. It is possible to use the
\csb{etocsetstyle} commands to recreate an artificial compatibility mode, in
order to achieve effects like the following, all things being otherwise equal to
the document class defaults:
\begin{enumerate}[noitemsep]
\item get the |hyperref| link to encapsulate only the names, but not the numbers
  of each entry of the table of contents,
\item use the document class style for chapters and sections, but modify it only
  for subsections,
\item do either of the above only for some portions of the table of contents.
\end{enumerate}

Here is how to proceed.

This has become easier since release |1.08k| as now \etoc preserves
automatically in \csb{etocsavedsectiontocline}, \csb{etocsavedchaptertocline}
etc... the meaning of the \LaTeX\ |\l@section|, |\l@chapter|, etc... macros as
they were at the time the TOC is typeset.

\begin{filecontentshere}{etocsnippet-\the\value{section}-A.tex}
\makeatletter
\newcommand{\MyStandardTOC}{%
  \begingroup
  % for the book or article classes:
  %\etocsetstyle{part}{}{}
  %  {\etocsavedparttocline{\etocnumber\hspace{1em}\etocname}{\etocpage}}{}%
  % for the scrbook or scrartcl classes:
  \etocsetstyle{part}{}{}
    {\etocsavedparttocline{\numberline{\etocnumber}\etocname}{\etocpage}}{}%
  % following is identical in book/article/scrbook/scrartcl classes:
  \etocsetstyle{chapter}{}{}   %%% only for book and scrbook
    {\etocsavedchaptertocline{\numberline{\etocnumber}\etocname}{\etocpage}}{}%
  \etocsetstyle{section}{}{} 
    {\etocsavedsectiontocline{\numberline{\etocnumber}\etocname}{\etocpage}}{}%
  \etocsetstyle{subsection}{}{}
    {\etocsavedsubsectiontocline{\numberline{\etocnumber}\etocname}{\etocpage}}{}%
  % etc... if further sectioning units are used
  \etocstandarddisplaystyle % this is for the title, page-marks, etc...
  \tableofcontents     
  \endgroup}
\makeatother
\end{filecontentshere}
\attachfile[description={demo \the\value{section}-A}]{etocsnippet-\the\value{section}-A.tex}

One can add to the above arbitrary text formatting commands, for example
replace |\etocpage| by |\textcolor{blue}{\etocpage}|.

If the document has only one table of contents then there is no need
to put the commands inside a macro, or even inside a group.\footnote{and if
moreover one just wants to keep the same layout as in the default, one may
question why using \etoc... there is \emph{one} good reason: numbers and names
are separately \texttt{hyperref} links, whereas normally there is only one link
holding both the number and the name corresponding to one toc entry.} With these
commands 
\etoc will construct a TOC completely identical to what would have been done by
one of the document class: |article|, |book|, |scrartcl|, |scrbook|.\footnote{For the
|memoir| class, one needed prior to \etoc |1.08k| a bit more: each of the command \csa{booknumberline},
\csa{partnumberline} and \csa{chapternumberline} had to be saved. They can now
be used directly in the line styles, because their meanings are not modified
anymore by \etoc during its TOC typesetting.}
The number and the name of each entry are each separately an |hyperref| link, as
is always the case with \etoc, when not in compatibility mode. Replacing
\csb{etocnumber} with \csb{etocthenumber} will give a TOC where the numbers are
not links anymore, but the names still are. Or one may decide to use \csb{etocthename}
and keep an hyperlinked number with
\csb{etocnumber}. 

Here is a subtler example where one only marginally modifies the
sections (adding color to the number and removing the |hyperref| link) and keeps
the subsections as in the default, \emph{except} for those of one specific
section, for which the layout is completely modified:
\MyQuasiStandardTOC{\ref{toc:overview}}
\bigskip
This example only has sections and subsections, and the code used in \csa{MyStandardTOC} was:
\begin{filecontentshere}{etocsnippet-\the\value{section}-B.tex}
\etocsetstyle{section}{}
  {\ifnum\etocthenumber=4
      \etocsetstyle{subsection}
        {\par\nopagebreak\begingroup
         \leftskip1.5em \rightskip\@tocrmarg \parfillskip\@flushglue 
         \parindent 0pt \normalfont\normalsize\rmfamily\itshape
         % \columnsep1em
         % \begin{minipage}{\dimexpr\linewidth-\leftskip-\rightskip\relax}%
         % \begin{multicols}{2}%
         \etocskipfirstprefix}
        {\allowbreak\,--\,}
        {\etocname\ \textup{(\etocnumber)}}
        {.\par\endgroup}%
        % {.\par\end{multicols}\end{minipage}\par\endgroup}%
    \else
      \etocsetstyle{subsection}
       {}{}
       {\etocsavedsubsectiontocline{\numberline{\etocnumber}\etocname}{\etocpage}}
       {}%
    \fi} 
  {\etocsavedsectiontocline{\numberline{{\color{cyan}\etocthenumber}}\etocname}{\etocpage}}
  {}%
\end{filecontentshere}
\attachfile[description={demo \the\value{section}-B}]{etocsnippet-\the\value{section}-B.tex}
Notice the page head-mark added by this standard TOC. Sections and subsections
are printed exactly as in the default (except for the subsections of one
specific user-chosen section and except for the color of the section numbers),
with no need to specify explicitely any length, font or other formatting
instructions. But we had to examine the |scrartcl| sources to determine what to
use for \csa{leftskip} and \csa{rightskip} for our customized section
entries.

\section{Emulating the book class}\label{sec:thirdexample}

As explained in \autoref{subs:compat}: without explicit use of an
\csb{etocsetstyle} command the package will leave to the document class the
hand regarding the ``toc line styles''. It is sometimes asked by users (for
example those using \etoc for its \csb{localtableofcontents}) how to stay
close to but not completely identical with the design implemented by the
standard classes, such as |book|. I can recommend package |tocloft| for this,
as it is compatible with \etoc (see \autoref{subs:tocloft}) and thus \etoc will
obey the |tocloft| customizations (as long as no use has been made of
\csb{etocsetstyle}). It is also possible to modify only the style for, say,
sections and leave the parts, chapters, subsections as in the document class,
via the technique from \autoref{sec:anothercompat}.

But for complete control, here is a translation of the |book| class code into
\etoc lingua. It is then easy to modify the relevant lengths or adjust the
used fonts. I thank \textsc{Denis Bitouzé} for prompting me to include this in
the \etoc manual, as it resulted from some conversation we had about this. The
code is not 100\% faithful to the |book| class, and particularly its rendering
of (multi-line) non-numbered units differs (... I think, as I copied pasted as
is the code from where I had stored it and did not do much thinking about it
again). Some proficiency in low-level \TeX\ and \LaTeX\ macros is needed to
understand what the code says, but for modifying fonts or some lengths such
in-depth understanding is not needed.

With some extra code one can \emph{automatically adjust the widths} assigned
to typesetting sectioning numbers in order to prevent overflows, even with for
example \MakeUppercase{\romannumeral 38}; but this is a more advanced feature
which I have moved to \autoref{sec:thirdexampleextra}.

First we set up some lengths. I use macro registers, not real \LaTeX\ lengths.
When using |em|'s however, this means that one must pay attention to when the
actual dimension assignment is made, as this will then depend upon the current
font settings. In the code below, at the location where the \csa{TOCnumwidthB}
and \csa{TOCnumwidthC} will be used, the |1em| from their specification will
be matched to the normal medium series font, not the bold font; this is
deliberate so that one can compare more readily with the other dimensions;
besides, with the \csa{TOCcomputenumwidths} from
\autoref{sec:thirdexampleextra} these macros will actually hold a dimension
using |pt| as dimensional unit.

\begin{filecontentshere}{etocsnippet-\the\value{section}-A.tex}
% it will be easy to globally shift the TOC horizontally if needed
\def\TOCleftmargin     {0pt}
\def\TOCrightmargin    {2.55em}% like LaTeX's \@tocrmarg

% this is for dotted leaders
\newbox\TOCleaderbox
\def\TOCleaderboxwidth {0.7777em}% about like what standard classes do

% vertical spacing
\def\TOCverysmallvskip {0pt plus .2pt}
\def\TOCmedvskip       {1em plus 1pt}
\def\TOCbigvskip       {2.25em plus 1pt}

% the ``numwidths'' for typesetting the numbering of division units.
% I don't recall exactly how (and for which fonts) these figures were chosen.
% They quickly prove too small if using Roman numerals (as do too the book
% class defaults even though they are a bit larger).
\def\TOCnumwidthB {1.5em} % chapter
\def\TOCnumwidthC {2.278em}% section, I think default is 2.3em
\def\TOCnumwidthD {3.056em}% analog in standard class is 3.2em
\def\TOCnumwidthE {3.833em}% analog in standard class is 4.1em
\def\TOCnumwidthF {4.611em}% analog in standard class is 5em
\def\TOCnumwidthG {5.389em}% analog in standard class is 6em

% The code for the ``global toc style''.

\newcommand*\TOCglobalstyle {%
\etocsettocstyle
   {\if@twocolumn \@restonecoltrue \onecolumn \else \@restonecolfalse \fi
    \parindent\z@ \leftskip\z@skip \rightskip \z@skip
    \setbox\TOCleaderbox\hbox to \TOCleaderboxwidth{\hss.\hss}%
    \chapter *{\noindent\kern\TOCleftmargin\relax % uses "pt"...
        \contentsname
        \@mkboth {\MakeUppercase \contentsname}{\MakeUppercase \contentsname}}%
    \rightskip    \TOCrightmargin\relax
    \parfillskip -\rightskip % or a smaller value if desired
    \leftskip     \TOCleftmargin \relax }
   {\if@restonecol \twocolumn \fi\cleardoublepage}%
%
\etocsetstyle{part}
 {}
 {\addpenalty {-\@highpenalty}%
  \addvspace \TOCbigvskip
  \leavevmode
   {\large \bfseries % use a group to limit font change
      \interlinepenalty\@M
      \etocifnumbered{\etocnumber\hspace{1em}}{}%
      \etocname
      \nobreak\hfil\makebox[-\parfillskip][r]{\etocpage}}\par
  \nobreak
  }
 {}
 {}%
%
\etocsetstyle{chapter}
 {\advance\leftskip\TOCnumwidthB\relax}
 {\addpenalty {-\@highpenalty }%
  \vskip \TOCmedvskip\relax
  \leavevmode
  {\interlinepenalty\@M
   \etocifnumbered
      {\llap{\makebox[\TOCnumwidthB][l]{\bfseries\etocnumber}}}
      {\advance\leftskip-\TOCnumwidthB\relax}%
   \bfseries\etocname
      \nobreak\hfil\makebox[-\parfillskip][r]{\etocpage}\par }%
  \penalty \@highpenalty 
  }
 {}
 {\advance\leftskip-\TOCnumwidthB\relax}%
%
 \TOCsetlinestyle {section}      {\TOCnumwidthC}%
 \TOCsetlinestyle {subsection}   {\TOCnumwidthD}%
 \TOCsetlinestyle {subsubsection}{\TOCnumwidthE}%
 \TOCsetlinestyle {paragraph}    {\TOCnumwidthF}%
 \TOCsetlinestyle {subparagraph} {\TOCnumwidthG}%
}% end of \TOCglobalstyle

%The common code for line styles is abstracted into a macro:
 
\newcommand\TOCsetlinestyle [2]{% #1= unit, #2= numwidth as macro
\etocsetstyle{#1}
 {\advance\leftskip#2\relax}
 {\vskip \TOCverysmallvskip\relax
  \leavevmode
  {\interlinepenalty\@M
   \etocifnumbered
     {\llap{\makebox[#2][l]{\etocnumber}}}{\advance\leftskip-#2\relax}%
   \etocname
   \nobreak\leaders \copy\TOCleaderbox
   \hfil\makebox[-\parfillskip][r]{\etocpage}%
   \par }%
 }
 {}
 {\advance\leftskip-#2\relax}%
}
\makeatother
\end{filecontentshere}
\attachfile[description={demo \the\value{section}-A}]{etocsnippet-\the\value{section}-A.tex}
Nota Bene: the code deliberately handles the non-numbered sectioning units
unlike the way of the standard document classes (particularly regarding the
alignment of multi-line headings.)

The whole thing was encapsulated in \csa{TOCglobalstyle}, because we also want
a \csa{TOClocalstyle} for local tables of contents which typically will want
to use |\section*| rather than |\chapter*| and not insert page marks in the
headers. The \csa{TOClocalstyle} is to be issued once, after the main document
TOC, or rather before using \localtoc. If one wants a full
TOC at end of document one will naturally have to issue again
\csa{TOCglobalstyle} there.

\begin{filecontentshere}{etocsnippet-\the\value{section}-B.tex}
\makeatletter
\newcommand*\TOClocalstyle {%
\etocsettocstyle
    {\if@twocolumn \@restonecoltrue \onecolumn \else \@restonecolfalse \fi
     \setbox\TOCleaderbox\hbox to \TOCleaderboxwidth{\hss.\hss}%
     \parindent\z@
     \dimen@ 2.25em % for left indenting
     \section *{\kern\dimen@ % use of \dimen@ works here by sheer luck
       \contentsname
       % un-comment this if marks are wanted:
       %\@mkboth {\MakeUppercase \contentsname}{\MakeUppercase \contentsname}%
       }% end of \section
     \parskip \z@skip
     \vspace{-1.25\baselineskip}% somewhat ad hoc
     \leftskip  2.25em
     \rightskip 4.5em
     \advance\rightskip-\TOCrightmargin\relax
     \leavevmode\leaders\hrule\@height\p@\hfill\kern\z@\par
     \rightskip 4.5em 
     \parfillskip -\TOCrightmargin\relax }
    {\nobreak\vskip-.5\baselineskip
     \leavevmode\leaders\hrule\@height\p@\hfill\kern\z@\par
     \bigskip
     \if@restonecol \twocolumn \fi }%
%
\etocsetstyle{section}
 {\advance\leftskip\TOCnumwidthC\relax}
 {\addpenalty \@secpenalty
  \etociffirst{}{\addvspace{\TOCmedvskip}}%
  \leavevmode
  {\interlinepenalty\@M
   \bfseries\etocifnumbered
      {\llap{\makebox[\TOCnumwidthC][l]{\etocnumber}}}
      {\advance\leftskip-\TOCnumwidthC}%
   \etocname\nobreak\hfil\makebox[-\parfillskip][r]{\etocpage}\par }%
  \penalty \@highpenalty }
 {}
 {\advance\leftskip-\TOCnumwidthC\relax}%
% the rest is identical with code for global tocs:
 \TOCsetlinestyle {subsection}   {\TOCnumwidthD}%
 \TOCsetlinestyle {subsubsection}{\TOCnumwidthE}%
 \TOCsetlinestyle {paragraph}    {\TOCnumwidthF}%
 \TOCsetlinestyle {subparagraph} {\TOCnumwidthG}%
}% end of \TOClocalstyle
\makeatother
\end{filecontentshere}
\attachfile[description={demo \the\value{section}-B}]{etocsnippet-\the\value{section}-B.tex}
As mentioned previously, this handles non-numbered (multi-line) sectioning
units somewhat differently from what happens in the standard document classes.

For some reason this code has some hard-coded |2.25em| and |4.5em| which were
not abstracted into macros or lengths. The code inserts horizontal rules above
and below the TOC contents in a non-separable by pagebreak way.

See \autoref{sec:thirdexampleextra} for more.

\section{A framed display}

We now opt for a ``framed'' style, using the package default
line styles and some colors added (it has been put in a float which appears
\vpageref{toc:b}).

%
% (13 octobre 2013)
% \footnote{inside the |figure| environment and before the
%   framed toc, which uses |multicols|, we added \csa{normalcolor} as work-around
%   to an interaction bug (related to the \csa{color\{red\}} command we added to
%   the |.toc| file) between |multicols|, |color| and the |figure|
%   environment. This bug has nothing to do with \etoc.}
%  RETIRÉ le 28 avril 2015 pour 1.08f

\begin{filecontentshere}{etocsnippet-\the\value{section}-A.tex}
\etocdefaultlines
\begingroup 
\renewcommand{\etoccolumnsep}{2em}
\renewcommand{\etocinnerleftsep}{1.5em}
\renewcommand{\etocinnerrightsep}{1.5em}
% specify a background color for the toc contents
\renewcommand{\etocbkgcolorcmd}{\color{yellow!10}}
% set up the top and bottom rules 
\renewcommand{\etoctoprule}{\hrule height 1pt}
\renewcommand{\etoctoprulecolorcmd}{\color{red!25}}
\renewcommand{\etocbottomrule}{\hrule height 1pt}
\renewcommand{\etocbottomrulecolorcmd}{\color{red!25}}
% set up the left and right rules
\renewcommand{\etocleftrule}{\vrule width 5pt}
\renewcommand{\etocrightrule}{\vrule width 5pt}
\renewcommand{\etocleftrulecolorcmd}{\color{red!25}}
\renewcommand{\etocrightrulecolorcmd}{\color{red!25}}
% use \fcolorbox to set up a colored frame for the title
\fboxrule1pt
\renewcommand{\etocbelowtocskip}{0pt\relax}
\etocframedstyle {\normalsize\rmfamily\itshape
  \fcolorbox{red}{white}{\parbox{.8\linewidth}{\centering
      This is a table of contents \`a la \etoc, but just for
      the sections and subsections in this part. As it is put
      in a frame, it has to be small enough to fit on 
      one page. It has the label |toc:b|.}}}
\begin{figure}[ht!]
  \centering
\tableofcontents \label{toc:b} \ref{toc:globalcmds}
\end{figure}
\endgroup
\end{filecontentshere}
\attachfile[description={demo \the\value{section}-A}]{etocsnippet-\the\value{section}-A.tex}

\filecontentsexec\filecontentsheremacro

%\begin{figure}[ht!]
%  \centering
% plus nécessaire ?
%\normalcolor % work-around to a bug involving color and multicols (and figure)
% \tableofcontents \label{toc:b} \ref{toc:globalcmds}
% \end{figure}
% \endgroup

% Il y a un color leak du framed mais uniquement lorsqu'il est mis dans le
% float. 2013/10/13, qui révèle un bug (?? NON) du style framed je vais regarder
% mais bon. Le leak apparaît avec ruled aussi, et même avec juste multicolstyle
% MAIS PAS EN UNE SEULE COLONNE (même framed ou ruled). il semble qu'il y aie
% donc un problème d'interaction avec multicol là. à voir. Pas le temps
% maintenant.

% 2013/10/14
% il s'agit en fait d'un bug de color+multicols+figure qui n'a rien à voir avec
% etoc: 
% http://tex.stackexchange.com/questions/138783/color-leak-from-multicols-within-a-figure
% J'ai trouvé le work-around qui consiste simplement à ajouter un \normalcolor
% _avant_ le multicols à l'intérieur de figure

\section{Another TOC with a background color}\label{ssec:again}

Let us now try out some more sophisticated line styles. The display will use
the \csb{etocframedstyle} package command, which requires that the produced
table of contents fits on a single page. We wrap it up in a
\hyperref[toc:floating]{figure environment} showing up
\vpageref{toc:floating}.

This design uses the \etoc `framed' style with a background color. The frame
borders have been set to have the same color as the one serving as background
for the entire thing. It would be advantageous to use rather inside
\csb{etocsettocstyle} commands from a package like |tcolorbox| as this allows
sophisticated breakable boxes (with |TikZ/pgf| for decoration.)

The details of the line styles used here are a bit involved, they were written
by the author at some early stage of this documentation and have only been
slightly revised to use more \LaTeX-commands and less \TeX-primitives. Similar
code is used also for \hyperref[toc:clone]{this other toc}.

% archivage de commentaires
% 1.07l on the occasion of traduction into German documentation:
     % APRIL 26, 2014 Improvement in the section style for better placement of
     % page number when the section name is more than one line long. Use of
     % \makebox rather than \hbox, to be more LaTeX like.
% attention car \ref{toc:floating} fera référence au compteur de
% toutes les toc, pas visibletoc. 

\begin{filecontentshere}{etocsnippet-\the\value{section}.tex}
\begin{figure}[htbp!]\centering
\colorlet{subsecnum}{black}
\colorlet{secbackground}{green!30}
\colorlet{tocbackground}{red!20!green!20}

\renewcommand{\etocbkgcolorcmd}{\color{tocbackground}}
\renewcommand{\etocleftrulecolorcmd}{\color{tocbackground}}
\renewcommand{\etocrightrulecolorcmd}{\color{tocbackground}}
\renewcommand{\etocbottomrulecolorcmd}{\color{tocbackground}}
\renewcommand{\etoctoprulecolorcmd}{\color{tocbackground}}

\renewcommand{\etocleftrule}{\vrule width 3cm}
\renewcommand{\etocrightrule}{\vrule width 1cm}
\renewcommand{\etocbottomrule}{\hrule height 12pt}
\renewcommand{\etoctoprule}{\hrule height 12pt}

\renewcommand{\etocinnertopsep}{0pt}
\renewcommand{\etocinnerbottomsep}{0pt}
\renewcommand{\etocinnerleftsep}{0pt}
\renewcommand{\etocinnerrightsep}{0pt}

\newcommand\shiftedwhiterule[2]{%
    \hbox to \linewidth{\color{white}%
    \hskip#1\leaders\vrule height1pt\hfil}\nointerlineskip
    \vskip#2}

\etocsetstyle{subsubsection}
{\etocskipfirstprefix}
{\shiftedwhiterule{\leftskip}{6pt}}
{\sffamily\footnotesize
  \leftskip2.3cm\hangindent1cm\rightskip.5cm\relax
  \makebox[1cm][l]{\color{subsecnum}\etocnumber}%
  \color{black}\etocname
  \nobreak\leaders\hbox to.2cm{\hss.}\hfill
  \rlap{\makebox[.5cm][r]{\etocpage\hspace{.1cm}}}\par
  \nointerlineskip\vskip3pt}
{}

\etocsetstyle{subsection}
{\etocskipfirstprefix}
{\shiftedwhiterule{1.5cm}{6pt}}
{\sffamily\small
  \leftskip1.5cm\hangindent.8cm\rightskip.5cm\relax
  \makebox[.75cm][l]{\color{subsecnum}\etocnumber}%
  \color{black}\etocname
  \nobreak\leaders\hbox to.2cm{\hss.}\hfill
  \rlap{\makebox[.5cm][r]{\etocpage\hspace{.1cm}}}\par
  \nointerlineskip\vskip3pt}
{}

\newcommand{\coloredstuff}[2]{%
            \leftskip0pt\rightskip0pt\parskip0pt
            \fboxsep0pt % \colorbox uses \fboxsep also when no frame!
       \noindent\colorbox{secbackground}
               {\parbox{\linewidth}{%
                    \vskip5pt
                    {\noindent\color{#1}#2\par}\nointerlineskip
                    \vskip3pt}}%
       \par\nointerlineskip}

\etocsetstyle{section}
{\coloredstuff{blue}{\hfil \bfseries\large Contents of Part One\hfil}}
{\vskip3pt\sffamily\small}
{\coloredstuff{blue}
    {\leftskip1.5cm\rightskip.5cm\parfillskip-\rightskip
     \makebox[0pt][r]{\makebox[.5cm][l]{\etocnumber}}%
     \etocname\nobreak\hfill\makebox[.5cm][r]{\etocpage\hspace{.1cm}}}%
 \vskip6pt}
{}

\etocframedstyle[1]{}
\tableofcontents \label{toc:floating} \ref{toc:overview}
\vspace{-\baselineskip}
\centeredline{|\tableofcontents \ref{toc:overview}| 
(\emph{cf.} \hyperref[toc:clone]{this other toc})}
\end{figure}
\end{filecontentshere}
\attachfile[description={demo \the\value{section}}]{etocsnippet-\the\value{section}.tex}

\filecontentsexec\filecontentsheremacro

% , and the
% reader is referred to its \hyperref[ssec:tocclone]{subsection} for the
% coding used.

\section{A (crazy) inline display}

Let us finally make some crazy inline display of the table of
contents of this entire document. We will typeset the subsections as
footnotes... This kind of style is suitable for a hyperlinked
document, probably not for print! (although I like it, but my personal tastes in
many matters do not seem to be widely shared).

%%%% Note: 27 april 2014 

%%%% except for a miraculous situation depending from the quantity of previous
%%%% material this TOC will have links extending accross pagebreaks, which
%%%% dvipdfmx does not know how to handle completely. Apart from that the output
%%%% is ok, thus no need to try seriously to avoid them. 

\begin{filecontentsdef}{etocsnippet-\the\value{section}.tex}{\foo}
\begingroup
\newsavebox{\forsubsections}
\etocsetstyle{part}{\upshape. \etocskipfirstprefix}
                   {. \upshape}
                   {\bfseries\etocname:~~}
                   {}
\etocsetstyle{section}{\itshape\etocskipfirstprefix}
                      {, }
                      {\mdseries\etocname}
                      {}
\etocsetstyle{subsection}
    {\begin{lrbox}{\forsubsections}\footnotesize\upshape\etocskipfirstprefix}
    {; }
    {\etocname}
    {.\end{lrbox}\footnote{\unhbox\forsubsections}}
\etocsetstyle{subsubsection}
    { (\itshape\etocskipfirstprefix}
    {, }
    {\etocname}
    {\/\upshape)}
\etocsettocstyle{Here is the inline table of contents. }{.\par}
\tableofcontents \label{toc:crazyinline}
\endgroup
\end{filecontentsdef}

\filecontentsexec\foo

The code used:
\filecontentsprint\foo
\attachfile[description={demo \the\value{section}}]{etocsnippet-\the\value{section}.tex}


\clearpage
\etocdepthtag.toc {surprising}
\part{Surprising uses of \etoc}
\label{part:surprising}

\thispartstats %% (pas de sous-section)

\etocstandardlines
\etocsettocstyle {}{}
\localtableofcontents

\section{The TOC of TOCs}

\begingroup % \endgroup just after the \tableofcontents command
\etocinline
\etocsetlevel{part}{1}
\etocsetlevel{visibletoc}{0}
\etocsetstyle{visibletoc}
    {\etocskipfirstprefix}
    {, }
    {{\color{niceone}\etocname}}
    {}
\etocsettocstyle{}{}
\etocsetnexttocdepth{visibletoc}


Here is the numbered and linked list of all tables of contents which are
displayed within this document:\footnote{The TOCs put in
  floats may change the order: the numbers are listed
  in the order the TOCs are typeset in the document; but the numbering
  itself is from the order of the TOCs in the \emph{source} of
  this document... }
\tableofcontents\endgroup. And to obtain
it here we just wrote:\par\smallskip 
{\leftskip1cm\rightskip2cm
  \ttfamily\small\baselineskip11pt \noindent Here is the
  numbered and linked list of all tables of contents which are
  displayed within this
  document:~\string\tableofcontents.\par}

  The preparatory work was the following. First, we defined a
  counter |visibletoc| whose vocation is to get incremented at
  each displayed toc. \etoc has its own private counter but it
  counts all TOCs, even those not displayed because the |tocdepth|
  value was |-2| or |-3|.

  We could have added manually |\refstepcounter{visibletoc}|
  and |\label| commands at all suitable locations in the
  document source, and we would then have used here |\ref|
  commands, but this imposes heavy manual editing of the source.

  There is a much better way: there is a hook
  \csb{etocaftertitlehook} and we told it to increment the
  |visibletoc| counter and to write a line to the |.toc| file,
  in a manner analogous to what sectioning commands such as
  |chapter|, |section|, or |subsection| do. As \etoc
  increments its own private counter even before typesetting
  the title of a table of contents, this provides (most of the
  time) a better link destination than any counter manipulated
  from inside \csb{etocaftertitlehook} (for which the link
  would target the area just after the title). So, rather than
  including |\refstepcounter{visibletoc}| inside
  \csb{etocaftertitlehook}, we just put there
  |\stepcounter{visibletoc}| followed by the command
  \csb{etoctoccontentsline}|{visibletoc}{\thevisibletoc}|. This \etoc
  command \csb{etoctoccontentsline}\marg{level\_name}\marg{name} has the same
  effect as:
  \centeredline{|    ||\addcontentsline{toc}|\marg{level\_name}\marg{name}}
  but its usefulness is to circumvent\footnote{using \csa{addtocontents} rather
    than \csa{addcontentsline}} the patching for automatic creation
  of bookmarks done to \csa{addcontentsline} by the |hyperref| package, 
  as pdf bookmarks don't make 
  much sense here (and would elicit a complaint
  of |hyperref| that the bookmark level is `unknown').\footnote{%
  The package provides a starred variant
  \staritb{etoctoccontentsline}, which does allow the creation
  of bookmarks and has a third mandatory argument which is the
  Level to be used by these bookmarks; depending on the context
  the starred as well as the non-starred variants may be
  profitably preceded by \csa{phantomsection}.}

  Finally, the preamble of the document did
  |\etocsetlevel{visibletoc}{6}|. The level |6| (or anything
  with a higher number) is ignored, even if |tocdepth| has
  value |10| for example; this is independently of whether \etoc
  uses the document class default line styles or its own line
  styles, or the ones defined by the user with the
  \csb{etocsetstyle} command. So there is no need to worry that
  something could go wrong. 

  Then, only here we have set |\etocsetlevel{visibletoc}{0}|. And to display
  only this kind of entries we assign temporarily to |part| and |chapter| level
  |1| (or anything higher than zero) and set |tocdepth| to the value |0|. We
  also did \csa{etocsetstyle\{visibletoc\}\{\string\etocskipfirstprefix\}\{,
    \}\{\string\etocname\}\{\}} which defines an inline display with the comma
  as separator. Finally, as \etoc issues |\par| automatically by default just
  before typesetting a table of contents, we used the command \csb{etocinline}
  (also known as \cs{etocnopar}) which turns off this behavior.

Here are the implementation details:

\begingroup
\begin{filecontentshere}{etocsnippet-\the\value{section}.tex}
   < in the preamble >
\newcounter{visibletoc}
\renewcommand{\etocaftertitlehook}
   {\stepcounter{visibletoc}\etoctoccontentsline{visibletoc}{\thevisibletoc}}
\etocsetlevel{visibletoc}{6}
\begin{document}
   < document body >
\subsection{Surprising uses of etoc}
\begingroup
    \etocinline
    \etocsetlevel{part}{1}
    % \etocsetlevel{chapter}{1} % (no chapters in scrartcl class)
    \etocsetlevel{visibletoc}{0}
    \etocsetstyle{visibletoc}
        {\etocskipfirstprefix}{, }{{\color{niceone}\etocname}}{}
    \etocsettocstyle{}{}     % don't set any title, rules or frame or multicol!
    \etocsetnexttocdepth{visibletoc} % display only the `visibletoc' entries from .toc

Here is the numbered and linked list of all tables of contents which are
displayed within this document: \tableofcontents.
\endgroup
\end{filecontentshere}
\attachfile[description={demo \the\value{section}}]{etocsnippet-\the\value{section}.tex}
\endgroup

After |\etocsetstyle{visibletoc}{..}{..}{..}{..}|, all future TOCs (not in
compatibility mode) will use the
defined style for level |0| (which is normally the level for
chapters). To keep these changes strictly local the simplest
manner is to put everything inside a group.

The \autoref{subsec:interverting} gives another use of the
shuffling of levels. 


\section[Arbitrary ``Lists Of...'', \csbhyp{etoctoccontentsline}]{%
         Arbitrary ``Lists Of...'', \csbhyp{etoctoccontentsline} and
         \csbhyp{etocimmediatetoccontentsline}}
\label{etoctoccontentsline}
\label{etocimmediatetoccontentsline}

This idea of interverting the levels is very powerful and allows
to let \etoc display lists of arbitrary things contained in the
document. All of that still
using nothing else than the |.toc| file! 
Example: imagine a document with dozens of
exercises, perhaps defined as |\newtheorem{exercise}{}[section]|. Let
us explain how to instruct \etoc to display an hyperlinked list
of all these exercises. For this we put in the preamble:
\begin{verbatim}
 \newtheorem{exerci}{}[section] 
    % the exercice number will be recoverable via \etocname: v--here--v
 \newcommand*{\exercisetotoc}{\etoctoccontentsline{exercise}{\theexerci}}
 \newenvironment{exercise}{\begin{exerci}\exercisetotoc}{\end{exerci}}
 \etocsetlevel{exercise}{6}
\end{verbatim}
In this way, \csb{etocname} will give the exercise number (but \csb{etocnumber}
will be empty). Had we used instead
\begin{verbatim}
 \newcommand*{\exercisetotoc}
    {\etoctoccontentsline{exercise}{\protect\numberline{\theexerci}}}
\end{verbatim}
the exercise number would then have been available via \csb{etocnumber}, and
\csb{etocname} would have been empty. It doesn't matter which one of the two
methods is used. The \etoc command \csb{etoctoccontentsline}|{..}{..}| is
provided as a substitute to \csa{addcon\-tentsline}|{toc}{..}{..}|: this is to
avoid the patching which is done by |hyperref| to \csa{addcontentsline} in its
process of creation of bookmarks. If one wants to authorize |hyperref| to create
bookmarks at a specific level \meta{n}, one can use (here with \meta{n}$=$|2|)
the starred variant \starit{etoctoccontentsline} which has an additional
argument:
\begin{verbatim}
\newcommand{\exercisetotoc}{\etoctoccontentsline*{exercise}{\theexerci}{2}}
\end{verbatim}

The counter |exerci| is already
incremented by the |exerci| theorem environment, and
provides the correct destination for the link added by package
|hyperref|. The command \csa{exercisetotoc} adds for each exercise a line
to the |.toc| file, corresponding to a fictitious document
unit with name `|exercise|'. A
four-column list, including the sections, can then be
typeset with the following code:
\begin{filecontentshere}{etocsnippet-\the\value{section}.tex}
  \etocsetnexttocdepth{2}     % sections are at level 1 and will show up
\begingroup
  \etocsetlevel{exercise}{2}   % but:
  \etocsetlevel{chapter}{3}    %     no chapters
  \etocsetlevel{subsection}{3} %     no subsections
  \etocsetlevel{part}{3}       %     no parts
  \etocsetstyle{exercise}{}{}  % \etocname = exercise number
    {\noindent\etocname\strut\leaders\etoctoclineleaders\hfill\etocpage\par}
    {\pagebreak[2]\vskip\baselineskip}
  \etocsetstyle{section}{}{}
    {\noindent\strut{\bfseries\large\etocnumber\hskip.5em\etocname}\par
     \nopagebreak[3]}{}
  \etocruledstyle[4]{\Large\bfseries List of the exercises}
  \setlength{\columnseprule}{.4pt}
  \tableofcontents
\endgroup
\end{filecontentshere}
\attachfile[description={demo \the\value{section}}]{etocsnippet-\the\value{section}.tex}

A related command \csb{etocimmediatetoccontentsline} (and its starred version)
is also provided.  For discussion and the meaning of ``immediate'', refer to
the analogous case of \csb{etocimmediatedepthtag.toc}.

\section{The TOC as a tree}\label{tocastree}

Using |tikz|\footnote{\url{http://ctan.org/pkg/pgf}} and the package
|forest|\footnote{\url{http://ctan.org/pkg/forest}} we shall display the table
of contents of this part as a tree. The technique is to
use the \etoc modified command \toc not for typesetting, but to
prepare a macro, or rather here a \emph{token list} variable, with all the
instructions to be executed later. \textsc{Leslie Lamport}'s book has no mention
whatsoever of token lists, and \LaTeX{} gives the impression to not really
expect the general user to ever hear about them (or delimited macros); this
whole section and the next are thus for 
advanced users.

Putting the \csb{etocnumber} and \csb{etocname}
commands in \csa{treetok} would be of no use: to which number or name would they
then refer to, in a delayed execution? 

We need to store, not the macro names, but the macro contents. And also we wish
to maintain the correct |hyperref| hyperlinks.\footnote{This manual up to the
version of May 14, 2013 used package |tikz-qtree| but there were problems with
hyperlinks. No such problem arises either when using |forest| or the native
|tikz| syntax for trees (which will be illustrated in the next section).} The
commands \csb{etocname}, etc\dots, are robust, it is easier to work with 
\csb{etocthelinkednumber}, \csb{etocthelinkedname}, and \csb{etocthelinkedpage}
which contain the same information in an easier accessible form.

For this |forest| tree we have designed very special \etoc styles for sections
and subsections. They use a token list register called |\treetok| and a
macro |\appendtotok| whose r\^ole is to append to a given token list variable
the contents of a macro given as second argument. All this will happen in
reaction to a |\tableofcontents| command, but \emph{nothing} has yet been
printed in the process.\footnote{There is always a \csa{par}, which here is not
a problem, but can be suppressed if need be via the command \csb{etocinline} or
its synonym \csb{etocnopar}.} This is the later job of a |forest| environment
which will be given the contents of |\treetok|.


% anciens commentaires extraits du code avant incorporation à filecontentsdef

% 7 mars: j'utilise \etocthelinkedname défini à partir de 1.07f
% mais bien sûr je sais que ça ne marche pas (sauf dans l'arbre pour le lien de
% la section du bas) dans un QTree. Mais ça marche parfaitement dans un arbre
% TikZ natif.

% 9 septembre 2013: je remplace QTree par Forest, et il n'y a pas de problème
% avec les hyperliens, ça marche out of the box (une fois que j'ai appris un peu
% de sa syntaxe et de celle de TikZ).

% 7 mars: j'utilise maintenant \etocthelinkedname

% 11 octobre
% forest ne veut pas @\the\treetok avec un \treetok vide, donc
% il faut lui donner une valeur par défaut.

% 12 octobre
% pour que varioref fonctionne bien, je dois mettre la \tableofcontents
% au plus près de l'environnement forest

\let\appendtotok\relax

\begin{filecontentsdef}{etocsnippet-\the\value{section}.tex}{\foo}
% \newtoks\treetok % put this (uncommented) preferably in the preamble
% \newtoks\tmptok  % (idem)

\newcommand*\appendtotok[2]{% #1=toks variable, #2=macro, expands once #2
  #1\expandafter\expandafter\expandafter
    {\expandafter\the\expandafter #1#2}}

\newcommand*\PrepareSectionNode{%
  \tmptok {\centering\bfseries}%
  \appendtotok\tmptok\etocthelinkedname
  \edef\foresttreenode{ [{\noexpand\parbox{2cm}{\the\tmptok}}}% 
}

\newcommand*{\PrepareSubsectionNode}{%
  \tmptok {\raggedright}%
  \appendtotok\tmptok\etocthelinkedname
  \edef\foresttreenode{ [{\noexpand\parbox{6cm}{\the\tmptok}}}%
}

\etocsetstyle{section}
  {\etocskipfirstprefix}
  {\appendtotok\treetok{ ]}}
  {\PrepareSectionNode \appendtotok\treetok\foresttreenode}
  {\appendtotok\treetok{ ]}}

\etocsetstyle{subsection}
  {\etocskipfirstprefix}
  {\appendtotok\treetok{ ]}}
  {\PrepareSubsectionNode \appendtotok\treetok\foresttreenode}
  {\appendtotok\treetok{ ]}}

\etocsettocstyle
    {\treetok{[{\hyperref[part:overview]{Overview}}}}
    {\global\appendtotok\treetok{ ]}}

% forest does not like @\the\treetok if \treetok is empty. On first latex
% run, this will be the case because the TOC style defined above will not
% have been executed, as the label {toc:overview} does not refer to a valid 
% TOC yet. So we must give a safe default value to \treetok
\treetok{[{run latex again}]}

\begin{figure}[th!]\centering
     \etocsetnexttocdepth{subsection}
     \tableofcontents \label{toc:forest}\ref{toc:overview}
     \hypersetup{hidelinks}%
     \bracketset{action character=@}
     \begin{forest} 
                  for tree={anchor=center,child anchor=west,
                            grow'=east,draw,thick,
                            edge={draw,thick,dashed,color=teal}},
                  where={level()==1}{circle,thick,fill=blue!5,
                                    before computing xy={l=3cm}}{},
                  where={level()==2}{fill=red!5,
                                    before computing xy={l=6cm}}{},
                  rectangle, thick, fill=cyan!5, inner sep=6pt,
     @\the\treetok 
     \end{forest}
\end{figure}
\end{filecontentsdef}
\filecontentsexec\foo

The resulting tree has been put in a \hyperref[toc:forest]{float}, which
appears \vpageref[above]{toc:forest}. Here is the 
code used for its production:
\filecontentsprint\foo
\attachfile[description={demo \the\value{section}}]{etocsnippet-\the\value{section}.tex}
Why |\hypersetup{hidelinks}|? as explained in
\autoref{ssec:hidelinks}, I prefer the links in TOCs not to be
colorized, nor framed, so this document inserts a command
%\csa{hypersetup}\texttt{\{hidelinks\}} % ok pour hyphénation
%\csa{hypersetup}|{hidelinks}| % pas ok
|\hypersetup{hidelinks}| % ok maintenant 12 octobre 2013
 in the |.toc| file. But at the time the
|\treetok| contents are unpacked the |\hyperlink| commands
originating in
|\etocthelinkedname|, etc\dots{} will be executed in the normal
environment for links (which, in this document, is to colorize
them). Rather than having \etoc's code try to guess what the current ``style''
for links is (a concept not really provided by |hyperref| it
seems) and store it in |\etocthelinkedname|, etc\dots, I opted for
the simpler solution to leave it up to the user to recreate
whatever conditions are desired. So here  it is necessary to re-issue
|\hypersetup{hidelinks}| in the |figure| environment.

There are some other examples in this documentation where
|\tableofcontents| is used to prepare material for later
typesetting:
\begin{itemize}
\item printing the statistics at the start of each Part (see
  \autoref{ssec:statistics}) is done using save boxes (so the problem of the
  appearance of the links does not arise then).
\item the typesetting of the TOC as a table in the pre-|1.08| way (see
  \autoref{ssec:tocastableold}); there we also have to issue
  |\hypersetup{hidelinks}| after having collected the names, numbers and
  page numbers in a token list register.
\item and the two additional tree examples in the next section.
\end{itemize}


\section{The TOC as a molecule}\label{sec:molecule}

It is also possible to construct a TOC tree obeying the TikZ
syntax for trees: but this is a more complicated task for the
\etoc line styles for reasons related to the way braces are
handled by \TeX{} (they need, when filling up the token list to be
always balanced at each step, else complicated tricks must be
employed.)

The simplest strategy is to allocate a token list (or use a macro) for each
level used: we may need a \csa{parttok}, a \csa{chaptertok}, a
\csa{sectiontok} and a \csa{subsectiontok}, to help in the task of filling
up the total \csa{treetok}. As we are interested here in the table of
contents of this (or another) document part, only a \csa{sectiontok} and a
\csa{subsectiontok} will be needed.


\begin{filecontentshere}{etocsnippet-\the\value{section}.tex}
% \newtoks\treetok % put this (uncommented) preferably in the preamble
% \newtoks\sectiontok 
% \newtoks\subsectiontok 
\newcommand*{\treenode}{}

\newcommand*{\appendchildtree}[2]{% token list t1 becomes: t1 child {t2}
   \edef\tmp{\the#1 child {\the#2}}%
   #1\expandafter{\tmp}%
}
\newcommand*{\preparetreenode}{%
  \tmptok\expandafter{\etocthelinkednumber}% expanded one time (mandatory)
  \edef\treenode{node {\the\tmptok}}%
}

\etocsetstyle{section}
  {\etocskipfirstprefix}
  {\appendchildtree\treetok\sectiontok}
  {\preparetreenode \sectiontok\expandafter{\treenode}}
  {\appendchildtree\treetok\sectiontok}

\etocsetstyle{subsection}
  {\etocskipfirstprefix}
  {\appendchildtree\sectiontok\subsectiontok}
  {\preparetreenode \subsectiontok\expandafter{\treenode}}
  {\appendchildtree\sectiontok\subsectiontok}

\etocsettocstyle
  {\treetok{\node {\hyperref[part:overview]{Overview}}}}
  {\global\appendtotok\treetok{ ;}}

\begin{figure}[thbp!]\centering
   \etocsetnexttocdepth{subsection}
   \tableofcontents \label{toc:molecule} \ref{toc:overview}
   \hypersetup{hidelinks}%
   \begin{tikzpicture}
              [grow cyclic,
               level 1/.style={level distance=4cm,sibling angle=72},
               level 2/.style={level distance=2cm,sibling angle=60},
               every node/.style={ball color=red,circle,text=SkyBlue},
               edge from parent path={[dashed,very thick,color=cyan]
                           (\tikzparentnode) --(\tikzchildnode)}] 
     \the\treetok
   \end{tikzpicture}
\end{figure}
\end{filecontentshere}
\attachfile[description={demo \the\value{section}}]{etocsnippet-\the\value{section}.tex}

\filecontentsexec\filecontentsheremacro

% Pour que \pageref fonctionne correctement, je dois mettre
% le \tableofcontents dans la figure. 

The |\tableofcontents| command appears just above the
|tikzpicture| environment in a figure float (to make sure that the label of the
table of contents
refers to the same page as the one where the picture will actually be printed).
We thus get the table of contents as a ``\hyperref[toc:molecule]{molecule}'',
which  
appears \vpageref[above]{toc:molecule}.

This \hyperref[toc:molecule]{TikZ TOC} is fully hyperlinked, like the
previous 
\hyperref[toc:forest]{Forest TOC}.

\etocsettocstyle
  {\treetok{\node {\autoref{part:globalcmds}}}}
  {\global\appendtotok\treetok{ ;}}

\etocsetnexttocdepth {subsection}
\tableofcontents \ref{toc:globalcmds}

\noindent  
\parbox{4cm}{\hypersetup{hidelinks}%
    \begin{tikzpicture}
              [grow cyclic,
               level 1/.style={level distance=2.5cm,sibling angle=60},
               level 2/.style={level distance=1cm,sibling angle=45},
               every node/.style={ball color=red!50,circle,text=black},
               edge from parent path={[very thick,color=cyan]
                       (\tikzparentnode) --(\tikzchildnode)}] 
     \the\treetok
   \end{tikzpicture}}%
\begin{minipage}{\dimexpr\linewidth-4cm\relax}
  On the side, the (fully hyperlinked) table of contents of
  \autoref{part:globalcmds}.
  \def\MacroFont{\ttfamily\small\hyphenchar\font-1 \baselineskip10pt\relax}%
\begin{verbatim}
\etocsettocstyle
  {\treetok{\node {\autoref{part:globalcmds}}}}
  {\global\appendtotok\treetok{ ;}}
\etocsetnexttocdepth {subsection}
\tableofcontents \ref{toc:globalcmds}
\noindent  
\parbox{4cm}{\hypersetup{hidelinks}%
   \begin{tikzpicture}
      [grow cyclic,
       level 1/.style={level distance=2.5cm,sibling angle=60},
       level 2/.style={level distance=1cm,sibling angle=45},
       every node/.style={ball color=red!50,circle,text=black},
       edge from parent path={[very thick,color=cyan]
               (\tikzparentnode) --(\tikzchildnode)}] 
     \the\treetok
   \end{tikzpicture}}%
...
\end{verbatim}
\end{minipage}

\section{The TOC as a TikZ mind map}
\label{sec:mindmap}

This is in the same spirit as the ``molecule'' example. The use of the \eTeX{}
primitive \csa{unexpanded} will simplify the code.\footnote{The ``molecule''
example was added to this documentation on |2013/03/03|. The ``mindmap''
example was motivated on |2015/03/11| by
\url{http://tex.stackexchange.com/a/232584/4686}. Further help was then obtained via
\url{http://tex.stackexchange.com/q/232816/4686} and this led to the  
\hyperref[toc:mindmaptitlepage]{title page} which is a further example.}

% car dans le filecontentsdef je dois faire comme si pour verbatim
% mais aussi l'exécuter, donc il me faut annuler définitions précédents pour
% contourner messages d'erreurs de LaTeX.

\let\appendchildtree\relax
\let\childnode\relax
\let\appendtotok\relax
\expandafter\let\csname c@partco\endcsname\relax

\begin{filecontentsdef}{etocsnippet-\the\value{section}.tex}{\foo}
\begingroup
% \newtoks\treetok % done in preamble
% \newtoks\parttok

\newcommand*\partnode {}  % just to check we don't overwrite something
\newcommand*\childnode {}

\newcommand*\tmprotate {} % just to check we don't overwrite something
\newcommand*\tmpoption {} % just to check we don't overwrite something
\newcommand*\tmpstuff  {} % just to check we don't overwrite something

\newcommand*\appendtotok[2]{% #1=toks variable, #2=macro, expands once #2
   #1\expandafter\expandafter\expandafter{\expandafter\the\expandafter #1#2}}

\newcommand*{\appendchildtree}[3]{% 
% this is to construct "t1 child [#3]{t2}" from #1=t1 and #2=t2
% t1 and t2 are two toks variable (not macros)
% #3 = for example teal!60
   \edef\tmpstuff {\the#1 child [#3]{\the#2}}%
   #1\expandafter {\tmpstuff }%
}

\newcounter{partco}

% 1,2,3,4,5,... -> 1,2,3,1,2,3,1,2,3
\def\pseudomodthree #1{\numexpr #1 + 3 - 3*((#1+1)/3)\relax}

\etocsetstyle{part}
  {\etocskipfirstprefix}
% This updates the global tree with the data  from the previous
% part and all its children sections. Moved here because for some parts the
% sections are not displayed due to depth tags.
  {\ifnum\value{partco}=3
     \appendchildtree\treetok\parttok {branch color= green!50,level distance=10cm}%
   \else
\ifcase\pseudomodthree{\value{partco}}%
   \or \appendchildtree\treetok\parttok {branch color= teal!60}%   first
   \or \appendchildtree\treetok\parttok {branch color= yellow!80}% second
   \else\appendchildtree\treetok\parttok {branch color= green!50}% third and next ...
   \fi\fi
   }
  {\stepcounter{partco}%
% customize manually  some TikZ set-up (should be done inside the TikZ thing I guess)
   \def\tmpoption {}%
   \def\tmprotate {}% first
   %\ifnum\value{partco}=5 \def\tmprotate {[counterclockwise from =-40]}\fi
   %\ifnum\value{partco}=8 \def\tmprotate {[counterclockwise from =-50]}\fi
% define the part node
   \edef\partnode{node \tmpoption 
                  {\unexpanded\expandafter{\etocthelinkednumber}. 
                   \unexpanded\expandafter{\etocthelinkedname}}\tmprotate }%
% this is a starting point which will be filled it by the section children
   \parttok\expandafter{\partnode}}
  {\ifcase\pseudomodthree{\value{partco}}%
   \or \appendchildtree\treetok\parttok {branch color= teal!60}%   first
   \or \appendchildtree\treetok\parttok {branch color= yellow!80}% second
   \else\appendchildtree\treetok\parttok {branch color= green!50}% third and next ...
   \fi
   }

\etocsetstyle{section}
  {}
  {}
  {% define the section node
   \edef\childnode{child {node {\unexpanded\expandafter{\etocthelinkednumber} 
                        \unexpanded\expandafter{\etocthelinkedname}}}}%
   % append it to the current \parttok
   \appendtotok\parttok\childnode
    }
  {}

\etocsettocstyle
  {\setcounter{partco}{0}%
   \treetok{\node [root concept]{\textbf{The \etoc documentation}}}}
  {\global\appendtotok\treetok{ ;}}
% The \global above is mandatory because etoc always typesets TOC inside a group

\etocsetnexttocdepth{section}
% use of depth tags to cut out some sections.
\etocsettagdepth {preamble}   {none}
\etocsettagdepth {overview}   {part}
\etocsettagdepth {arbitrarily}{part}
\etocsettagdepth {examples}   {section}
\etocsettagdepth {surprising} {part}
\etocsettagdepth {linestyles} {part}
\etocsettagdepth {globalcmds} {part}
\etocsettagdepth {custom}     {section}
\etocsettagdepth {tips}       {part}
\etocsettagdepth {etocandworld}{part}
\etocsettagdepth {code}       {section}

\tikzset{
    branch color/.style={
        concept color=#1!white,
        every child/.append style={concept color=#1!white!30!white, font=\normalsize},
    }
}%

\begin{figure}[thp!]
\tableofcontents\label{toc:mindmap}%
\centeredline{\resizebox{.85\paperwidth}{!}%
{\begin{tikzpicture}[mindmap,
                    grow cyclic, 
                    text width=2cm, 
                    align=flush center, 
                    nodes={concept}, 
                    concept color=orange!60,
                    root concept/.append style={text width=4cm, font=\Large},
   level 1/.append style={level distance=5cm,sibling angle=40, text width=3cm},
   level 2/.append style={level distance=7cm,sibling angle=30, text width=3cm},
   level 1 concept/.append style={font=\normalsize},
                    ]
\the\treetok
\end{tikzpicture}}}
\end{figure}
\endgroup
\end{filecontentsdef}
\filecontentsexec\foo

It is difficult to get everything to fit on one page. However \csa{resizebox}
comes to the rescue. And it preserves hyperlinks. Nevertheless for this
example I excluded some sections from the display, using the technique of the
\etoc \hyperref[etocdepthtag.toc]{depth tags}. The fully hyperlinked TOC
appears \vpageref{toc:mindmap}.

\filecontentsprint\foo
\attachfile[description={demo \the\value{section}}]{etocsnippet-\the\value{section}.tex}
An interesting alternative is to use \etoc rather to convert the entire TOC
into a TikZ tree (perhaps excluding some parts) and print it out to a file
from which it can be recovered and manipulated directly by the author of the
document. Things written to the |.log| file get broken into lines. Here is a
technique to get non-broken output. Once the \csa{treetok} has been computed
by \etoc (as in the \hyperref[toc:molecule]{molecule} example, or the current
example), this demo will write it out to file with extension
|.toctree|:
\begin{verbatim}
  \newwrite\TOCasTree
  \immediate\openout\TOCasTree=\jobname.toctree
  \immediate\write\TOCasTree{\the\treetok}%
\end{verbatim}
The author can then copy it from there and customize it manually to get a
suitable tikz picture. See also
\centeredline{\url{http://tex.stackexchange.com/a/232792}}
for an elaboration of this.


\section{The TOC as a table}
\label{sec:tocastable}

With release |1.08| it is easier to typeset a TOC as a table. It is
possible to open a tabular in the title part of the TOC (first argument
to \csb{etocsettocstyle}) and then close it after the contents (second
argument to \csb{etocsettocstyle}), and specify in the line styles how
to use the tabulation |&| and tabular end of row |\\|. There are some
conditions and a few caveats:

\begin{enumerate}
\item it is mandatory to issue \csb{etocglobaldefs} for \etoc's
  definitions to have global scope,
\item it is impossible to start one of the \meta{start}, \meta{prefix},
  \meta{contents} or \meta{finish} specification with a sole |\hline|,
  \emph{i.e.} one not preceded by a |\\| (it is however possible to put
  |\\| at the end of \meta{prefix} and the |\hline| at the start of
  \meta{contents}).
\item as is explained next, it is recommended to put the
  |\\| at the start of the \meta{prefix} or \meta{contents}
  specifications in order to close the \emph{previous} row, rather
  that at the end with the idea to close the \emph{current} row;
  and when the TOC is a partial one (a \csa{localtableofcontents}) this
  is (in almost all situations) mandatory.
\end{enumerate}

Here is an example of a TOC as a |longtable| (yes this is only \emph{one} table),
as is possible relatively simply now with |1.08|. The code follows.

\begin{filecontentsdef}{etocsnippet-\the\value{section}-A.tex}{\foo}
\begingroup
\etocglobaldefs % necessary for \etocname etc... to survive &
\makeatletter
% hack into longtable \hline to avoid annoying (here) stray lines at top
\def\LT@@hline{%
  \ifx\@let@token\hline
    \global\let\@gtempa\@gobble
    \global\let\@gtempb\@firstofone %%% ADDED
    \gdef\LT@sep{\penalty-\@medpenalty\vskip\doublerulesep}%
  \else
    \global\let\@gtempa\@empty 
    \global\let\@gtempb\@gobble     %%% ADDED
    \gdef\LT@sep{\penalty-\@lowpenalty\vskip-\arrayrulewidth}%
  \fi
  \ifnum0=`{\fi}%
  \multispan\LT@cols
     \unskip\leaders\hrule\@height\arrayrulewidth\hfill\cr
  \@gtempb{%                        %%% ADDED
  \noalign{\LT@sep}%
  \multispan\LT@cols
     \unskip\leaders\hrule\@height\arrayrulewidth\hfill\cr
  \noalign{\penalty\@M}%
  }%                                %%% ADDED
  \@gtempa}
\makeatother

% observe the locations of the \\
\etocsetstyle{part}
  {}
  {}
  {\\\hline\multicolumn{3}{c}{\bfseries\vrule height6ex depth3ex width0pt
                              \etocifnumbered{\etocnumber. }{}\etocname}}
  {}

\etocsetstyle{section}
  {}
  {\etociffirst{\\\hline}{\\}}
  {\etocnumber&\etocname &\etocpage }
  {}

\etocsetstyle{subsection}
  {}
  {\\}
  {&\makebox[1cm][c]{\etocnumber}%
    \parbox[t]{\dimexpr6cm-\tabcolsep\relax}{\sloppy\itshape\etocname\strut}%
   &\itshape\etocpage }
  {}

\etocsettocstyle
    {\hypersetup{hidelinks}%
     \begin{longtable}{|>{\bfseries}c|p{7cm}|r|}
     \hline
     \multicolumn{3}{|c|}{\Large\bfseries\strut\strut TABLE OF CONTENTS}%
     }
    {\\\hline\end{longtable}}

\etocsetnexttocdepth {subsection}

\tableofcontents
\endgroup
\end{filecontentsdef}

\filecontentsexec\foo

\filecontentsprint\foo
\attachfile[description={demo \the\value{section}-A}]{etocsnippet-\the\value{section}-A.tex}
Examining the code above the reader will wonder why the |\\| are
always given first in \meta{prefix+contents} and not, as is more
intuitive, rather last. In some favorable cases (but almost never
for local tables of contents) one may indeed construct
TOC-as-tables with the |\\| located at the end of the style
specifications. The problem in the previous example was with the
positioning of the |\hline|'s.

Due to technical aspects of how \TeX{} constructs alignments any
definition or assignment done after an |\\| starts a new row, and
thus makes |\hline| an illegal token (this shows as a |misplaced
\noalign| error.) Not only does \etoc have to do such definitions
to construct \csb{etocname} etc..., it is furthermore the case that
some packages put things in the |.toc| file and as a result there
is never any guarantee that between two \csa{contentsline} there
will not be such a token like |\relax| which in the contexts of
alignments forces \TeX{} to start a cell and thus makes it
impossible then to insert an |\hline|.

The safest way is thus to start with an |\\| each line style
specification in order to close the \emph{previous} table row. We
had a little problem with the fact that we wanted parts not only
to have a rule above them (easy, they do |\\\hline|) but also
below them: after each part there is a section, and it is these
sections which are used to insert the missing |\hline|
(this is done with the help of the \csb{etociffirst}
conditional). 

% obsolète avec la nouvelle \part* "\etoc" avant l'abstract (1.09f)
% The attentive reader will notice one last subtlety: the title was
% supposed to be followed not by one, but by two |\hline|'s. To
% solve this we could have used a one-time macro redefining itself,
% but we noticed that the title was followed by the unnumbered
% Abstract, thus the \csb{etocifnumbered} switch came to the rescue.

Last technical note: because we put the |\\\hline| inside the branches, there
was no need to employ the expandable variants \csb{etocxiffirst} and
\csb{etocxifnumbered}.

For the hardliner's old way see \autoref{ssec:tocastableold}.

Here is also a much simpler example. It is a local table of
contents.

\begin{filecontentsdef}{etocsnippet-\the\value{section}-B.tex}{\foo}
\begin{center}
\etocsetstyle{section}
             {}
             {\etociffirst{\\\hline\hline}{\\\hline}}
             {\etocname & \etocnumber & \etocpage }
             {}

\etocsettocstyle
   {\hypersetup{hidelinks}\begin{tabular}{|p{4cm}|c|c|}\hline
    \multicolumn{1}{|c|}{\bfseries Section}&
    \bfseries number&
    \bfseries page}
   {\\\hline\end{tabular}}

\etocglobaldefs % MANDATORY !!
\etocsetnexttocdepth{1}

\tableofcontents\ref{toc:overview}
\end{center}
\end{filecontentsdef}

\filecontentsexec\foo

\filecontentsprint\foo
\attachfile[description={demo \the\value{section}-B}]{etocsnippet-\the\value{section}-B.tex}

\section{A TOC self-adjusting widths for its typesetting}
\label{sec:thirdexampleextra}

This is a continuation of \autoref{sec:thirdexample}. The goal is to adjust
automatically the ``numwidths'' used for typesetting the unit numbers in the
(local) tables of contents.
\begin{filecontentshere}{etocsnippet-\the\value{section}.tex}
\makeatletter
\newcommand*\TOCcompute@numwidths [2]{% #1=empty/"local", #2=minimal indent
  \begingroup
    \def\TOCnumwidthB {0pt}%
    \def\TOCnumwidthC {0pt}%
    \def\TOCnumwidthD {0pt}%
    \def\TOCnumwidthE {0pt}%
    \def\TOCnumwidthF {0pt}%
    \def\TOCnumwidthG {0pt}%
    \etocsetstyle{part}{}{}{}{}%
    \etocsetstyle{chapter}{}
      {\setbox0\hbox{\bfseries\etocthenumber\kern#2}}
      {\ifdim\wd0>\TOCnumwidthB\edef\TOCnumwidthB{\the\wd0}\fi}{}%
    \etocsetstyle{section}{}
      {\setbox0\hbox{\bfseries\etocthenumber\kern#2}}
      {\ifdim\wd0>\TOCnumwidthC\edef\TOCnumwidthC{\the\wd0}\fi}{}%
    \etocsetstyle{subsection}{}
      {\setbox0\hbox{\etocthenumber\kern#2}}
      {\ifdim\wd0>\TOCnumwidthD\edef\TOCnumwidthD{\the\wd0}\fi}{}%
    \etocsetstyle{subsubsection}{}
      {\setbox0\hbox{\etocthenumber\kern#2}}
      {\ifdim\wd0>\TOCnumwidthE\edef\TOCnumwidthE{\the\wd0}\fi}{}%
    \etocsetstyle{paragraph}{}
      {\setbox0\hbox{\etocthenumber\kern#2}}
      {\ifdim\wd0>\TOCnumwidthF\edef\TOCnumwidthF{\the\wd0}\fi}{}%
    \etocsetstyle{subparagraph}{}
      {\setbox0\hbox{\etocthenumber\kern#2}}
      {\ifdim\wd0>\TOCnumwidthG\edef\TOCnumwidthG{\the\wd0}\fi}{}%
    %
    \etocsettocstyle{}
     {\global\let\TOCnumwidthB\TOCnumwidthB
      \global\let\TOCnumwidthC\TOCnumwidthC
      \global\let\TOCnumwidthD\TOCnumwidthD
      \global\let\TOCnumwidthE\TOCnumwidthE
      \global\let\TOCnumwidthF\TOCnumwidthF
      \global\let\TOCnumwidthG\TOCnumwidthG}%
    \etocnopar
    \csname #1tableofcontents\endcsname
\typeout{Next TOCs will use \TOCnumwidthB\space for chapter number width}%
\typeout{Next TOCs will use \TOCnumwidthC\space for section number width}%
\typeout{Next TOCs will use \TOCnumwidthD\space for subsection number width}%
\typeout{Next TOCs will use \TOCnumwidthE\space for subsubsection number width}%
\typeout{Next TOCs will use \TOCnumwidthF\space for paragraph number width}%
\typeout{Next TOCs will use \TOCnumwidthG\space for subparagraph number width}%
    \endgroup
}%
\newcommand*\TOCcomputenumwidths [1][0.5em]{%
  \TOCcompute@numwidths {}{#1}%
}%
\newcommand*\TOCcomputelocalnumwidths [1][0.5em]{%
  \TOCcompute@numwidths {local}{#1}%
}%
\makeatother
\end{filecontentshere}
\attachfile[description={demo \the\value{section}}]{etocsnippet-\the\value{section}.tex}
The optional parameter to \csa{TOCcomputenumwidths} specifies the minimal
indent. In case nothing is numbered you may wish a higher value than |0.5em|.
For each local table of contents to have its own width computations, the macro
\csa{TOCcomputelocalnumwidths} is provided. As the code makes global
assignments, either use (once) \csa{TOCcomputenumwidths} or do
\csa{TOCcomputelocalnumwidths} for each local table of contents.
\begin{verbatim}
  \TOCcomputelocalnumwidths  % may use optional argument to replace 0.5em
  \localtableofcontents
\end{verbatim}
Notes:
\begin{enumerate}[nosep]
\item naturally these are only suggestions. For example one could put
  everything in single macros \csa{TOCtoc} and \csa{TOClocaltoc} to
  simultaneously compute the numwidths and then typeset the (local) table of
  contents.
\item if you want to adjust the |tocdepth| recall from
  \autoref{ssec:bookmarksdepth} that it influences |hyperref| hence you may
  need to use a group |\begingroup...\endgroup|. Or, one can use
  \csb{etocsetnexttocdepth}\marg{level} but (with the code as here) this must
  then be issued twice, once for \csa{TOCcomputelocalnumwidths}, once for
  \csa{localtableofcontents}.
\item the bold font serves above for both chapter and section numwidth
  computations, but the code from \autoref{sec:thirdexample} uses |\bfseries|
  only in local TOCs. Thus the \csa{TOCcomputenumwidth} will set the parameter
  \csa{TOCnumwidthC} to a value slightly larger than needed in the main TOC.
  Hence the section style in \csa{TOCcompute@numwidths} should possibly insert
  the |\bfseries| in the box only after testing for the optional parameter
  |local|.
\end{enumerate}

\clearpage
\etocdepthtag.toc {linestyles}

\part{Commands for the toc line styles}
\label{part:linestyles}

\thispartstats

\etocsetstyle{section}
{\begin{enumerate}[leftmargin=.75cm, label=\etocifnumbered
      {{\fboxrule1pt\fcolorbox{green}{white}{\etocnumber}}}{}]}
% Dec 7, 2012. I hit upon a problem whose origin I found was
% with xcolor, as xcolor modifies \fbox
% (try \section{\fbox{A}} with and without xcolor). The fix
% was to \protect the \fbox used in the |enumitem| label.
% Strangely enough, with |hyperref| active, the problem did
% not show up. Anyhow I now use \fcolorbox rather than \fbox
% and there is no problem anymore. Also I don't have now to
% use \normalcolor which already needed protection.
{\normalsize\bfseries\rmfamily\item}
{\etocname{} (page \etocpage)}
{\end{enumerate}}

\etocsetstyle{subsection}
{\begin{enumerate}[leftmargin=0cm, label=\etocnumber]}
{\normalfont \item}
{\etocname{} (p.~\etocpage)}
{\end{enumerate}}

\etocsetstyle{subsubsection}
{\par\nobreak\begingroup\normalfont\footnotesize\itshape\etocskipfirstprefix}
{\allowbreak\,--\,}
{\etocname}
{.\hfil\par\endgroup\pagebreak[3]}

% 27 janvier 2013 22:30
% je définis les macros (non protégées) 
% \etocthename, \etocthenumber, \etocthepage

\etocruledstyle[1]{\etocfontminusone\color{green}%
     \fboxrule1pt\fboxsep1ex
     \framebox[\linewidth]
              {\normalcolor\hss Contents of \autoref{part:linestyles}\hss}}

\localtableofcontents \label{toc:a}

\section{The \csbhyp{etocsetstyle}, \csbhyp{etocname} and \csbhyp{etocpage} commands}\label{sec:etocsetstyle}
\label{etocsetstyle}
\label{etocname}
\label{etocpage}

Let us explain how \etoc was used to produce the table of
contents displayed at the beginning of this \autoref{part:linestyles}.
This
is a local table of contents, and we used the command \localtoc.


We shall distinguish between the \emph{line styles} and the
\emph{toc display style}. The line styles were (essentially)
obtained in the following manner:%
\footnote{the present document has
  {\ttfamily\string\renewcommand\string{%
      \string\familydefault\string}\string{\string\sfdefault\string}}
  in its preamble, hence \csa{normalfont} switches to the
  |sans| typeface; so in the section line-style, I wrote
  \csa{rmfamily} instead.}

\begingroup\small
\begin{filecontentshere}{etocsnippet-\the\value{section}.tex}
\etocsetstyle{section}
{\begin{enumerate}}
{\normalsize\bfseries\rmfamily\item}
{\etocname{} (page \etocpage)}
{\end{enumerate}}

\etocsetstyle{subsection}
{\begin{enumerate}}
{\normalfont\item}
{\etocname{} (p.~\etocpage)}
{\end{enumerate}}

\etocsetstyle{subsubsection}
{\par\nobreak\begingroup\normalfont
        \footnotesize\itshape\etocskipfirstprefix}
{\allowbreak\,--\,}
{\etocname}
{.\hfil\par\endgroup\pagebreak[3]}
\end{filecontentshere}
\attachfile[description={demo \the\value{section}}]{etocsnippet-\the\value{section}.tex}
\endgroup

These provisory style definitions rely on the automatic
numbering generated by the |enumerate| environments but it is
much better to use the further command \csb{etocnumber} inside
the item label, which gives the real thing. The improved
definitions will thus be explained later.

With this style, one would have 
to be imaginative to design something then for paragraph and
subparagraph entries! perhaps as superscripts? Well, usually
one does not need paragraphs and subparagraphs numbered and
listed in the TOC, so our putative user here chose a design
where no provision is made for them and added the definitive:
\begin{verbatim}
\etocsetstyle{paragraph}{}{}{}{}
\etocsetstyle{subparagraph}{}{}{}{}
\end{verbatim}
This is also the situation with the default package line styles!

Each \csb{etocsetstyle} command has five mandatory arguments:\\
\hbox to \linewidth
{\hfil\csb{etocsetstyle}\color{blue}\marg{levelname}%
  \marg{start}\marg{prefix}\marg{contents}\marg{finish}\hfil}
The initially recognized \meta{levelname}'s are the sectioning
levels of the standard document classes: from \emph{part} (or
\emph{book} which is used by the |memoir| class) down to
\emph{subparagraph}.

The \meta{start} code is executed when a toc entry of that level is
encountered and the previous one was at a higher level. The
\meta{finish} code is executed when one again encounters a higher
level toc entry. In the meantime all entries for that level are
typeset by executing first the \meta{prefix} code and then the
\meta{contents} code. 

The (robust) commands \csb{etocname}, \csb{etocnumber} and \csb{etocpage} are
provided for use inside the \meta{prefix} and \meta{contents} parts of the
\csb{etocsetstyle} specification. They represent of course, the name, number,
and page number of the corresponding toc entry. If package |hyperref| is
active in the document and has added hyperlinks to the TOC data, then these
links are kept in the commands \csb{etocname}, \csb{etocnumber} and
\csb{etocpage} (this last one will have a link only if |hyperref| was passed
option \emph{linktoc=all}.)%
%
\footnote{In case of \emph{linktoc=page}, only \csb{etocpage} is an hyperlink;
see the discussion of \csb{etoclink} on how to create (possibly also with the
\emph{name} or \emph{number}) hyperlinks with the same target.}

\section{The \csbhyp{etocskipfirstprefix} and \csbhyp{etociffirst} commands}
\label{etocskipfirstprefix}
\label{etociffirst}
\label{etocxiffirst}

The chosen |subsubsection| style made use of the command
\csb{etocskipfirstprefix}, which instructs \etoc to \emph{not} use
for the first item the specified \meta{prefix} code.\footnote{With
versions earlier than |1.08| it had to be the very last token in
the \meta{start} code. It may now appear anywhere therein.}

The command \csb{etociffirst}\marg{YES CODE}\marg{NO CODE} (new
with |1.08|) is a more flexible way to customize the \meta{prefix}
(and \meta{contents}) specifications. It executes the \meta{YES
CODE} branch if this is the first unit at that level (inside a
lower level) and the \meta{NO CODE} if not. This is a robust
command which survives to expansion (for example in an |enumitem| label).

The variant \csb{etocxiffirst} does the same, but is expandable.


\section{The \csbhyp{etocnumber} command}
\label{etocnumber}

So far, our specifications would use the numbering generated
by the |enumerate| environments, but of course we generally want
the actual numbers as found in the |.toc| file. This is
available via the \csb{etocnumber} command. To get the labels
in the |enumerate| list to use it we can proceed with the
syntax {\ttfamily label=\char32} from the package |enumitem|:
\begin{verbatim}
\etocsetstyle{section}
{\begin{enumerate}[label=\etocnumber]}
{\normalsize\bfseries\rmfamily\item}
{\etocname{} (page \etocpage)}
{\end{enumerate}}
\end{verbatim}
Rather than just \csb{etocnumber} we then used something like
|\fbox{\etocnumber}|. Note that \csb{etocnumber} is a robust
command which explains why it can be used inside the label specification
without needing an added |\protect|.


\section{The \csbhyp{etocifnumbered} switch}
\label{etocifnumbered}
\label{etocxifnumbered}

The \csa{fbox} would give an unaesthetic result in the case of
an unnumbered section (which ended up in the table of
contents via an \csa{addcontentsline} command).\footnote{as
  seen we use \csa{fcolorbox} rather than \csa{fbox}. Due
  to some redefinition made by package |xcolor|, had we used
  \csa{fbox} (and not used |hyperref|) we would have needed
  \csa{protect}\csa{fbox}.}

The \csb{etocifnumbered}\marg{A}\marg{B} command executes
\meta{A} if the number exists, and \meta{B} if not. So we use
it in the code which was finally chosen for the |section| level:
\begin{verbatim}
\etocsetstyle{section}
{\begin{enumerate}[leftmargin=.75cm, label=\etocifnumbered
      {{\fboxrule1pt\fcolorbox{green}{white}{\etocnumber}}}{}]}
{\normalsize\bfseries\rmfamily\item}
{\etocname{} (page \etocpage)}
{\end{enumerate}}

\etocsetstyle{subsection}
{\begin{enumerate}[leftmargin=0cm, label=\etocnumber]}
{\normalfont \item}
{\etocname{} (p.~\etocpage)}
{\end{enumerate}}
\end{verbatim}

If we had changed only the |section| level, and not the
|subsection| level, an error on compilation would have occurred
because the package style for subsections expects to start `in
vertical mode'. An additional \csa{par} token in the
\meta{contents} part of the |section| level would have fixed
this: |{...(page \etocpage)\par}|.

The command \csb{etocifnumbered} is robust;  \csb{etocxifnumbered}
(new with |1.08|) has the same effect but is expandable.


\section{The \csbhyp{etocthename}, \csbhyp{etocthenumber}, and
\csbhyp{etocthepage} commands}
\label{etocthename}
\label{etocthenumber}
\label{etocthepage}

It is sometimes desirable to have access to the name, number and page
number without the hyperref link data: something similar to the starred
variant of the \csa{ref} command, when package |hyperref| is used. For
example one may wish to use the unit or page number in some kind of
numeric context, or change its formatting. This is provided by
\csb{etocthename}, \csb{etocthenumber}, and \csb{etocthepage}.

These commands are not protected, so in moving argument
contexts (for example in a label specification) they should be
preceded by |\protect|.

\section{The \csbhyp{etoclink} command}
\label{etoclink}

The command \csb{etoclink}\marg{text} can be used in the line style
specifications in a manner analogous to \csb{etocname}, \csb{etocnumber} and
\csb{etocpage}.  It creates a link (if such a link was added by |hyperref| to
the |.toc| file entry) whose target is the corresponding document unit and
whose name is the given \meta{text} mandatory argument.

Hence |\etoclink{\etocthename}| is under default conditions of |hyperref| like
the original |\etocname|, because the latter is already hyperlinked.  Under
\emph{linktoc=page} context |\etoclink{\etocthename}| adds the hyperlink which
is missing from \csb{etocname}.  Similarly under the default |hyperref|
condition (\emph{linktoc=section}) \csb{etocpage} is not an hyperlink, but one
can use |\etoclink{\etocthepage}|.

If \csa{hypersetup} is used with \emph{linktoc=none} then no miracle happens,
\csb{etoclink} does nothing special and none of \csb{etocname},
\csb{etocnumber} and \csb{etocpage} are links.



The command \csb{etoclink} is robust. Since |etoc 1.08j| it contains the link
destination in an already expanded form, so for example can be used even after
a |&| in a tabular construction, if \csb{etocglobaldefs} was issued.

\section{The \csbhyp{etocthelinkedname}, \csbhyp{etocthelinkednumber},
\csbhyp{etocthelinkedpage} and \csbhyp{etocthelink} commands}
\label{etocthelinkedname}
\label{etocthelinkednumber}
\label{etocthelinkedpage}
\label{etocthelink}


These macros are fragile and contain the link destination in already expanded
form. So their meaning can be stored for delayed usage. For example this is
done here when doing the \hyperref[tocastree]{examples with trees}.

Notice though that \csb{etocthelinkednumber} and \csb{etocthelinkedname} are
hyperlinks only if |hyperref| was configured to let the heading name be
linked (this is the default).  So under |hyperref| option \emph{linktoc=page},
both \csb{etocthelinkednumber} and \csb{etocthelinkedname} are no different
from respectively \csb{etocthenumber} and \csb{etocthename}.

For this reason, a further macro is provided: \csb{etocthelink} will fetch
the link destination if available be it from the name or from the page number.
Then |\etocthelink{foo}| hyperlinks an arbitrary text to the target destination
inside the produced PDF.

All these commands are fragile. The \csb{etocname}, \csb{etocnumber},
\csb{etocpage} and \csb{etoclink} are simply their robust variants. They too
contain the hyperlink destination in already expanded form since |1.08a| for
the first three, since |1.08j| for \csb{etoclink}.

Obsolete example of \begingroup
        \etocsetstyle {section}
          {\begin{itemize*}[itemjoin={{; }}, itemjoin*={{, and }}]}
          {\global\let\TmpEtocNumber\etocthelinkednumber
           \global\let\TmpEtocName\etocthelinkedname 
           \global\let\TmpEtocPage\etocthelinkedpage }
          {\item [{\bfseries\TmpEtocNumber.}]\TmpEtocName\ 
                 (\emph{p. \TmpEtocPage})}
          {\end{itemize*}.}%
    \etocsetnexttocdepth {section}%
    \etocsettocstyle {a table of contents done as an inline 
                          \texttt{enumitem} environment: }{}%
    \etocinline\tableofcontents \ref{toc:globalcmds}
\endgroup

\begin{verbatim}
Obsolete example of \begingroup
        \etocsetstyle {section}
          {\begin{itemize*}[itemjoin={{; }}, itemjoin*={{, and }}]}
          {\global\let\TmpEtocNumber\etocthelinkednumber
           \global\let\TmpEtocName\etocthelinkedname 
           \global\let\TmpEtocPage\etocthelinkedpage }
% (the above needed as \item closes a group in enumitem inline environments)
          {\item [{\bfseries\TmpEtocNumber.}]\TmpEtocName\ 
                 (\emph{p. \TmpEtocPage})}
          {\end{itemize*}.}%
    \etocsetnexttocdepth {section}%
    \etocsettocstyle {a table of contents done as an inline 
                          \texttt{enumitem} environment: }{}%
    \etocinline\tableofcontents \ref{toc:globalcmds}
\endgroup
\end{verbatim}

\etoc |1.08a| offers a simpler way to the same result: thanks to
\csb{etocglobaldefs} there is no need
anymore here for \csb{etocthelinkedname}, as \csb{etocname} works.
\begin{verbatim}
Example of 
\begingroup\etocglobaldefs % <-- NEW mit etoc 1.08.
        \etocsetstyle {section}
          {\begin{itemize*}[itemjoin={{; }}, itemjoin*={{, und }}]}
          {}
          {\item [{\bfseries\etocnumber.}] \etocname\ (\emph{p. \etocpage })}
          {\end{itemize*}.}%
    \etocsetnexttocdepth {section}%
    \etocsettocstyle {a table of contents done as an inline
                       \texttt{enumitem} environment: }{}%
    \etocinline\tableofcontents \ref{toc:globalcmds}
\endgroup
\end{verbatim}
Example of 
\begingroup\etocglobaldefs % <-- NEW mit etoc 1.08.
        \etocsetstyle {section}
          {\begin{itemize*}[itemjoin={{; }}, itemjoin*={{, und }}]}
          {}
          {\item [{\bfseries\etocnumber.}]
                 \etocname\ (\emph{p. \etocpage })}
          {\end{itemize*}.}%
    \etocsetnexttocdepth {section}%
    \etocsettocstyle {a table of contents done as an inline
                       \texttt{enumitem} environment: }{}%
    \etocinline\tableofcontents \ref{toc:globalcmds}
\endgroup

\section{The \csbhyp{etocsavedsectiontocline}, etc... commands.}
\label{etocsavedsectiontocline}
\label{etocsavedchaptertocline}

Since |1.08k| \etoc preserves
automatically in \csb{etocsavedsectiontocline}, \csb{etocsavedchaptertocline}
etc... the meaning of the \LaTeX\ |\l@section|, |\l@chapter|, etc... in force
at the time each \csb{tableofcontents} or \csb{localtableofcontents}
macro is executed.

See \autoref{sec:anothercompat} for usage.

\section{The \csbhyp{etocsetlevel} command}
\label{etocsetlevel}

As already explained in \autoref{part:surprising}, one
can inform \etoc of a level to associate to a given sectioning
command with \csb{etocsetlevel}. For example:
\begin{verbatim}
\etocsetlevel{cell}{0}
\etocsetlevel{molecule}{1}
\etocsetlevel{atom}{2}
\etocsetlevel{nucleus}{3}
\end{verbatim}
In compatibility mode, it will be assumed that the macros |\l@cell|,
|\l@molecule|, ..., have been defined somewhere either by the user or a class:
doing only |\etocsetlevel| is not enough for the corresponding level to work
out-of-the-box in compatibility mode.

However, if no table of contents is typeset in compatibility mode, then all that
matters  is that the various line styles have been set. If, for example
|section| is at level |1|, then there is no need to do some
\csb{etocsetstyle}|{molecule}{..}{..}{..}{..}| after
\csb{etocsetlevel}|{molecule}{1}| if
\csb{etocsetstyle}|{section}{..}{..}{..}{..}| has already been done (and it has
been done by the package itself in its definition of its own line styles).
 
The accepted levels run from |-2| to |6| inclusive.  Anything else is
mapped to |6|, which is a dummy level, never displayed. The package
does:
\begin{verbatim}
\etocsetlevel{book}{-2}
\etocsetlevel{part}{-1}
\etocsetlevel{chapter}{0}
\etocsetlevel{section}{1}
\etocsetlevel{subsection}{2}
\etocsetlevel{subsubsection}{3}
\etocsetlevel{paragraph}{4}
\etocsetlevel{subparagraph}{5}
\end{verbatim}
\etoc own custom styles are activated by \csb{etocdefaultlines}. They
are illustrated by the main table of contents of this
document. 

These level assignments can be modified at anytime: see
\autoref{part:surprising} for various applications of this
technique. As one 
further example, let's mention here that the \hyperref[toc:main]{main table of
contents} of this document was typeset following these instructions:
\begin{filecontentshere}{etocsnippet-\the\value{section}.tex}
\etocsettocdepth {subsubsection} % set the initial tocdepth
\etocdefaultlines % use the package default line styles. At this early stage in
                  % the document they had not yet been modified by \etocsetstyle
                  % commands, so \etoctoclines could have been used, too.
\etocmarkboth\contentsname
\etocmulticolstyle[1]                   % one-column display
    {\pdfbookmark[1]{Table of contents}{MAINTOC}% create a bookmark in the pdf
     \noindent\bfseries\Large
     \leaders\hrule height1pt\hfill
     \MakeUppercase{Table of Contents}}
\begingroup                             % use a group to limit the scope of the
  \etocsetlevel{subsection}{3}          %   subsection level change.
  \etocsetlevel{subsubsection}{4}       % anything > tocdepth=3.
  \tableofcontents \label{toc:main}
\endgroup
\end{filecontentshere}
\attachfile[description={demo \the\value{section}}]{etocsnippet-\the\value{section}.tex}
In this way, the subsections used the style originally designed for
subsubsections, the subsubsections were not printed. Without this modification,
the appearance would have been very different: the package line styles were
targeted to be employed in documents with many many sub-sub-sections, in a
two-column layout, giving thus a more compact output that what is achieved by
the default \LaTeX{} table of contents. But here, we have few sub-sub-sections
and it is more interesting to drop them and print in a visually different manner
sections and subsections. 


\section{Scope of commands added to 
         the \texorpdfstring{\texttt{.toc}}{.toc} file}

\begingroup % pour \small et \MacroFont en particulier.
\small

\subsection{Testing the scope}

Let us switch to the color red, and also add this command to the |.toc| file:

\color{red!50}
\addtocontents{toc}{\string\color{red!50}}

\def\MacroFont{\ttfamily \footnotesize\hyphenchar\font45 }
\begin{verbatim}
   \color{red!50}                             % changing text color
   \addtocontents{toc}{\string\color{red!50}} % and also in the .toc file
\end{verbatim}


\subsection{This is a (pale) red subsection for illustrative purposes}

Actually, this title here was printed black, due to the way the |scrartcl| class
works (it would have been red in the |article| class), but we are more
interested in how it looks in the tables of contents: it does appear red in the
\hyperref[toc:main]{main table of contents} at the beginning of
this document, and also in the \hyperref[toc:a]{table of
contents for this part}. Both entries obey as expected the
|\color{red!50}| command inserted in the |.toc| file.

But let us now close this subsection and start a section.


\section{Am I also red?}

The question is about how it appears in the tables of contents: the answer is
that, yes it is red in the \hyperref[toc:main]{main TOC}, and no
it is not red in the \hyperref[toc:a]{local TOC for this part}.
The reason is that the \meta{finish} code for the subsection level closed a
group, as it used |\end{enumerate}|.

This illustrates the discussion from \autoref{ssec:limitations}. 

The default package line styles do not contain group opening and closing
instructions: the influence of a command added to the |.toc| file will propagate
until cancelled by another explicit such command inserted in the |.toc|
file.

\begin{verbatim}
    \normalcolor
    \addtocontents{toc}{\string\normalcolor}
\end{verbatim}
\endgroup

\normalcolor
\addtocontents{toc}{\string\normalcolor}

Back to black. Note that this scope problem arises in real life in a
multi-lingual document, as the |babel| package writes to the |.toc| file the
language changes occurring in the document. 


\clearpage
\etocdepthtag.toc {globalcmds}

\part{Commands for the toc display style}
\label{part:globalcmds}

\thispartstats

\etocsettocstyle{}{}
\etocstandardlines
\localtableofcontents \label{toc:globalcmds}


\section{Specifying the toc display style}


The \emph{toc display} style says whether the TOC appears with
multiple columns or just one, whether the title is typeset as
in the |article| or |book| class, or should be centered above
the entries, with rules on its sides, or if the entire TOC
should be put in a frame. For example, to opt for a ruled
heading and single column layout, one issues commands of the
following type:
\begin{verbatim}
\etocruledstyle[1]{Title} \tableofcontents    (or \localtableofcontents)
shortcuts:         \etocruled[1]{Title}  (or  \etoclocalruled[1]{Title})
\end{verbatim}

\subsection{The command \csbhyp{etocsettocstyle}}
\label{etocsettocstyle}

This is a command with two mandatory arguments:\\
\centerline{\csb{etocsettocstyle}\marg{before\_toc}%
\marg{after\_toc}}
The \marg{before\_toc} part is responsible for typesetting the
heading, for example it can be something like
\starit{section}|{\contentsname}|. 

Generally speaking this heading
should leave \TeX{} in ``vertical mode'' when the actual
typesetting of the contents will start: the line styles (either
from the standard classes or the package default line styles)
all expect to get started in `vertical mode'.

The first argument to \csb{etocsettocstyle} can also contain
instructions to mark the page headings.  Or
it could check (book class) to see if two-column mode is on,
and switch to one-column style, and the \meta{after\_toc} part
would then reenact the two-column mode.

\textbf{\TeX\ hacker note:} We have seen in the previous chapter some examples
of using |\begin{enumerate}| and |\end{enumerate}| within TOC line styles.
There is a real difficulty with doing however something like this:
\begin{verbatim}
\etocsettocstyle{\begin{enumerate}}{\end{enumerate}}
\etocsetstyle{section}{}{\item \sectionname}{}{}
\end{verbatim}
Indeed for example on first compilation of a document, the |.toc| file is
empty and there will be the typical ``Something's wrong--perhaps a missing
\string\item''. Using \csb{etocchecksemptiness} does not help, because as is
explained there, on first encountering a new TOC added at end of a document,
\etoc considers it non-empty, hence querying \csb{etocifwasempty} serves
nothing. No, one must do something like this:
\begin{verbatim}
\makeatletter
\etocsettocstyle
  {\begin{enumerate}}
  {\if@newlist\item Please run \LaTeX\ again\fi
   \end{enumerate}}
\makeatother
\etocsetstyle{section}{}{\item \sectionname}{}{}
\end{verbatim}

The commands to be described next \csb{etocmulticolstyle},
\csb{etocruledstyle}, and \csb{etocframedstyle} all call
\csb{etocsettocstyle} as a lower-level routine, to start a 
\texttt{multi\-cols} environment in \marg{before\_toc} and close it in
\marg{after\_toc}. 

\subsection{The commands \csbhyp{etocmulticolstyle}, \csbhyp{etocmulticol}, and \csbhyp{etoclocalmulticol}}
\label{etocmulticolstyle}
\label{etocmulticol}
\label{etoclocalmulticol}

This is a command with one optional and one mandatory argument:\\
\centerline{\csb{etocmulticolstyle}%
  \oarg{number\_of\_columns}\marg{heading}} The
\meta{number\_of\_columns} can go from 1 to 10 (it defaults to 2; if its
value is 1, naturally no |multicols| environment is then created). The
\meta{heading} will typically be some `vertical' material like:
  \meta{heading} = |\section*|\marg{title}
but one may also have horizontal material like |\fbox{Hello World}| (\etoc
adds automatically a |\par| at the end of this ``heading'' argument to
\csb{etocmulticolstyle}). Here is for example
how the main table of contents of this document was
configured:
\begin{verbatim}
\etocmulticolstyle{\noindent\bfseries\Large
                   \leaders\hrule height1pt\hfill
                   \MakeUppercase{Table of Contents}}
\end{verbatim}
After \csb{etocmulticolstyle} all future \csa{tableofcontents} will use the
specified style, if it does not get changed in-between. A shortcut for
just one table of contents and 
no impact on the styles of later TOCs is:\\
\centerline{\csb{etocmulticol}\oarg{number\_of\_columns}\marg{heading}}
And there is also
\csb{etoclocalmulticol}\oarg{number\_of\_columns}\marg{heading}.

\subsection{The command \csbhyp{etoctocstyle}}
\label{etoctocstyle}

\centeredline{\csb{etoctocstyle}\oarg{kind}%
\marg{number\_of\_columns}\marg{title}}
\centeredline{=
\csb{etocmulticolstyle}|[|{\itshape number\_of\_columns}|]|%
|{\kind*{|\itshape title\upshape|}}|}
where |kind| is one of |chapter|, |section|, . . . and defaults
to |chapter| or |section| depending on the document class.

\subsubsection{The command \csbhyp{etoctocstylewithmarks}}
\label{etoctocstylewithmarks}
\label{etoctocstylewithmarksnouc}

\centeredline{\csb{etoctocstylewithmarks}\oarg{kind}%
\marg{number\_of\_columns}\marg{title}\marg{mark}}
\centeredline
{=\csb{etocmulticolstyle}|[|{\itshape number\_of\_columns}|]|%
|{\kind*{|\itshape title \ttfamily\upshape\string\markboth%
|{\MakeUppercase{|{\rmfamily\itshape mark}|}}}}|} 
where |kind| is one of |chapter|, |section|, ... The
actual display of the marks depends on the settings of the
page style. There is variant \csb{etoctocstylewithmarksnouc}
which does not uppercase.

\paragraph{Do we really want paragraph entries in the TOC?}

\paragraph{really?}

\subsection{The commands  \csbhyp{etocruledstyle}, \csbhyp{etocruled} and \csbhyp{etoclocalruled}}
\label{etocruledstyle}
\label{etocruled}
\label{etoclocalruled}

The general format of \csb{etocruledstyle} is:\\
\centerline{\csb{etocruledstyle}%
\oarg{number of columns}\marg{title of the toc}}
\noindent 
The title is horizontal material (the |LR| mode of 
\emph{\LaTeX{}, a document preparation system}): if it
does not fit on one line it should be put in a \csa{parbox}  of
a given width.
The green frame for the heading of the table of contents at
the \hyperref[toc:a]{start of the second part of this
  document} was obtained with:
\begin{verbatim}
\etocruledstyle[1]{\etocfontminusone\color{green}%
     \fboxrule1pt\fboxsep1ex
     \framebox[\linewidth]
              {\normalcolor\hss Contents of this part\hss}}
\end{verbatim}


As a shortcut to set the style with \csb{etocruledstyle} and
then issue a
\csa{tableofcontents}, all inside a group
so that  future table of contents will not be
affected, there is:\\
\centerline{\csb{etocruled}\oarg{number\_of\_columns}\marg{title}}
And the local form will be \csb{etoclocalruled}.

\subsection{The commands \csbhyp{etocframedstyle},  \csbhyp{etocframed}, and \csbhyp{etoclocalframed}}
\label{etocframedstyle}
\label{etocframed}
\label{etoclocalframed}

Same mechanism:\\
\centerline{\csb{etocframedstyle}%
  \oarg{number\_of\_columns}\marg{title}}
and the accompanying shortcut:\\
\centerline{\csb{etocframed}\oarg{number\_of\_columns}\marg{title}} The
shortcut is used if one does not want to modify the style of the next
TOCs (the other way is to put the whole thing inside braces or a
|\begingroup...\endgroup|; there is also \csb{etoclocalframed} for a
local table of contents).

The entire table of contents is framed. The title itself is not framed:
if one wants a frame one should set it up inside the \meta{title}
argument to \csb{etocframedstyle} or \csb{etocframed}. The colors for
the background and for the components (top, left, right, bottom) of the
border are specified via suitable |\renewcommand|'s (see
\autoref{ssec:customdisplay}).

A |minipage| is used, hence the produced table of contents isn't
compatible with a page break. For allowing page breaks, use of
the commands of
\href{http://ctan.org/pkg/mdframed}{mdframed}\footnote{\url{http://ctan.org/pkg/mdframed}}
or 
\href{http://ctan.org/pkg/tcolorbox}{tcolorbox}\footnote{\url{http://ctan.org/pkg/tcolorbox}}
in the arguments of \csb{etocsettocstyle}  
is recommended.

Examples in this document are on pages \pageref{toc:d},
\pageref{toc:floating}, \pageref{toc:b}, and \pageref{toc:clone}.


\subsection{Headings, titles, \csbhyp{etocoldpar}, \csbhyp{etocinnertopsep}}
\label{etocinnertopsep}
\label{etocoldpar}

For \csb{etocmulticolstyle} the mandatory \meta{heading} argument can be
either 
vertical mode material like |\section*{\emph{Table of Contents}}| or
horizontal mode material like in the simple |\etocmulticolstyle{Hello World}|.

No explicit |\par| or empty line can be inserted in the mandatory
argument of \csb{etocmulticolstyle}, but \etoc provides \csb{etocoldpar}
as a substitute: it does |\let\etocoldpar\par| before the |multicols|
environment and inserts this |\etocoldpar|\footnote{this command
  \csb{etocoldpar} (= working \csa{par} in the argument to
  \csb{etocmulticolstyle}) is not related to the switch \csb{etocinline}
  whose purpose is to tell \etoc not to do a \csa{par} before the table
  of contents.} at the end of the heading, then does a vertical skip of
value \csb{etocinnertopsep}. The command \csb{etocoldpar} can also be
used explicitely if needed in the mandatory argument to
\csb{etocmulticolstyle} (it is not allowed to insert an empty line
in this argument).

On the other hand the commands \csb{etocruledstyle} and
\csb{etocframedstyle} expect an argument ``in LR mode'' (to use the
terminology from \emph{LaTeX, a document preparation system}). This
means that multiline titles are only possible if enclosing
them inside something like a \csa{parbox}.



An important dimension used by all three of \csb{etocmulticolstyle},
\csb{etocruledstyle} and \csb{etocframedstyle} is
\csb{etocinnertopsep}. It gives the amount of separation
between the heading and the start of the contents. Its default
value is |2ex| and it is changed with
|\renewcommand*{\etocinnertopsep}|\marg{new\_value}, not with
|\setlength|. 



\subsection{The compatibility mode \csbhyp{etocstandarddisplaystyle}}
\label{etocstandarddisplaystyle}

\etoc will then emulate what the document class would have
done regarding the global display style of the table of
contents, in its absence. All customizing from inside the
class should be obeyed, too.

\subsubsection{The commands \csbhyp{etocarticlestyle}, \csbhyp{etocbookstyle},
  \dots}

These are the commands used internally by \etoc in compatibility mode
depending on the document class. For example \csb{etocarticlestyle} instructs
\etoc to use |\section*{\contentsname}| (with marks on the page) and
\csb{etocbookstyle} says to use |\chapter*{\contentsname}|. It can prove
useful to issue \csb{etocarticlestyle} for a \csa{localtableofcontents} inside
a chapter, in |book| class and compatibility mode for the global TOC display
style.

\subsection{The command \csbhyp{etocinline}}
\label{etocinline}
\label{etocnopar}
\label{etocdisplay}

With \csb{etocinline}, or its synonym |\etocnopar|, the
|\tableofcontents| command and its variants do \emph{not} first issue a
|\par| to close the previous paragraph. Hence, the table of contents can
be printed in an inline style; or, if used only for preparing some token
list or macro, it will leave nothing in the token stream on execution.

Issue \csb{etocdisplay} to return to the default situation that
|\tableofcontents| and variants issue a |\par| to switch to vertical
mode before typesetting the TOC title and contents.

\section{Starred variants and hooks}
\label{tableofcontents*}
\label{localtableofcontents*}
\label{etocbeforetitlehook}
\label{etocaftertitlehook}
\label{etocaftercontentshook}
\label{etocaftertochook}

The \toc, \localtoc, \csb{etocmulticol}, and all their cousins have starred
variants (the star must be before the other arguments). The non-starred
variants execute the \csb{etocaftertitlehook}, whose default definition is to
do nothing. The starred variants do not execute this hook.

For example, imagine you are using |book| class and want \localtoc to use a
section-like title, but unnumbered. Assuming the main \toc comes first in the
document, you can insert this after it:
\begin{verbatim}
  \etocarticlestyle
  \renewcommand{\etocaftertitlehook}{\addcontentsline{toc}{section}{\contentsname}}
\end{verbatim}
This configures the way \localtoc will behave (or \toc) from now on in the
document.

The first line tells essentially to use |\section*{\contentsname}|, and the
second line says to insert the title in the |.toc| file itself (thus to be
displayed by the main table of contents). Notice that |hyperref| package will
then automatically create suitable anchor and one should \emph{not} use
explicitly \cs{phantomsection} here (it would let the anchor be located below
not above the title).

With this set-up issuing \localtoc|*| will ignore the \csb{etocaftertitlehook}
hence not send the local toc title to the |.toc| file. This mimicks the
|memoir| class behavior, and can also be used with it. For more on |memoir|
class with \etoc, see \autoref{ssec:memoir}.

There are further hook macros:
\csb{etocaftercontentshook}, \csb{etocbeforetitlehook} and
\csb{etocaftertochook} which are initially defined to do nothing and can be
used for some special effects. They are executed whether or not the table of
contents command was starred.%
%
\footnote{Hackers can test within these hooks if the context is starred or not
  via an \cs{ifx}\cs{Etoc@aftertitlehook}\cs{@empty} conditional. Perhaps a
  future release will provide \cs{etociftocisstarred} wrapper.}


\clearpage
\etocdepthtag.toc {custom}

\part{Using and customizing the \etoc own styles}
\label{part:custom}

\thispartstats

\etocdefaultlines
\renewcommand{\etoctoprule}{\hrule height2pt depth0pt}
\renewcommand{\etoctoprulecolorcmd}{\color{red}}

\etocruledstyle{\normalfont\normalsize\rmfamily\fboxrule1pt\color{red}%
  \fbox{\parbox{.8\linewidth}{\centering\normalcolor This is a table of
      contents for the sections and
      subsections in this part. It carries the label |toc:c|}}} 

\localtableofcontents \label{toc:c}


\section{Summary of the main style commands}

\subsection{Setting up local styles}

\hbox{\color{green}\fboxrule1pt\fboxsep1em
\setbox0\hbox{\csb{etocthename}, \csb{etocthenumber}, \csb{etocthepage}, \csb{etoclink}\marg{linkname}}%
\framebox[\linewidth][c]
{\vbox{\hsize\wd0\normalcolor\noindent
\csb{etocsetstyle}\marg{levelname}%
  \marg{start}\marg{prefix}\marg{contents}\marg{finish}\\
\csb{etocname}, \csb{etocnumber}, \csb{etocpage},
\csb{etocifnumbered}\marg{A}\marg{B}\\
\csb{etocthename}, \csb{etocthenumber}, \csb{etocthepage}, \csb{etoclink}\marg{linkname}
}}}

\subsection{Setting up toc display styles}

\medskip
\hbox{\color{green}\fboxrule1pt\fboxsep1em
\setbox0\hbox{\csb{etoctocstylewithmarksnouc}\oarg{kind}%
\marg{number\_of\_columns}\marg{title}\marg{mark}}%
\framebox[\linewidth][c]
{\vbox{\hsize\wd0
\normalcolor\noindent
\csb{etocmulticolstyle}\oarg{number\_of\_columns}\marg{heading}\\
\csb{etoctocstyle}\oarg{kind}\marg{number\_of\_columns}\marg{title}\\
\csb{etoctocstylewithmarks}\oarg{kind}\marg{number\_of\_columns}%
\marg{title}\marg{mark}\\
\csb{etoctocstylewithmarksnouc}\oarg{kind}\marg{number\_of\_columns}%
\marg{title}\marg{mark}\\
\csb{etocruledstyle}\oarg{number\_of\_columns}\marg{title}\\
\csb{etocframedstyle}\oarg{number\_of\_columns}\marg{title}\\
\csb{etocsettocstyle}\marg{before\_toc}\marg{after\_toc}}}}

\subsection{Displaying tables of contents}


\medskip \hbox{\color{green}\fboxrule1pt\fboxsep1em
  \setbox0\hbox{\csb{etocname}, \csb{etocnumber},
    \csb{etocpage}, \csb{etocifnumbered}\marg{A}\marg{B}}%
  \framebox[\linewidth][c]
  {\vbox{\hsize\wd0\normalcolor\noindent
      \toc\\
      \localtoc\\
      \csb{etocmulticol}\oarg{number\_of\_columns}\marg{heading}\\
      \csb{etoclocalmulticol}\oarg{number\_of\_columns}\marg{heading}\\
      \csb{etocruled}\oarg{number\_of\_columns}\marg{title}\\
      \csb{etoclocalruled}\oarg{number\_of\_columns}\marg{title}\\
      \csb{etocframed}\oarg{number\_of\_columns}\marg{title}\\
      \csb{etoclocalframed}\oarg{number\_of\_columns}\marg{title}\\
      \hbox{}{\itshape\ttfamily\ \ \ \  and their starred variants}
   }}}

\subsection{Labels and references}
\label{ssec:labelref}

The commands (starred or not) to actually display the table of contents
can be followed with optional labels or references:\par

\medskip \hbox{\color{green}\fboxrule1pt\fboxsep1em
  \setbox0\hbox{\csb{etocname}, \csb{etocnumber},
    \csb{etocpage}, \csb{etocifnumbered}\marg{A}\marg{B}}%
  \framebox[\linewidth][c]
  {\vbox{\hsize\wd0\normalcolor\noindent
      \toc \csa{label}|\{toc:here\}|\\ 
      \toc \csa{ref}|\{toc:far\}| \\
      \toc \csa{label}|\{toc:here\}| \csa{ref}|\{toc:far\}| \\
      \localtoc \csa{label}|\{toc:here\}|\\ 
      \localtoc \csa{ref}|\{toc:far\}| \\
      \localtoc \csa{label}|\{toc:here\}| \csa{ref}|\{toc:far\}| \\
      \hbox{}{\itshape\ttfamily\ \ \ \ similarly with\ }%
      \csb{etocmulticol}{\itshape\ttfamily\ etc . . . }
   }}}


\medskip 

New with |1.08e|: \localtoc \csa{ref}|{toc:far}| as synonym for \toc
\csa{ref}|{toc:far}|.

% (obsolète depuis 1.08e)
% The commands for local tables of
% contents do \emph{not} react to a \csa{ref} following them. 

When re-displaying another toc, only its contents are transferred:
both the line styles and the toc display style are the ones
currently defined, not the ones from the cloned toc.


\section{The package default line styles: \csbhyp{etocdefaultlines}}
\label{etocdefaultlines}

These line styles were written at an early stage in the
development of the package; although the next section explains how
to customize the font choicess or vertical spaces, etc\dots, used
by these line styles, most other changes would require copying
them from the sources and modify them directly. Admittedly they
have been written at a rather scary low-\TeX{} level, and will not
serve as a very friendly starting point. 

Activating their use is done via \csb{etocdefaultlines}, or
\csb{etoctoclines} if the line styles have not been modified with
\csb{etocsetstyle}. Sections and sub-sections are printed in
essentially the same manner, except that the leading for
sub-sections is a bit smaller (with document classes lacking a
\csa{chapter} command, the sections are printed in bold typeface;
this is the case in the present document). Sub-sub-sections are
printed inline, in one paragraph, with no numbers or page numbers.
This style was designed and tested with documents having lots of
sub-sub-sections, and should be used on a two-column layout: it
provides (only in that situation with many sub-sub-sections) a
more compact presentation than what is achieved by the \LaTeX{}
default.\footnote{and there will never be a Part or Chapter entry
  alone at the bottom of a column or page (except if it has no
  sub-unit).} On the other hand, used with a one-column layout,
and with few sub-sub-sections, the style is a bit more spread out
vertically than the \LaTeX{} default, sub-sections are not
visually much different from sections (especially for document
classes with a \csa{chapter} command), so the result is less
hierarchical in appearance than in the \LaTeX{} default.

In this document, for the \hyperref[toc:main]{main table of contents}, we did 
|\etocsetlevel{subsection}{3}| hence the sub-sections were printed with the
sub-sub-section inline style. 

Let us, to the contrary, typeset now this main table of contents as if the
document had been done with a class having the \csa{chapter} command: we will
print sections as chapters, and subsections as sections. We use
\csb{etocsetlevel} for that, and also we need to change the font style of
``sections'' (which in truth are our subsections) to use not the bold but the
medium series; we modify the \csb{etocfontone} command for that. Also we use dot
leaders which are less spread out than in the package default.


\begin{filecontentshere}{etocsnippet-\the\value{section}.tex}
\etocruledstyle[2]{\normalfont\normalsize\rmfamily\itshape
  \fbox{\parbox{.6\linewidth}{
      \leftskip 0pt plus .5fil
      \rightskip 0pt plus -.5fil
      \parfillskip 0pt plus 1fil This is the global table of
      contents on two columns, using \etoc default line styles, but with
      sections as chapters, and subsections as sections.
      }}}
\etocdefaultlines
\etocsetnexttocdepth{1}
\begingroup
\etocsetlevel{section}{0}
\etocsetlevel{subsection}{1}
\renewcommand*{\etocfontone}{\normalfont \normalsize}
\renewcommand*{\etoctoclineleaders}
        {\hbox{\normalfont\normalsize\hbox to 1ex {\hss.\hss}}}
\sloppy
\tableofcontents
\endgroup
\end{filecontentshere}
\attachfile[description={demo \the\value{section}}]{etocsnippet-\the\value{section}.tex}

\filecontentsexec\filecontentsheremacro

\section{Customizing \etoc}

\subsection{Customizing  the \etoc pre-defined line styles}

We will simply list the relevant commands as defined in the
package. Customizing them goes through suitable
\csa{renewcommand}s:
\begin{verbatim}
\newcommand*\etocfontminustwo{\normalfont \LARGE \bfseries}
\newcommand*\etocfontminusone{\normalfont \large \bfseries}
\newcommand*\etocfontzero{\normalfont \large \bfseries}
\newcommand*\etocfontone{\normalfont \normalsize \bfseries}
% (in classes with chapter, \etocfontone does not do \bfseries)
\newcommand*\etocfonttwo{\normalfont \normalsize}
\newcommand*\etocfontthree{\normalfont \footnotesize}

\newcommand*\etocsepminustwo{4ex plus .5ex minus .5ex}
\newcommand*\etocsepminusone{4ex plus .5ex minus .5ex}
\newcommand*\etocsepzero{2.5ex plus .4ex minus .4ex}
\newcommand*\etocsepone{1.5ex plus .3ex minus .3ex}
\newcommand*\etocseptwo{.5ex plus .1ex minus .1ex}
\newcommand*\etocsepthree{.25ex plus .05ex minus .05ex}

\newcommand*\etocminustwoleftmargin{1.5em plus 0.5fil}
\newcommand*\etocminustworightmargin{1.5em plus -0.5fil}
\newcommand*\etocminusoneleftmargin{1em}
\newcommand*\etocminusonerightmargin{1em}

\newcommand*\etocbaselinespreadminustwo{1}
\newcommand*\etocbaselinespreadminusone{1}
\newcommand*\etocbaselinespreadzero{1}
\newcommand*\etocbaselinespreadone{1}
\newcommand*\etocbaselinespreadtwo{1}
\newcommand*\etocbaselinespreadthree{.9}
\newcommand*\etoctoclineleaders
    {\hbox{\normalfont\normalsize\hbox to 2ex {\hss.\hss}}}
\newcommand*\etocabbrevpagename{p.~}  % initial of "page"
\newcommand*\etocpartname{Part}  % prior to 1.08b, was \partname
% but this didn't make sense e.g. with babel+frenchb whose \frenchpartname
% takes into account the value of the part counter.
\newcommand*\etocbookname{Book} % to be modified according to language
\end{verbatim}

No customizing of the standard line styles is possible from
within \etoc. As already explained, when
\csb{etocstandardlines} has been issued, the package just makes
itself very discrete and acts only at the global level, and
the TOC entries are (hopefully) formatted as would have
happened in the absence of \etoc.\footnote{with the
  KOMA-script classes, we noticed that
  \csb{etocstandarddisplaystyle} was apparently needed for the
  KOMA options |toc=left| to be active at the level of the line entries.}  


The \csb{etocstandardlines} compatibility mode will work also with
sectioning commands made known to \etoc via \csb{etocsetlevel},
under the condition of course that these sectioning commands
are accompanied with all the relevant definitions for
typesetting toc entries in the \LaTeX{} default manner
(existence of the macros \csa{l@something} . . .).

Using the command \csb{etocsetstyle}, be it in the preamble or
in the body of the document, has the secondary effect of
switching off the compatibility mode.

\subsection{Customizing the toc display styles}
\label{ssec:customdisplay}

Again we list the relevant macros, what they do should be
legible from their names. Note that \csa{renewcommand}'s and
not \csa{setlength}'s have to be used for what appear to be
lengths, and that color commands are not just color
specifications, they must include \csa{color}, and are canceled
by re-defining them to do \csa{relax}.
\begin{verbatim}
\newcommand*\etocabovetocskip{3.5ex plus 1ex minus .2ex} 
\newcommand*\etocbelowtocskip{3.5ex plus 1ex minus .2ex}

\newcommand*\etoccolumnsep{2em}
\newcommand*\etocmulticolsep{0ex}
\newcommand*\etocmulticolpretolerance{-1}
\newcommand*\etocmulticoltolerance{200}
\newcommand*\etocdefaultnbcol{2}
\newcommand*\etocinnertopsep{2ex}
\newcommand*\etoctoprule{\hrule}
\newcommand*\etoctoprulecolorcmd{\relax}

% for the framed style only:
\newcommand*\etocinnerleftsep{2em}
\newcommand*\etocinnerrightsep{2em}
\newcommand*\etocinnerbottomsep{3.5ex}

\newcommand*\etocleftrule{\vrule}
\newcommand*\etocrightrule{\vrule}
\newcommand*\etocbottomrule{\hrule}
\newcommand*\etocleftrulecolorcmd{\relax}
\newcommand*\etocrightrulecolorcmd{\relax}
\newcommand*\etocbottomrulecolorcmd{\relax}

\newcommand*\etocbkgcolorcmd{\relax}

% hooks
\newcommand\etocframedmphook{\relax}
\end{verbatim}

The \csa{etocframedmphook} is positioned immediately
after the beginning of a minipage environment where the
contents of the framed TOC are typeset. 

The \csa{...colorcmd} commands are initially set to expand to
\csa{relax} (hence do not require package |color| or |xcolor|
to be loaded). If one has modified a command such as
\csa{etocbkgcolorcmd} to expand to a color command and wants
to reset it to do nothing, one \emph{must} use
|\renewcommand{\etocbkgcolorcmd}{\relax}| and not
\csa{let}\csa{etocbkgcolorcmd}\csa{relax}.

Regarding the dimensions of the top rule they can be specified
in |ex|'s or |em|'s as in this example:
\centeredline{|\renewcommand{\etoctoprule}{\hrule height 1ex}|} 
The package code is done in such a manner
that it is the font size in instance at the end of typesetting
the title argument to \csb{etocruledtoc} or
\csb{etocframedtoc} which will be used for the meaning of the
`1ex'. Of course also the other rule commands can have their
dimensions in font relative units, but their values are
decided on the basis of the font in effect just before the
table of contents.

The top and bottom rules do not have to be rules and can be
horizontal \emph{leaders} (of a specified height) in the general
\TeX{} sense. However the left and right rules are not
used as (horizontal) leaders but as objects of a given specified
width. Note that \emph{only} the Plain \TeX{} syntax for rules is
accepted here. 

\section{One more example of colored TOC layout}
\label{ssec:tocclone}

The command \csb{etocframedstyle} puts the title on the top
rule in a centered position. This is not very convenient for
this example so we included the title as part of the
\meta{start} code at section level, to get it \emph{inside}
the frame.

\begin{filecontentshere}{etocsnippet-\the\value{section}.tex}
\begingroup
\definecolor{subsecnum}{RGB}{13,151,225}
\definecolor{secbackground}{RGB}{0,177,235}
\definecolor{tocbackground}{RGB}{212,237,252}

\renewcommand{\etocbkgcolorcmd}{\color{tocbackground}}
\renewcommand{\etocleftrulecolorcmd}{\color{tocbackground}}
\renewcommand{\etocrightrulecolorcmd}{\color{tocbackground}}
\renewcommand{\etocbottomrulecolorcmd}{\color{tocbackground}}
\renewcommand{\etoctoprulecolorcmd}{\color{tocbackground}}

\renewcommand{\etocleftrule}{\vrule width 1cm}
\renewcommand{\etocrightrule}{\vrule width .5cm}
\renewcommand{\etocbottomrule}{\hrule height 12pt}
\renewcommand{\etoctoprule}{\hrule height 12pt}

\renewcommand{\etocinnertopsep}{0pt}
\renewcommand{\etocinnerbottomsep}{0pt}
\renewcommand{\etocinnerleftsep}{0pt}
\renewcommand{\etocinnerrightsep}{0pt}

\newcommand\shiftedwhiterule[2]{%
    \hbox to \linewidth{\color{white}%
    \hskip#1\leaders\vrule height1pt\hfil}\nointerlineskip\vskip#2}

\etocsetstyle{subsubsection}{\etocskipfirstprefix}
  {\shiftedwhiterule{\leftskip}{6pt}}
  {\sffamily\footnotesize
     \leftskip2.5cm\hangindent1cm\rightskip1cm\noindent
     \hbox to 1cm{\color{subsecnum}\etocnumber\hss}%
     \color{black}\etocname\leaders\hbox to .2cm{\hss.}\hfill
     \rlap{\hbox to 1cm{\hss\etocpage\hskip.2cm}}\par
     \nointerlineskip\vskip3pt}
  {}

\etocsetstyle{subsection}{\etocskipfirstprefix}
  {\shiftedwhiterule{1.5cm}{6pt}}
  {\sffamily\small
     \leftskip1.5cm\hangindent1cm\rightskip1cm\noindent
     \hbox to 1cm{\color{subsecnum}\etocnumber\hss}%
     \color{black}\etocname\leaders\hbox to .2cm{\hss.}\hfill
     \rlap{\hbox to 1cm{\hss\etocpage\hskip.2cm}}\par
     \nointerlineskip\vskip6pt}
  {}

\newcommand{\coloredstuff}[2]{%
            \leftskip0pt\rightskip0pt\parskip0pt
            \fboxsep0pt % \colorbox uses \fboxsep also when no frame!
       \noindent\colorbox{secbackground}
               {\parbox{\linewidth}{%
                    \vskip5pt
                    {\noindent\color{#1}#2\par}\nointerlineskip
                    \vskip3pt}}%
       \par\nointerlineskip}

\etocsetstyle{section}
{\coloredstuff{white}
     {\hfil \hyperref[toc:b]{\bfseries\large I am a twin of  
     that other TOC (click me!)}\hfil}}
{\vskip3pt\sffamily\small}
{\coloredstuff{white}
    {\leftskip1.5cm\rightskip.5cm\parfillskip-\rightskip
     \makebox[0pt][r]{\makebox[.5cm][r]{\etocnumber\hspace{.2cm}}}%
     \etocname\hfill\makebox[.5cm][r]{\etocpage\hspace{.2cm}}}%
 \vskip6pt }
{}

\etocframedstyle[1]{}
\tableofcontents \label{toc:clone} \ref{toc:globalcmds}
\endgroup
\end{filecontentshere}
\attachfile[description={demo \the\value{section}}]{etocsnippet-\the\value{section}.tex}

\filecontentsexec\filecontentsheremacro
% 1.07l on the occasion of traduction into German documentation 
     % APRIL 26, 2014 Improvement in the section style for better placement of
     % page number when the section name is more than one line long. Use of
     % \makebox rather than \hbox, to be more LaTeX like.

The TOC has been put in a \hyperref[toc:clone]{float} which appears
\vpageref{toc:clone}. The coding is a bit involved\footnote{and reveals the
  author's preference for the \TeX{} syntax...} as it does not use any
additional package. Also, it was written at some early stage and I have not
revised it since.

A better solution would be to use some package to set
up a background color possibly extending accross pages, as the
framed style (which we used to get this background
color) can only deal with material short enough to fit on one
page.

Regarding colors, generally speaking all color commands inside
\etoc are initially defined to do nothing, and the choice to
use or not colors is left to the user.

\clearpage
\etocdepthtag.toc {tips}

\part{Tips}
\label{part:tipsandtricks}

\thispartstats

%%%% \invisiblelocaltableofcontents \label{toc:tipsandtricks}

\etocsettocstyle{}{}
\etocstandardlines
\localtableofcontents

%\section{... and tricks}

\section[The \csbhyp{etocsetlocaltop.toc} command]
        {The \csbhyp{etocsetlocaltop.toc} and
          \csbhyp{etocimmediatesetlocaltop.toc} commands}
\label{etocsetlocaltop.toc}
\label{etocimmediatesetlocaltop.toc}

It is important to understand that \csb{localtableofcontents} works entirely
from data \emph{in the |.toc| file}. If the document, say with |article|
class, contains starred sectioning commands, which are not accompanied
by suitable \csa{addcontentsline}, then these units are completely
transparent to \csb{localtableofcontents}:
\begin{itemize}
\item If \localtoc is issued before |\section*{Foo}|, say locally to a |\section|,
  then the local TOC will include not only the |subsection|s between the
  |\section| and the |\section*{Foo}| but also those following, and it will
  stop only at encountering a later |\section| or |\part| from the document's body.
\item If the command is issued right after |\section*{Foo}| and the later was
  itself subsequent to a (numbered) |\subsection|, then \etoc will think it
  must display a TOC local to the \emph{subsection}.
\end{itemize}

Since release |1.08k|, \etoc provides the one-argument command
\csb{etocsetlocaltop.toc} to insert into the |.toc| file a kind
of ``ghost'' of a given sectioning unit. Here is an example:

\begin{verbatim}
\part*{Extra unnumbered part}
\etocsetlocaltop.toc{part}
\localtableofcontents
\end{verbatim}

So with no |\part| heading inserted into the table of contents via an
|\addcontentsline|, still \localtoc will know it is local to a part.  In this
example the local contents will be delimited by the next numbered |\part|, or
|\part*| with |\addcontentsline|, or also by a later, second,
|\etocsetlocaltop.toc{part}|.

As a (counter)-example consider this document:
\begin{verbatim}
\documentclass{article}
\usepackage{etoc}
\begin{document}
\tableofcontents

\part*{A}
\etocsetlocaltop.toc{part}
\localtableofcontents

\section{I}

\section{II}

\part*{B}

\section{III}

\part*{C}

\section{IV}
\end{document}
\end{verbatim}
It uses only |\part*|.  Thanks to the \csb{etocsetlocaltop.toc} the \localtoc
knows it should report only sections.  But the other |\part*| are invisible to
it as nothing is recorded in the |.toc| file.  So the local table of contents
in this example will list \emph{all} sections not only |I| and |II|.  To fix thix one may
e.g.\@ insert another |\etocsetlocaltop.toc{part}|, this time after |\part*{B}|
(or make this a numbered part, or use |\addcontentsline| for it).

The above document amended with added  |\etocsetlocaltop.toc{part}| after each
unnumbered part will thus have its main TOC without any |Part| heading, but
each |\part| can show a correct \localtoc.  The simpler
approach would be to use |\addcontentsline| with each unnumbered |\part| so
that it ends up in the |.toc| file, but \etoc is keen on allowing the most
diverse point of views.

It should be stressed that the various |\etocsetlocaltop.toc|\marg{sect. unit}
do impact the global \toc: they really act like actual sectioning units,
except for not inducing any typesetting.  In usual document classes, this
would appear to mean that they are completely transparent to the global \toc.
Not the case with \etoc, which adds a virtual assembly of levels: the |.toc|
data originating in |\etocsetlocaltop.toc|\marg{sect. unit} will trigger the
execution of the \marg{finish} parts of the line styles of finer sectioning
units encountered before (either in the global \toc or in an active
\localtoc); and it triggers the \marg{start} parts of the line styles of finer
units encountered after it (again in the global \toc, but also in any
\localtoc which is already activated at a coarser lever).

Depending on how the toc line styles are configured this may translate into
some visual effect; for example with the \etoc own line styles the
\marg{start} and \marg{finish} mostly insert penalties or vertical spaces.

It is a matter of debate if this is good design; a variant serving purely to
influence boundaries of local table of contents with no collateral effects
could be provided.  And the name of the macro was perhaps not so well chosen
as it suggests it acts as would such an hypothetical variant.  In absence of
feature requests we leave the matter standing for now.%
%
\footnote{This documentation was updated and this paragraph added for the
  |1.09f| release.}

Usage of \csb{etocsetlocaltop.toc} interacts with
\csb{etocchecksemptiness} in the expected way: it modifies (as explained
above) the selection made by \csb{localtableofcontents}, hence the decision
whether this local TOC will end up empty or not.

There is also \csb{etocimmediatesetlocaltop.toc}.  This may be useful in some
very special circumstances involving |\include|.  For related discussion see
the documentation of \csb{etocimmediatedepthtag.toc}.

\section{Hacking framed parboxes}

\begin{verbatim}
\etocdefaultlines
\renewcommand\etoctoprule{\hrule height 2pt depth 2pt}
\etocruled{\color{green}\fboxrule2pt\fboxsep1ex
               \fbox{\raisebox{-\fontdimen22\textfont2}
                    {\color{blue}\parbox{.5\linewidth}
                       {\normalfont This text is perfectly centered
                        vertically with respect to the
                        surrounding horizontal rules.}}}}
\ref{toc:globalcmds}
\end{verbatim}

\etocdefaultlines

\renewcommand\etoctoprule{\hrule height 2pt depth 2pt}

\etocruled{\color{green}\fboxrule2pt\fboxsep1ex
              \fbox{\raisebox{-\fontdimen22\textfont2}
                    {\color{blue}\parbox{.5\linewidth}
                       {\normalfont This text is perfectly centered
                        vertically with respect to the
                        surrounding horizontal rules.}}}}
              \ref{toc:globalcmds}


\section{Interverting the levels}
\label{subsec:interverting}

Let us display and count all subsections occurring in this
document (see \autoref{part:surprising} for other uses of
this technique):  
\begin{verbatim}
\etocsetnexttocdepth{2}
\begingroup
\etocsetlevel{part}{3}
\etocsetlevel{section}{3}
\etocsetstyle{subsection}
    {\small\begin{enumerate}[itemsep=0pt,label=,leftmargin=0pt]}
    {\normalfont\bfseries\item}
    {\roman{enumi}. \mdseries\etocname{} (\etocnumber, p.~\etocpage)}
    {\end{enumerate}}
\renewcommand{\etoccolumnsep}{2.75em}
\renewcommand{\columnseprule}{1pt}
\etocmulticol[3]{\subsection{All subsections of this document}}
\endgroup
\end{verbatim}

\etocsetnexttocdepth{2}

\begingroup
\etocdefaultlines
\etocstandarddisplaystyle
\etocsetlevel{book}{3}
\etocsetlevel{part}{3}
\etocsetlevel{chapter}{3}
\etocsetlevel{section}{3}
\etocsetstyle{subsection}{\small
\begin{enumerate}[itemsep=0pt,label=,leftmargin=0pt]}
{\normalfont\bfseries\item}
{\roman{enumi}. \mdseries\etocname{} (\etocnumber, p.~\etocpage)}
{\end{enumerate}}

\renewcommand{\etoccolumnsep}{2.75em}
\renewcommand{\columnseprule}{1pt}

%%\etocmarkbothnouc{List of all subsections}
%% le mark (\markright) est fait par \subsection

\etocmulticol[3]{\subsection{All subsections of this document}\label{toc:allsubsections}}

\endgroup

\section{Displaying statistics}\label{ssec:statistics}

Each part of this document starts with a paragraph telling how many
sections and subsections it has. Well, each one of this paragraph is a
table of contents! We designed a macro \csa{thispartstats} to do that.
It uses ``storage'' boxes to keep the information about the first and
last section or subsection. Using boxes is the simplest manner to
encapsulate the |hyperref| link for later use (whether there is one or
none). However, one cannot modify then the font or the color.
%  (using the
% \TeX{} primitive \csa{setbox} rather than the \LaTeX{} \csa{sbox} would
% allow to change the color of the un-boxed saved box)
If such a need
arises, one must switch from using boxes to using macros, and store the
|hyperref| data for later use as was done in the code presented in
\autoref{sec:molecule}. We present also this second method.

But first, the code of \csa{thispartstats}:\par
\begin{filecontentshere}{etocsnippet-\the\value{section}-A.tex}
\newsavebox\firstnamei  \newsavebox\firstnumberi
\newsavebox\lastnamei   \newsavebox\lastnumberi
\newsavebox\firstnameii \newsavebox\firstnumberii
\newsavebox\lastnameii  \newsavebox\lastnumberii
\newcounter{mycounti}   \newcounter{mycountii}
\newcommand*{\thispartstatsauxi}{} \newcommand*{\thispartstatsauxii}{}
\newcommand*{\oldtocdepth}{}
\newcommand*{\thispartstats}{%
  \setcounter{mycounti}{0}%
  \setcounter{mycountii}{0}%
  \def\thispartstatsauxi{%
         \sbox{\firstnamei}{\etocname}%
         \sbox{\firstnumberi}{\etocnumber}%
         \def\thispartstatsauxi{}}%
  \def\thispartstatsauxii{%
         \sbox{\firstnameii}{\etocname}%
         \sbox{\firstnumberii}{\etocnumber}%
         \def\thispartstatsauxii{}}%
  \begingroup
  \etocsetstyle{subsection} {} {}
    {\thispartstatsauxii
     \stepcounter{mycountii}%
     \sbox{\lastnameii}{\etocname}%
     \sbox{\lastnumberii}{\etocnumber}} {}%
  \etocsetstyle{section} {} {}
    {\thispartstatsauxi
     \stepcounter{mycounti}%
     \sbox{\lastnamei}{\etocname}%
     \sbox{\lastnumberi}{\etocnumber}}
    {Here are some statistics for this part: it contains \arabic{mycounti}
    section\ifnum\value{mycounti}>1 s\fi{} and \arabic{mycountii}
    subsection\ifnum\value{mycountii}>1 s\fi. The name of the first section is
    \unhbox\firstnamei{} and the corresponding number is \unhbox\firstnumberi. 
    The name of the last section is \unhbox\lastnamei{} and its number is
    \unhbox\lastnumberi. The name of the first subsection is \unhbox\firstnameii{}
    and the corresponding number is \unhbox\firstnumberii. The name of the last
    subsection is \unhbox\lastnameii{} and its number is \unhbox\lastnumberii.}%
  \etocinline % cancels the automatic \par automatically before the TOC
  \etocsettocstyle {}{}
  \etocsetnexttocdepth{2}%
  \localtableofcontents  % to be used at the top level of a Part.
  \endgroup
}
\end{filecontentshere}
\attachfile[description={demo \the\value{section}-A}]{etocsnippet-\the\value{section}-A.tex}
And now, the variant with macros rather than boxes (this variant as it
stands here is for using within a section).
\begin{filecontentshere}{etocsnippet-\the\value{section}-B.tex}
\makeatletter
\newcommand*\firstsubname   {}  \newcommand*\lastsubname    {}
\newcommand*\firstsubnumber {}  \newcommand*\lastsubnumber  {}
\newcommand*\thisspecialstatsaux{}
\newcommand*{\thisspecialstats}{%
  \setcounter{mycounti}{0}%
  \def\thisspecialstatsaux{%
         \let\firstsubname\etocthelinkedname
         \let\firstsubnumber\etocthelinkednumber
         \def\thisspecialstatsaux{}}
  \begingroup
  \etocsetstyle{subsection} {} {}
    {\thisspecialstatsaux
     \stepcounter{mycounti}%
     \let\lastsubname\etocthelinkedname
     \let\lastsubnumber\etocthelinkednumber }
    {Here are some statistics for this section. It contains \arabic{mycounti}
      subsections. The name of its first is \emph{\firstsubname{}} and the 
      corresponding number is {\firstsubnumber}. The name of the last 
      subsection is \emph{\lastsubname{}} and its number is {\lastsubnumber}.}% 
   \etocsettocstyle {}{}
   \etocinline
   \etocsetnexttocdepth {1}%
   \localtableofcontents % to be used within a section
  \endgroup
}
\makeatother
\end{filecontentshere}
\attachfile[description={demo \the\value{section}-B}]{etocsnippet-\the\value{section}-B.tex}

\section{Using depth tags}
\label{ssec:tocwithdepthtags}

We want a TOC which will have a heading for each |\part| (except
the last part with the code source, which we decide not to
include), and will additionally open up \autoref{part:globalcmds}
up to paragraphs. To achieve this we added to this source various
\csb{etocdepthtag.toc} commands, and it remains now to set the
levels for each tag using \csb{etocsettagdepth} (this was used
earlier in this document, in \autoref{sec:secondexample}, within a
group hence it did not affect the other tables of contents).

However, the package line styles do not display paragraphs, and the
standard line styles of the document class give too much vertical
spacing (in this context) when displaying a Part heading in the TOC. So
we cook up our own, quickly designed line styles, in the style of
\autoref{sec:firstexample} (but with a way to put page numbers on the
right which is more like the method used by \LaTeX2e's
|\@dottedtocline|; and multi-line headings now leave empty the area
underneath the numbers contrarily to the code from
\autoref{sec:firstexample}). And after a few minutes for choosing
lengths (now that this has been done once, it can be recycled easily) we
get:

\begin{filecontentsdef}{etocsnippet-\the\value{section}.tex}{\foo}
\etocsetnexttocdepth {all}
\begingroup 
\parindent 0pt \leftskip 0cm \rightskip .75cm \parfillskip -\rightskip
\newcommand*{\EndParWithPagenoInMargin}
    {\nobreak\hfill
     \makebox[0.75cm][r]{\mdseries\normalsize\etocpage}%
     \par}
\renewcommand*\etoctoclineleaders
    {\hbox{\normalfont\normalsize\hbox to .75ex {\hss.\hss}}}
\newcommand*{\EndParWithPagenoInMarginAndLeaders}
    {\nobreak\leaders\etoctoclineleaders\hfill
     \makebox[0.75cm][r]{\mdseries\normalsize\etocpage}%
     \par }
\etocsetstyle {part}
              {}
              {\leavevmode\leftskip 1cm\relax}
              {\bfseries\large\llap{\makebox[1cm][r]{\etocnumber\ \ }}%
               \etocname\EndParWithPagenoInMargin\smallskip}
              {}
\etocsetstyle {section}
              {}
              {\leavevmode\leftskip 1.75cm\relax}
              {\bfseries\normalsize\llap{\makebox[.75cm][l]{\etocnumber}}%
               \etocname\EndParWithPagenoInMarginAndLeaders}
              {}
\etocsetstyle {subsection}
              {}
              {\leavevmode\leftskip 2.75cm\relax }
              {\mdseries\normalsize\llap{\makebox[1cm][l]{\etocnumber}}%
               \etocname\EndParWithPagenoInMarginAndLeaders}
              {}
\etocsetstyle {subsubsection}
              {}
              {\leavevmode\leftskip 4cm\relax }
              {\mdseries\normalsize\llap{\makebox[1.25cm][l]{\etocnumber}}%
               \etocname\EndParWithPagenoInMarginAndLeaders}
              {}
\etocsetstyle {paragraph}
              {}
              {\leavevmode\leftskip 5.5cm\relax }
              {\mdseries\normalsize\llap{\makebox[1.5cm][l]{\etocnumber}}%
               \etocname\EndParWithPagenoInMarginAndLeaders}
              {}
\etocsettagdepth {preamble}   {none}
\etocsettagdepth {overview}   {part}
%\etocsettagdepth {arbitrarily}{part}% not needed explicitely, keeps value
%\etocsettagdepth {examples}   {part}
%\etocsettagdepth {surprising} {part}
%\etocsettagdepth {linestyles} {part}
\etocsettagdepth {globalcmds} {paragraph}
\etocsettagdepth {custom}     {part}
%\etocsettagdepth {tips}       {part}
%\etocsettagdepth {etocandworld}{part}
\etocsettagdepth {code}       {none}
\renewcommand\etoctoprule {\hrule height 3pt\relax }
\renewcommand\etoctoprulecolorcmd {\color{blue}}
\renewcommand\etocaftercontentshook 
   {\medskip\begingroup \color{blue}\hrule height 3pt \endgroup }
\etocruledstyle [1]{\Large\bfseries 
                    \fbox{\makebox[8cm]{A TOC using depth tags}}}
\sloppy
\tableofcontents
\endgroup
\end{filecontentsdef}

\filecontentsexec\foo

\filecontentsprint\foo
\attachfile[description={demo \the\value{section}}]{etocsnippet-\the\value{section}.tex}

\section{Typesetting the TOC as a table (the old way)}
\label{ssec:tocastableold}

Due to, among other things, the fact that alignment cells create and close
groups, and that by default definitions of \csb{etocname}, \csb{etocnumber},
\csb{etocpage} made by \etoc are local, it was not easy to typeset a TOC as
table with \etoc, prior to release |1.08|. 

Not only \csb{etocname} etc... caused a problem, but also the basic
redefinition of \csa{contentsline} was made by \etoc only after the
first argument to \csb{etocsettocstyle} had been executed, hence if this
argument were to open a tabular, the \etoc redefinition of
\csa{contentsline} would be done in the first cell of the first row and
get lost thereafter.

Thus one had to resort to the technique explained in \autoref{tocastree}
of using the execution of \csa{tableofcontents} as a way to store data
which was then displayed later.

For the record, here is how the TOC from \autoref{sec:tocastable} was
coded in the old days.%
%
\footnote{At release |1.09f| the design of the TOC from
  \autoref{sec:tocastable} was modified; the code here reproduces
  the former looks.} 
%
We don't have here the problems with the
positioning of |\hline|'s we face with the newer method; on the other
hand we must manipulate token registers which are not familiar to most
\LaTeX{} users (macros could be used, but would be more cumbersome,
except perhaps if using the \eTeX{} \csa{unexpanded}).

The method here is the most powerful because it filters out of the
|.toc| file only the data we want (the other things are not ignored,
they are executed but hopefully do not create havoc; typically they are
language changing instructions, etc...),
and we are less susceptible to fall potential victims of various
external macros inserted in the |.toc| file by other packages.

Note: rather than |\toks| registers it would be easier here to use \eTeX{}
\csa{unexpanded} primitive. See for example \autoref{sec:mindmap}.

\begin{filecontentshere}{etocsnippet-\the\value{section}.tex}
\newtoks\toctabletok
\newcommand*\appendtotok[2]{% #1=toks variable, #2=macro, expands once #2
  #1\expandafter\expandafter\expandafter {\expandafter\the\expandafter #1#2}}

\newcommand*\PreparePart{%
  \toks0 \expandafter{\etocthelinkednumber}%
  \toks2 \expandafter{\etocthelinkedname}%
  \toks4 \expandafter{\etocthelinkedpage}%
  \edef\toctablepiece {\noexpand\hline
                      \noexpand\strut\the\toks0 &\noexpand\bfseries\the\toks2 
                                 &\the\toks4 \noexpand\\\noexpand\hline}% 
}
\newcommand*\PrepareSection{%
  \toks0 \expandafter{\etocthelinkednumber}%
  \toks2 \expandafter{\etocthelinkedname}%
  \toks4 \expandafter{\etocthelinkedpage}%
  \edef\toctablepiece {\the\toks0 &\the\toks2 &\the\toks4 \noexpand\\}% 
}
% new version for 1.07k, 2014/03/06
\newcommand*{\PrepareSubsection}{%
  \toks0 \expandafter{\etocthelinkednumber}%
  \toks2 \expandafter{\expandafter\itshape\etocthelinkedname\strut}%
  \toks4 \expandafter{\expandafter\itshape\etocthelinkedpage}%
  \edef\toctablepiece{&\noexpand\makebox[1cm][c]{\the\toks0}%
                      \noexpand\parbox[t]{\dimexpr6cm-\tabcolsep\relax}
                                         {\noexpand\sloppy\the\toks2}%
                      &\the\toks4 \noexpand\\}%
}

\begingroup
\etocsetstyle{part}{}{}{\PreparePart \appendtotok\toctabletok\toctablepiece}{}

\etocsetstyle{section}{}{}{\PrepareSection \appendtotok\toctabletok\toctablepiece}{}

\etocsetstyle{subsection}{}{}{\PrepareSubsection\appendtotok\toctabletok\toctablepiece}{}

\etocsettocstyle
    {\toctabletok{\hypersetup{hidelinks}%
                 \begin{longtable}{|>{\bfseries}c|p{7cm}|r|}\hline
                 \multicolumn{3}{|c|}{\Large\bfseries\strut TABLE OF CONTENTS}%
                 \\\hline\hline}}
    {\global\toctabletok\expandafter{\the\toctabletok\hline\end{longtable}}}
\etocsettocdepth {subsection}
\tableofcontents
\the\toctabletok
\endgroup
\end{filecontentshere}
\attachfile[description={demo \the\value{section}}]{etocsnippet-\the\value{section}.tex}

\clearpage
\etocdepthtag.toc {etocandworld}

\part{\etoc and the outside world}

\section{Compatibility with other packages}

\subsection{Generalities}

The contents of the |.toc| file (if it already exists) are read into memory by
\etoc once, at the time of |\begin{document}|.\footnote{New with |1.07m|.
    Earlier versions read the |.toc| file at the time of
    \csa{usepackage\{etoc\}}. Thanks to Denis Bitouzé who signaled a Babel
    related problem, which turned out to be caused by this.}

The |.toc| file remains available
  to other packages for read operations until the location of the first table
  of contents at which time a write stream is opened by \etoc and from that
  point the file is erased until its contents are again written to the disk by
  \LaTeX{} at the end of the compilation.

Don't use |\if<condition> stuff \tableofcontents\fi|, but:
\centeredline{|\if<condition> stuff \expandafter\tableofcontents\fi|}
Also a |\else| immediately following \csa{tableofcontents} or
\csa{localtableofcontents} requires a previous \csa{expandafter}.


\etoc can not really cohabit with packages modifying the \csa{tableofcontents}
  command: some sort of truce can be achieved if \etoc is loaded last, hence is
  the winner. 

\begin{framed}
    Do not modify the |\tableofcontents| command like this:
    \centeredline{|\let\oldtableofcontents\tableofcontents|}
    \centeredline{|\renewcommand\tableofcontents{\oldtableofcontents foo}|}
    as this will make the |\label/\ref| mechanism impossible. 

    Rather use \centeredline{|\renewcommand\etocaftertochook{foo}|} and there
    is also \csb{etocaftercontentshook} which is executed a bit
    earlier\footnotemark{} just before the closing part of the toc display
    style (and thus still within a group.)

    Prepending is less of a problem (and anyhow there is also
    \csb{etocbeforetitlehook} available to the user).

    Under certain circumstances \etoc imposes its views on
    \csa{tableofcontents} at the time of |\begin{document}|. You may thus have
    to use \csa{AtBeginDocument} to delay your (necessarily ugly and
    non-recommendable) patches. Patching after |\begin{document}| is
    naturally possible but I feel almost a rebel to mention this to \LaTeX{} users!
\end{framed}
\footnotetext{contrarily to \csb{etocaftertochook},
      \csb{etocaftercontentshook} is not executed if the |tocdepth| did not
      allow the printing of the TOC.}

\etoc \textbf{requires} the |.toc| file to use the \csa{contentsline}
    macro. It \textbf{can not} work if there is no |.toc| file or if the
    |.toc| file does not contain the relevant data or if the |.toc| file does
    not use the \csa{contentsline} macro or if the \csa{contentsline} macro
    does not invoke the \csa{l@<divisionunit>} macros.

\subsection{Compatibility with \texttt{beamer}}

For the very reasons mentioned right before, \etoc is incompatible with the
|beamer| class. However, if |beamer| is used in an article mode, i.e., with
the article class in conjunction with the |beamerarticle| package, then \etoc
should work.

\subsection{Compatibility with \texttt{Babel}}

\begin{framed}
  One must load \etoc \emph{after} \texttt{babel}. This is in order for
  |babel|'s shorthands to be active at the time when \etoc loads the |.toc|
  file.
\end{framed}

\subsection{Compatibility with \texttt{hyperref}}

Please inform the author in case of issues: \etoc was from the start designed
to be |100%| compatible with package |hyperref|.

The macros \csb{etocname}, \csb{etocnumber}, and \csb{etocpage} contain the
|hyperref| links, if present (note that the \emph{linktoc=all} option of
|hyperref| tells it to put a link also in the page number corresponding to a
given toc entry). For example, the tables of contents of the present document
are all fully linked. It doesn't matter whether \etoc or |hyperref| is loaded
first.

% \typeout{ICI}
% \showhyphens{Compatibility}
% [] \T1/txss/m/n/10.95 Com-pat-i-bil-ity

% 2015/11/12
% Pour une raison que j'ignore dans la TOC principale j'ai un problème avec
% cette sous-section.

\subsection{Com\-pat\-i\-bil\-ity with \texttt{multicol}}

\etoc loads the package |multicol|.

\subsection{Compatibility with \texttt{tocloft}}\label{subs:tocloft}

Release |1.07k| added compatibility with package
|tocloft|:\footnote{\url{http://ctan.org/pkg/tocloft}} steps are
taken to prevent the redefinition of |\tableofcontents| done by
|tocloft| at |\begin{document}|.
%
As long as \etoc is left in compatibility mode the customization done by
|tocloft| will be obeyed, for both the line styles and the TOC title.
One may still benefit from the \emph{depth tags} management by \etoc,
from its |\localtableofcontents|, from its |\label+\ref| mechanism. One
may use |\etocsetstyle| to define via \etoc the layout for one TOC and
then use rather |tocloft| for another one, if |\tableofcontents| follows
\csb{etocstandardlines} and \csb{etocstandarddisplaystyle}. In this
compatibility mode |\etocsetlevel{division unit}{6}| will render
invisible the chosen division level, but exchanging levels is otherwise
not possible.

\begin{framed}
  One should load \etoc \emph{after} \texttt{tocloft}. A warning is
  issued if otherwise, because if \etoc is loaded before it will realize that at
  the time of |\begin{document}| and trick \texttt{tocloft} into believing
  having been loaded with the |titles| option.
\end{framed}

It is possible to modify midway in the document the macros \csa{l@section},
\csa{l@subsection} ... but the effect will be seen only in table of contents
typeset by \etoc in compatibility mode (and of course after those
customizations).  It will have no effect on true \etoc TOCs.

\subsection{Compatibility with the \texttt{memoir} class}
\label{ssec:memoir}
\label{etocmemoirtoctotocfmt}
\label{etocmemoirstyle}

Release |1.07l| has also improved the compatibility with the |memoir| class: its
|appendix| level has been made known to \etoc. It is at the same level as
|chapter|, thus the chapter line style should possibly do a test for some user
defined boolean whose activation may be added to the |.toc| file at the suitable
location via |\addtocontents{toc}{..}|, if one needs to distinguish the two
kinds of divisions.

The |memoir| mechanism relative to \toc versus \toc|*| is obeyed
automatically, and applies with \localtoc too.

But, attention, this means that \localtoc should preferentially be used with
the |*|.  Else the |memoir| mechanism will insert a specific line in the
|.toc| file, using by default the |chapter| sectioning level.  But \etoc has
already written to the |.toc| file an instruction that the user wants a local
table of contents.  As a result, the fake |chapter| will let \etoc consider
that the \localtoc has empty contents, except if it used in a |\part| or
|\book|.

This may even cause successive document builds to never stabilize if
\csb{etocchecksemptiness} was issued in the preamble: as the local TOC is
empty, on next run the extra entry in |.toc| is absent, so the local TOC is
not empty and is typeset, but then |.toc| changes, so the rerunfilecheck
mechanism instructs to compile once more, and we end in a never stabilizing
conundrum.

Thus we see that the fact that \localtoc by default use like the global \toc a
chapter style is inconvenient. One can use the |memoir| macros to modify this:
according to |memoir| documentation, |\tocheadstart| and |\printtoctitle| seem
to be the most relevant. If you do that you will probably want the added line
in |.toc| file to use |{section}| not |{chapter}|. \etoc provides to this
effect \csb{etocmemoirtoctotocfmt}\marg{kind}\marg{name} whose first argument
\meta{kind} is |chapter|, |section|, |subsection|, etc... and the second
argument stands for the title and thus \csa{contentsname} is
appropriate. Hence
\begin{verbatim}
  \etocmemoirtoctotocfmt{section}{\contentsname}
\end{verbatim}
seems the natural choice in this context as an addition to the customizing the
|memoir| toc related macros to achieve a section like rendering (for more
details on the latter, please refer to |memoir| manual).  This is appropriate
for local TOCs in chapters.  Adapt to finer sectioning levels.

Another approach is to overrule the \etoc
default under |memoir| like this
\begin{verbatim}
  \etocarticlestyle % means to use \section*{\contentsname} (and marks)
  \renewcommand{\etocaftertitlehook}{\addcontentsline{toc}{section}{\contentsname}}
\end{verbatim}
exactly as one would do with |book| class for example.  This emulates the
default under memoir that table of contents write a line to the |.toc| file representing
themselves, except that |chapter| has been replaced by |section|.  So we can
use \localtoc after a \csa{chapter}.  But if you want one after a
\csa{section}, you should modify \csb{etocaftertitlehook} to assign
|subsection| level to the \localtoc own styling.


\subsection{Compatibility with package \texttt{tocvsec2}}

  \etoc used to be incompatible with package
  |tocvsec2|\footnote{\url{http://ctan.org/pkg/tocvsec2}}; it now cohabits, sort
  of, as it deactivates |tocvsec2|'s modification of |\tableofcontents|
  and also cancels its other |toc|-related macros, but
  reimplements partially their functionality with \csb{etocsettocdepth.toc}. By
  the way, at least two latex runs are necessary for new uses of this command in
  a document to have an effect in tables of contents.

\subsection{Compatibility with package \texttt{tableof}}

It is possible to use simultaneously \etoc and
{\color{niceone}|tableof|}\footnote{\url{http://ctan.org/pkg/tableof}}. Release
|1.08| of \etoc requires at least version |1.4a| of |tableof|. If
\csb{etocglobaldefs} is put in the preamble, this must be after the loading of
package |tableof|. {\color{niceone}|tableof|} command \csa{nexttocwithtags}
should work as expected. 

{\color{niceone}|tableof|} commands \csa{tableof}, \csa{tablenotof}, ... will
typeset the (a priori global) table of contents according to the document
class defaults, obeying the \etoc depth tags; as explained in the |tableof|
documentation they do not typeset a TOC title. They should \emph{not} be used
in case \csb{etocglobaldefs} was issued before, except if its scope has been
terminated since then, or \csb{etoclocaldefs} has cancelled its influence.

\subsection{Compatibility with package \texttt{tocstyle}}

Unknown. (not tested a.t.t.o.w).


\section{\TeX nical matters}

The \csb{etocname}, \csb{etocnumber}, \csb{etocpage} commands are protected
against premature expansion. They contain suitable |hyperref| links if package
|hyperref| is loaded and active for the TOC. The commands \csb{etoclink} and
\csb{etocifnumbered} are also protected against premature expansion. Also
\csb{etociffirst} and \csb{etoctoccontentsline}.

On the other hand \csb{etocthename}, \csb{etocthenumber}, \csb{etocthepage}
are \emph{not} protected against expansion. And neither are
\csb{etocthelinkedname}, \csb{etocthelinkednumber}, \csb{etocthelinkedpage}.
The latter contain hyperlink data, if present in the |.toc| file.

The commands such as \csb{etocsetstyle}, \csb{etocsetlevel},
\csb{etocsettocstyle}, \csb{etocmulticolstyle},
\csb{etocruledstyle}, \csb{etocframedstyle} obey \LaTeX{}'s
groups. All TOCs are typeset inside groups.

When a \localtoc is inserted by the user in the document, a
line containing an \etoc inner command and an identification
number is added to the |.toc| file on first subsequent compilation.
The correct local table of
contents will be displayed only on the second compilation.


\section{Errors and catastrophes}

  After using \csb{etocsetstyle} for one level, the remaining
  uncustomized levels use the \etoc default styles (those
  which are activated by \csb{etocdefaultlines}). One has to
  make sure that all levels needed for the next table of
  contents are mutually compatible: in particular the \etoc
  default line styles expect each to be started in ``vertical mode''.

  When using multiple \toc commands in a document, one should beware from
  adding typesetting instructions directly in the |.toc| file, as they will be
  executed by \etoc for all TOCs: even for a \localtoc it doesn't matter if
  that instruction seems to concern material outside of its scope, it will get
  executed nevertheless. If absolutely necessary extra commands in the |.toc|
  file should be configured in such a way that they can be activated or
  deactivated easily from the document source, as need be.

  As is usual with toc and labels, after each change, one has
  to run latex a certain number of times to let the produced
  document get its final appearance (at least twice).\par

\clearpage
\etocdepthtag.toc {code}

\part{The code}

\localtableofcontents

\section{Timestamp}

This is the documentation as of \texttt{\etocdocdate}, printed from the
source file with the time stamp \texttt{\etocdtxtimestamp}. The package
version is \texttt{\etocpkgversion}, of \texttt{\etocpkgdate}.

\catcode1 13

\begingroup
\renewcommand\lowast{{\normalsize\raisebox{-.4\height}{*}}}
\small

    \section{Change history}

\setlength{\columnsep}{\etoccolumnsep}

\makeatletter

% 27 avril 2014 un petit hack pour hyphénation (éventuelle) en allemand
% j'ai déjà ~ qui sera de catcode 0, cependant il faudrait aussi les accolades,
% donc finalement pour aller vite, je rends le + actif. Je modifie aussi le test
% fait par \jfverbaspace (n'ayant pas commenté mon code, j'ai dû réfléchir pour
% me rappeler à peu près ce que c'était censé faire).

\def\jfverbatim{\@beginparpenalty \predisplaypenalty 
  \parindent \z@ 
  \parfillskip \@flushglue 
  \parskip \tw@\p@ plus 1fil\relax
  \let \do \@makeother \dospecials \makestarlowast \catcode`$ \active
  \begingroup\lccode`~`$
  \lowercase{\endgroup\def~[##1]{\foreignlanguage{ngerman}{##1}}}%
  \catcode`^ \active
  \begingroup\lccode`~`^
  \lowercase{\endgroup\def~{\nopagebreak}}% ajouté 2014/04/28, oblige à un peu
                                % plus de mark-up cependant
  \catcode`\~\z@ 
  \footnotesize\normalfont\baselineskip10pt\relax
% 2022/08/30, I remove all "v"'s from version numbers.
%  \def\v{\vskip\baselineskip v}% ajouté 2015/05/09; faudra trouver mieux.
  \def\1{\vskip\baselineskip 1}% ajouté 2015/05/09; faudra trouver mieux.
% 2022/08/26, stop using \frenchspacing
  % \frenchspacing
% 2022/08/26.  I realized that rendering was broken, and finally identified
% the bad commit to be in LaTeX 2022/06/01 release.  Its \obeyspaces not only
% makes the ascii32 \active but it also redefines it!  Solution could be to
% actually use \obeyedspace in the definition of active space about 20 lines
% below but this would tie to LaTeX 2022/06/01 or later for building etoc.pdf
  \catcode`\ \active %  was \obeyspaces
  \jf@xverbatim
}

\begingroup 
\catcode `|=0 \catcode `[= 1 \catcode`]=2 
\catcode `\{=12 \catcode `\}=12 \catcode`\\=12 
|long|gdef|jf@xverbatim#1\end{jfverbatim}[#1|end[jfverbatim]]
|endgroup

\def\endjfverbatim{} 

\newdimen\jfverbadim
\makeatother

\begin{multicols}{2}
\makeatletter
\everypar{\leftskip\jfverbadim\bgroup
          \def\par{\egroup\jfverbadim\z@\@@par}%
          \def\jfverbaspace#1{\if\@sptoken\string#1\unskip\else\ \fi#1}}
%
% see 2022/08/26 above note
\begingroup\obeyspaces\def\x{\endgroup%
\def {\ifvmode\advance\jfverbadim.5em\relax\else\expandafter\jfverbaspace\fi}}\x
\makeatother
\begin{jfverbatim}
1.09g [2022/11/17]^

   Compatibility hotfix with recent hyperref 7.00u of 2022-11-13.
   Thanks to Denis Bitouzé for signaling the breakage to the author.

~1.09f [2022/08/30]^

   No more shipping of a German translation of the documentation,
   as it was last updated in April 2015.

   (etoc.pdf) User level commands hyperlink from their code source definitions
   to their descriptions in the documentation part.  Macros used in the code
   source hyperlink to where they first got defined there.

   Wrap the \etocpartname (from etoc's package provided toc line style)
   together with the part number in a potential common hyperlink.

   Try to sync the emulation of the global display style with KOMA-script
   v3.37 (in particular regarding the noparskipfake KOMA toc feature).

   Improve documentation of some aspects under memoir class.

   Remove the \nonumberline token, even though empty, from the meaning of
   \etocthename (KOMA-script classes).

   Add \etocimmediatedepthtag.toc to work around problems related to
   \include (see user doc).  Thanks to Norman Ramsey who reported the problem
   and proposed a work-around in July 2016.  Apologies for the somewhat longish
   delay in incorporating it...

   Also add \etocimmediatesettocdepth.toc.

   Also add \etocimmediatetoccontentsline and its starred variant.

   Also add \etocimmediatesetlocaltop.toc.

   Fix an obscure bug (see source code comments) in the
   \etocsetlocaltop.toc mechanism.

~1.09e [2021/09/23]^

   Needed (if etoc is used without hyperref) updates to
   internal macros to prepare for the upcoming LaTeX November
   2021 change to \contentsline.

   Related updates to the user macro \etoctoccontentsline.

~1.09d [2021/07/13]^

   Some minor synching with tableof 1.4c. 

   Add \etockeeporiginaltableofcontents to provide a work-around to a
   compatibility issue with listings's \lstlistoflistings, which abuses
   \tableofcontents for doing something unrelated to the actual contents.
   Thanks to Denis Bitouzé for report.

   Usage: \usepackage{etoc}\etockeeporiginal-tableofcontents, then
   however you must employ \etoctableofcontents, not \tableofcontents.

~1.09c [2020/05/15]^

   Syncs with KOMA-script deprecation of \iftocfeature.

~1.09a, 1.09b [2019/11/17]^

   Sync with memoir v3.7i which has a better location of the TOC
   hyperref anchor. The \etocaftertitlehook can now freely be
   used also with memoir class (formerly its usage in case of
   memoir class was preempted by etoc itself). For more details
   refer to the section "Compatibility with the memoir class".

~1.09 [2019/03/09]^

   New features: \etoclocaltop, \localtableofcontentswithrelativedepth. Thanks
   to Tony Roberts for feature request.

   Note to hackers: internal control sequence \Etoc@localtop is gone.

   etoc now requires e-TeX (\numexpr, \unless).

~1.08p [2018/07/04]^

   Fixed bug surfacing in case of linktoc=page option of hyperref.
   Thanks to Denis Bitouzé for report (cf.
   https://github.com/ho-tex/hyperref/issues/65,
   https://github.com/dbitouze/yathesis/issues/61).

~1.08o [2018/06/15]^

   Fixed bug showing up if an unnumbered TOC entry starts with a brace,
   and document uses hyperref. Caused by a typo in a macro name at
   previous release.


~1.08n [2018/02/23]^

   Refactoring of core macros detecting \numberline and its variants.


~1.08m [2018/02/07]^

   Fix to 1.08k's introduced incompatibility with KOMA-script
   and tocbasic's \nonumberline.


~1.08l [2017/10/23]^

   Workaround an issue with Emacs/AUCTeX wrongly reporting about
   actually non-existent LaTeX errors, which was triggered by some
   strings written (indirectly) to log file by etoc under some
   circumstances.


~1.08k [2017/09/28]^

   Adds \etocsetlocaltop.toc. See corresponding manual section for
   details.

   Adds \etocsavedparttocline, \etocsavedchaptertocline,
   \etocsavedsectiontocline, ... They can be used in the context of
   the technique explained in section "Another compatibility mode".

   Formerly, etoc redefined for the duration of the TOC the memoir
   macro \chapternumberline and its likes to have same meaning as
   \numberline (of course, not when executed in compatibility mode),
   for the sake of extraction of \etocnumber.

   New method detects presence of any \<foo>numberline macro without
   any change to originals; they can thus be used as is when applying
   the approach of "Another compatibility mode" section from manual.


~1.08j [2017/09/21]^

   Since 1.08a-2015/03/13 \etocname, \etocnumber, \etocpage
   contain, if hyperref is present and configured for using
   hyperlinks in the TOC, the link destination in already expanded
   form. This means one can use them even if the style closes a
   group (for example from a & in a tabular), if \etocglobaldefs
   was issued; also one can save their meaning for delayed usage
   (with for example \LetLtxMacro as they are robust).

   But for some legacy reason \etoclink, contrarily to
   \etocthelink, was handled differently. Now, \etoclink also
   contains the link destination in already expanded form, and can
   thus be used even if the line style issues a &, as long as
   \etocglobaldefs is issued.

   Also, bugs dating back to the early days of the package, but
   surfacing only under relatively rare conditions such as usage
   of hyperref with its option "linktoc=page" got fixed.


~1.08i [2016/09/29]^

   This fixes an issue dating back to 1.08e-2015/04/17: under
   \etocchecksemptiness regime, some circumstances (such as
   adding to an already compiled document a \localtableofcontents
   before the main \tableofcontents) created an "Undefined
   control sequence \Etoc@localtop" error. Thanks to Denis Bitouzé
   for reporting the problem.

   On this occasion, \etocdoesnotcheckemptiness
   has been added to unset the flag.

   A rather more exotic issue was fixed: the emptiness check for
   local tocs could get confused if the tocdepth counter was varying
   in some specific ways from inside the toc file.

   After adding to a document a \localtableofcontents, two LaTeX
   passes are needed for etoc to get a chance to print the
   correct local contents. Formerly, etoc issued a Warning on
   the first pass; it now also induces LaTeX into
   announcing "There were undefined references", as this is nearer
   to the end of the log file and console output.


~1.08h [2016/09/25]^

   New functioning of \etocsetnexttocdepth: the tocdepth counter is
   modified only at the time of the table of contents, not before.
   This fixes an issue which arose when \etocsetnexttocdepth was
   used multiple times with no intervening table of contents.
   Thanks to Denis Bitouzé for reporting the problem.

   The PDF documentation includes about 25 LaTeX code snippets also
   as file attachment annotations, additionally to their verbatim
   typesetting. The ordering of the documentation contents has been
   slightly re-organized.

   A previous documentation-only update on 2016/09/09 added a new
   section with the (approximate) translation into etoc lingua of the
   book class toc style, for easy customizability.


~1.08g [2015/08/29]^

   Downgraded to a mere info message the etoc-issued warning
   (relative to \settocdepth/\maxtocdepth) under class memoir.


~1.08f [2015/04/28]^

   Minor changes to the documentation. \etocsetlevel more economical.


~1.08e [2015/04/17]^

   The command \etocchecksemptiness tells etoc to not print, from
   that point on, the headings of the local tables of contents if
   they have empty contents. This is mainly for class authors who
   might want to have their \section or \chapter automatically do
   a \localtableofcontents. Could prove also useful for batch
   conversions of documents. Thanks to Paul Gaborit who asked for 
   such a feature.

   The command \etocnotocifnotoc extends this behaviour to global
   TOCs: indeed why should documents with no sectioning units take
   this as an excuse not to use package etoc ?

   The command \etocifwasempty{yes}{no} can be used for
   suitable extra action.

   A \tableofcontents\ref{foo} now expects foo to be a label to a
   _local_ TOC. The use with foo a label to a _global_ TOC is not
   supported anymore as it had no utility and made the code more
   complex.

   The syntax \localtableofcontents\ref{foo} is now accepted as a
   synonym to the earlier syntax \tableofcontents\ref{foo}.


~1.08d [2015/04/09]^

   Translation into German of the additions made to the documentation
   for the 1.08x series of releases.

   Thanks to Christine Römer!


~1.08c [2015/03/30]^

   - removed a few unneeded \long from the code.
  
   - removed use of \arabic at one location of the code, as it may get
  redefined by some language modules for babel or polyglossia.


~1.08b [2015/03/18]^

   Bug fixes: 

   - extra space token removed from `\localtableofcontents` (showed
   only for inline TOCs.)

   - \etocpartname (a macro used by the package own default line
   styles) was defined to be \partname, but this is not compatible
   at least with babel+french context. Now simply expands to Part.

   - some problems fixed in the German documentation.

   - [2015/03/28] some more problems fixed in the documentation. Added
   mention of \etocarticlestyle and \etocbookstyle.


~1.08a [2015/03/13]^

   \etocname, \etocnumber and \etocpage are now the robust
   variants of \etocthelinkedname, \etocthelinkednumber and
   \etocthelinkedpage. This should arguably have been done since
   the addition of the latter to etoc with 1.07f [2013/03/07].
   The earlier robust commands \etocname etc... contained
   the hyperlink destination only in an unexpanded form.

   The documentation has a brand new title page and a new section
   The TOC as a TikZ mind map both illustrating further uses of
   etoc to display tables of contents as trees in an automatic 
   manner.


~1.08 [2015/03/10]^

   \etocskipfirstprefix may now appear anywhere in the <start>
   part of a level style. 

   New commands \etociffirst, \etocxiffirst, \etocxifnumbered,
   \etocglobaldefs and \etoclocaldefs.

   It is now possible to issue line style specifications directly
   with & and \\ tokens, in order to typeset a TOC as a tabular
   or longtable with the opening for example in the first
   argument of \etocsettocstyle and the closing in its second
   argument.

   It is mandatory for such uses to issue \etocglobaldefs which
   tells etoc to proceed globally for certain definitions. This
   is also useful in the context of the inline environments of
   package enumitem.

   On this occasion, various old parts of the code have been
   improved.


~1.07n [2015/03/05]^

   No more use of \toks@ when etoc constructs \etocthelinkedname
   etc... Thus \toks@ can be put in the line styles in order to
   accumulate information. Only useful if it is certain nothing
   else will change \toks@ either.

   In the documentation: list of main commands now in alphabetic
   order.


~1.07m [2015/01/23]^

   Reading of .toc file is delayed to \begin{document} to account for
   possible Babel active characters used therein. Thanks to Denis
   Bitouzé who reported a Babel related problem.

   Improved global toc display emulation under KOMA-script classes.

   New command \etocbeforetitlehook. New command \etocdisplay.


~1.07l [doc of 2014/04/29]^

   Added to the documentation an example of use of \etocthelinkedname together
   with an enumitem inline itemize* environment; moved main TOC to immediately
   after the title, and license to the first pages.

   Incorporation of the translation into German done on the initiative of
   $[Christine Römer] by $[Felix Baral-Weber, Jenny Rothkrämer-Vogt, Daniel
   Büttner, Claudia Dahl, Christian Otto and Christine Römer (FSU Jena).] My
   grateful thanks to all!


~1.07l [2014/04/22]^

   Fixes a bug with the 1.07k compatibility layer with tocloft which had broken
   the 1.07k (sic) compatibility with memoir (yes, memoir class 1.07k testing
   had been done before adding the tocloft thing to the source code . . . ).
   Also, etoc when detecting tocvsec2 now checks if this is under the memoir
   class, as then nothing special needs to be done to rescue \tableofcontents,
   contrarily to the situation with the native tocvsec2. 


~1.07k [2014/03/06]^

   Compatibility with package tocloft; and improved compatibility with
   class memoir. Novel TOC example in Overview.


~1.07j [2013/12/03]^

   Some issues with the documentation formatting (now two-sided) have been
   addressed, and a novel documentation section ``Typesetting the TOC as a
   table'' has been added. Very minor code change (\Etoc@readtoc).


~1.07i [2013/10/21]^

   Changes to the \etocmulticolstyle and \etocruledstyle codes 
   to lessen the risk of a page break after the title (in the one-column case).


~1.07h [2013/10/16]^

   New commands \etocdepthtag.toc, \etocsettagdepth, \etocobeydepthtags,
   \etocignoredepthtags. 


~1.07g [2013/10/13]^

   New commands \etocsettocdepth, \etocsettocdepth.toc,
   \etocobeytoctocdepth, \etoc~-ignoretoctocdepth which
   emulate part of tocvsec2 functionality ; measures to
   make tocvsec2 partially compatible with etoc.

   New commands \etocsetnexttocdepth, \invisibletableofcontents,
   \invisiblelocaltableofcontents.

   Switched from tikz-qtree to forest for the first `toc as
   tree' example. 

   Command names are linked to their descriptions, and many
   other changes in the documentation.

   Removed printing of temporary message when the local toc
   id is not yet stabilized; indeed \localtableofcontents
   can have many uses, such as filling up some token list
   register and one may wish to not have anything typeset, 
   even in an intermediate run. 

   All of tex etoc.dtx, etex etoc.dtx, xetex etoc.dtx, latex
   etoc.dtx, pdflatex etoc.dtx are now possible, and the
   extracted file etoc.tex allows easy customization of
   compilation options for the documentation (default is via
   dvipdfmx which produces the smallest file).


~1.07f [2013/03/07]^

   New macros \etocthelinkedname, \etocthelinkednumber,
   \etocthelinkedpage, and \etocthelink.


~1.07e [2013/03/01]^

   Improvements in the package own line styles with
   regards to penalties and vertical spaces. 

   Addition to the documentation of an example of
   a tree-like table of contents (uses tikz).

   More such examples added 2013/03/03.


~1.07d [2013/02/24]^

   Minor code improvements and new documentation 
   section ``Another compatibility mode''.


~1.07b [2013/02/02]^

   Removal of the \xspace from the macros \etocname, 
   \etocnumber, \etocpage.

   Additional examples in the documentation.


~1.07 [2013/01/29]^

   New commands:

      \etocthename, \etocthenumber, \etocthe~-page, \etoclink, 

      \etoctoccontentsline, \etoctoccontentsline~lowast

      \etocnopar, \etocaftercontentshook

   Modified command: \etocmulticolstyle

   New documentation section ``Surprising uses of etoc'' which
   explains how to do  ``Lists of arbitrary things'', in
   addition to the tables of contents.


~1.06 [2012/12/07]^

   The standard macros \l@section etc... are modified only
   during the calls to \tableofcontents; they can thus be
   customized as will by the user (with the help of a
   package like tocloft) and this will be taken into account
   by etoc for the TOCs typeset in compatibility mode.


~1.05 [2012/12/01]^

   \localtableofcontents replaces \tableofcontents~lowast (for
   compatibility with the memoir class).

   Compatibility with KOMA-script and memoir document
   classes.


~1.04 [2012/11/24]^

   A (possibly local) table of contents can be labeled:

       \tableofcontents \label{toc:1}

   and reproduced elsewhere in the document (with a possibly
   completely different layout):

       \tableofcontents \ref{toc:1}


~1.02 [2012/11/18]^

   Initial version.

\end{jfverbatim}
\end{multicols}
\endgroup  % group for modified verbatim printing of the changes log

\makeatletter
    \let\check@percent\original@check@percent
\makeatother

\small

\section{Implementation}

% ce \noindent est obsolète 2022/08/26 à cause des hooks à macrocode plus bas
% transférés depuis xint.dtx.  Il est doublement obsolète car je rajoute un
% paragraphe de texte de toute façon avant le premier macrocode.
% \indent % !!!!!!!!!!!!!!!!! Lundi 09 mars 2015 à 09:32:22
% il faut faire un paragraphe après \section sinon pas d'espacement
% vertical en sortie de blocs macrocode. Pas évident à trouver, vu que
% je customisais différentes choses qui pouvaient affecter macrocode.

% 9 mars 2015
% Pour rappel on avait dans le préambule:
% \def\MacroFont{\ttfamily\small\hyphenchar\font45 \baselineskip11pt\relax}
% ce qui donne donc le \macro@font qui sera utilisé.

% 26 septembre 2021
\catcode1 14 % pour pouvoir utiliser ^^A, car je l'avais mis à \active

\StopEventually{\normalsize
  \ifnum\NoSourceCode=1
     \texttt{\parindent 0pt\rightskip 1cm minus 1cm
     This documentation has been compiled without inclusion of the source
     code. To produce the documentation with source code included:\endgraf
     \ \ \ \ run etex on etoc.dtx to produce etoc.tex,\endgraf
     \ \ \ \ then thrice pdflatex on etoc.tex.\endgraf
}%
  \fi
\end{document}}

%%%%%%%%%%%%
% 26 août 2022, transfert depuis xint de hack de doc
%
% This worked remarkably well with almost no changes! Particularly for
% hyperlinking to the documentation part from the macro definitions! But
% also for internall cross-links in implementation part despite no usage
% there of any sectioning mark-up (so I don't need the \@sect hack, and
% related \csa, \csan, \csh, \cshn, \cshintitle, \cshnintitle macros).
% I noticed in passing that I never used any \begin{macro} mark-up here
% in the etoc.dtx. Perhaps I should and should one day look at what doc=V3
% brings...
%
% See xint.dtx for comments, as I have removed most when copying.
\makeatletter
\def\odef #1{\expandafter\def\expandafter#1\expandafter}% needed from xintkernel

%%% xint.dtx does \def\macro@font {\ttfamily }% (with a font allowing hyphenation)
%%% Our \macro@font has been defined earlier from \MacroFont in preamble and
%%% is \ttfamily\small\hyphenchar\font45 \baselineskip11pt\relax
%%% etoc.dtx: see further below for how the * is handled in \macro@finish
\renewcommand\lowast{{\iflabelmacro@allowed\xintdocMacrocodeFallbackColorCmd\fi
                      \raisebox{-.25\height}{*}}}
\AddToHook{env/macrocode/begin}{\makestarlowast}
% https://github.com/latex3/latex2e/issues/563
% (but I don't use sectioning commands in implementation part of etoc.dtx so far)
\AddToHook{env/macrocode/after}{\@nobreakfalse}
\AddToHook{env/macrocode/begin}{\partopsep0pt\relax}
\begingroup
\catcode`\|=\z@ \catcode`\[=\@ne \catcode`\]=\tw@
\catcode`\{=12 \catcode`\}=12
% Let % be active to use a color for it and gray-out
% comments left in code (there are few)
\catcode`\%=13 \catcode`\ =\active \catcode`\\=\active
|gdef|xmacro@code#1%    \end{macrocode}[#1|end[macrocode]]
|endgroup
%%% 2022/08/27: for etoc.dtx try to really use comment color in comments
%%%             this is not a complete solution, but enough for use case
\begingroup\catcode`\%=\active\catcode`\^^M 13
\gdef%{\begingroup\color{macrocodecommentcolor}^^A
                  \let\xintdocMacrocodeFallbackColorCmd\@empty^^A
       \@percentchar\odef
{\expandafter\endgroup
}}\endgroup
\begingroup\let\newcount\@gobble\@definecounter{CodelineNo}\endgroup
\def\theCodelineNo{\reset@font\scriptsize\arabic{CodelineNo}}
\def\theHCodelineNo{\the\value{section}.\the\value{CodelineNo}}
%%% not needed for etoc.dtx
%%% \def\xintMakePrivateLetters{\catcode`: 11 \catcode`? 11 \catcode`@ 11 
%%%                             \catcode`^ 11 \catcode`_ 11 }
%%% \def\xintexprMakePrivateLetters{\xintMakePrivateLetters \catcode`! 11 }
%%% \let\MakePrivateLetters\xintMakePrivateLetters
\definecolor{xintnamecolor}{RGB}{228,57,0}
\colorlet{verbcolor}{Maroon}
%
\colorlet{privatecommentcolor}{cyan}
\colorlet{macrocodecommentcolor}{gray}
\colorlet{macrocodenewmacrocolor}{verbcolor}
\colorlet{macrocodelinktouserdoccolor}{xintnamecolor}% and bold face
\colorlet{macrocodelinktosectioncolor}{DarkBlue}% and bold face
\colorlet{macrocodelinktocodelinecolor}{DarkBlue}
\colorlet{macrocodenoncscolor}{Green}
\def\xintdocMacrocodeFallbackColorCmd{\normalcolor}
\odef\init@crossref{\init@crossref%
     \everypar{\refstepcounter{CodelineNo}%
               \llap{{\xintdocMacrocodeFallbackColorCmd\theCodelineNo}\
                      \hskip\@totalleftmargin}%
               }%
     \catcode`\%\active
}%
\def\scan@macro{%
   % we do not insert it yet
   % \special@escape@char
   \step@checksum
%   \ifscan@allowed
      \let\macro@namepart\@empty
      % we need this for reasons explained below
      \let\macro@spacepart\@empty
      \def\next{\futurelet\next\macro@switch}%
%   \else \let\next\@empty \fi
   \next
}
% unchanged:
% \def\macro@switch{\ifcat\noexpand\next a%
%      \let\next\macro@name
%      \else \let\next\short@macro  \fi
%    \next}
\def\short@macro#1{\special@escape@char#1}
% \def\macro@name#1{\edef\macro@namepart{\macro@namepart#1}%
%      \futurelet\next\more@macroname}
% \def\more@macroname{\ifcat\noexpand\next a%
%      \let\next\macro@name
%      \else \let\next\macro@finish \fi
%      \next}
\def\more@macroname{\ifcat\noexpand\next a%
     \expandafter\macro@name
     % we keep the \next for usage later and start filtering out of the way spaces
     % this is caused by necessity of handling things such as \let<space>\foo\bar
     % but also not be fooled by \let<space>#6\macro
     \else \expandafter\macro@gatherspaces \fi
     }
\def\macro@gatherspaces{%
    \ifx\next\@xobeysp
        \expandafter\macro@gatherspaces@i
    \else
        \expandafter\macro@finish
    \fi}%
\def\macro@gatherspaces@i#1{%
    \odef\macro@spacepart{\macro@spacepart#1}% #1 = active space
    \futurelet\next\macro@gatherspaces}%
\newif\iflabelmacro@allowed
\newcounter{xintMacroCnt}
%%% pour l'instant pas relevant pour etoc, pas de mark-up par \subsection etc...
\def\xintimplabelprefix{src-}
\let\xintdoclabelprefix\empty
%%% next thing is used in xint.dtx in a hack of \@sect but we don't have so
%%% far sectioning mark-up in etoc.dtx implementation part
%%% \let\xintlabelprefix\xintimplabelprefix
\catcode`_ 11 \catcode`* 11
\def\macro@finish{%
  \iflabelmacro@allowed
   \expandafter\in@\expandafter{\expandafter.\macro@namepart,}%
   {.csname,.expandafter,.noexpand,.else,%
    %.t,.w,.x,.y,.z,.XINT_x,.XINT_y,%
    %.XINT_tmpa,.XINT_tmpb,.XINT_tmpc,.XINT_tmpd,.XINT_tmpe,% _ is letter here
    %.XINT_expr_defbin_b,.XINT_expr_defbin_c,.XINT_expr_defbin_d,%
    .empty,.space,}%
   \ifin@
     {\xintdocMacrocodeFallbackColorCmd\special@escape@char\macro@namepart}%
   \else
     \ifcsname alreadydefined-\macro@namepart\endcsname
       \hyperref[xintmacro-\macro@namepart]{\special@escape@char\macro@namepart}%
     \else
       % this will make a rather large number of macro names in the string pool...
       \global\expandafter\let\csname alreadydefined-\macro@namepart\endcsname\@empty
       \label{xintmacro-\macro@namepart}%
       \stepcounter{xintMacroCnt}%
       % try to link to a labeled reference in the user documentation (xint-all.pdf)
       \ifcsname r@\xintdoclabelprefix\macro@namepart\endcsname
          {\hypersetup{linkcolor=macrocodelinktouserdoccolor}%
           \hyperref[\xintdoclabelprefix\macro@namepart]%
                    {\textbf{\special@escape@char\macro@namepart}}}%
       \else
       % try to link to a labeled section in implementation part
       %% THIS BRANCH WILL NEVER BE USED IN etoc.dtx FROM ABSENCE OF
       %% ASSOCIATED MARK-UP
       \ifcsname r@\xintimplabelprefix\macro@namepart\endcsname
          {\hypersetup{linkcolor=macrocodelinktosectioncolor}%
           \hyperref[\xintimplabelprefix\macro@namepart]%
                    {\textbf{\special@escape@char\macro@namepart}}}%
       \else
          \textcolor{macrocodenewmacrocolor}{\textbf{\special@escape@char\macro@namepart}}%
       \fi\fi
     \fi
   \fi
   \labelmacro@allowedfalse
   \expandafter\in@\expandafter{\expandafter.\macro@namepart,}{.expandafter,}%
   \ifin@
      \ifx\next\scan@macro\labelmacro@allowedtrue\fi
   \fi
  \else % end of labelmacro@allowedtrue branch
%%% etoc.dtx adds complications to handle \newcommand*
    \if0\ifx\next\scan@macro0\else\ifx\next\lowast0\else1\fi\fi
      \expandafter\in@\expandafter{\expandafter.\macro@namepart,}%
                {.def,.edef,.let,.gdef,.xdef,%
                 .chardef,.newif,.newtoks,.newcommand,}%.odef,.oodef,.fdef,}%
      \ifin@\labelmacro@allowedtrue\fi
    \fi
    \ifcsname r@xintmacro-\macro@namepart\endcsname
      \hyperref[xintmacro-\macro@namepart]{\special@escape@char\macro@namepart}%
    \else
      {\xintdocMacrocodeFallbackColorCmd\special@escape@char\macro@namepart}%
    \fi
  \fi
  % \ifnot@excluded
  %    \edef\@tempa{\noexpand\SpecialIndex{\bslash\macro@namepart}}%
  %    \@tempa  
  % \fi
  \macro@spacepart
}%
\catcode`_ 8 \catcode`* 11
%%% In order mainly to colorize #1, #2, etc... we do this rather
%%% non-economical thing of colorizing all of macrocode with
%%% the "non control sequence color", hence this means all
%%% control sequences will have their own color command...
%%% This is because when doing this in June 2022 for xint, I did
%%% not want to hack more doc.sty scanning process of tokens,
%%% but perhaps I should, it would be more economical.  Kept as is
%%% when transferring to etoc.dtx 2022/08/26
{\sbox0{\color{macrocodenoncscolor}\xdef\foo{\current@color}}}
\ifpdf
   \edef\xintdoc@macrocode@pushcolor
      {\pdfcolorstack\noexpand\@pdfcolorstack push{\foo}\relax}
   \def\xintdoc@macrocode@popcolor{\pdfcolorstack\@pdfcolorstack pop\relax}
\else
\ifxetex
   \edef\xintdoc@macrocode@pushcolor{\special{color push \foo}}
   \def\xintdoc@macrocode@popcolor{\special{color pop}}
\else
\ifnum\Withdvipdfmx=1
     \edef\xintdoc@macrocode@pushcolor{\special{color push \foo}}
     \def\xintdoc@macrocode@popcolor{\special{color pop}}
\fi\fi\fi
%%% 2022/08/26 \par added for etoc.dtx
\AddToHook{env/macrocode/before}{\xintdoc@macrocode@pushcolor\par}
\AddToHook{env/macrocode/end}{\xintdoc@macrocode@popcolor}
% let's use some more quiet color for links inside the code
\AddToHook{env/macrocode/begin}{\hypersetup{linkcolor=macrocodelinktocodelinecolor}}
% let code line numbers really be fully in the margin
\MacroIndent\z@

\makeatother

Control sequences are mostly hyperlinks.  When a user level command is
defined it hyperlinks to the user documentation with
\textbf{\textcolor{macrocodelinktouserdoccolor}{this colour}} (and bold
face); for other macro definitions
\textbf{\textcolor{macrocodenewmacrocolor}{this colour}} is used, and
bold face.  It is not an hyperlink then.  When a previously defined
macro is used it uses \textcolor{macrocodelinktocodelinecolor}{this
  colour} and is then an hyperlink to the macro definition in the source
code.  Comments have been configured
\textcolor{macrocodecommentcolor}{to be rendered in their own colour},
and \textcolor{macrocodenoncscolor}{non commented-out and non-control
  sequences tokens use this colour}.  Other tokens use the fall-back
normal colour.

Warning: the code author's brain reboots frequently, and more and more often.
Hence most comments are not for the general reader, they are for the author
himself and they document more the history of the package than its actual
functioning, because the historical evolution is the way the author can
remember and understand the code.  There are a few precious isolated
paragraphs which may prove vaguely useful to people not the author.

%  9 avril 2015 (1.08d) pour forcer indentation après macrocode
% par un effet particulier si avant macrocode un enumerate, inefficient,
% mais vraiment pas envie d'investiguer.
%
% l'esthétique est un peu douteuse mais je laisse ? 

% non finalement je supprime

% \makeatletter
% \def\endmacrocode{%
%                  \ifpm@module \endgroup \pm@modulefalse \fi
%                  \everypar{}%
%                  \global\@inlabelfalse
%                  \endtrivlist\@endpefalse % <<-- ajouté 
%                  \close@crossref}
% \makeatother


% November 2012
% I don't want to have to type at this location (far from the top of the
% file) explicitly the package version or version date, as it is
% inconvenient to have to remember to do this when updating the package.
% Also, I prefer not to add macros to the |.sty| file giving the package
% date, name, or version. So I extracted this from the real macrocode
% environment (leaving out the \init@crossref.)

% The catcode hackery next is to avoid to have <*package> to be listed
% in the commented source code...
% (c) 2012/11/19 jf burnol ;-)

\MakePercentIgnore

%
% \catcode`\<=0 \catcode`\>=11 \catcode`\*=11 \catcode`\/=11
% \let</none>\relax
% \def<*package>{\catcode`\<=12 \catcode`\>=12 \catcode`\*=12 \catcode`\/=12}
%
%</none>
%<*package>
%    \begin{macrocode}
\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{etoc}
[2022/11/17 v1.09g Completely customisable TOCs (JFB)]
\RequirePackage{multicol}
\DeclareOption*{\PackageWarning{etoc}{Option `\CurrentOption' is unknown.}}
\ProcessOptions\relax
%    \end{macrocode}
% |1.08| suppresses |\ifEtoc@part| and defines |\ifEtoc@skipprefix|. It
% also defines |\etocglobaldefs|, |\etoclocaldefs| and |\Etoc@global|.
%    \begin{macrocode}
\newtoks\Etoc@toctoks
\def\Etoc@par{\par}
\def\etocinline{\def\Etoc@par{}}
\let\etocnopar\etocinline
\def\etocdisplay{\def\Etoc@par{\par}}% 1.07m 2015/01/23
%    \end{macrocode}
% |\etocglobaldefs| should be used only for special things such as TOC as a
% table; it should be put in a group to limit its scope. If used in the
% preamble, it must come \emph{after} |tableof| if the latter is loaded too.
%    \begin{macrocode}
\let\Etoc@global\@empty              % 1.08 2015/03/10
\def\etocglobaldefs{\let\Etoc@global\global\let\tof@global\global}
\def\etoclocaldefs {\let\Etoc@global\@empty\let\tof@global\@empty}
\newif\ifEtoc@jj  % book
\newif\ifEtoc@j   % part
\newif\ifEtoc@    % chapter
\newif\ifEtoc@i   % section
\newif\ifEtoc@ii  % subsection
\newif\ifEtoc@iii % subsubsection
\newif\ifEtoc@iv  % paragraph
\newif\ifEtoc@v   % subparagraph
\newif\ifEtoc@number
\newif\ifEtoc@hyperref
\newif\ifEtoc@parskip   % 1.07d
\newif\ifEtoc@tocwithid
\newif\ifEtoc@standard
\newif\ifEtoc@skipprefix % 1.08
\newif\ifEtoc@isfirst    % 1.08
\newif\ifEtoc@localtoc
\newif\ifEtoc@skipthisone
\newif\ifEtoc@stoptoc
\newif\ifEtoc@notactive
\newif\ifEtoc@mustclosegroup
\newif\ifEtoc@emptytoc     % 1.08e
\newif\ifEtoc@checksemptiness % 1.08e. Default is 'no checks'.
\def\etocchecksemptiness       {\Etoc@checksemptinesstrue }
\def\etocdoesnotcheckemptiness {\Etoc@checksemptinessfalse }% 1.08i
\newif\ifEtoc@notocifnotoc % 1.08e
\def\etocnotocifnotoc {\Etoc@checksemptinesstrue\Etoc@notocifnotoctrue }
\def\etoc@{\etoc@}
\newif\ifEtoc@bracedname % 1.08p
%    \end{macrocode}
% |1.07g| uses a second counter; this could be avoided, but ok, let's not be
% that strict.
%    \begin{macrocode}
\newcounter{etoc@tocid}
\newcounter{etoc@tocdepth}% 1.07g
%    \end{macrocode}
% |2015/03/08| Why do I use |jj| in the flags and |minustwo| here? and
% is there an entity full of forgiveness out there to save my soul even
% if taking into consideration my use of single and doubled |@|'s ?
% Although I desperately need to waste time I miraculously decided not
% to change everything today and thus the somewhat dispendious set-up
% below is maintained.
%    \begin{macrocode}
\@ifclassloaded{memoir}{\def\Etoc@minf{-\thr@@}}{\def\Etoc@minf{-\tw@}}
\def\Etoc@@minustwo@@{-\tw@}
\let\Etoc@@minusone@@\m@ne
\let\Etoc@@zero@@    \z@
\let\Etoc@@one@@     \@ne
\let\Etoc@@two@@     \tw@
\let\Etoc@@three@@   \thr@@
\chardef\Etoc@@four@@ 4
\chardef\Etoc@@five@@ 5
\chardef\Etoc@@six@@  6
\def\Etoc@@minustwo@{minustwo}
\def\Etoc@@minusone@{minusone}
\def\Etoc@@zero@    {zero}
\def\Etoc@@one@     {one}
\def\Etoc@@two@     {two}
\def\Etoc@@three@   {three}
\def\Etoc@@four@    {four}
\def\Etoc@@five@    {five}
%    \end{macrocode}
% |1.07g|.
%    \begin{macrocode}
\expandafter\def\csname Etoc@-3@@\endcsname {-\thr@@}
\expandafter\let\csname Etoc@-2@@\endcsname \Etoc@@minustwo@@
\expandafter\let\csname Etoc@-1@@\endcsname \Etoc@@minusone@@
\expandafter\let\csname Etoc@0@@\endcsname  \Etoc@@zero@@
\expandafter\let\csname Etoc@1@@\endcsname  \Etoc@@one@@
\expandafter\let\csname Etoc@2@@\endcsname  \Etoc@@two@@
\expandafter\let\csname Etoc@3@@\endcsname  \Etoc@@three@@
\expandafter\let\csname Etoc@4@@\endcsname  \Etoc@@four@@
\expandafter\let\csname Etoc@5@@\endcsname  \Etoc@@five@@
\expandafter\let\csname Etoc@6@@\endcsname  \Etoc@@six@@
\let\Etoc@all@@   \Etoc@@five@@
\let\Etoc@none@@  \Etoc@minf
%    \end{macrocode}
% Versions earlier than |1.08| did |\Etoc@newlevel| in a quite
% embarrassing way with an |\edef|.
%
% |1.08f|'s \csa{etocsetlevel} avoids multiple insertions of the same level
% in the \csa{Etoc@levellist} list.
%
% |1.08k| modified \csa{Etoc@newlevel}: formerly a token |\l@#1| was stored in
% place of braced name |{#1}|. This changed is to facilitate creation of the
% |\etocsavedsectiontocline| etc... macros later on, at each TOC. But the
% stored |#1| is not expanded immediately, although it is in other parts of
% \csa{etocsetlevel}, which may cause timing problems if |#1| is a macro.
%    \begin{macrocode}
\let\Etoc@levellist\@empty
\def\Etoc@newlevel #1{\expandafter\def\expandafter\Etoc@levellist\expandafter
        {\Etoc@levellist\Etoc@levellist@elt{#1}}}
\def\etocsetlevel#1#2{%
   \@ifundefined{Etoc@#1@@}{\Etoc@newlevel{#1}}{}%
   \ifcase#2\relax
      \expandafter\let \csname Etoc@#1@@\endcsname\Etoc@@zero@@
      \expandafter\let \csname Etoc@#1@\endcsname\Etoc@@zero@
   \or
      \expandafter\let \csname Etoc@#1@@\endcsname\Etoc@@one@@
      \expandafter\let \csname Etoc@#1@\endcsname\Etoc@@one@
   \or
      \expandafter\let \csname Etoc@#1@@\endcsname\Etoc@@two@@
      \expandafter\let \csname Etoc@#1@\endcsname\Etoc@@two@
   \or
      \expandafter\let \csname Etoc@#1@@\endcsname\Etoc@@three@@
      \expandafter\let \csname Etoc@#1@\endcsname\Etoc@@three@
   \or
      \expandafter\let \csname Etoc@#1@@\endcsname\Etoc@@four@@
      \expandafter\let \csname Etoc@#1@\endcsname\Etoc@@four@
   \or
      \expandafter\let \csname Etoc@#1@@\endcsname\Etoc@@five@@
      \expandafter\let \csname Etoc@#1@\endcsname\Etoc@@five@
   \or
      \expandafter\let \csname Etoc@#1@@\endcsname\Etoc@@six@@
   \else
    \ifnum#2=\m@ne
     \expandafter\let \csname Etoc@#1@@\endcsname\Etoc@@minusone@@
     \expandafter\let \csname Etoc@#1@\endcsname\Etoc@@minusone@
    \else
     \ifnum#2=-\tw@
      \expandafter\let \csname Etoc@#1@@\endcsname\Etoc@@minustwo@@
      \expandafter\let \csname Etoc@#1@\endcsname\Etoc@@minustwo@
     \else
      \PackageWarning{etoc}
         {unexpected value `#2' in \string\etocsetlevel.^^J%
          Should be -2,-1, 0, 1, 2, 3, 4, 5, or 6. Set to 6 (=ignored)}%
      \expandafter\let\csname Etoc@#1@@\endcsname\Etoc@@six@@
     \fi
    \fi
   \fi
}
\etocsetlevel{book}{-2}
\etocsetlevel{part}{-1}
\etocsetlevel{chapter}{0}
\etocsetlevel{section}{1}
\etocsetlevel{subsection}{2}
\etocsetlevel{subsubsection}{3}
\etocsetlevel{paragraph}{4}
\etocsetlevel{subparagraph}{5}
%    \end{macrocode}
% The first two parameters of |\Etoc@et@hop| are exchanged in |1.08|
% compared to earlier versions; this is in relation to changes done in
% |\Etoc@etoccontentsline|.
%
% |1.08i 2016/09/29| has a |fourorthree| rather than as formerly a |sixorfive|.
%
% \LaTeX\ of November 2021 will have its |\contentsline| always grab four
% arguments. So we must adjust |\Etoc@et@hop| et al., else usage of \etoc
% without hyperref will be broken. Done at |1.09e 2021/09/23|.
%
%^^A Side note to myself: I see there is now a |\@gobblethree| in latex.ltx and
%^^A I wonder since when. No time to lose on checking that.
%^^A Answer: 2020-02-27 ltdefns.dtx 1.5g |\@gobblethree|: Macro added
%
% |1.09g| adapts to |hyperref| depending on
% whether the latter is at |7.00u| or earlier.  Indeed internal changes to
% |hyperref| at |7.00u| broke \etoc.  Thanks to Denis~\textsc{Bitouzé} for
% reporting the issue.
%    \begin{macrocode}
\AtBeginDocument{%
\@ifpackageloaded{parskip}{\Etoc@parskiptrue}{}%
\@ifpackageloaded{hyperref}{%
    \Etoc@hyperreftrue
    \@ifpackagelater{hyperref}{2022/11/13}%
    {%
      \def\Etoc@getthepage {%
        \ifx\Hy@toclinkstart\Etoc@getthepage@token
          \expandafter\expandafter\expandafter\Etoc@getthepage@hyp
        \else
          \expandafter\Etoc@getthepage@nohyp
        \fi}%
      \def\Etoc@getnb@a {%
       \ifx\Hy@toclinkstart\Etoc@getnb@token
        \expandafter\expandafter\expandafter\Etoc@getnb@hyp
       \else
        \expandafter\Etoc@getnb@nohyp
       \fi}%
      \def\Etoc@getit {%
       \ifx\Hy@toclinkstart\Etoc@getit@token
        \expandafter\expandafter\expandafter\Etoc@getit@hyp
       \else
        \expandafter\Etoc@getit@nohyp
       \fi}%
     }%
     {%
      \def\Etoc@getthepage {%
        \ifx\hyper@linkstart\Etoc@getthepage@token
          \expandafter\Etoc@getthepage@hyp
        \else
          \expandafter\Etoc@getthepage@nohyp
        \fi}%
      \def\Etoc@getnb@a {%
       \ifx\hyper@linkstart\Etoc@getnb@token
        \expandafter\Etoc@getnb@hyp
       \else
        \expandafter\Etoc@getnb@nohyp
       \fi}%
      \def\Etoc@getit {%
       \ifx\hyper@linkstart\Etoc@getit@token
        \expandafter\Etoc@getit@hyp
       \else
        \expandafter\Etoc@getit@nohyp
       \fi}%
     }%
     \def\Etoc@et@hop#1#2#3#4#5{#2{#3}{#4}{#5}#1}%
     \let\Etoc@gobblefourorthree\@gobblefour
   }%
   {%
    \let\Etoc@getthepage\Etoc@getthepage@nohyp
    \let\Etoc@getnb@a\Etoc@getnb@nohyp
    \let\Etoc@getit  \Etoc@getit@nohyp
    \def\Etoc@et@hop#1#2#3#4{#2{#3}{#4}#1}%
    \long\def\Etoc@gobblefourorthree#1#2#3{}%
   }%
\@ifl@t@r\fmtversion{2021/11/15}%
   {%
    \def\Etoc@et@hop#1#2#3#4#5{#2{#3}{#4}{#5}#1}%
    \let\Etoc@gobblefourorthree\@gobblefour
   }%
   {}%
}
%    \end{macrocode}
% |2015/03/08| One has to be careful about the |Etoc@end@<level>| user
% defined macros which may close groups. This has always been the reason
% for the |\global|'s here and elsewhere.
%
% |1.08| uses |\Etoc@level| rather than a |#1| which used to be anyhow always
% the |\Etoc@tmp|. Now |\Etoc@level| is what was called formerly |\Etoc@tmp|
% in |\Etoc@etoccontentsline|.
%
% Attention that |\Etoc@setflags| must not modify |\Etoc@next|!
%    \begin{macrocode}
\def\Etoc@setflags {%
    \ifcase \Etoc@level
        \global\Etoc@vfalse
        \global\Etoc@ivfalse
        \global\Etoc@iiifalse
        \global\Etoc@iifalse
        \global\Etoc@ifalse
        \global\Etoc@true
    \or
        \global\Etoc@vfalse
        \global\Etoc@ivfalse
        \global\Etoc@iiifalse
        \global\Etoc@iifalse
        \global\Etoc@itrue
    \or
        \global\Etoc@vfalse
        \global\Etoc@ivfalse
        \global\Etoc@iiifalse
        \global\Etoc@iitrue
    \or
        \global\Etoc@vfalse
        \global\Etoc@ivfalse
        \global\Etoc@iiitrue
    \or
        \global\Etoc@vfalse
        \global\Etoc@ivtrue
    \or
        \global\Etoc@vtrue
    \else
        \global\Etoc@vfalse
        \global\Etoc@ivfalse
        \global\Etoc@iiifalse
        \global\Etoc@iifalse
        \global\Etoc@ifalse
        \global\Etoc@false
        \ifnum\Etoc@level=\m@ne
            \global\Etoc@jtrue
        \else
            \global\Etoc@jfalse
            \global\Etoc@jjtrue
        \fi
    \fi
}
%    \end{macrocode}
% |1.08| This was originally in |\Etoc@etoccontentsline|, intermixed
% with the definitions of |\Etoc@contents| and |\Etoc@prefix|. Separated
% here for clarity of code. One has to be careful that this may close
% groups. The conditionals are all global. The |\Etoc@level| has been
% |\global\let| to a |\chardef| variable. The final |\else| of the
% |\ifcase| assumes none of the |\Etoc@end@..| routines modify it,
% naturally.
%    \begin{macrocode}
\def\Etoc@doends {%
    \ifcase \Etoc@level
        \ifEtoc@v  \Etoc@end@five \fi
        \ifEtoc@iv \Etoc@end@four \fi
        \ifEtoc@iii\Etoc@end@three\fi
        \ifEtoc@ii \Etoc@end@two  \fi
        \ifEtoc@i  \Etoc@end@one  \fi
    \or
        \ifEtoc@v  \Etoc@end@five \fi
        \ifEtoc@iv \Etoc@end@four \fi
        \ifEtoc@iii\Etoc@end@three\fi
        \ifEtoc@ii \Etoc@end@two  \fi
    \or
        \ifEtoc@v  \Etoc@end@five \fi
        \ifEtoc@iv \Etoc@end@four \fi
        \ifEtoc@iii\Etoc@end@three\fi
    \or
        \ifEtoc@v  \Etoc@end@five \fi
        \ifEtoc@iv \Etoc@end@four \fi
    \or
        \ifEtoc@v  \Etoc@end@five \fi
    \or
    \else
        \ifEtoc@v  \Etoc@end@five \fi
        \ifEtoc@iv \Etoc@end@four \fi
        \ifEtoc@iii\Etoc@end@three\fi
        \ifEtoc@ii \Etoc@end@two  \fi
        \ifEtoc@i  \Etoc@end@one  \fi
        \ifEtoc@   \Etoc@end@zero \fi
        \ifnum \Etoc@level =-\tw@
            \ifEtoc@j \Etoc@end@minusone\fi
        \fi
    \fi
}
%    \end{macrocode}
% |1.08| the |\Etoc@next| will (possibly) execute the |begin| code,
% \emph{before} |\Etoc@contents| and |\Etoc@prefix| get defined,
% contrarily to what I did in earlier versions. I still reset the flags
% before execution of the |begin| codes (although the flags are not
% supposed to be used therein anyhow).
%
% Also the \meta{begin} code does |\Etoc@isfirsttrue|.
%
% |1.08k| This was originally in |\Etoc@etoccontentsline|. Extracted for
% re-use by |\etocsetlocaltop.toc|. Calls |\Etoc@setflags| which must not
% modify |\Etoc@next|.
%    \begin{macrocode}
\def\Etoc@dobegins{%
    \let\Etoc@next\@empty
    \Etoc@global\Etoc@isfirstfalse
%    \end{macrocode}
% |2015/03/08| If my naming scheme had not been so baroque, I could easily do
% things in a more concise way here...
%    \begin{macrocode}
    \ifcase\Etoc@level
        \ifEtoc@
        \else
            \def\Etoc@next{\Etoc@begin@zero}%
        \fi
    \or
        \ifEtoc@i
        \else
            \def\Etoc@next{\Etoc@begin@one}%
        \fi
    \or
        \ifEtoc@ii
        \else
            \def\Etoc@next{\Etoc@begin@two}%
        \fi
    \or
        \ifEtoc@iii
        \else
            \def\Etoc@next{\Etoc@begin@three}%
        \fi
    \or
        \ifEtoc@iv
        \else
            \def\Etoc@next{\Etoc@begin@four}%
        \fi
    \or
        \ifEtoc@v
        \else
            \def\Etoc@next{\Etoc@begin@five}%
        \fi
    \else
        \ifnum\Etoc@level=\m@ne
            \ifEtoc@j
            \else
                \def\Etoc@next{\Etoc@begin@minusone}%
            \fi
        \else
            \ifEtoc@jj
            \else
                \def\Etoc@next{\Etoc@begin@minustwo}%
            \fi
        \fi
    \fi
    \Etoc@setflags
    \Etoc@next
}
%    \end{macrocode}
% Heart of \etoc hack into execution of |.toc| file. The |.toc|
% file must contain (at least indirectly via expansion)
% |\contentsline {<unit>}...| instructions, with
% the standard meaning of executing |\l@unit| (the hyperref
% modifications are taken into account). It is the various |\l@unit|'s
% which are (locally) |\let| to |\Etoc@lxyz| and it is |\Etoc@lxyz|
% which does the parsing of the arguments in order to extract name,
% number and page number. Once they are obtained, via the execution of
% this indirectly hacked |\contentsline|, the code executes the
% |\Etoc@prefix| and |\Etoc@contents| corresponding to that unit level,
% according to the user |\etocsetstyle| declarations. Before that the
% begin part is executed when \etoc first encounters that level
% coming from a higher one and the end part will be executed when
% hitting a more important level.
%
% |\etocskipfirstprefix| was already part of the very first release of
% \etoc. Up to |1.07n| it was just an elegant |\@thirdofthree| possibly
% executed just before a |\@firstoftwo{\Etoc@swa{#1}}{\Etoc@swb{#1}}|
% line. But this made it impossible for me to execute things after the
% |begin| parts.
%
% Executing stuff before |begin| is now a potential problem because the user
% can close some group in the |begin| code (this was in fact impossible in
% versions |<1.08| because this would have erased the definitions of
% |\Etoc@contents| and |\Etoc@prefix|). Thus I am not so free now to define
% things before execution of begin, if I allow people to close a group
% therein, except if I make them global.
%
% The mechanism of |\etocskipfirstprefix| made it impossible to add
% anything at the end of the |begin| codes. Thus I changed it in |1.08|
% to simply work with a (global) boolean flag. This gives user the
% freedom to use |\etocskipfirstprefix| anywhere in the |begin| code and
% it made room for a delimited macro I called |\etoconlyonfirst|. But
% then I dropped it in favor of definition of the |\etociffirst|
% conditional.
%
% Macros |\Etoc@swa| and |\Etoc@swb| which did the |\Etoc@et@hop| thing have
% been suppressed, their effect is incorporated to the end of
% |\Etoc@etoccontentsline|.
%    \begin{macrocode}
\def\etocskipfirstprefix {\global\Etoc@skipprefixtrue }
%    \end{macrocode}
% |2015/03/08| let's record that |\Etoc@level| used to be called
% |\Etoc@tmp| in versions earlier than |1.08| (and |\Etoc@tmp| is used
% in the completely different ulterior |\Etoc@lxyz| context). The code
% sets it for example to be |\Etoc@section@@| which has been let by
% |\etocsetlevel| to |\@ne|, thus is always self-terminating in
% |\ifnum..\fi| contexts.
%
% |1.08i-2016/09/29| makes some changes in the organization of the
% conditionals. It could happen in certain special circumstances (created by
% that part in |\Etoc@localtableofcontents| which is executed after the test
% of emptiness) that |\Etoc@localtop| was still undefined. Earlier version of
% the code was a bit lazy and did not avoid some unneeded |\ifnum| with
% |\Etoc@localtop| in context where the flag |\ifEtoc@stoptoc| was |\iftrue|;
% this was not an issue when code was first written, |\Etoc@localtop| was
% always initialized back then. But the code in |\Etoc@localtableofcontents|
% handling local TOCs with unrecognized ids would call execution of the |.toc|
% file under some special context with flag |\ifEtoc@stoptoc| artificially set
% to true. If |\Etoc@localtop| had not been initialized an undefined control
% sequence error would occur. Furthermore as |\ifEtoc@notactive| was also set
% to true, the case of no error leads then to unneededly expand |\Etoc@setflags|
% code slowing down compilation.
%
% Also |1.08i| splits the macro into two, with accompanying slight
% refactoring. I had such problems with the behaviour of TeX booleans in
% 2011/12 that I got excessively cautious then, and was using an |\Etoc@next|
% for the |\Etoc@setflags| rather than leaving it like here deep inside
% conditional branches.
%
% Attention! |1.09|'s \cs{etoclocaltop} is the former \cs{Etoc@localtop}
% \emph{minus one}. Hence some slight change in conditional here.
%    \begin{macrocode}
\def\Etoc@etoccontentsline #1{%
  \global\expandafter\let\expandafter\Etoc@level\csname Etoc@#1@@\endcsname
  \Etoc@skipthisonefalse
  \ifnum\Etoc@level=\Etoc@@six@@
    \Etoc@skipthisonetrue
  \else
   \ifEtoc@localtoc
    \ifEtoc@stoptoc
      \Etoc@skipthisonetrue
    \else
     \ifEtoc@notactive\Etoc@setflags
       \Etoc@skipthisonetrue
     \else
      \unless\ifnum\Etoc@level>\etoclocaltop
        \Etoc@skipthisonetrue
        \global\Etoc@stoptoctrue
      \fi
     \fi
    \fi
   \fi
  \fi
  \let\Etoc@next\Etoc@gobblefourorthree
  \ifEtoc@skipthisone
  \else
   \unless\ifnum\c@tocdepth<\Etoc@level
    \ifEtoc@standard
      \let\Etoc@next\Etoc@savedcontentsline
    \else
      \let\Etoc@next\Etoc@etoccontentsline@
    \fi
   \fi
  \fi
  \Etoc@next{#1}%
}
%    \end{macrocode}
% |1.08| New way to handle the compatibility mode. One has to worry
% only for the local tables of contents (in inactive state, which still
% must be parsed for global level flags) but in this case
% |\Etoc@setflags| was done above already. Earlier method proceeded with
% dummy empty line styles.
%
% |2015/03/08| Ever since the first release of \etoc, the code has
% to be careful that the |\Etoc@end@<level>| user defined macros may
% close groups. This is the reason why some assignments have to be done
% globally. The |\let\Etoc@next\Etoc@gobblesixorfive| above could be
% local, because it is used only in case the stuff below is skipped,
% inclusive of |\Etoc@doends| which may close groups. (code has changed since,
% slightly).
%
% |1.08| extracts to a separate macro |\Etoc@doends|. Earlier code
% did |\global\let\Etoc@next\relax| but we can now give a default |\relax|
% value to |\Etoc@next| with no need of a |\global| prefix.
%
% |1.08k| extracts |\Etoc@dobegins|.
%    \begin{macrocode}
\def\Etoc@etoccontentsline@ #1{%
    \Etoc@doends   % separated since 1.08
    \Etoc@dobegins % separated since 1.08k. Does \Etoc@setflags.
%    \end{macrocode}
% |1.08|:
% \begin{enumerate}
% \item  separates the definition of |\Etoc@prefix| and
% |\Etoc@contents| from the execution of the |end| parts. And it does
% the definition with some |\csname|'s.
%
% \item implements |\etocskipfirstprefix| with a boolean, this is less slick
% but more flexible than the earlier method.
%
% \item defines the |\etociffirst| conditional.
%
% \item has |\Etoc@level| rather than |\Etoc@tmp| and thus we can dispense
% with the |\ifEtoc@part| switch as we will be able to test the equality
% |\Etoc@level=-1| inside of |\Etoc@lxyz|.
%
% \item adds the |\Etoc@global| prefix.
% \end{enumerate}
% |1.08i| uses an |\edef| rather than |\def| with a chain of |\expandafter|.
%    \begin{macrocode}
    \Etoc@global\edef\Etoc@prefix  {\expandafter\noexpand
         \csname Etoc@prefix@\csname Etoc@#1@\endcsname\endcsname }%
    \Etoc@global\edef\Etoc@contents{\expandafter\noexpand
         \csname Etoc@contents@\csname Etoc@#1@\endcsname\endcsname }%
    \ifEtoc@skipprefix \Etoc@global\let\Etoc@prefix\@empty\fi
    \global\Etoc@skipprefixfalse
%    \end{macrocode}
% |1.08| modifies the ending to not use the |\Etoc@swa| and |\Etoc@swb|
% things. With this version, the |\Etoc@next| here is only to gobble
% everything if it has to (or gobble only the \etoc things, when in
% compatibility mode).
%
% For the record we don't do |\csname l@#1\endcsname| mainly because
% hyperref patches |\contentsline|.
%
% The location where |\Etoc@savedcontentsline| is |\let| to
% |\contentsline| has been moved with release |1.08| to before the
% title as set by |\etocsettoctyle|, thus it is now possible to open a
% tabular in this part. And with the |\Etoc@global| prefix the user may
% opt for global definitions of |\etocname| and the like, thus use
% freely |&| and other group closing things. Also, some care has been
% put into doing only expandable things after expansion of the
% \meta{prefix} and \meta{contents} parts of a sectioning unit
% style.
%
% |1.09e| prepares for LaTeX November 2021 upcoming release
% whose |\contentsline| will always grab four arguments whether or
% not hyperref is loaded. The |\Etoc@et@hop| definition done at
% begin document must now swap the same number of arguments
% whether or not hyperref is loaded (else \etoc would be broken in
% absence of hyperref).
%    \begin{macrocode}
    \Etoc@et@hop{\Etoc@prefix\Etoc@contents}{\Etoc@savedcontentsline{#1}}%
}
%    \end{macrocode}
% START OF MAINLY OBSOLETE COMMENTS
%
% |2013/03/07|: up to |1.06| \etoc defined only \csa{etocname}, \csa{etocnumber} and
% \csa{etocpage}. The |hyperref| added data is recycled in the simplest
% manner, prefixing it with \csa{leavevmode}. The included
% \csa{Hy@tocdestname} is (was, see below |1.07f| and |1.08a|) left
% unexpanded. We have to spend some time with delimited macros to dis-entangle
% the |.toc| data, and reconstruct the possible |hyperref| data. If the page
% number is not hyperlinked, \csa{etocpage} does \emph{not} add the link found
% possibly in the name.
%
% |1.07| adds \csa{etocthename}, \csa{etocthenumber}, \csa{etocthepage} which
% are left fragile and do not have the links data, and
% \csa{etoclink}\marg{linkname} which is robust and reconstructs an
% arbitrarily named link.
%
% A need (for things like building up a token list to be used in a
% |tikzpicture|) arose later to have some form of the link which could be
% saved by a simple command like one can do
% |\global\let\lastname\etocthename|, and avoid having to manipulate
% \csa{Hy@tocdestname}. So |1.07f| adds \csa{etocthelinkedname},
% \csa{etocthelinkednumber}, \csa{etocthelinkedpage}, \csa{etocthelink}: they
% use \csa{hyperlink} with an expanded \csa{Hy@tocdestname}.
%
% |1.07f| also adds \csa{leavevmode} to \csa{etoclink} which
% should have been done earlier, as it was included in \csa{etocname} etc...
%  attention,  \csa{@namedef}|{A}{B}| and not \csa{@namedef}|{A} {B}| !!
% on the other hand this gives a simple way to insert a space as the first
% token in the paramaters. For \csa{Etoc@again} (which appears later in the
% code), a \csa{@firstofone} construct is however the simplest of all.
%
% END OF MAINLY OBSOLETE COMMENTS
%
% |1.08| adds |\Etoc@global| prefix (|2015/03/09|).
%
% |1.08a| drops the original constructions of |\etocname| etc... The obvious
% decision to convert \csa{etocname}, etc ... to be the robust versions of
% \csa{etocthelinkedname}, etc ... was delayed two years
% (from |1.07f 2013/03/07| to |1.08a 2015/03/13|) for sentimental reason. But
% the original
% versions contained the hyperref destination only in unexpanded form, this
% forced to use \csa{etocthelinkedname}, etc... in cases when the thing had to
% be stored for delayed use. Now the user can do this directly with
% \csa{etocname}, \csa{etocnumber}, \csa{etocpage} (taking into account though
% that these are robust macros, thus perhaps using something like |\LetLtxMacro|.)
%
% |1.08j| turns |\etoclink| into the robust version of |\etocthelink|. Indeed
% so far only \csa{etocthelink} contained |\Hy@tocdestname| expanded. But
% \csa{etoclink} did not, and thus it could not be used after a group was
% closed for example by a |&| from the sectioning style, even if having used
% |\etocglobaldefs|.
%
% |1.08n| adds |\futurelet|-based methods to avoid unbracing things.
%
% |1.08p| uses |\Etoc@@getnb| (and |\Etoc@@getit|) to intercept cases
% when |\numberline| is hidden behind braces
% (\url{https://github.com/ho-tex/hyperref/issues/65}).
%    \begin{macrocode}
\def\Etoc@lxyz #1#2{%
    \Etoc@global\let\etocthelink\@firstofone % fall-back, was let \@empty up to 1.08i (inc.)
    \Etoc@global\def\etocthename       {#1}%  (if linked, will be removed later)
    \Etoc@global\def\etocthelinkedname {#1}%  (probably redefined later)
    \futurelet\Etoc@getthepage@token
       \Etoc@getthepage #2\etoc@ % defines \etocthelinkedpage
    \futurelet\Etoc@getnb@token
       \Etoc@@getnb #1\relax\relax\etoc@  % sets number, name, and \etocthelink
    \ifEtoc@number
    \else
     \ifnum\Etoc@level=\m@ne
       \futurelet\Etoc@getit@token
          \Etoc@@getit #1\hspace\relax\etoc@   % additional job for parts
     \fi
    \fi
    \Etoc@global\expandafter\let\csname etoclink \endcsname\etocthelink
    \Etoc@global\expandafter\let\csname etocname \endcsname\etocthelinkedname
    \Etoc@global\expandafter\let\csname etocnumber \endcsname\etocthelinkednumber
    \Etoc@global\expandafter\let\csname etocpage \endcsname\etocthelinkedpage
    }
%    \end{macrocode}
% |1.08| adds the |\Etoc@global|'s.
%
% |1.08j| fixes an old |\ifx #1\hyperlink@start| bug.
%
% Potential (but rather exotic) brace removal problems avoided at |1.08n|.
%
% |1.09g| delays definition of \cs{Etoc@getthepage} to \cs{AtBeginDocument} to
% check if |hyperref| is at version |7.00u 2022-11-13| or later, as that
% version replaced \cs{hyper@linkstart} with \cs{protected} macro
% \cs{Hy@toclinkstart} which furthermore requires one more expansion step.
% Formerly, the \cs{ifEtoc@hyperref} test was executed via the expansion of
% \cs{Etoc@getthepage} but now this test is tacitly done only once at begin
% document to define appropriately \cs{Etoc@getthepage}.  Falls back to
% \cs{Etoc@getthepage@nohyp}.
%    \begin{macrocode}
\def\Etoc@getthepage@nohyp #1\etoc@ {%
    \Etoc@global\def\etocthepage       {#1}%
    \Etoc@global\def\etocthelinkedpage {#1}%
}
%    \end{macrocode}
% |1.07k| corrects a bug here with an extra space before |##1| in
% |\@namedef{etoclink } ##1|. In 99.99\% of use cases however, the
% macro gets redefined at a later stage, thus the bug did not show.
%
% |1.07n| replaces use of |\toks@| by macro |\Etoc@tmp|. Thus, the user has
% the (not so recommended) possibility to use |\toks@| in the styles, even to
% store information whose scope extends beyond the execution of each
% |\contentsline|.
%
% |1.08| adds the |\Etoc@global|'s.
%
% |1.08j| does not define \csa{etoclink<space>} anymore, only \csa{etocthelink}
% which contains the |\Hy@tocdestname| already expanded.
%    \begin{macrocode}
\def\Etoc@getthepage@hyp #1#2#3#4#5\etoc@ {%
    \Etoc@global\def\etocthepage {#4}%
    \edef\Etoc@tmp {{#3}}%
    \Etoc@global\expandafter\def\expandafter\etocthelinkedpage\expandafter
      {\expandafter\hyperlink \Etoc@tmp{#4}}%
    \Etoc@global\edef\etocthelink##1{\noexpand\hyperlink\Etoc@tmp{##1}}%
}
%    \end{macrocode}
% |1.08j| fixes an old buggy |\ifx #1\hyper@linkstart|. This could show if
% hyperref was present with |linktoc=page| option for example, because in that
% case |#1| could be some tokens within braces. As this is rare case though,
% no bug was reported.
%
% Anyway I refactored the whole thing at |1.08n|.
%
% |1.08p| adds workaround for an extra brace pair inserted by hyperref
% in case of |linktoc=page| option
% \centeredline{\url{https://github.com/ho-tex/hyperref/issues/65}}
%
% |1.09f| examines also if next token in a space token; if it is we know
% that we are not with a hyperref-customized entry and that we do not have a
% numbered entry.  We thus jump directly to \csa{Etoc@getnb@nohyp@nonbr}, so
% \csa{etocthename} is certainly not redefined and there is no risk of space
% gobbling and brace removal.  This precaution is a bit academic though as
% code from previous release could derail (i.e. mis-interpret data) only in
% especially crafted circumstances.
%    \begin{macrocode}
\def\Etoc@@getnb {%
    \Etoc@bracednamefalse
    \let\Etoc@next\Etoc@getnb
    \ifx\Etoc@getnb@token\@sptoken\let\Etoc@next\Etoc@getnb@nohyp@nonbr\fi
    \ifx\Etoc@getnb@token\bgroup  \let\Etoc@next\Etoc@getnb@checkifbraced\fi
    \Etoc@next
}
\def\Etoc@tworelax{\relax\relax}
\def\Etoc@getnb@checkifbraced #1#2\etoc@ {%
    \def\Etoc@tmp{#2}%
    \ifx\Etoc@tmp\Etoc@tworelax
        \expandafter\expandafter\expandafter\Etoc@getnb@nameisbraced
        \expandafter\@firstofone
    \else
        \expandafter\Etoc@getnb
    \fi {#1}#2\etoc@
}
\def\Etoc@getnb@nameisbraced {%
    \Etoc@bracednametrue
    \futurelet\Etoc@getnb@token\Etoc@getnb
}
%    \end{macrocode}
% |1.09g| adds an \cs{Etoc@getnb@a} which defaults to \cs{Etoc@getnb@nohyp}
% and gets defined only at begin document to adapt to |hyperref| depending on
% whether the latter is at |7.00u| or earlier.
%    \begin{macrocode}
\def\Etoc@getnb {%
    \ifx\Etoc@getnb@token\bgroup
       \expandafter\Etoc@getnb@nohyp@nonbr
    \else
       \expandafter\Etoc@getnb@a
    \fi
}
%    \end{macrocode}
% |1.08| adds the |\Etoc@global|'s.
%
% |1.08j| corrects an old |\ifx#1\numberline| into |\ifx\numberline#1|.
%
% |1.08k| uses a delimited macro to identify \csa{numberline},
% \csa{chapternumberline} etc... in one go, avoiding
% the |\let\chapternumberline\numberline| etc... which were done formerly
% in \csa{Etoc@tableofcontents}. Currently \etoc does not yet use \eTeX.
%
% |1.08m| fixes incompatibility of |1.08k|'s delimited macro method with KOMA's
% \csa{nonumberline}.
%
% Both |1.08k| and
% |1.08m| actually would have needed some |\detokenize| for complete safety
% and so far \etoc does not use e-\TeX. So here at |1.08n| I refactored the
% whole thing. And I added a |\futurelet|-based brace detection in
% |\Etoc@getnb| so here |#1| is guaranteed not braced now.
%
% |1.08n| tries to handle reasonably the |\nonumberline| of KOMA-script.
% If it expands to |\numberline{}|, \etoc will thus consider the line
% numbered with an empty number.
%
% At |1.09f| complications to get rid of a KOMA-script |\nonumberline|
% even though its meaning is |\empty| then, but for case of delayed use.
%    \begin{macrocode}
\def\Etoc@getnb@nohyp #1{%
    \in@{#1}{\numberline\chapternumberline\partnumberline\booknumberline}%
    \ifin@
       \let\Etoc@next\Etoc@getnb@nohyp@nmbrd
    \else
       \let\Etoc@next\Etoc@getnb@nohyp@nonbr
       \in@{#1}{\nonumberline}%
       \ifin@
           \ifx\nonumberline\empty
               \let\Etoc@next\Etoc@getnb@nohyp@nonumberline
           \else
               \def\Etoc@next{\expandafter\Etoc@getnb@nohyp@nmbrd}%
           \fi
       \fi
    \fi
    \Etoc@next #1%
}
\def\Etoc@getnb@nohyp@nmbrd #1#2#3\relax\relax\etoc@ {%
    \Etoc@global\Etoc@numbertrue
    \Etoc@global\def\etocthenumber       {#2}%
    \Etoc@global\def\etocthelinkednumber {#2}%
    \ifEtoc@bracedname
        \Etoc@global\def\etocthename{{#3}}%
    \else
        \Etoc@global\def\etocthename{#3}%
    \fi
    \Etoc@global\let\etocthelinkedname \etocthename
}
%    \end{macrocode}
% \csa{etocthename} and \csa{etocthelinkedname} already defined in
% \csa{Etoc@lxyz}, no need to update.
%    \begin{macrocode}
\def\Etoc@getnb@nohyp@nonbr #1\etoc@ {%
    \Etoc@global\Etoc@numberfalse
    \Etoc@global\let\etocthenumber       \@empty
    \Etoc@global\let\etocthelinkednumber \@empty
}
%    \end{macrocode}
% Special KOMA branch: |#1| starts with |\nonumberline| which has here same
% meaning as |\empty|.  It is in the current provisory definition of
% \csa{etocthename}.  We get rid of this token, in case usage is delayed,
% to avoid improbable problems.
%    \begin{macrocode}
\def\Etoc@getnb@nohyp@nonumberline #1\relax\relax\etoc@ {%
    \Etoc@global\Etoc@numberfalse
    \Etoc@global\let\etocthenumber       \@empty
    \Etoc@global\let\etocthelinkednumber \@empty
    \ifEtoc@bracedname
        \Etoc@global\expandafter\def\expandafter\etocthename
                                                \expandafter{\expandafter{#1}}%
    \else
        \Etoc@global\expandafter\def\expandafter\etocthename\expandafter{#1}%
    \fi
    \Etoc@global\let\etocthelinkedname \etocthename
}
%    \end{macrocode}
% |1.07n| replaces use of |\toks@| by macro |\Etoc@tmp|. |1.08| adds
% the |\Etoc@global|'s.
%
% |1.08j| corrects the old |\ifx#1\numberline| into |\ifx\numberline#1|.
%
% |1.08k| uses a delimited macro to identify \csa{numberline},
% \csa{chapternumberline} etc... in one go.
%
% But anyway this was completely refactored at |1.08n|. Unfortunately
% bad macro naming scheme caused a typo in a macro name, and it was
% left undefined.
% Fixed at |1.08o|.
%
% At |1.08p| which fixed an hyperref problem in case of |linktoc=page|
% we are lazy because the problem with extra braces should not happen
% in this branch (hyperref does not brace the hyperlink). So we ignore
% the |\ifEtoc@bracedname| setting.
%
% At |1.09f| complications to get rid of a KOMA-script |\nonumberline|
% even though its meaning is |\empty| then, but for case of delayed use.
%    \begin{macrocode}
\def\Etoc@getnb@hyp #1#2#3#4#5#6\etoc@ {%
    \edef\Etoc@tmp {{#3}}%
    \Etoc@global\edef\etocthelink ##1{\noexpand\hyperlink {#3}{##1}}%
    \Etoc@global\def\etocthename {#4}% temporary definition
    \Etoc@global\expandafter\def\expandafter\etocthelinkedname
                \expandafter {\expandafter\hyperlink \Etoc@tmp{#4}}%
    \futurelet\Etoc@hyp@getnb@token\Etoc@getnb@hyp@a #4\relax\relax\etoc@
}
%    \end{macrocode}
% In case of an upfront brace, the sectioning heading is not numbered, so we
% can avoid potential brace removal problems by jumping now to the not
% numbered branch not hyperlinked branch; indeed \csa{etocthelinkedname} has
% already been defined with the |\hyperlink| so we can bail out.
%    \begin{macrocode}
\def\Etoc@getnb@hyp@a {%
    \ifx\Etoc@hyp@getnb@token\bgroup
       \expandafter\Etoc@getnb@nohyp@nonbr
    \else
       \expandafter\Etoc@getnb@hyp@b
    \fi
}
\def\Etoc@getnb@hyp@b #1{%
    \in@{#1}{\numberline\chapternumberline\partnumberline\booknumberline}%
    \ifin@
       \let\Etoc@next\Etoc@getnb@hyp@nmbrd
    \else
%    \end{macrocode}
% If not numbered we can bail out to the "nohyp" branch, as
% \csa{etocthelinkedname} has already been defined with the |\hyperlink|.
%    \begin{macrocode}
       \let\Etoc@next\Etoc@getnb@nohyp@nonbr
       \in@{#1}{\nonumberline}%
       \ifin@
%    \end{macrocode}
% In case of presence of KOMA \csa{nonumberline} we need to expand it
% once, and then execute the numbered branch which will redefine
% \csa{etocthename} as well.  But in case it is empty we will have to
% correct \csa{etocthename}, just to be perfect.
%    \begin{macrocode}
           \ifx\nonumberline\empty
               \let\Etoc@next\Etoc@getnb@hyp@nonumberline
           \else
               \def\Etoc@next{\expandafter\Etoc@getnb@hyp@nmbrd}%
           \fi
       \fi
    \fi
    \Etoc@next #1%
}           
\def\Etoc@getnb@hyp@nmbrd #1#2#3\relax\relax\etoc@ {%
    \Etoc@global\Etoc@numbertrue
    \Etoc@global\def\etocthenumber {#2}%
    \Etoc@global\expandafter\def\expandafter\etocthelinkednumber
                \expandafter{\expandafter\hyperlink \Etoc@tmp{#2}}%
    \Etoc@global\def\etocthename {#3}%
    \Etoc@global\expandafter\def\expandafter\etocthelinkedname
                \expandafter{\expandafter\hyperlink \Etoc@tmp{#3}}%
}
%    \end{macrocode}
% Special KOMA branch: |#1| starts with |\nonumberline| which has here same
% meaning as |\empty|.  We need to remove it.
%    \begin{macrocode}
\def\Etoc@getnb@hyp@nonumberline #1\relax\relax\etoc@ {%
    \Etoc@global\Etoc@numberfalse
    \Etoc@global\let\etocthenumber       \@empty
    \Etoc@global\let\etocthelinkednumber \@empty
    \ifEtoc@bracedname
        \Etoc@global\expandafter\def\expandafter\etocthename
                                                \expandafter{\expandafter{#1}}%
    \else
        \Etoc@global\expandafter\def\expandafter\etocthename\expandafter{#1}%
    \fi
    \Etoc@global\expandafter\expandafter\expandafter\def
                \expandafter\expandafter\expandafter\etocthelinkedname
                \expandafter\expandafter\expandafter{%
                \expandafter\expandafter\expandafter\hyperlink
                \expandafter\Etoc@tmp\expandafter{\etocthename}}%
}
%    \end{macrocode}
% |1.08| adds the |\Etoc@global|'s.
%
% |1.08n| refactors this but it is still not extremely robust.
%
% |1.08p| completes the fix of |linktoc=page| problematic hyperref. If
% the name was found to be braced, keep the brace pair on extracted
% name. But not for extracted number... don't ask why, I did not want
% spending ages on working around hyperref's bug.
%    \begin{macrocode}
\def\Etoc@@getit{%
    \ifEtoc@bracedname
        \expandafter\expandafter\expandafter\Etoc@getit@nameisbraced
        \expandafter\@firstofone
    \else
        \expandafter\Etoc@getit
    \fi
}
\def\Etoc@getit@nameisbraced {\futurelet\Etoc@getit@token\Etoc@getit }
%    \end{macrocode}
% |1.09g| delays defining \cs{Etoc@getit} to at begin document to adapt to
% |hyperref| depending on whether the latter is at |7.00u| or earlier.
%    \begin{macrocode}
\def\Etoc@getit@nohyp #1\hspace#2#3\etoc@ {%
    \ifx\relax#2%
    \else
      \Etoc@global\def\etocthenumber       {#1}%
      \Etoc@global\def\etocthelinkednumber {#1}%
      \Etoc@global\Etoc@numbertrue
      \Etoc@getit@nohyp@getname #3\etoc@
    \fi
}
\def\Etoc@getit@nohyp@getname #1\hspace\relax\etoc@ {%
    \ifEtoc@bracedname
        \Etoc@global\def\etocthename       {{#1}}%
    \else
        \Etoc@global\def\etocthename       {#1}%
    \fi
    \Etoc@global\let\etocthelinkedname\etocthename
}
%    \end{macrocode}
% |1.07n| replaces use of |\toks@| by macro |\Etoc@tmp|. |1.08| adds
% the |\Etoc@global|'s.
%
% |1.08j| adds \csa{etocthelink} definition here which was missing. This bug
% showed in case hyperref was used with option |linktoc=page|, for |part|
% styles: the |\etocthelink| would not create a link if used therein. But the
% |linktoc=page| condition could easily however trigger the more serious
% |\ifx| bug in |\Etoc@getnb| also fixed at |1.08j|, and this would have
% overshadowed this one by a real compilation error rather than a missing link
% in the procuced PDF.
%
% |1.08n| refactors the whole thing. |1.08o| chooses better names for
% macros.
%
% For |1.08p| fix of hyperref's extra brace (see |\Etoc@@getnb|,
% |\Etoc@@getit|), this branch should not suffer the issue, hence I
% don't bother checking |\ifEtoc@bracedname| status.
%    \begin{macrocode}
\def\Etoc@getit@hyp #1#2#3#4#5#6\etoc@ {%
    \edef\Etoc@tmp {{#3}}%
    \Etoc@global\edef\etocthelink ##1{\noexpand\hyperlink \Etoc@tmp{##1}}%
    \Etoc@global\def\etocthename {#4}% temporary definition
    \Etoc@global\expandafter\def\expandafter\etocthelinkedname
                \expandafter{\expandafter\hyperlink \Etoc@tmp{#4}}%
    \Etoc@getit@hyp@a #4\hspace\relax\etoc@
}
\def\Etoc@getit@hyp@a #1\hspace#2#3\etoc@ {%
    \ifx\relax#2% not extremely safe
    \else
      \Etoc@global\Etoc@numbertrue
      \Etoc@global\def\etocthenumber {#1}%
      \Etoc@global\expandafter\def\expandafter\etocthelinkednumber
                  \expandafter{\expandafter\hyperlink \Etoc@tmp{#1}}%
      \Etoc@getit@hyp@getname #3\etoc@
    \fi
}
\def\Etoc@getit@hyp@getname #1\hspace\relax\etoc@ {%
    \Etoc@global\def\etocthename {#1}%
    \Etoc@global\expandafter\def\expandafter\etocthelinkedname
                \expandafter{\expandafter\hyperlink \Etoc@tmp{#1}}%
}%
%    \end{macrocode}
% |1.08a| of |2015/03/12| does the long-postponed thing to let |\etocname|
% etc.. be simply the robust variant of |\etocthelinkedname| etc...
%    \begin{macrocode}
\let\etocthename   \@empty
\let\etocthenumber \@empty
\let\etocthepage   \@empty
\let\etocthelinkedname   \@empty
\let\etocthelinkednumber \@empty
\let\etocthelinkedpage   \@empty
\let\etocthelink   \@firstofone % prior to 1.08j its was \let to \@empty
\DeclareRobustCommand*{\etocname}  {}
\DeclareRobustCommand*{\etocnumber}{}
\DeclareRobustCommand*{\etocpage}  {}
\DeclareRobustCommand*{\etoclink}  {\@firstofone}
\DeclareRobustCommand*{\etocifnumbered}
   {\ifEtoc@number\expandafter\@firstoftwo\else\expandafter\@secondoftwo\fi}
\expandafter\let\expandafter\etocxifnumbered\csname etocifnumbered \endcsname
%    \end{macrocode}
% |1.08| defines |\etociffirst|
%    \begin{macrocode}
\DeclareRobustCommand*{\etociffirst}
   {\ifEtoc@isfirst\expandafter\@firstoftwo\else\expandafter\@secondoftwo\fi}
\expandafter\let\expandafter\etocxiffirst\csname etociffirst \endcsname
%    \end{macrocode}
% |1.07j| modifies |\Etoc@readtoc|.
%    \begin{macrocode}
\def\Etoc@readtoc {%
  \ifeof \Etoc@tf
  \else
     \read \Etoc@tf to \Etoc@buffer
     \Etoc@toctoks=\expandafter\expandafter\expandafter
       {\expandafter\the\expandafter\Etoc@toctoks\Etoc@buffer}%
     \expandafter\Etoc@readtoc
  \fi
}
%    \end{macrocode}
% |1.07m| moves the reading of the toc file At Begin Document. Needed for
% Babel activated characters.\par^^A extra \par needed to avoid empty line...
%    \begin{macrocode}
\Etoc@toctoks {}% (superfluous, but for clarity)
\AtBeginDocument{\IfFileExists{\jobname.toc}
    {{\endlinechar=\m@ne
      \makeatletter
      \newread\Etoc@tf
      \openin\Etoc@tf\@filef@und
      \Etoc@readtoc
      \global\Etoc@toctoks=\expandafter{\the\Etoc@toctoks}%
      \closein\Etoc@tf}}
    {\typeout{No file \jobname.toc.}}}
%    \end{macrocode}
% 1.07d: parskip and |\@nobreakfalse| stuff moved to |\Etoc@tableofcontents|
%    \begin{macrocode}
\def\Etoc@openouttoc{%
  \ifEtoc@hyperref
   \ifx\hyper@last\@undefined
    \IfFileExists{\jobname .toc}
      {\Hy@WarningNoLine
         {old toc file detected, not used; run LaTeX again (cheers from etoc)}%
       \global\Etoc@toctoks={}%
      }
      {}%
   \fi
  \fi
  \if@filesw
   \newwrite \tf@toc
   \immediate \openout \tf@toc \jobname .toc\relax
  \fi
  \global\let\Etoc@openouttoc\empty
}
%    \end{macrocode}
% |1.08| has a new way to handle |\Etoc@standardtrue|.
%
% Also the expansion of |\Etoc@levelist| is moved to inside
% |\Etoc@tableofcontents| as set-up by |\etocsettocstyle|. This opens up
% the possibility for the user to open a group in the title (for example
% start a tabular) which would be closed (by the first |&|) sometime
% later. In combination with |\etocglobaldefs| it will be now much
% easier to typeset TOC as tables with \etoc!
%    \begin{macrocode}
\def\Etoc@toctoc{%
  \global\Etoc@vfalse
  \global\Etoc@ivfalse
  \global\Etoc@iiifalse
  \global\Etoc@iifalse
  \global\Etoc@ifalse
  \global\Etoc@false
  \global\Etoc@jfalse
  \global\Etoc@jjfalse
  \the\Etoc@toctoks
  \ifEtoc@notactive
  \else
   \ifEtoc@v   \Etoc@end@five\fi
   \ifEtoc@iv  \Etoc@end@four\fi
   \ifEtoc@iii \Etoc@end@three\fi
   \ifEtoc@ii  \Etoc@end@two\fi
   \ifEtoc@i   \Etoc@end@one\fi
   \ifEtoc@    \Etoc@end@zero\fi
   \ifEtoc@j   \Etoc@end@minusone\fi
   \ifEtoc@jj  \Etoc@end@minustwo\fi
  \fi
}
%    \end{macrocode}
% Slightly better coded in |1.08b|. Had some bad experiences with TeX
% conditionals back in 2011/2012 when I started LaTeX programming, and the
% code was a remnant of extra cautious attitude. Also, now
% \csa{etoc@@startlocaltoc} is expandable if it does nothing.
%
% |2015/04/16|: |1.08e| removes a \csa{ifEtoc@notactive} test as |\ifnum| can
% be positive only once anyhow; although the \csa{ifEtoc@notactive} boolean
% could be faster than an |\ifnum|, it adds to it as long as the local toc id
% is not yet found.
%
% I replace (|1.08e|) the |\Etoc@global|'s for |\Etoc@localtop| by
% |\global|'s. The |\relax| is needed because |#2| may sometimes be a count,
% sometimes tokens.
%
% Attention! |1.09| defines a public \cs{etoclocaltop} in replacement of old
% \cs{Etoc@localtop} \emph{minus one}. Memo: \cs{etoclocaltop} has only
% meaningful meaning when the local toc has its "active" flag set. Except that
% I used a "notactive" flag to torture myself, so: has the "notactive" flag
% off.
%
% Also attention |1.09| now sets the |\c@tocdepth| there in relation to
% implementation of \localtocwrdp. This is needed for line styles in
% compatibility mode as the code from standard classes checks the tocdepth
% counter.
%    \begin{macrocode}
\def\etoc@@startlocaltoc#1#2{%
    \ifEtoc@localtoc
       \ifnum #1=#2\relax
          \ifEtoc@jj  \global\let\etoclocaltop\Etoc@@minustwo@@\fi
          \ifEtoc@j   \global\let\etoclocaltop\Etoc@@minusone@@\fi
          \ifEtoc@    \global\let\etoclocaltop\Etoc@@zero@@    \fi
          \ifEtoc@i   \global\let\etoclocaltop\Etoc@@one@@     \fi
          \ifEtoc@ii  \global\let\etoclocaltop\Etoc@@two@@     \fi
          \ifEtoc@iii \global\let\etoclocaltop\Etoc@@three@@   \fi
          \ifEtoc@iv  \global\let\etoclocaltop\Etoc@@four@@    \fi
          \ifEtoc@v   \global\let\etoclocaltop\Etoc@@five@@    \fi
          \global\c@tocdepth\Etoc@localtocdepth
          \global\Etoc@notactivefalse
          \global\Etoc@vfalse
          \global\Etoc@ivfalse
          \global\Etoc@iiifalse
          \global\Etoc@iifalse
          \global\Etoc@ifalse
          \global\Etoc@false
          \global\Etoc@jfalse
          \global\Etoc@jjfalse
       \fi
    \fi
}
\let\etoc@startlocaltoc\@gobble
%    \end{macrocode}
% |2015/03/16|: |1.08e| tests if a local table of contents turns out empty.
% The \csa{Etoc@localtop} there does not have the same meaning as when set-up
% by the regular \csa{etoc@@startlocaltoc}. It is off by 1 (in general). THIS
% IS OBSOLETE since |1.09|: a \cs{etoclocaltop} is used with same meaning in
% all code branches.
%
% After some hesitation I opted for making and obeying the test always (*) for
% local tables of contents, and do it also for global tables of contents but
% for the latter the user must issue \csa{etocnotocifnotoc} for the emptiness
% test to be obeyed. The emptiness tests are to be trusted only when the
% compilations have stabilized.
%
% (*) finally the user must issue \csa{etocchecksemptiness} once.
%
% |\Etoc@tocid| is the number of the toc (possibly gotten via a |\ref|
% following a \csa{tableofcontents}), or it is |\z@| if the emptiness test is
% from a global toc. Until the compilations stabilize, some local TOCs can get
% printed at wrong locations naturally and emptiness tests can not be trusted
% either. Releases earlier than |1.08e| authorized
% \csa{tableofcontents}|\ref{foo}| with |foo| the label of a \emph{global}
% toc. But as it was impossible (without much complications) to discriminate,
% until auxiliary files have stabilized, between a |\ref| to a local toc whose
% id is not yet in the |.toc| file and a |\ref| to a global toc whose id will
% in the end definitely not be in the |.toc| file, I decided that this silly
% possibility should not be supported anymore. This allowed to remove a few
% tokens from \csa{Etoc@tableofcontents} as well. And it also allowed
% improvements to \csa{Etoc@localtableofcontents}.
%
% Note: (|1.08i 2016/09/29|) the code has to handle both local and total toc.
% Hence the flag |\ifEtoc@notactive| has to be set prior to it. For a global
% toc, the |\Etoc@tocid| was set to |\z@|, and the |\ifnum| in
% |\etoc@startlocaltoc| did always fail, but I now prefer to simply nullify
% the |\etoc@startlocaltoc|. As its default fallback is |\@gobble| I simply
% test here for the |localtoc| flag. The |\Etoc@tocid| will be undefined for a
% global toc but it is not tested anymore.
%
% Note: the mechanism for recognizing the level when a local toc is
% encountered is different from the one in |\etoc@@startlocaltoc| which uses
% the level flags. Here we just record in |\Etoc@level| where we last stood.
% The initialization |\global\let\Etoc@level\Etoc@minf| is thus needed in case
% the |.toc| file contains an |\etoc@startlocaltoc| before any
% |\contentsline|.
%
% |1.08i| has two |testingcontentsline| macros, one for local, one for global.
%
% |1.09| renames the \cs{Etoc@localtop} which was used here to a public
% \cs{etoclocaltop} to make it usable in \cs{etocsettocstyle}.
%    \begin{macrocode}
\def\Etoc@setemptytocbool {%
    \global\Etoc@emptytoctrue
    \global\Etoc@stoptocfalse
    \global\let\Etoc@level\Etoc@minf
    \begingroup
      \ifEtoc@localtoc
        \def\etoc@startlocaltoc##1{%
          \ifnum##1=\Etoc@tocid\relax
              \global\let\etoclocaltop\Etoc@level
              \global\Etoc@notactivefalse
          \fi }%
        \let\contentsline\Etoc@testingcontentslinelocal
      \else
        \let\contentsline\Etoc@testingcontentsline
      \fi
      \Etoc@storetocdepth
        \the\Etoc@toctoks
      \Etoc@restoretocdepth
    \endgroup
}
\DeclareRobustCommand*\etocifwasempty
  {\ifEtoc@emptytoc\expandafter\@firstoftwo\else\expandafter\@secondoftwo\fi }
\expandafter
\let\expandafter\etocxifwasempty\csname etocifwasempty \endcsname
\def\Etoc@testingcontentslinelocal #1{%
  \ifEtoc@stoptoc
  \else
   \ifnum\csname Etoc@#1@@\endcsname=\Etoc@@six@@
   \else
    \global\expandafter\let\expandafter\Etoc@level\csname Etoc@#1@@\endcsname
%    \end{macrocode}
% |\ifEtoc@notactive| set to False by |\etoc@startlocaltoc| with right id. It
% that happened, check level of hit against unit. Will decide if empty or not.
% Set |stoptoc| flag afterwards in all cases. |\Etoc@localtop| will have been
% initialized by |\etoc@@startlocaltoc| as |\ifEtoc@notactive| flag can be
% false only then.
%
% |1.09| renamed the \cs{Etoc@localtop} as formerly here to \cs{etoclocaltop}
% and adds support for \localtocwrdp.
%    \begin{macrocode}
    \ifEtoc@notactive
    \else
     \ifnum\Etoc@level>\etoclocaltop
      \unless\ifnum\Etoc@level>\Etoc@localtocdepth
       \global\Etoc@emptytocfalse
       \global\Etoc@stoptoctrue
      \fi
     \else
      \global\Etoc@stoptoctrue
     \fi
    \fi
   \fi
  \fi
  \Etoc@gobblefourorthree\relax
}
\def\Etoc@testingcontentsline #1{%
  \ifEtoc@stoptoc
  \else
   \ifnum\csname Etoc@#1@@\endcsname=\Etoc@@six@@
   \else
    \unless\ifnum\csname Etoc@#1@@\endcsname>\c@tocdepth
     \global\Etoc@emptytocfalse
     \global\Etoc@stoptoctrue
    \fi
   \fi
  \fi
  \Etoc@gobblefourorthree\relax
}
%    \end{macrocode}
% |1.07g| suppresses the printing of |--unknown etoc ref: run latex again--| as
% sometimes one uses \csa{localtableofcontents} to prepare something else, and one
% does not want any text output even in intermediate runs.
%
% Also |1.07g| adds \csa{etocaftertochook} to help with
% \csa{invisiblelocaltableofcontents} (and then I did \csa{etocsetnexttocdepth}).
% |1.07h| makes the hook used by \csa{etocsetnexttocdepth} private.
%
% |2015/03/14|: |1.08b| suppresses a space token from an unprotected end of
% line at the end after the replacement text of \csa{etoc@startlocaltoc} (bug
% dating back to |1.03 2012/11/23|). I didn't see it due to the originally
% badly formatted source of |\Etoc@next|.
%
% |2015/03/16|: |1.08e| lets \csa{localtableofcontents} do a first scan of the
% |.toc| file (as stored in |\Etoc@toctoks|) to determine if the table of
% contents will in fact end up empty. In that case, nothing is typeset. The
% command \csa{etocaftertochook} is still executed though. Other ways were
% envisioned (like delimited macros) to determine this potential emptiness, but
% in the end I opted for execution of the |.toc| file with suitable definitions
% for \csa{contentsline} and \csa{etoc@startlocaltoc}. Notice though that if
% emptiness would result from empty line styles, this can not be detected.
% Emptiness means ``no executed \csa{contentsline}''.
%
% For this detection of emptiness, assignments (here and in
% \csa{Etoc@testingcontentsline}) are made globally, I think this is the best
% (just in case some portions of the |.toc| file turn out to be inside some
% groups --- perhaps for some silly color assignments, etc... --- whose
% boundaries do not necessarily respect unit levels).
%
% The flag |\Etoc@tocwithid| discriminates between a \localtoc and a
% \toc|\ref{foo}|; the latter could so far possibly refer to a local or also to
% a global table of contents but release |1.08e| has deprecated the latter use
% as it complicated the code, for something truly silly. Thus |\ref{foo}| must
% now be with |foo| a label of a local TOC. As a result |\Etoc@tocwithid| is
% less used now.
%
% In the case of a |\ref|ed-to toc whose label was just added hence is not yet
% in the |.aux| file, |\Etoc@tocid| is |0|. \etoc used to issue a warning to
% run latex again and did no printing at all. Release |1.08e| in such cases
% prints the heading (this may gain one compilation step). Emptiness test is
% not executed as it would necessarily turn out positive and can not be
% trusted anyhow. The TOC is declared non empty, which it probably is...
%
% Emptiness detection for local tables of contents (either from a
% \csa{localtableofcontents} or from a \csa{tableofcontents}|\ref{localtoc}|)
% can be trusted only when the |.toc| file has stabilized.The emptiness status
% of a local TOC whose Id is not yet in the |.toc| is by necessity undecided
% yet (and not to be trusted really as the numbering may have changed; only
% when compilation runs settle is the emptiness status to be trusted). The
% code declares the TOC non empty, as it will be in 95\% of use cases.
%
% Dropping support for \toc|\ref{globaltoc}| means here that when a TOC id is
% not found in the |.toc| file we can assume it definitely has to be a local
% TOC needing more compilations. The emptiness status is undecided, the code
% declares the TOC non empty.
%
% |1.08i-2016/09/29| now does |\Etoc@localtoctrue| right at the start (the
% earlier code could have to handle table of contents which were actually
% global, via the |\label/\ref| mechanism.) It does not rely on the |\ifnum|
% automatically false in |\etoc@@startlocaltoc| due to the special values |0|
% or |\z@| for |\Etoc@tocid|, but simply leaves |\etoc@startlocaltoc| to its
% default |\@gobble|. The |\Etoc@emptytocfalse| flag is upfront in case some
% code using |\etocifwasempty| is in user hooks. The default is to assume the
% TOC non-empty as its contents are actually still unknown. Under the
% |stoptoc| flag, the |\Etoc@etoccontentsline| is more efficient now.
%
% The |\Etoc@notactive| flag needs to be set before calling
% |\Etoc@setemptytocbool|.
%
% I hesitated with |1.08i| to write something to aux file in order to let
% \LaTeX\ prompt the user for extra pass, after insertion of some new
% |\localtableofcontents|, but finally I prefer to only trick \LaTeX\ into
% telling about undefined references.
%
% The \cs{PackageWarning} approach has the advantage
% that at least in Emacs/AUCTeX the |C-cC-c| will propose |LaTeX|, not |View|.
% But perhaps some automated scripts checking |aux| file will not like the
% extra line which is then removed in next pass, and could possibly do one
% extra unneeded compilation to check |aux| file remains identical. Hence the
% second approach. (edit |2017/10/23|: good thing I documented that! I had
% completely forgotten that rationale, but I wonder if it is correct.)
%
% Also the |\PackageWarning| does not trigger a visible message
% near the end of the log file or console output, contrarily to a
% \centeredline{|LaTeX Warning: There were undefined references.|}
% followed by a 
% \centeredline{|LaTeX Warning: Label(s) may have changed. Rerun to get cross-references right.|}
%
% Method used here seems to work fine also with |latexmk|: it does not seem to
% induce it into making too many runs.
%    \begin{macrocode}
\def\Etoc@localtableofcontents#1{%
    \gdef\etoclocaltop{-\@m}%
    \Etoc@localtoctrue
    \global\Etoc@emptytocfalse
    \edef\Etoc@tocid{#1}%
    \ifnum\Etoc@tocid<\@ne
      %\PackageWarning{etoc}{Unknown toc reference \@secondoftwo#1. Run LaTeX again}%
      \setbox0\hbox{\ref{Unknown toc ref \@secondoftwo#1. Rerun LaTeX}}%
      %\if@filesw\immediate\write\@mainaux{\noexpand\@tempswatrue}\fi
      \global\Etoc@stoptoctrue % do only heading
      \gdef\etoclocaltop{-\thr@@}%
      \Etoc@tableofcontents
      \expandafter\Etoc@gobbletoetoc@ % skip all the rest
    \fi
    \global\Etoc@notactivetrue
%    \end{macrocode}
% |1.08i|'s |\Etoc@setemptytocbool| now checks |localtoc| flag.
%    \begin{macrocode}
    \ifEtoc@checksemptiness
       \Etoc@setemptytocbool
    \fi
    \ifEtoc@emptytoc
       \ifEtoc@notactive
         %\PackageWarning{etoc}{Unknown toc ID \number\Etoc@tocid. Run LaTeX again}%
         \setbox0\hbox{\ref{Unknown toc ID \number\Etoc@tocid. Rerun LaTeX}}%
         %\if@filesw\immediate\write\@mainaux{\noexpand\@tempswatrue}\fi
         \global\Etoc@emptytocfalse % assume real one will be non-empty
         \global\Etoc@stoptoctrue   % and print only heading for this pass
         \gdef\etoclocaltop{-\thr@@}%
         \Etoc@tableofcontents
         \expandafter\expandafter\expandafter\Etoc@gobbletoetoc@
       \else
       %%  \PackageWarning{etoc}{This toc is apparently empty}%
       \fi
    \else
       \global\Etoc@stoptocfalse
       \global\Etoc@notactivetrue
%    \end{macrocode}
% Prior to |1.09| a \cs{Etoc@localtop} was reset here. This has now been
% moved to \cs{Etoc@tableofcontents} and \cs{Etoc@localtop} replaced by a
% public \cs{etoclocaltop} usable in line styles, and in \cs{etocsettocstyle}
% (under checksemptinesstrue regime).
%
% We can end up here either if the emptiness check was done and turned
% negative (then \cs{etoclocaltop} has the correct level for usage in first
% argument of \cs{etocsettocstyle}), or if the emptiness check was not done.
% For the latter case \cs{etoclocaltop} has setting |-\@m|.
%    \begin{macrocode}
       \edef\etoc@startlocaltoc##1%
           {\noexpand\etoc@@startlocaltoc{##1}{\Etoc@tocid}}%
       \Etoc@tableofcontents
    \fi
    \@gobble\etoc@
    \endgroup\ifEtoc@mustclosegroup\endgroup\fi
    \Etoc@tocdepthreset % 1.07h, renamed 1.08h
    \etocaftertochook   % 1.07g
%    \end{macrocode}
% |1.09| hesitates about putting this before of after the
% \cs{etocaftertochook}. The information of the used tocdepth is lost if
% puuting it first. The usage of \cs{etocaftertochook} may be broken if
% unexpected tokens follows.
%    \begin{macrocode}
    \let\Etoc@localtocdepth\c@tocdepth % 1.09
}% \Etoc@localtableofcontents
%    \end{macrocode}
% |2013/03/07|: I discover a \csa{@namedef} trick to construct the
% \csa{Etoc@again} space delimited macro:\\
% |    \@namedef {Etoc@again} {...stuff...}|\\
%  Original version was (copied from analogous stuff in |source2e|):\\
% |    {\def\1{\Etoc@again}\expandafter\gdef\1 {...stuff...}}|\\
% and in the end (now that I think about it) I simply use |\@firstofone|.\par
%    \begin{macrocode}
\def\Etoc@getrefno #1#2\etoc@ {#1}
\def\Etoc@getref #1{\@ifundefined{r@#1}{0}{\expandafter\expandafter\expandafter
          \Etoc@getrefno\csname r@#1\endcsname\relax\etoc@}}
\def\Etoc@ref#1{\Etoc@localtableofcontents{\Etoc@getref{#1}}}
\def\Etoc@label#1{\label{#1}\futurelet\Etoc@nexttoken\Etoc@t@bleofcontents}
\@firstofone{\def\Etoc@again} {\futurelet\Etoc@nexttoken\Etoc@t@bleofcontents}
%    \end{macrocode}
% |1.08e| adds test for emptiness. And uses another coding style for
% conditional branching. Easier to read. Not tested for efficiency.
%
% Also, |\ref{foo}| expects |foo| to be a label to a \emph{local} TOC. Earlier
% versions accepted a reference to a global TOC, I have removed the support
% from \csa{Etoc@tableofcontents}.
%
% The syntax \csa{localtableofcontents}|\ref{foo}| is now accepted.
%    \begin{macrocode}
\def\Etoc@dothis #1#2\etoc@ {\fi #1}
\def\Etoc@t@bleofcontents{%
    \gdef\etoclocaltop{-\@M}%
    \ifx\Etoc@nexttoken\label\Etoc@dothis{\expandafter\Etoc@label\@gobble}\fi
    \ifx\Etoc@nexttoken\@sptoken\Etoc@dothis{\Etoc@again}\fi
%    \end{macrocode}
% |\Etoc@ref| will hand over directly to |\Etoc@localtableofcontents|.
% Argument will be (or rather expand to) zero if the reference is non-existent
% yet. There was an |\Etoc@tocwithidfalse| flag which |1.08i| suppresses as it
% is not used afterwards (since |1.08e| I think.)
%    \begin{macrocode}
    \ifx\Etoc@nexttoken\ref\Etoc@dothis{\expandafter\Etoc@ref\@gobble}\fi
%    \end{macrocode}
% Flag to check if we were called from a |\localtableofcontents|.
%    \begin{macrocode}
    \ifEtoc@tocwithid\Etoc@dothis{\Etoc@localtableofcontents{\c@etoc@tocid}}\fi
%    \end{macrocode}
% From now on we are handling a global TOC. Earlier, I used the trick of
% setting |\Etoc@tocid| to |\z@| for compatibility with expansion of
% |\etoc@startlocaltoc|. But since |1.08i| |\etoc@startlocaltoc| is left to be
% |\@gobble|, and |\Etoc@tocid| is never tested. We don't need to set the
% |notactive| flag as now |\Etoc@testingcontentsline| tests first the
% |localtoc| flag (was already the case of |\Etoc@etoccontentsline|). I change
% a bit the style of conditionals here for clarity of code.
%    \begin{macrocode}
    \global\Etoc@emptytocfalse\ifEtoc@checksemptiness\Etoc@setemptytocbool\fi
    \ifEtoc@emptytoc
     \ifEtoc@notocifnotoc
      \expandafter\expandafter\expandafter\@gobble
     \fi
    \fi
    \Etoc@tableofcontents
    \endgroup\ifEtoc@mustclosegroup\endgroup\fi
    \Etoc@tocdepthreset % 1.07h, renamed 1.08h
    \etocaftertochook   % 1.07g
    \@gobble\etoc@
    }% \Etoc@t@bleofcontents
%    \end{macrocode}
% |1.07g| for consistency Etoc@ prefix added.
%
% |1.08c| does not use |\arabic| in the |\addtocontents| since I have seen
% that in some circumstances (for some right to left languages with
% polyglossia or babel), one can not rely on |\arabic| having its default
% definition. As the number written here will be used later in an \csa{ifnum}, I
% should not have used it in the first place (done |2015/03/30|).
%
% |1.08i| moves elsewhere definition of |\etoc@startlocaltoc|. In
% |\Etoc@table@fcontents| case it remains to be seen if a |\ref| follows which
% could turn the TOC into a local one. Handled by |\Etoc@t@bleofcontents|.
%    \begin{macrocode}
\def\Etoc@table@fcontents{%
    \refstepcounter{etoc@tocid}%
    \Etoc@tocwithidfalse
    \futurelet\Etoc@nexttoken\Etoc@t@bleofcontents}
\def\Etoc@localtable@fcontents{%
    \refstepcounter{etoc@tocid}%
    \addtocontents{toc}{\string\etoc@startlocaltoc{\the\c@etoc@tocid}}%
    \Etoc@tocwithidtrue
    \futurelet\Etoc@nexttoken\Etoc@t@bleofcontents}
%    \end{macrocode}
% |1.07g| defines |\etoctableofcontents| to be able to undo the evil and
% brutal doings of some packages with |\tableofcontents|.
%
% |1.08| patches |tableof|'s influence. Version |1.4a| or later of |tableof|
% is needed.
%    \begin{macrocode}
\let\etocaftertitlehook    \@empty
\let\etocaftercontentshook \@empty
%    \end{macrocode}
% Attention that there could be a |\ref| following, thus we don't yet know
% whether this is a local or global table of contents.
%
% The \cs{Etoc@tocdepthset} is for \cs{etocsetnexttocdepth} mechanism.
%    \begin{macrocode}
\def\etoctableofcontents{%
   \Etoc@openouttoc
   \Etoc@tocdepthset % new with 1.08h (\etocsetnexttocdepth)
   \begingroup % closed in \Etoc@t@bleofcontents or \Etoc@localtableofcontents
%    \end{macrocode}
% Prior to its release |1.4c|, |tableof| added a group pair via |\tof@begin|
% and |\tof@finish|. This was removed at |1.4c|. So no need to do anything now
% here about silencing |\tof@begingroup| and |\tof@endgroup|: they are
% inserted only in the |tableof| private copy of the |.toc| file which is
% used by its own table of contents typesetting command.
%
% |1.08i| removes definition of |\etoc@startlocaltoc| from here. It is done
% in |\Etoc@localtableofcontents| or uses its default of |\@gobble|.
%
% |1.09b| uses a |\def| in non-starred variant for allowing tricks to
% recognize later on if we are in a starred or non-starred case, whatever the
% user definition of \cs{etocaftertitlehook} may be.
%    \begin{macrocode}
      \@ifstar
      {\let\Etoc@aftertitlehook\@empty\Etoc@table@fcontents}
      {\def\Etoc@aftertitlehook{\etocaftertitlehook}\Etoc@table@fcontents}%
}% \etoctableofcontents
%    \end{macrocode}
% See at end of this file for the explanation of this |1.09d| added saving
% of original meaning at package loading time.
%    \begin{macrocode}
\let\etocoriginaltableofcontents\tableofcontents
\let\tableofcontents\etoctableofcontents
\newcommand*\localtableofcontents{%
   \Etoc@openouttoc
   \Etoc@tocdepthset % new with 1.08h (\etocsetnexttocdepth)
   \begingroup % closed in \Etoc@t@bleofcontents or \Etoc@localtableofcontents
%    \end{macrocode}
% Same comment relative to |tableof|. No need to do anything here.
%    \begin{macrocode}
      \@ifstar
      {\let\Etoc@aftertitlehook\@empty\Etoc@localtable@fcontents}
      {\def\Etoc@aftertitlehook{\etocaftertitlehook}\Etoc@localtable@fcontents}%
}% \localtableofcontents
%    \end{macrocode}
% |1.09| adds \localtocwrdp. The motivation is that it is impossible to set
% in a completely satisfactory way the tocdepth from the first argument of
% \cs{etocsettocstyle} because the emptiness check does not execute that
% argument. If one does not care about emptiness check, one can of course set
% the tocdepth from the first argument of \cs{etocsettocstyle}. One can even
% use \cs{etocsetnexttocdepth} for that since |1.09| but anyway direct usage
% of \cs{etocsettocdepth} (or |\setcounter{tocdepth}{...}| is easier as its
% effet when executed there is automatically limited to duration of the TOC.
%    \begin{macrocode}
\newcommand*\localtableofcontentswithrelativedepth[1]{%
   \edef\Etoc@localtocdepth
       {\numexpr\noexpand\etoclocaltop+\the\numexpr#1\relax\relax}%
   \localtableofcontents
}% \localtableofcontentswithrelativedepth
\let\Etoc@localtocdepth\c@tocdepth
%    \end{macrocode}
% |1.08| moves earlier the definitions of |\Etoc@savedcontentsline| as
% well as |\Etoc@levellist|. It will thus not be operative to do
% |\etocsetlevel| from inside the title now. But perhaps it will be
% easier to deal with tables.
%
% Also I remove a big |\@firstofone|, and use rather
% |\Etoc@gobbletoetoc@| for the gobbling case.
%
% Also, |1.08| modifies the code to do only expandable things after
% |\Etoc@toctoc|, in order to allow opening of an alignment in the first
% argument and closing in the second. Earlier versions had an
% |\Etoc@@next| initially set to relax after the first |\Etoc@toctoc|. I
% was in 2012/2013 quite uneasy with the TeX conditionals hence wanted
% for safety to move the things for the second invocation of
% |\Etoc@toctoc| after the |\fi\fi\fi|. I could define an |\afterfififi|
% macro, but it should be ok as it is done here.
%
% |1.08e| moved the |\Etoc@par| to \csa{Etoc@tableofcontents}. This was needed
% for the implementation of the emptiness test. It might have some impact in
% fringe cases as the \csa{refstepcounter} is now done before the |\par| is
% issued.
%
% |1.08e| suppresses the possibility to do a \csa{tableofcontents}|\ref{foo}|
% with |foo| the label of a global TOC: issueing \csa{tableofcontents} alone
% suffices. Allowed to simplify some code.
%
% |1.08g| moves |\Etoc@par| to before |\etocbeforetitlehook|, not after.
%    \begin{macrocode}
\long\def\Etoc@gobbletoetoc@ #1\etoc@ {}
\newcommand\etocsettocstyle[2]{%
\def\Etoc@tableofcontents
{%
    \ifnum\c@tocdepth>\Etoc@minf
    \else
     \expandafter\Etoc@gobbletoetoc@
    \fi
    \Etoc@par
    \etocbeforetitlehook % 1.07m
    \Etoc@storetocdepth % 1.07g
    \let\Etoc@savedcontentsline\contentsline % moved up here 1.08
    \let\contentsline\Etoc@etoccontentsline
    \ifEtoc@standard
    \else % moved here from \Etoc@toctoc (1.08)
%    \end{macrocode}
% Prior to |1.08|, this was done in |\Etoc@toctoc|
%
% |1.08k| defines here |\etocsavedchaptertocline|, |\etocsavedsectiontocline|,
% and so on for all declared level names, again at each TOC and for the
% duration of it.
%    \begin{macrocode}
        \def\Etoc@levellist@elt####1{%
            \expandafter\let\csname etocsaved####1tocline\expandafter\endcsname
                            \csname l@####1\endcsname
            \expandafter\let\csname l@####1\endcsname\Etoc@lxyz}%
        \Etoc@levellist
%    \end{macrocode}
% |1.08k| removes |\let\chapternumberline\numberline| etc... done formerly here
%    \begin{macrocode}
    \fi
%    \end{macrocode}
% |1.09| makes \cs{etocsetnexttocdepth} usable in |#1| (but this is not 100\%
% compatible with the emptiness check).
%
% |1.09| makes an \cs{etoclocaltop} usable in |#1| if under checksemptiness
% regime.
%    \begin{macrocode}
    #1%
    \Etoc@tocdepthset
    \ifEtoc@parskip\parskip\z@skip\fi %1.07d
    \Etoc@aftertitlehook
%    \end{macrocode}
% |1.09| has replaced former \cs{Etoc@localtop} (\emph{minus one}) by
% \cs{etoclocaltop}. Under checksemptinesstrue regime its value is already
% known, but it will be obtained again from the toc file execution. As it is
% used only if TOC is active, resetting it here this way is decorative and
% could be removed.
%    \begin{macrocode}
    \gdef\etoclocaltop{-\thr@@}%
    \Etoc@toctoc
    \etocaftercontentshook
    #2\@nobreakfalse % 1.07d: \@nobreakfalse moved here
    \Etoc@restoretocdepth  % 1.07g. moved here from before #2 by 1.08
%    \end{macrocode}
% |\contentsline| was set to |\Etoc@etoccontentsline| by a non-global |\let|,
% and it will recover its normal value from exiting a scope limiting group.
% But |tableof| (since |1.4a|) under |\etocglobaldefstrue| does a global
% redefinition of |\contentsline|.  Its |\tof@finish| then does a global
% restore of |\contentsline|, but it will be to the \etoc set
% value. |\tof@finish| is active only if either the table of contents was
% typeset using |\tableof|, |\tablenotof|, |\tableoftaggedcontents|, or
% |\nextocwithtags| was used.  If not active it is either undefined (no
% package |tableof|) or |\@empty|. Prior to |tableof| |1.4c|, the
% |\tof@finish| closed a group and could be undefined as well, but not if
% |\etocglobaldefstrue|.
%
% \etoc |1.09c| tested here only equality to |\@empty| to decide if it is
% needed to globally restore |\contentsline| but this meant the global restore
% was done systematically in case of absence of package |tableof|.
%
% If rather than |\@empty| the |\tof@finish| fall-back was |\relax| we could
% use here |\@ifundefined| to check in one go (matters of speaking because
% expansion of |\@ifundefined| is not in "one-go"). Maybe I should update
% |tableof|, but for time being I will simply add an extra test. All this is
% probably lots of time on irrelevant issue.
%    \begin{macrocode}
    \ifx\Etoc@global\global
     \@ifundefined{tof@finish}
     {}
     {\ifx\tof@finish\@empty
      \else
       \global\let\contentsline\Etoc@savedcontentsline
      \fi
     }%
    \fi
    \@gobble\etoc@
}% end of \Etoc@tableofcontents definition by \etocsettocstyle
}
%    \end{macrocode}
% |1.08| hacks the begin parts to update therein the |\ifEtoc@isfirst| flag
% (|2015/03/09|).
%
% |1.08c| removes unneeded |\long| from the |\def|'s inside |\etoc@setstyle|
% (|2015/03/29|).
%    \begin{macrocode}
\def\etocsetstyle{\Etoc@standardfalse\etoc@setstyle}
\long\def\etoc@setstyle#1#2#3#4#5{%
     \expandafter\def
     \csname Etoc@begin@\csname Etoc@#1@\endcsname\endcsname
                     {#2\Etoc@global\Etoc@isfirsttrue}%
     \expandafter\def
     \csname Etoc@prefix@\csname Etoc@#1@\endcsname\endcsname   {#3}%
     \expandafter\def
     \csname Etoc@contents@\csname Etoc@#1@\endcsname\endcsname {#4}%
     \expandafter\def
     \csname Etoc@end@\csname Etoc@#1@\endcsname\endcsname      {#5}%
}
%    \end{macrocode}
% Since the |1.09f 2022/08/30| release, some syntax highlighting is
% done ; but for some reason the \cs{etocfontone} below is colorized
% not like others.  For |1.09g 2022/11/17| hotfix release due to
% breaking change in |hyperref 7.00u 2022-11-13| I simply do not have time to
% investigate the matter... will be for next time.  If there is one!
%    \begin{macrocode}
\def\etocfontminustwo {\normalfont \LARGE \bfseries}
\def\etocfontminusone {\normalfont \large \bfseries}
\def\etocfontzero     {\normalfont \large \bfseries}
\def\etocfontone      {\normalfont \normalsize \bfseries}
\def\etocfonttwo      {\normalfont \normalsize}
\def\etocfontthree    {\normalfont \footnotesize}
%    \end{macrocode}
% placeholder for comments
%    \begin{macrocode}
\def\etocsepminustwo  {4ex \@plus .5ex \@minus .5ex}
\def\etocsepminusone  {4ex \@plus .5ex \@minus .5ex}
\def\etocsepzero      {2.5ex \@plus .4ex \@minus .4ex}
\def\etocsepone       {1.5ex \@plus .3ex \@minus .3ex}
\def\etocseptwo       {.5ex \@plus .1ex \@minus .1ex}
\def\etocsepthree     {.25ex \@plus .05ex \@minus .05ex}
%    \end{macrocode}
% placeholder for comments
%    \begin{macrocode}
\def\etocbaselinespreadminustwo {1}
\def\etocbaselinespreadminusone {1}
\def\etocbaselinespreadzero     {1}
\def\etocbaselinespreadone      {1}
\def\etocbaselinespreadtwo      {1}
\def\etocbaselinespreadthree    {.9}
%    \end{macrocode}
% placeholder for comments
%    \begin{macrocode}
\def\etocminustwoleftmargin  {1.5em plus 0.5fil}
\def\etocminustworightmargin {1.5em plus -0.5fil}
\def\etocminusoneleftmargin  {1em}
\def\etocminusonerightmargin {1em}
\def\etoctoclineleaders
        {\hbox{\normalfont\normalsize\hb@xt@2ex {\hss.\hss}}}
\def\etocabbrevpagename {p.~}
%    \end{macrocode}
% Versions earlier than |1.08b| (and since |1.05 2012/12/01|) defined
% \csa{etocpartname} (for use by \etoc's own line styles) to expand to
% \csa{partname}. But this didn't make sense in the context for example of
% |babel| and |frenchb|, because \csa{frenchpartname} does things depending on
% the current value of the counter |part|. The code in recent |frenchb| (but
% not yet |v2.5a| when |\etocpartname| was introduced) constructs control
% sequences |\ordinali|, etc... If the part counter is zero, this gives
% |\ordinal|. Usually this is not defined, hence no error happens (as it is
% constructed via |\csname|), but under class |memoir| the bug showed up. All
% this to explain that I found out about this long lasting problem only on
% |2015/03/14|. Probably a sign that \etoc's own line styles are rarely
% used...
%    \begin{macrocode}
\def\etocpartname       {Part}% modified 1.08b
\def\etocbookname       {Book}
%    \end{macrocode}
% placeholder for comments
% The macro \csa{etocdefaultlines} was initially called \csa{etoctoclines}. Now
% \csa{etoctoclines} just does \csa{Etoc@standardfalse}.
% Version |1.07e| has rewritten entirely the stuff related to penalties and
% \csa{addvspace}, as this was not satisfactory in the earlier versions, which
% were written at a early stage in the development of the
% package. Actually I am not fully satisfied with these line styles.
%
% Version |1.09f| wraps \csa{etocbookname}, respectively
% \csa{etocpartname}, in the book, resp. part, line styles inside a
% (potential) hyperlink together with the number.
%    \begin{macrocode}
\def\etocdefaultlines{\Etoc@standardfalse %
%% `book':
\etoc@setstyle{@minustwo}
  {\addpenalty\@M\etocskipfirstprefix}
  {\addpenalty\@secpenalty}
  {\begingroup
   \etocfontminustwo
   \addvspace{\etocsepminustwo}%
   \parindent \z@
   \leftskip  \etocminustwoleftmargin
   \rightskip \etocminustworightmargin
   \parfillskip \@flushglue
   \vbox{\etocifnumbered{\etoclink{\etocbookname\enspace\etocthenumber:\quad}}{}%
         \etocname
         \baselineskip\etocbaselinespreadminustwo\baselineskip
         \par}%
   \addpenalty\@M\addvspace{\etocsepminusone}%
   \endgroup}
  {}%
%% `part':
\etoc@setstyle{@minusone}
  {\addpenalty\@M\etocskipfirstprefix}
  {\addpenalty\@secpenalty}
  {\begingroup
   \etocfontminusone
   \addvspace{\etocsepminusone}%
   \parindent \z@
   \leftskip  \etocminusoneleftmargin
   \rightskip \etocminusonerightmargin
   \parfillskip \@flushglue
   \vbox{\etocifnumbered{\etoclink{\etocpartname\enspace\etocthenumber.\quad}}{}%
         \etocname
         \baselineskip\etocbaselinespreadminusone\baselineskip
         \par}%
   \addpenalty\@M\addvspace{\etocsepzero}%
   \endgroup}
  {}%
%% `chapter':
\etoc@setstyle{@zero}
  {\addpenalty\@M\etocskipfirstprefix}
  {\addpenalty\@itempenalty}
  {\begingroup
   \etocfontzero
   \addvspace{\etocsepzero}%
   \parindent \z@ \parfillskip \@flushglue
   \vbox{\etocifnumbered{\etocnumber.\enspace}{}\etocname
         \baselineskip\etocbaselinespreadzero\baselineskip
         \par}%
   \endgroup}
  {\addpenalty{-\@highpenalty}\addvspace{\etocsepminusone}}%
%% `section':
\etoc@setstyle{@one}
  {\addpenalty\@M\etocskipfirstprefix}
  {\addpenalty\@itempenalty}
  {\begingroup
   \etocfontone
   \addvspace{\etocsepone}%
   \parindent \z@ \parfillskip \z@
   \setbox\z@\vbox{\parfillskip\@flushglue
                   \etocname\par
                   \setbox\tw@\lastbox
                   \global\setbox\@ne\hbox{\unhbox\tw@\ }}%
   \dimen\z@=\wd\@ne
   \setbox\z@=\etoctoclineleaders
   \advance\dimen\z@\wd\z@
   \etocifnumbered
     {\setbox\tw@\hbox{\etocnumber, \etocabbrevpagename\etocpage}}
     {\setbox\tw@\hbox{\etocabbrevpagename\etocpage}}%
   \advance\dimen\z@\wd\tw@
   \ifdim\dimen\z@ < \linewidth
       \vbox{\etocname~%
             \leaders\box\z@\hfil\box\tw@
             \baselineskip\etocbaselinespreadone\baselineskip
             \par}% 1.08b adds the % here
   \else
       \vbox{\etocname~%
             \leaders\copy\z@\hfil\break
             \hbox{}\leaders\box\z@\hfil\box\tw@
             \baselineskip\etocbaselinespreadone\baselineskip
             \par}%
   \fi
   \endgroup}
  {\addpenalty\@secpenalty\addvspace{\etocsepzero}}%
%% `subsection':
\etoc@setstyle{@two}
  {\addpenalty\@medpenalty\etocskipfirstprefix}
  {\addpenalty\@itempenalty}
  {\begingroup
   \etocfonttwo
   \addvspace{\etocseptwo}%
   \parindent \z@ \parfillskip \z@
   \setbox\z@\vbox{\parfillskip\@flushglue
                   \etocname\par\setbox\tw@\lastbox
                   \global\setbox\@ne\hbox{\unhbox\tw@}}%
   \dimen\z@=\wd\@ne
   \setbox\z@=\etoctoclineleaders
   \advance\dimen\z@\wd\z@
   \etocifnumbered
     {\setbox\tw@\hbox{\etocnumber, \etocabbrevpagename\etocpage}}
     {\setbox\tw@\hbox{\etocabbrevpagename\etocpage}}%
   \advance\dimen\z@\wd\tw@
   \ifdim\dimen\z@ < \linewidth
       \vbox{\etocname~%
             \leaders\box\z@\hfil\box\tw@
             \baselineskip\etocbaselinespreadtwo\baselineskip
             \par}%
   \else
       \vbox{\etocname~%
             \leaders\copy\z@\hfil\break
             \hbox{}\leaders\box\z@\hfil\box\tw@
             \baselineskip\etocbaselinespreadtwo\baselineskip
             \par}%
   \fi
   \endgroup}
  {\addpenalty\@secpenalty\addvspace{\etocsepone}}%
%% `subsubsection':
\etoc@setstyle{@three}
  {\addpenalty\@M
   \etocfontthree
   \vspace{\etocsepthree}%
   \noindent
   \etocskipfirstprefix}
  {\allowbreak\,--\,}
  {\etocname}
  {.\hfil
    \begingroup
     \baselineskip\etocbaselinespreadthree\baselineskip
     \par
    \endgroup
   \addpenalty{-\@highpenalty}}%
%    \end{macrocode}
% placeholder for comments
%    \begin{macrocode}
\etoc@setstyle{@four}{}{}{}{}%
\etoc@setstyle{@five}{}{}{}{}%
} % end of \etocdefaultlines!
%    \end{macrocode}
% The |\etocinnertopsep| default value is too big as well as |\etocbelowtocskip|
% and |\etocabovetocskip|, I guess, but if I am remember correctly I chose them
% to mimick the standard TOC spacings in |article| class.
%    \begin{macrocode}
\def\etocabovetocskip{3.5ex \@plus 1ex \@minus .2ex}
\def\etocbelowtocskip{3.5ex \@plus 1ex \@minus .2ex}
\def\etoccolumnsep{2em}
\def\etocmulticolsep{0ex}
\def\etocmulticolpretolerance{-1}
\def\etocmulticoltolerance{200}
\def\etocdefaultnbcol{2}
\def\etocinnertopsep{2ex}
%    \end{macrocode}
% |1.07i| adds a |\nobreak| before the |\etocinnertopsep| and a test of vertical
% mode to see if truly adding a |\par| is a reasonable idea, in the
% case of single-column mode.
%
% |1.08b| revisits this old code written perhaps at a time I didn't know about
% |\expandafter| !
%    \begin{macrocode}
\newcommand\etocmulticolstyle[2][\etocdefaultnbcol]{%
\etocsettocstyle
   {\let\etocoldpar\par
    \addvspace{\etocabovetocskip}%
    \ifnum #1>\@ne
          \expandafter\@firstoftwo
    \else \expandafter\@secondoftwo
    \fi
    {\multicolpretolerance\etocmulticolpretolerance
    \multicoltolerance\etocmulticoltolerance
    \setlength{\columnsep}{\etoccolumnsep}%
    \setlength{\multicolsep}{\etocmulticolsep}%
    \begin{multicols}{#1}[#2\etocoldpar\addvspace{\etocinnertopsep}]}
    {#2\ifvmode\else\begingroup\interlinepenalty\@M\parskip\z@skip
                    \@@par\endgroup
       \fi
       \nobreak\addvspace{\etocinnertopsep}%
       \pretolerance\etocmulticolpretolerance
       \tolerance\etocmulticoltolerance}%
   }%
   {\ifnum #1>\@ne
          \expandafter\@firstofone
    \else \expandafter\@gobble
    \fi
    {\end{multicols}}%
    \addvspace{\etocbelowtocskip}}%
}
%    \end{macrocode}
% placeholder for comments
%    \begin{macrocode}
\def\etocinnerbottomsep{3.5ex}
\def\etocinnerleftsep{2em}
\def\etocinnerrightsep{2em}
\def\etoctoprule{\hrule}
\def\etocleftrule{\vrule}
\def\etocrightrule{\vrule}
\def\etocbottomrule{\hrule}
\def\etoctoprulecolorcmd{\relax}
\def\etocbottomrulecolorcmd{\relax}
\def\etocleftrulecolorcmd{\relax}
\def\etocrightrulecolorcmd{\relax}
%    \end{macrocode}
% |1.07i| moves the |\nobreak| to before the |\vskip\etocinnertopsep|
% (especially important for the single column case).
%    \begin{macrocode}
\def\etoc@ruledheading #1{%
   \hb@xt@\linewidth{\color@begingroup
          \hss #1\hss\hskip-\linewidth
          \etoctoprulecolorcmd\leaders\etoctoprule\hss
          \phantom{#1}%
          \leaders\etoctoprule\hss\color@endgroup}%
          \nointerlineskip\nobreak\vskip\etocinnertopsep}
\newcommand*\etocruledstyle[2][\etocdefaultnbcol]{%
\etocsettocstyle
   {\addvspace{\etocabovetocskip}%
    \ifnum #1>\@ne
          \expandafter\@firstoftwo
    \else \expandafter\@secondoftwo
    \fi
       {\multicolpretolerance\etocmulticolpretolerance
        \multicoltolerance\etocmulticoltolerance
        \setlength{\columnsep}{\etoccolumnsep}%
        \setlength{\multicolsep}{\etocmulticolsep}%
        \begin{multicols}{#1}[\etoc@ruledheading{#2}]}
       {\etoc@ruledheading{#2}%
         \pretolerance\etocmulticolpretolerance
         \tolerance\etocmulticoltolerance}}
   {\ifnum #1>\@ne\expandafter\@firstofone
         \else \expandafter\@gobble
    \fi
    {\end{multicols}}%
    \addvspace{\etocbelowtocskip}}}
%    \end{macrocode}
% |1.07k| defines |\Etoc@relax| and |\etocbkgcolorcmd| as |\long|: the user
% manual says to use |\renewcommand\etocbkgcolorcmd|, and an |\ifx| test is used
% in the framed style. It was thus a bug to have non-long definitions before. Or
% I could have said in the user manual to use |\renewcommand*|, or in
% |\etocframedstyle| I should test for the two, or I should pause to try to
% remember about this code and think about it.
%    \begin{macrocode}
\def\etocframedmphook{\relax}
\long\def\etocbkgcolorcmd{\relax}
\long\def\Etoc@relax{\relax}
%    \end{macrocode}
% placeholder for comments
%    \begin{macrocode}
\newbox\etoc@framed@titlebox
\newbox\etoc@framed@contentsbox
\newcommand*\etocframedstyle[2][\etocdefaultnbcol]{%
\etocsettocstyle{%
    \addvspace{\etocabovetocskip}%
    \sbox\z@{#2}%
    \dimen\z@\dp\z@
    \ifdim\wd\z@<\linewidth \dp\z@\z@ \else \dimen\z@\z@ \fi
    \setbox\etoc@framed@titlebox=\hb@xt@\linewidth{\color@begingroup
        \hss
        \ifx\etocbkgcolorcmd\Etoc@relax
        \else
            \sbox\tw@{\color{white}%
            \vrule\@width\wd\z@\@height\ht\z@\@depth\dimen\z@}%
            \ifdim\wd\z@<\linewidth \dp\tw@\z@\fi
            \box\tw@
            \hskip-\wd\z@
        \fi
        \copy\z@
        \hss
        \hskip-\linewidth
        \etoctoprulecolorcmd\leaders\etoctoprule\hss
        \hskip\wd\z@
        \etoctoprulecolorcmd\leaders\etoctoprule\hss\color@endgroup}%
    \setbox\z@\hbox{\etocleftrule\etocrightrule}%
    \dimen\tw@\linewidth\advance\dimen\tw@-\wd\z@
        \advance\dimen\tw@-\etocinnerleftsep
        \advance\dimen\tw@-\etocinnerrightsep
    \setbox\etoc@framed@contentsbox=\vbox\bgroup
        \hsize\dimen\tw@
        \kern\dimen\z@
        \vskip\etocinnertopsep
        \hbox\bgroup
        \begin{minipage}{\hsize}%
        \etocframedmphook
    \ifnum #1>\@ne
          \expandafter\@firstoftwo
    \else \expandafter\@secondoftwo
    \fi
        {\multicolpretolerance\etocmulticolpretolerance
        \multicoltolerance\etocmulticoltolerance
        \setlength{\columnsep}{\etoccolumnsep}%
        \setlength{\multicolsep}{\etocmulticolsep}%
        \begin{multicols}{#1}}
        {\pretolerance\etocmulticolpretolerance
         \tolerance\etocmulticoltolerance}}
    {\ifnum #1>\@ne\expandafter\@firstofone
         \else \expandafter\@gobble
     \fi
      {\end{multicols}\unskip }%
    \end{minipage}%
    \egroup
    \vskip\etocinnerbottomsep
    \egroup
    \vbox{\hsize\linewidth
        \ifx\etocbkgcolorcmd\Etoc@relax
        \else
            \kern\ht\etoc@framed@titlebox
            \kern\dp\etoc@framed@titlebox
            \hb@xt@\linewidth{\color@begingroup
            \etocleftrulecolorcmd\etocleftrule
            \etocbkgcolorcmd
            \leaders\vrule
                   \@height\ht\etoc@framed@contentsbox
                   \@depth\dp\etoc@framed@contentsbox
            \hss
            \etocrightrulecolorcmd\etocrightrule
            \color@endgroup}\nointerlineskip
            \vskip-\dp\etoc@framed@contentsbox
            \vskip-\ht\etoc@framed@contentsbox
            \vskip-\dp\etoc@framed@titlebox
            \vskip-\ht\etoc@framed@titlebox
        \fi
    \box\etoc@framed@titlebox\nointerlineskip
    \hb@xt@\linewidth{\color@begingroup
    {\etocleftrulecolorcmd\etocleftrule}%
    \hss\box\etoc@framed@contentsbox\hss
    \etocrightrulecolorcmd\etocrightrule\color@endgroup}
    \nointerlineskip
    \vskip\ht\etoc@framed@contentsbox
    \vskip\dp\etoc@framed@contentsbox
    \hb@xt@\linewidth{\color@begingroup\etocbottomrulecolorcmd
          \leaders\etocbottomrule\hss\color@endgroup}}
    \addvspace{\etocbelowtocskip}}}
%    \end{macrocode}
% placeholder for comments
%    \begin{macrocode}
\newcommand\etoc@multicoltoc[2][\etocdefaultnbcol]{%
    \etocmulticolstyle[#1]{#2}%
    \tableofcontents}
\newcommand\etoc@multicoltoci[2][\etocdefaultnbcol]{%
    \etocmulticolstyle[#1]{#2}%
    \tableofcontents*}
\newcommand\etoc@local@multicoltoc[2][\etocdefaultnbcol]{%
    \etocmulticolstyle[#1]{#2}%
    \localtableofcontents}
\newcommand\etoc@local@multicoltoci[2][\etocdefaultnbcol]{%
    \etocmulticolstyle[#1]{#2}%
    \localtableofcontents*}
%    \end{macrocode}
% placeholder for comments
%    \begin{macrocode}
\newcommand*\etoc@ruledtoc[2][\etocdefaultnbcol]{%
    \etocruledstyle[#1]{#2}%
    \tableofcontents}
\newcommand*\etoc@ruledtoci[2][\etocdefaultnbcol]{%
    \etocruledstyle[#1]{#2}%
    \tableofcontents*}
\newcommand*\etoc@local@ruledtoc[2][\etocdefaultnbcol]{%
    \etocruledstyle[#1]{#2}%
    \localtableofcontents}
\newcommand*\etoc@local@ruledtoci[2][\etocdefaultnbcol]{%
    \etocruledstyle[#1]{#2}%
    \localtableofcontents*}
%    \end{macrocode}
% placeholder for comments
%    \begin{macrocode}
\newcommand*\etoc@framedtoc[2][\etocdefaultnbcol]{%
    \etocframedstyle[#1]{#2}%
    \tableofcontents}
\newcommand*\etoc@framedtoci[2][\etocdefaultnbcol]{%
    \etocframedstyle[#1]{#2}%
    \tableofcontents*}
\newcommand*\etoc@local@framedtoc[2][\etocdefaultnbcol]{%
    \etocframedstyle[#1]{#2}%
    \localtableofcontents}
\newcommand*\etoc@local@framedtoci[2][\etocdefaultnbcol]{%
    \etocframedstyle[#1]{#2}%
    \localtableofcontents*}
%    \end{macrocode}
% placeholder for comments
%    \begin{macrocode}
\def\etocmulticol{\begingroup
    \Etoc@mustclosegrouptrue
    \@ifstar
    {\etoc@multicoltoci}
    {\etoc@multicoltoc}}
\def\etocruled{\begingroup
    \Etoc@mustclosegrouptrue
    \@ifstar
    {\etoc@ruledtoci}
    {\etoc@ruledtoc}}
\def\etocframed{\begingroup
    \Etoc@mustclosegrouptrue
    \@ifstar
    {\etoc@framedtoci}
    {\etoc@framedtoc}}
\def\etoclocalmulticol{\begingroup
    \Etoc@mustclosegrouptrue
    \@ifstar
    {\etoc@local@multicoltoci}
    {\etoc@local@multicoltoc}}
\def\etoclocalruled{\begingroup
    \Etoc@mustclosegrouptrue
    \@ifstar
    {\etoc@local@ruledtoci}
    {\etoc@local@ruledtoc}}
\def\etoclocalframed{\begingroup
    \Etoc@mustclosegrouptrue
    \@ifstar
    {\etoc@local@framedtoci}
    {\etoc@local@framedtoc}}
%    \end{macrocode}
% placeholder for comments
%    \begin{macrocode}
\def\etocarticlestyle{%
    \etocsettocstyle
    {\section *{\contentsname
                \@mkboth {\MakeUppercase \contentsname}
                         {\MakeUppercase \contentsname}}}
    {}}
\def\etocarticlestylenomarks{%
    \etocsettocstyle
    {\section *{\contentsname}}
    {}}
%    \end{macrocode}
% placeholder for comments
%    \begin{macrocode}
\def\etocbookstyle{%
    \etocsettocstyle
    {\if@twocolumn \@restonecoltrue \onecolumn \else \@restonecolfalse \fi
     \chapter *{\contentsname
                \@mkboth {\MakeUppercase \contentsname}
                         {\MakeUppercase \contentsname}}}
    {\if@restonecol \twocolumn \fi}}
\def\etocbookstylenomarks{%
    \etocsettocstyle
    {\if@twocolumn \@restonecoltrue \onecolumn \else \@restonecolfalse \fi
     \chapter *{\contentsname}}
    {\if@restonecol \twocolumn \fi}}
\let\etocreportstyle\etocbookstyle
\let\etocreportstylenomarks\etocbookstylenomarks
%    \end{macrocode}
% |v3.7i| of memoir has moved the \cs{phantomsection} to a better location,
% before typesetting the title and we follow suit at |1.09a|, and less rashly
% at |1.09b|. Formerly \etoc used \cs{etocaftertitlehook} to mimick the
% memoir code but as its name indicate, it is supposedly executed after the
% title... and this also had the defect of making \cs{etocaftertitlehook} not
% anymore a user command. Thus we here use some refactoring of the
% \cs{Etoc@aftertitlehook} internal mechanism to help recognize if we are
% in the starred case or not.
%
% \cs{phantomsection} is always defined by memoir, empty if hyperref absent.
%    \begin{macrocode}
\def\etocmemoirtoctotocfmt #1#2{%
    \def\Etoc@addsuitablecontentsline{\addcontentsline {toc}{#1}{#2}}%
}
\def\etocmemoirstyle{%
    \etocsettocstyle
        {\ensureonecol \par \begingroup \phantomsection
         \ifx\Etoc@aftertitlehook\@empty
         \else
           % non-starred variant
           \ifmem@em@starred@listof
           \else
             \Etoc@addsuitablecontentsline
           \fi
         \fi
         \@nameuse {@tocmaketitle} %<< space token here from memoir code
         \ifx\Etoc@aftertitlehook\@empty
          \else
%    \end{macrocode}
% Execute etoc hook before the \cs{cfttocbeforelisthook} and keep distinction
% between starred and non-starred contexts for other hooks. Notice that the
% memoir class way of implementing \cs{tableofcontents} leaves no way for code
% executed by the TOC code to know if it is executed in starred or non-starred
% context.
%    \begin{macrocode}         
          \Etoc@aftertitlehook \let \Etoc@aftertitlehook \relax
         \fi
         \parskip \cftparskip \@nameuse {cfttocbeforelisthook}}
        {\@nameuse {cfttocafterlisthook}\endgroup\restorefromonecol}}
%    \end{macrocode}
% |1.09c| (|2020/05/15|) does an update as KOMA-script has deprecated
% |\iftocfeature|.  Thanks to Bilel Omrani for report.  I did not check
% if cloning of KOMA code required some further updates.
%
% Finally |1.09f| added some such updates.
%    \begin{macrocode}
\ifdefined\Iftocfeature
  \def\etoc@Iftocfeature{\Iftocfeature}%
\else
  \def\etoc@Iftocfeature{\iftocfeature}%
\fi
\def\etocscrartclstyle{%
    \etocsettocstyle
        {\let\if@dynlist\if@tocleft
%    \end{macrocode}
% Added at |1.07m 2015/01/23|.
%    \begin{macrocode}
         \def\@currext{toc}%
%    \end{macrocode}
% |1.09f| adds this \csa{list@fname} definition hunk although
% \csa{listoftocname} is presumably always defined.  Only to match
% closely KOMA-script code.
%    \begin{macrocode}
         \@ifundefined{listoftocname}%
            {\def\list@fname{\listofname~toc}}%
            {\expandafter\let\expandafter\list@fname\csname listoftocname\endcsname}%
         \etoc@Iftocfeature {toc}{onecolumn}
             {\etoc@Iftocfeature {toc}{leveldown}
              {}
              {\if@twocolumn \aftergroup \twocolumn \onecolumn \fi }}
             {}%
%    \end{macrocode}
% |1.07k|: next line to do as within current |scrartcl 2013/12/19 v3.12|
% KOMA-Script article class.^^A motivated \par in the env/macrocode/before hook
%    \begin{macrocode}
         \etoc@Iftocfeature {toc}{numberline}{\def \nonumberline {\numberline {}}}{}%
         \expandafter\tocbasic@listhead\expandafter {\list@fname}%
         \begingroup \expandafter \expandafter \expandafter
         \endgroup \expandafter
         \ifx
             \csname microtypesetup\endcsname \relax
         \else
             \etoc@Iftocfeature {toc}{noprotrusion}{}
                 {\microtypesetup {protrusion=false}%
                  \PackageInfo {tocbasic}%
                  {character protrusion at toc deactivated}}%
         \fi
%    \end{macrocode}
% |1.09f| adds this hunk with the noparskipfalse test to match current
% scrartcl (testing done with scrbook |2022/07/04 v3.37|).
%    \begin{macrocode}
         \etoc@Iftocfeature{toc}{noparskipfake}{}{%
               \ifvmode \@tempskipa\lastskip \vskip-\lastskip
               \addtolength{\@tempskipa}{\parskip}\vskip\@tempskipa\fi
         }%
         \setlength {\parskip }{\z@ }%
         \setlength {\parindent }{\z@ }%
         \setlength {\parfillskip }{\z@ \@plus 1fil}%
         \csname tocbasic@@before@hook\endcsname
         \csname tb@toc@before@hook\endcsname}
         {%
%    \end{macrocode}
% At |1.09f| I considered adding this \csa{BeforeClosingMainAux} hunk
% to the second argument of \csa{etocsettocstyle}-emulation of KOMA-script.
% But:
% \begin{itemize}
% \item there seems to be no interface to \csa{tocbasic@end@toc@file},
%
% \item
%   it defaults to issuing a \csa{par}, but we want etoc to still be able
%   to produce other TOCs, possibly inline, and they should not be
%   influenced by it and I don't want at this stage to add an interface
%   to enable/disable and have to document it,
%
% \item
%   the whole thing appears to me to be ill-conceived in so far as it
%   sort of implies the \csa{tableofcontents} is used only once, as each
%   instance will again add this \csa{tocbasic@end@toc@file} to end of
%   toc file, which may thus end up being executed multiple times.
% \end{itemize}
% So rather than putting the thing in the |.toc| file, we will execute
% it here.  This way it will not impact other TOCs typeset via etoc
% design facilities in the document.
%    \begin{macrocode}
%          \BeforeClosingMainAux
%          {\addtocontents
%            {toc}{\string\providecommand\string\tocbasic@end@toc@file{}%
%                  \string\tocbasic@end@toc@file}%
%          }%
         \providecommand\tocbasic@end@toc@file{}\tocbasic@end@toc@file
         \csname tb@toc@after@hook\endcsname
         \csname tocbasic@@after@hook\endcsname}}
\let\etocscrbookstyle\etocscrartclstyle
\let\etocscrreprtstyle\etocscrartclstyle
%    \end{macrocode}
% placeholder for comments
%    \begin{macrocode}
\def\etocstandarddisplaystyle{\etocarticlestyle}
\newcommand*\etocmarkboth[1]{%
    \@mkboth{\MakeUppercase{#1}}{\MakeUppercase{#1}}}
\newcommand*\etocmarkbothnouc[1]{\@mkboth{#1}{#1}}
\newcommand\etoctocstyle[3][section]{\etocmulticolstyle[#2]%
    {\csname #1\endcsname *{#3}}}
\newcommand\etoctocstylewithmarks[4][section]{\etocmulticolstyle[#2]%
    {\csname #1\endcsname *{#3\etocmarkboth{#4}}}}
\newcommand\etoctocstylewithmarksnouc[4][section]{\etocmulticolstyle[#2]%
    {\csname #1\endcsname *{#3\etocmarkbothnouc{#4}}}}
%    \end{macrocode}
% placeholder for comments
%    \begin{macrocode}
\def\Etoc@redefetocstyle#1{%
    \renewcommand\etoctocstylewithmarks[4][#1]
    {\etocmulticolstyle[##2]%
          {\csname ##1\endcsname *{##3\etocmarkboth{##4}}}}
    \renewcommand\etoctocstylewithmarksnouc[4][#1]
    {\etocmulticolstyle[##2]%
          {\csname ##1\endcsname *{##3\etocmarkbothnouc{##4}}}}
    \renewcommand\etoctocstyle[3][#1]{%
     \etocmulticolstyle[##2]{\csname ##1\endcsname *{##3}}}}
\@ifclassloaded{scrartcl}
    {\renewcommand*\etocstandarddisplaystyle{\etocscrartclstyle}}{}
\@ifclassloaded{book}
    {\renewcommand*\etocfontone{\normalfont\normalsize}
     \renewcommand*\etocstandarddisplaystyle{\etocbookstyle}
     \Etoc@redefetocstyle{chapter}}{}
\@ifclassloaded{report}
    {\renewcommand*\etocfontone{\normalfont\normalsize}
     \renewcommand*\etocstandarddisplaystyle{\etocreportstyle}
     \Etoc@redefetocstyle{chapter}}{}
\@ifclassloaded{scrbook}
    {\renewcommand*\etocfontone{\normalfont\normalsize}
     \renewcommand*\etocstandarddisplaystyle{\etocscrbookstyle}
     \Etoc@redefetocstyle{chapter}}{}
\@ifclassloaded{scrreprt}
    {\renewcommand*\etocfontone{\normalfont\normalsize}
     \renewcommand*\etocstandarddisplaystyle{\etocscrreprtstyle}
     \Etoc@redefetocstyle{chapter}}{}
%    \end{macrocode}
%|1.07k (2014/03/06)| adds the |appendix| to the list of known levels if class
%|memoir| is detected.
%    \begin{macrocode}
\@ifclassloaded{memoir}
    {\etocsetlevel{appendix}{0}%
     \renewcommand*\etocfontone{\normalfont\normalsize}
     \etocmemoirtoctotocfmt{chapter}{\contentsname}%
     \renewcommand*\etocstandarddisplaystyle{\etocmemoirstyle}
     \Etoc@redefetocstyle{chapter}}{}
%    \end{macrocode}
%|1.07k (2014/03/06)| adds the compatibility with the |tocloft| package; in
% compatibility mode etoc will obey the |tocloft| customisation for the division
% headings as well as for the toc title.
%
%|1.07l (2014/04/02)| fixes the bug from the |tocloft| compatibility layer which
%was |memoir| incompatible: |memoir| has its version of |tocloft| which doesn't
%have the |\if@cftnctoc| boolean.
%    \begin{macrocode}
\def\etoctocloftstyle {%
    \etocsettocstyle
    {\@cfttocstart\par\begingroup
      \parindent\z@ \parskip\cftparskip \@cftmaketoctitle
      \if@cfttocbibind\@cftdobibtoc\fi }%
    {\endgroup\@cfttocfinish }%
}
\@ifclassloaded{memoir}{}
{\@ifpackageloaded{tocloft}
    {\if@cftnctoc\else
     \renewcommand*\etocstandarddisplaystyle{\etoctocloftstyle}
     \AtBeginDocument{\let\tableofcontents\etoctableofcontents}
     \fi }
    {\AtBeginDocument
      {\@ifpackageloaded{tocloft}
       {\if@cftnctoc\else
         \PackageWarning {etoc}
         {Package `tocloft' was loaded after `etoc'!^^J%
**** to prevent it from overwriting \protect\tableofcontents, it will be tricked^^J%
**** into believing to have been loaded with option `titles'. For better^^J%
**** compatibility, please load `tocloft' before `etoc'}%
        \AtEndDocument{\PackageWarning{etoc}
                       {Please load `tocloft' /before/ `etoc'!}}\fi
        \@cftnctoctrue }%
       {}%
      }%
     }%
}
%    \end{macrocode}
% \LaTeX\ 2021 fall release lets |\contentsline| always grab four arguments,
% so with |1.09e 2021/09/23| we make sure our |\addtocontents| will always
% provide |\contentsline| with four arguments. This extra |{}| is done
% without checking LaTeX's version by laziness, as an impact on documents
% compiled with former LaTeX could be visible only with very special contexts
% that only the author himself would ever consider.
%
% Let's also add |\protected@file@percent| at |1.09e| although this is a
% priori of no relevance as \etoc reads the toc file with |\endlinechar=-1|
% regime.
%
% When using |\addcontentsline| nothing needs to be done as both things are
% handled by \LaTeX\ upstream.
%    \begin{macrocode}
\def\Etoc@addtocontents #1#2%
    {\ifEtoc@hyperref
       \addtocontents {toc}{\protect\contentsline
                {#1}{#2}%
                {\thepage }{\@currentHref }%
                \ifdefined\protected@file@percent\protected@file@percent\fi
       }%
     \else
       \addtocontents {toc}{\protect\contentsline
          {#1}{#2}{\thepage }{}%
          \ifdefined\protected@file@percent\protected@file@percent\fi
       }%
     \fi}
\def\Etoc@addcontentsline@ #1#2#3{%
    \@namedef{toclevel@#1}{#3}\addcontentsline {toc}{#1}{#2}%
}
\DeclareRobustCommand*{\etoctoccontentsline}
    {\@ifstar{\Etoc@addcontentsline@}{\Etoc@addtocontents}}
%    \end{macrocode}
% |1.09f| adds \csa{etocimmediatetoccontentsline}.
%    \begin{macrocode}
\def\Etoc@addtocontents@immediately#1#2{%
    \begingroup
       \let\Etoc@originalwrite\write
       \def\write{\immediate\Etoc@originalwrite}%
       \Etoc@addtocontents{#1}{#2}%
    \endgroup
}
\def\Etoc@addcontentsline@@immediately#1#2#3{%
    \begingroup
       \let\Etoc@originalwrite\write
       \def\write{\immediate\Etoc@originalwrite}%
       \Etoc@addcontentsline@{#1}{#2}{#3}%
    \endgoroup
}
\DeclareRobustCommand*{\etocimmediatetoccontentsline}
    {\@ifstar{\Etoc@addcontentsline@@immediately}{\Etoc@addtocontents@immediately}}
%    \end{macrocode}
% All the following added for version |1.07g [2013/10/13]|. Motivated by
% a demand about  |tovsec2|. But it is impossible to make |tocvsec2|
% compatible, if not re-doing all `toc' macros in |tocvsec2|
% (|1.3, 2011/08/07|). I do not retain the stack idea, which does not convince
% me as useful. The empty line in the |.toc| file is put there by
% |tocvsec2| (see its code line 143).
%
% I take this opportunity to add to the start of the toc file
% |\let\etoc@startlocaltoc\@gobble| in case |etoc| is not detected, I should
% possibly have done that long ago (like I did in |tableof|).
%
% In |1.07h| I decide that I should not have used |\Etoc@| but |\etoc@| for
% |\Etoc@settocdepth|. So I now use lowercase and add a temporary line for
% transition in the very improbable situation that someone actually did already
% use the just released |1.07g|.
%
% In |1.07i| the deactivation of |\etoc@settocdepth| done at the start
% of the |.toc| file (for the case this file is used after having
% removed |etoc| from the document, or imported in another document) is
% done via letting it to |\@gobble| rather than |\count@| (which would
% not be ok, as what follows would be undefined too). The reason for the
% |\count@| also used originally in |\etocignoretoctocdepth| is that
% when I first worked on |1.07g| I possibly had more than one token
% after |\etoc@settocdepth|, but I changed that later.
%
% |1.09| renames \cs{Etoc@resettocdepth} to \cs{Etoc@restoretocdepth}.
%    \begin{macrocode}
\def\Etoc@storetocdepth   {\global\c@etoc@tocdepth\c@tocdepth }
\def\Etoc@restoretocdepth {\global\c@tocdepth\c@etoc@tocdepth }
\def\etocobeytoctocdepth {\def\etoc@settocdepth
        {\afterassignment\Etoc@@nottoodeep \global\c@tocdepth}}
\def\Etoc@@nottoodeep {\ifnum\c@tocdepth>\c@etoc@tocdepth
                          \global\c@tocdepth\c@etoc@tocdepth\fi }
\def\etocignoretoctocdepth {\let\etoc@settocdepth\@gobble }
\def\etocsettocdepth   {\futurelet\Etoc@nexttoken\Etoc@set@tocdepth }
\def\Etoc@set@tocdepth {\ifx\Etoc@nexttoken\bgroup
                            \expandafter\Etoc@set@tocdepth@
                       \else\expandafter\Etoc@set@toctocdepth
                       \fi }
\def\Etoc@set@tocdepth@ #1{\@ifundefined {Etoc@#1@@}
      {\PackageWarning{etoc}
          {Unknown sectioning unit #1, \protect\etocsettocdepth\space ignored}}
      {\global\c@tocdepth\csname Etoc@#1@@\endcsname}%
}
\def\Etoc@set@toctocdepth  #1#{\Etoc@set@toctocdepth@ }
\def\Etoc@set@toctocdepth@ #1{%
  \@ifundefined{Etoc@#1@@}%
   {\PackageWarning{etoc}
        {Unknown sectioning depth #1, \protect\etocsettocdepth.toc ignored}}%
   {\addtocontents {toc}
   {\protect\etoc@settocdepth\expandafter\protect\csname Etoc@#1@@\endcsname}}%
}
%    \end{macrocode}
% |1.09f| adds \csa{etocimmediatesettocdepth.toc}.
%    \begin{macrocode}
\def\etocimmediatesettocdepth #1#{\Etoc@set@toctocdepth@immediately}
\def\Etoc@set@toctocdepth@immediately #1{%
  \@ifundefined{Etoc@#1@@}%
   {\PackageWarning{etoc}
        {Unknown sectioning depth #1, \protect\etocimmediatesettocdepth.toc ignored}}%
   {\begingroup
      \let\Etoc@originalwrite\write
      \def\write{\immediate\Etoc@originalwrite}%
      \addtocontents {toc}
      {\protect\etoc@settocdepth\expandafter\protect
       \csname Etoc@#1@@\endcsname}%
    \endgroup
   }%
}
%    \end{macrocode}
% |1.07h| adds the depth tags, and an even more general mechanism could be added
% at some point: we could insert `action' tags and have the user map them to
% arbitrary commands. For the time being we just provide
% |\etocdepthtag.toc {name}| and |\etocsettagdepth {tag_name}{level}| where
% level is numeric or
% alphabetical. The numeric
% level |-3| is now again not accepted by |\etocsetlevel|, it can be used with
% |\etocsettagdepth| (which accepts equivalently |none|).
%    \begin{macrocode}
\def\etocdepthtag   #1#{\Etoc@depthtag } % \etocdepthtag.toc {name}
\def\Etoc@depthtag  #1{\addtocontents {toc}{\protect\etoc@depthtag {#1}}}
%    \end{macrocode}
% |1.09f| adds \csa{etocimmediatedepthtag.toc}.  This can serve in some
% circumstances, see user documentation.  Apologies for long delay to Norman
% Ramsey who reported problem and his fix in July... 2016!
%    \begin{macrocode}
\def\etocimmediatedepthtag   #1#{\Etoc@depthtag@immediately }
\def\Etoc@depthtag@immediately #1{%
  \begingroup
    \let\Etoc@originalwrite\write
    \def\write{\immediate\Etoc@originalwrite}%
    \addtocontents {toc}{\protect\etoc@depthtag {#1}}%
  \endgroup
}
\def\etocignoredepthtags {\let\etoc@depthtag \@gobble }
\def\etocobeydepthtags   {\let\etoc@depthtag \Etoc@depthtag@ }
\def\Etoc@depthtag@ #1{\@ifundefined{Etoc@depthof@#1}%
       {}% ignore in silence if tag has no associated depth
       {\afterassignment\Etoc@@nottoodeep
                 \global\c@tocdepth\csname Etoc@depthof@#1\endcsname}%
}
\def\etocsettagdepth #1#2{\@ifundefined{Etoc@#2@@}%
       {\PackageWarning{etoc}
         {Unknown sectioning depth #2, \protect\etocsettagdepth\space ignored}}%
       {\@namedef{Etoc@depthof@#1}{\@nameuse{Etoc@#2@@}}}%
}
%    \end{macrocode}
% We must cancel all |tocvsec2| toc-related actions. But a check must be done
% for the memoir class, as its |tocvsec2| emulation does not have the
% incompatible things etoc needs to revert. This extra check added with etoc
% |1.07l|. Release |1.08g| modifies the info message under class memoir (and
% downgrades it from warning to info).
%    \begin{macrocode}
\def\Etoc@tocvsec@err #1{\PackageError {etoc}
        {the command \protect#1\space is incompatible with etoc}
        {use \protect\etocsettocdepth.toc as replacement (see etoc manual)}%
}%
\AtBeginDocument {%
   \@ifclassloaded{memoir}
    {\PackageInfo {etoc}
     {Regarding memoir class command \protect\settocdepth, consider^^J
     \protect\etocsettocdepth.toc as a drop-in replacement with
     more capabilities^^J (see etoc manual). Similarly
     \protect\etocsettocdepth\space and
     \protect\etocsetnexttocdepth^^J should replace
     use of memoir's \protect\maxtocdepth\space command.}}
    {\@ifpackageloaded {tocvsec2}
     {\def\maxtocdepth  #1{\Etoc@tocvsec@err \maxtocdepth   }%
      \def\settocdepth  #1{\Etoc@tocvsec@err \settocdepth   }%
      \def\resettocdepth  {\@ifstar {\Etoc@tocvsec@err \resettocdepth }%
                                    {\Etoc@tocvsec@err \resettocdepth }%
                          }%
      \def\save@tocdepth #1#2#3{}%    % if etoc is added to file previously
      \let\reset@tocdepth\relax       % using tocvsec2
      \let\remax@tocdepth\relax
      \let\tableofcontents\etoctableofcontents
      \PackageWarning {etoc}
      {package tocvsec2 detected and its modification of^^J
       \protect\tableofcontents\space reverted. Use
       \protect\etocsettocdepth.toc as a replacement^^J
       for the tocvsec2 toc-related commands}}{}%
   }%
}%
%    \end{macrocode}
% |1.07g|. Initial version of \csa{etocsetnexttocdepth}.
%
% |1.08h|: avoid after-effect of consecutive uses of \csa{etocsetnexttocdepth}
% with no intervening TOC, due to the fact that the command did an immediate
% modification of the |tocdepth counter|. This is now delayed until
% the actual TOC typesetting.
%
% |1.09|: slight refactoring of \cs{etocsetnexttocdepth} to let it be usable
% from first argument of \cs{etocsettocstyle} although it is even simpler to
% use \cs{etocsettocdepth} there, because the setting is automatically undone
% at end of TOC.
%
% Recall that etoc allows to change all numeric
% levels assigned to sectioning names, and the one used by
% \cs{etocsetnexttocdepth} is determined at time of next toc only, when
% \cs{Etoc@tocdepthset} will expand.
%    \begin{macrocode}
\def\invisibletableofcontents {\etocsetnexttocdepth {-3}\tableofcontents }%
\def\invisiblelocaltableofcontents
                         {\etocsetnexttocdepth {-3}\localtableofcontents }%
\def\etocsetnexttocdepth #1{%
    \@ifundefined{Etoc@#1@@}
     {\PackageWarning{etoc}
       {Unknown sectioning unit #1, \protect\etocsetnextocdepth\space ignored}}
     {\Etoc@setnexttocdepth{\csname Etoc@#1@@\endcsname}}%
}%
\def\Etoc@setnexttocdepth#1{%
    \def\Etoc@tocdepthset{%
        \Etoc@tocdepthreset
        \edef\Etoc@tocdepthreset {%
               \global\c@tocdepth\the\c@tocdepth\space
               \global\let\noexpand\Etoc@tocdepthreset\noexpand\@empty
         }%
        \global\c@tocdepth#1%
        \global\let\Etoc@tocdepthset\@empty
    }%
}%
\let\Etoc@tocdepthreset\@empty % new 1.08h functioning of \etocsetnexttocdepth
\let\Etoc@tocdepthset  \@empty %
%    \end{macrocode}
% |1.08k|. Serves to make local TOCs even after headings which were not added
% to the |.toc| file; but of course the local TOCs can only display
% sub-headings which made their way into the |.toc| file...
%    \begin{macrocode}
\def\etocsetlocaltop #1#{\Etoc@set@localtop}%
\def\Etoc@set@localtop #1{%
  \@ifundefined{Etoc@#1@@}%
   {\PackageWarning{etoc}
        {Unknown sectioning depth #1, \protect\etocsetlocaltop.toc ignored}}%
   {\addtocontents {toc}
   {\protect\etoc@setlocaltop\expandafter\protect\csname Etoc@#1@@\endcsname}}%
}%
%    \end{macrocode}
% |1.09f| adds \csa{etocimmediatesetlocaltop.toc}.
%    \begin{macrocode}
\def\etocimmediatesetlocaltop #1#{\Etoc@set@localtop@immediately}%
\def\Etoc@set@localtop@immediately #1{%
  \@ifundefined{Etoc@#1@@}%
   {\PackageWarning{etoc}
        {Unknown sectioning depth #1, \protect\etocimmediatesetlocaltop.toc ignored}}%
   {\begingroup
       \let\Etoc@originalwrite\write
       \def\write{\immediate\Etoc@originalwrite}%
       \addtocontents {toc}
           {\protect\etoc@setlocaltop\expandafter\protect
                                     \csname Etoc@#1@@\endcsname}%
    \endgroup
   }%
}%
\def\etoc@setlocaltop #1{%
  \global\let\Etoc@level #1%
  \Etoc@skipthisonefalse
  \ifnum\Etoc@level=\Etoc@@six@@
   \Etoc@skipthisonetrue
  \else
   \ifEtoc@localtoc
    \ifEtoc@stoptoc\Etoc@skipthisonetrue
    \else
     \ifEtoc@notactive
      \Etoc@setflags
      \Etoc@skipthisonetrue
     \else
%    \end{macrocode}
% Attention, |1.09| has \cs{etoclocaltop} which is former \cs{Etoc@localtop}
% \emph{minus one}. Hence the shape of the conditional. Memo: it makes sense
% only for code executed under "active" status of the TOC.
%    \begin{macrocode}
      \unless\ifnum\Etoc@level>\etoclocaltop
       \Etoc@skipthisonetrue
       \global\Etoc@stoptoctrue
      \fi
     \fi
    \fi
   \fi
  \fi
  \let\Etoc@next\@gobble
  \ifEtoc@skipthisone
  \else
   \ifnum\c@tocdepth<\Etoc@level
   \else
    \ifEtoc@standard
    \else
     \let\Etoc@next\@firstofone
    \fi
   \fi
  \fi
%    \end{macrocode}
% At |1.09f| the |\global\Etoc@skipprefixfalse| is added.  This fixes a
% weird problem that an |\etocskipfirstprefix| from this level (which a priori
% only serves to delimit the local contents) impacted (in the global TOC for
% example) the rendering of the first finer subsequent heading.  Not resetting
% the boolean was an oversight, and it shows in context of the package
% built-in level styles as they do use |\etocskipfirstprefix|.  But this also
% stresses that the name of the macro is a bit of a misnomer, yes it serves to
% delimit local table of contents, but really it is implemented as a ghost of
% a sectioning unit which does have an impact (on the global TOC or local TOCs
% from encompassing levels), as it triggers when encountered the \marg{finish}
% portions of previous finer levels (and the \marg{finish} code of its own
% level will be executed sooner or later), and the \marg{start} code of
% subsequent finer levels (as well as its own \marg{start} code at least once,
% depending on how levels are nested).
%    \begin{macrocode}
  \Etoc@next{\Etoc@doends\Etoc@dobegins\global\Etoc@skipprefixfalse}%
}%
%    \end{macrocode}
% |1.07h|. In order for the |.toc| file to be usable without error even
% without etoc. In |1.07i| use of |\@gobble| for |\etoc@settocdepth|.
%    \begin{macrocode}
\addtocontents {toc}{\protect\@ifundefined{etoctocstyle}%
           {\let\protect\etoc@startlocaltoc\protect\@gobble
            \let\protect\etoc@settocdepth\protect\@gobble
            \let\protect\etoc@depthtag\protect\@gobble
            \let\protect\etoc@setlocaltop\protect\@gobble}{}}%
%    \end{macrocode}
% Initializations.
%    \begin{macrocode}
\def\etocstandardlines {\Etoc@standardtrue}
\def\etoctoclines      {\Etoc@standardfalse}
\etocdefaultlines
\etocstandardlines
\etocstandarddisplaystyle
\etocobeytoctocdepth
\etocobeydepthtags
\let\etocaftertochook    \@empty % public for end user.
\let\etocbeforetitlehook \@empty % new with 1.07m
%    \end{macrocode}
% |listings| abuses |\tableofcontents| for its |\lstlistoflistings|. It
% doesn't seem worth to let my version of |\tableofcontents| have to check for
% this special circumstance. So at |1.09d|, simply add this (and induced
% annoying updates to documentation at at least two locations):
%    \begin{macrocode}
\def\etockeeporiginaltableofcontents
   {\let\tableofcontents\etocoriginaltableofcontents}%
\endinput
%    \end{macrocode}
% \MakePercentComment
\Finale
%%
%% End of file `etoc.dtx'.
