% -*- coding: iso-latin-1; time-stamp-format: "%02d-%02m-%:y %02H:%02M:%02S %Z" -*-
%<*none>
\def\doctimestamp {Time-stamp: <03-12-2013 17:49:49 CET>}
%</none>
%<*!package>
\def\jfbpkgname {etoc} \def\jfbpkgdate {2013/12/03} \def\jfbpkgversion {v1.07j}
\def\jfbpkgdescription {Completely customisable TOCs (jfB)}
%</!package>
%%
%% Package: etoc
%% Version: 2013/12/03 v1.07j
%% Copyright (C) 2012-2013 by 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, either
%     version 1.3c of this license or (at your option) any later
%     version. 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. 
%
% This Work has the LPPL maintenance status Author-Maintained.
%
% 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.ins, etoc.tex, etoc.dvi, etoc.pdf
%
% Extraction of the package (.sty) and driver (.tex) files:
%  - if etoc.ins is present:   tex etoc.ins
%  - without etoc.ins:         tex etoc.dtx 
%
% It is also possible to run latex/pdflatex directly on etoc.dtx
%
% At least three ways to produce etoc.pdf:
%  (1) latex etoc.dtx (three times), then dvips, then ps2pdf
%  (2) pdflatex etoc.dtx (three times)
%  (3) latex etoc.tex (three times), then dvipdfmx
%
% Method (3) produces the smallest pdf files.
% Options can be set in etoc.tex:
%  - scrdoc class options (paper size, font size, ...) 
%  - with or without source code, 
%  - with dvipdfmx or with latex/pdflatex. 
%
% 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
%
% etoc.tex, etoc.ins, etoc.aux, etoc.toc, etc... may be discarded
%
%<*none>
\iffalse
%</none>
%<*driver>----------------------------------------------------------------------
%% run latex thrice on this file etoc.tex then dvipdfmx on etoc.dvi 
%% to produce the documentation etoc.pdf, with source code included. 
%%
%% customize as desired the class options and the two toggles below.
%%
\NeedsTeXFormat{LaTeX2e}
\ProvidesFile{\jfbpkgname.tex}%
   [\jfbpkgdate\space\jfbpkgversion\space\jfbpkgdescription]%
\PassOptionsToClass{a4paper,11pt}{scrdoc}
\chardef\Withdvipdfmx 1 % replace 1 by 0 for using latex/pdflatex, rather.
\chardef\NoSourceCode 0 % replace 0 by 1 for the doc *without* the source code
\input etoc.dtx
%%% Local Variables:
%%% mode: latex
%%% End:
%</driver>----------------------------------------------------------------------
%<*insfile>---------------------------------------------------------------------
%% Run tex on this file to extract etoc.sty and etoc.tex from etoc.dtx
%%
%% At least three ways to produce etoc.pdf:
%%  (1) latex etoc.dtx (three times), then dvips, then ps2pdf
%%  (2) pdflatex etoc.dtx (three times)
%%  (3) latex etoc.tex (three times), then dvipdfmx
%%
%% Method (3) produces the smallest pdf files.
%% Options can be set in etoc.tex:
%%  - scrdoc class options (paper size, font size, ...) 
%%  - with or without source code, 
%%  - with dvipdfmx or with latex/pdflatex. 
%%
%% 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
%%
\input docstrip.tex
\askforoverwritefalse
\def\jfbpkgpreamble{\defaultpreamble^^J\MetaPrefix^^J%
\string\ProvidesPackage{\jfbpkgname}^^J%
\space[\jfbpkgdate\space\jfbpkgversion\space\jfbpkgdescription]}%
\generate{\nopreamble
\file{\jfbpkgname.tex}{\from{\jfbpkgname.dtx}{driver}}%
\usepreamble\jfbpkgpreamble
\file{\jfbpkgname.sty}{\from{\jfbpkgname.dtx}{package}}}%
\catcode32=13\relax% active space
\let =\space%
\Msg{************************************************************************}
\Msg{*}
\Msg{* To finish the installation you have to move the following}
\Msg{* file into a directory searched by TeX:}
\Msg{*}
\Msg{*     etoc.sty} 
\Msg{*}
\Msg{* To produce the documentation run latex thrice on file etoc.tex}
\Msg{* and then run dvipdfmx on file etoc.dvi}
\Msg{*}
\Msg{* Happy TeXing!}
\Msg{*}
\Msg{************************************************************************}
\endbatchfile
%</insfile>---------------------------------------------------------------------
%<*none>------------------------------------------------------------------------
\fi
%
\def\getdtxtimestamp #1 <#2 #3 #4>{#2 at #3 #4}
\def\getdocdate      #1 <#2-#3-#4 #5>{#4/#3/#2}
\edef\dtxtimestamp {\expandafter\getdtxtimestamp\doctimestamp }
\edef\docdate      {\expandafter\getdocdate\doctimestamp }
\chardef\noetex 0
\expandafter\ifx\csname numexpr\endcsname\relax \chardef\noetex 1 \fi
\ifnum\noetex=1 \chardef\extractfiles 0 % extract files, then stop
\else
% \ifdefined does not count as \if with Knuth tex !
% no way to use it or \ifcsname here ! (besides hiding it in macros)
    \expandafter\ifx\csname ProvidesFile\endcsname\relax
      \chardef\extractfiles 0 % etex etc.. on etoc.dtx
    \else % latex/pdflatex on etoc.tex or on etoc.dtx
      \ProvidesFile{\jfbpkgname.dtx}%
        [`\jfbpkgname' source and documentation (\dtxtimestamp)]%
      \expandafter\ifx\csname Withdvipdfmx\endcsname\relax
        % latex run is on etoc.dtx
        \chardef\extractfiles 1 % 1 = extract .sty, .ins, .tex and typeset
        \chardef\Withdvipdfmx 0 % 0 = pdflatex or latex+dvips
        \chardef\NoSourceCode 1 % 
        \PassOptionsToClass{a4paper,11pt}{scrdoc}% 
      \else % latex run is on etoc.tex
        \chardef\extractfiles 2 % do not extract files
      \fi
    \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 \jfbpkgname.sty^^J}%
\Msg{*^^J}%
\Msg{* To produce the documentation with source code included run latex^^J}%
\Msg{* thrice on file etoc.tex and then dvipdfmx on etoc.dvi^^J}%
\Msg{*^^J}%
\Msg{* Happy TeXing!^^J}%
\Msg{*^^J}%
\Msg{********************************************************************^^J}%
}%
\begingroup
    \input docstrip.tex
    \askforoverwritefalse
    \def\jfbpkgpreamble{\defaultpreamble^^J\MetaPrefix^^J%
    \string\ProvidesPackage{\jfbpkgname}^^J%
    \space[\jfbpkgdate\space\jfbpkgversion\space\jfbpkgdescription]}%
    \generate{\nopreamble
    \file{\jfbpkgname.ins}{\from{\jfbpkgname.dtx}{insfile}}%
    \file{\jfbpkgname.tex}{\from{\jfbpkgname.dtx}{driver}}%
    \usepreamble\jfbpkgpreamble
    \file{\jfbpkgname.sty}{\from{\jfbpkgname.dtx}{package}}}%
\endgroup
\fi % end of file extraction
\ifnum\extractfiles=0 % tex/etex/xetex/etc on etoc.dtx, files extracted, stop
      \MessageDeFin\expandafter\end\fi
% no use of docstrip to extract files if latex run was on etoc.tex
\ifdefined\MessageDeFin\AtEndDocument{\MessageDeFin}\fi
%-------------------------------------------------------------------------------
% twoside option à partir de version du 3 déc 2013 (1.07j)
\documentclass[abstract,twoside]{scrdoc}
\ifnum\NoSourceCode=1 \OnlyDescription\fi

\makeatletter
\ifnum\Withdvipdfmx=1
   \@for\@tempa:=hyperref,bookmark,graphicx,xcolor\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[latin1]{inputenc}
\usepackage[hscale=0.66,vscale=0.75]{geometry}
\pagestyle{headings}


\makeatletter
% 2013/03/07. 
% This macro allows to conveniently center a line inside a paragraph and still
% use there in \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=}

   \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}

% mais \verb fait \ttfamily hardcoded!!! (contrairement au
% \verbatim@font de latex)

%----
% 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

\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.

\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}
\usepackage[dvipsnames]{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[english]{babel}
\AtBeginDocument{
  \renewcommand\partname{Part}
  \addto\captionsenglish{\renewcommand\partname{Part}}
}

\usepackage{tikz}
\usetikzlibrary{trees}    % added for "cyclic" grow function 2013/03/02
\usepackage{forest}       % switched from tikz-qtree to forest 2013/09/09
% No problem with hyperlinks then, contrarily to tikz-qtree.

% NOTE: (12 octobre)
%  - 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

\usepackage[pdfencoding=pdfdoc]{hyperref}
\hypersetup{%
linktoc=all,%      why is the important stuff
%% bookmarksdepth=3,% in a *hard* to find README? anyhow 
%% (but not needeed anymore now, v1.07g)
breaklinks=true,%
colorlinks,%   
linkcolor=RoyalBlue,% Orchid
urlcolor=OliveGreen,%
pdfauthor={Jean-Fran\c cois Burnol},%
pdftitle={The etoc package},%
pdfsubject={LaTeX, table of contents},%
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

%--------
% 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)
    \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)
\makeatletter
\newcommand*{\MyQuasiStandardTOC}[1]{%
  \begingroup
  \let\savedsectionline\l@section
  \let\savedsubsectionline\l@subsection 
  \etocsetstyle{section}{}
    {\ifnum\etocthenumber=3
      \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}{}{}
        {\savedsubsectionline{\numberline{\etocnumber}\etocname}{\etocpage}}{}%
     \fi} 
    {\savedsectionline
      {\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, 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
}


\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{table\-of\-contents}\xspace}
\newcommand\localtoc{\csa{local\-table\-of\-contents}\xspace}

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

\hyphenation{toc-depth sec-num-depth etoc-framed-style etoc-ruled-style}
\hyphenation{etoc-toc-style-with-marks etoc-ruled etoc-framed}
\hyphenation{etoc-stan-dard-display-style}
\hyphenation{etoc-the-page etoc-the-name etoc-the-num-ber etoc-if-num-bered}
\hyphenation{etoc-link etoc-stan-dard-lines etoc-toc-lines}
\hyphenation{etoc-in-ner-top-sep}
\hyphenation{etoc-the-linked-name etoc-the-linked-num-ber etoc-the-linked-page}
\hyphenation{etoc-the-link}
\hyphenation{etoc-skip-first-pre-fix etoc-the-page
  etoc-ruled-style etoc-mul-ti-col-style etoc-default-lines}
\hyphenation{etoc-local-ruled}

\frenchspacing

\renewcommand\familydefault\sfdefault

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

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

% 10 octobre 2013. 
\bookmark[named=FirstPage,level=1]{Title page}

\begin{center}
  {\normalfont\Large The \etoc package}\\
  \textsc{Jean-François Burnol}\par
  \footnotesize \ttfamily jfbu (at) free (dot) fr\\
  Package version: \jfbpkgversion\ (\jfbpkgdate)
  \let\thefootnote\empty
  \footnote{Documentation generated from the source file
  with timestamp ``\dtxtimestamp''.}\par
\end{center}
\setcounter{footnote}{0}

\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 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}


\begingroup
\small 

\etocdepthtag.toc {preamble}


\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. 

\endgroup
\clearpage

%----
% MAIN TOC
%
\etocsettocdepth {subsubsection}
\etoctoclines
\etocmarkboth\contentsname
\etocmulticolstyle[1]
     {\pdfbookmark[1]{Table of contents}{MAINTOC}%
      \noindent\bfseries\Large
      \leaders\hrule height1pt\hfill
      \MakeUppercase{Table of Contents}}

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

\etocsettocdepth {subsection}

% \clearpage

\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 (but one would need to add to these line styles some suitably
chosen penalties to reduce the possibilities for bad page breaks in TOCs).

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| 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 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} and the \autoref{toc:allsubsections} (which is a TOC!)
have their line styles expressed in terms of enumerate 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
\csa{etocsettocstyle} (or some higher-level commands) and the
former by the command \csa{etocsetstyle}.


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

The command to inform \etoc of what to do with \csa{etocname}, \csa{etocnumber},
and \csa{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.

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{ssub: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.} 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 \csa{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 \csa{etocsetstyle} in the \emph{preamble or body} of the document
  turns off from that point on the compatibility mode for line styles. One
  re-activates the compatibility mode with \csb{etocstandardlines}; and the
  command \csb{etoctoclines} will re-activate the line styles as defined by the
  last uses of \csa{etocsetstyle}, if their scope was not limited to a group or
  environment.

The
command \csb{etocdefaultlines} resets the line styles to be
the package initial default ones. 

Even if \csb{etocsetstyle} has been used, the global display
style remains initially as defined by the document class;
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}.

\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. 

We could use 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|.



\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


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. See also
\autoref{ssec:tocwithdepthtags} which provides a TOC with parts and
paragraphs, with  multi-line headings as in the standard classes
layout (and the technique for setting there the page numbers on the right
is closer than here to what \LaTeX2e's |\@dottedtocline| macro
does).



\begin{verbatim}
\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{verbatim}


\section{Linked list of the main package commands}
% 16 octobre

\begingroup\raggedcolumns
\advance\linewidth18pt
\begin{multicols}{3}\parindent0pt\relax
\csb{etocstandardlines}\par
\csb{etocdefaultlines}\par
  \csb{etoctoclines}\par
  \csb{etocsetstyle}\par
\csb{etocname}\par
\csb{etocpage}\par
\csb{etocskipfirstprefix}\par
  \csb{etocnumber}\par
\csb{etocifnumbered}\par
\csb{etocthename}\par
\csb{etocthenumber}\par
  \csb{etocthepage}\par
\csb{etoclink}\par
\csb{etocthelinkedname}\par
  \csb{etocthelinkednumber}\par
\csb{etocthelinkedpage}\par
\csb{etocthelink}\par
  \csb{etocsetlevel}\par
\csb{etocsettocdepth}\par
\csb{etocsetnexttocdepth}\par
  \csb{etocsettocdepth.toc}\par
\csb{etocobeytoctocdepth}\par
  \csb{etocignoretoctocdepth}\par
\csb{etocdepthtag.toc}\par
\csb{etocsettagdepth}\par
  \csb{etocobeydepthtags}\par
\csb{etocignoredepthtags}\par
  \csb{etocstandarddisplaystyle}\par
\csb{etocsettocstyle}\par
\csb{etocmulticolstyle}\par
  \csb{etocmulticol}\par
\csb{etoclocalmulticol}\par
% \csb{etoctocstyle}\par
%   \csb{etoctocstylewithmarks}\par
% \csb{etoctocstylewithmarksnouc}\par
  \csb{etocruledstyle}\par
\csb{etocruled}\par
\csb{etoclocalruled}\par
  \csb{etocframedstyle}\par
\csb{etocframed}\par
\csb{etoclocalframed}\par
\csb{etocinline}\par
  \csb{etocaftertitlehook}\par
\csb{etocaftercontentshook}\par
\csb{etocaftertochook}\par
\csb{etoctoccontentsline}\par
%\vspace{5\baselineskip}\hrule height 0pt
\end{multicols}
\endgroup



% 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{Labeling and reusing elsewhere}

\etoc allows arbitrarily many \csa{tableofcontents} commands in
your document. The line styles and the toc display style may of
course be changed in-between. Furthermore 
\csa{localtableofcontents} 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 . . .

\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{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
%%  \centeredline{The original is \hyperref[toc:c]{there}.}
\end{figure*}

We used this:
\begin{verbatim}
\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{verbatim}
Important: one should not use elsewhere \toc|\ref{toc:d}|. To clone again, one
must use a reference to the original label: \toc|\ref{toc:c}|.

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

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: 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|.

\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{etocsettoc\-depth.toc}}
\label{etocsettocdepth.toc}

This command \csb{etocsettocdepth.toc} implements some functionality of
|tocvsec2|\footnote{\url{http://ctan.org/pkg/tocvsec2}. I thank D.B. 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.}}

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


So \csb{etocignoretoctocdepth} is provided to cancel the
\csa{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}}
\label{etocdepthtag.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
\csa{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
makes it easier to achieve this variable local control of the |tocdepth| at the
time of typesetting TOCs.

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 (as mentioned
already, 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}.


\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{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).



\section{Two Examples}

\subsection{A Beautiful Thesis example}

Here is another 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{verbatim}
\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{verbatim}

% \clearpage

\begingroup
\newlength{\tocleftmargin}
\setlength{\tocleftmargin}{5cm}
\newlength{\tocrightmargin}
\setlength{\tocrightmargin}{1cm}

\etocsetstyle{section}
{\addvspace{1ex}\parfillskip0pt
 \leftskip\tocleftmargin
 \rightskip\the\tocrightmargin plus 1fil
 \parindent0pt\color{cyan}}
{\bfseries\LARGE\upshape\addvspace{1ex}\leavevmode}
{\llap{Chapter\hspace{.5em}{\etocnumber}\hspace{.75cm}}\etocname
 \hfill\makebox[-\tocrightmargin][l]{\makebox[0pt]{\etocpage}}\par}
{}

\etocsetstyle{subsection}
{}
{\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}
% And again, for the fun of it:
% \def\tmptitle{My Very Beautiful Thesis}
% \tableofcontents \ref{toc:c}
\endgroup


\subsection{A TOC with a background color}\label{ssec:again}

Let us now try out some more sophisticated line styles. The
display will use the \csa{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}. 


\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\noindent
\hbox to 1cm{\color{subsecnum}\etocnumber\hss}%
\color{black}\etocname\leaders\hbox to .2cm{\hss.}\hfill
\rlap{\hbox to .5cm{\hss\etocpage\hskip.1cm}}\par
\nointerlineskip\vskip3pt}
{}

\etocsetstyle{subsection}{\etocskipfirstprefix}
{\shiftedwhiterule{1.5cm}{6pt}}
{\sffamily\small
\leftskip1.5cm\hangindent.8cm\rightskip.5cm\noindent
\hbox to .75cm{\color{subsecnum}\etocnumber\hss}%
\color{black}\etocname\leaders\hbox to .2cm{\hss.}\hfill
\rlap{\hbox to .5cm{\hss\etocpage\hskip.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}{\kern1cm\hbox to .5cm{\etocnumber\hss}%
    \etocname\hfill
{\hbox to .5cm{\hss\etocpage\hskip.1cm}}}%
 \vskip6pt}
{}


% attention car \ref{toc:floating} fera référence au compteur de
% toutes les toc, pas visibletoc. 

\etocframedstyle[1]{}
\tableofcontents \label{toc:floating} \ref{toc:overview}
\vspace{-\baselineskip}
\centeredline{|\tableofcontents \ref{toc:overview}| 
(\emph{cf.} \autoref{ssec:again} and \hyperref[toc:clone]{this other toc})}
\end{figure*}

The actual design is not pre-built in \etoc; it uses its `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. This design (with other colors)
is in use also for \hyperref[toc:clone]{this other toc}, and the
reader is referred to its \hyperref[ssec:tocclone]{subsection} for the
coding used.

% 11 octobre 2013 ceci était une section avant:
% (17 octobre, je m'aperçois qu'à cause des différents chgts, des
% sous-sections devenant des sections etc... \thisspecialstats ici ne
% faisait pas du tout des statistiques; vaut mieux supprimer et faire
% simplement \localtableofcontents pour maintenir le même layout.)

% les \clearpage sont embêtants; surtout si je prétends qu'on peut
% recompiler facilement sous d'autres conditions...

% on va plutôt faire un \vspace suffisant, cela sera un moindre mal

\vspace{1cm}

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

\thispartstats %% (pas de sous-section)

% in dtx of release 1.07h there was here a \thisspecialstats, but it
% originated from the period when this \part was only a \section. So its
% effect was not the intended one, basically it had the same effect as this:
\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 \csa{etocaftertitlehook} (for which the link
  would target the area just after the title). So, rather than
  including |\refstepcounter{visibletoc}| inside
  \csa{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
  \csa{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{verbatim}
   < 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{verbatim}

\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}}
\label{etoctoccontentsline}

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, \csa{etocname} will give the exercise number (but \csa{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 \csa{etocnumber}, and
\csa{etocname} would have been empty. It doesn't matter which one of the two
methods is used. The \etoc command \csa{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{verbatim}
  \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{verbatim}


\section{A TOC with a fancy layout}

Here is  a table of contents where
the sections from a given chapter are to be represented by a number
range (like 18--22 for a given chapter, 42--49 for another one ...
of course to be inserted automatically in the TOC). 

This is not an image inclusion, the TOC is produced from its original
|tex| source inserted in this document after replacement of 
|part|, |chapter| or |section| with |dummypart|, |dummychapter| and
|dummysection| (and there is also a dummy page count).  We
copied the line styles used in the original and
displayed the table of contents following:
\begin{verbatim}
    \etocsetlevel{dummypart}  {-1} \etocsetlevel{part}   {2}
    \etocsetlevel{dummychapter}{0} \etocsetlevel{chapter}{2}
    \etocsetlevel{dummysection}{1} \etocsetlevel{section}{2}
                    \etocsetnexttocdepth{dummysection}
\end{verbatim}
Each chapter displays the numbers of only the first and the last sections it
  contains. See the
source file |etoc.dtx| for the details of how this is done. 

Another technique for doing this kind of things is explained in 
  \autoref{ssec:statistics}.  

%\clearpage

\begingroup

    \etocsetlevel{dummypart}{-1}
    \etocsetlevel{dummychapter}{0}
    \etocsetlevel{dummysection}{1}
    \etocsetlevel{part}{2}
    \etocsetlevel{chapter}{2}
    \etocsetlevel{section}{2}

    \newif\ifextraidone
    \newif\ifextraiidone

    \etocsetstyle{dummypart}
    {}
    {}
    {\begin{center}\Large\bfseries PART \etocnumber
    \ifextraiidone\\\etocname.\fi\end{center}
    \ifextraidone\else
    \noindent\hskip.7\linewidth
        \hbox to .2\linewidth
% février (ou janvier?) 2013
% je modifie ici en ajoutant un \hss, pour compenser la plus petite
% taille de txrm. Ok.
        {\hss\small\textsc{\bfseries Sections.\hss Page.}}\par\fi
    \extraidonetrue
    }
    {}

    \newcommand\mytocleaders{\hbox to .125\linewidth{...\hss}}
    \etocsetstyle{dummychapter}
    {}
    {\par\noindent\etocifnumbered
        {\makebox[.15\linewidth][r]{\bfseries\etocnumber.}}
        {\hspace*{.15\linewidth}}}
    {\hbox to .65\linewidth
        {\hspace{1em}\etocname\leaders\mytocleaders\hss}%
     \hskip-.1\linewidth
     \hbox to .2\linewidth{\hspace{1.5em}...\hss
                    \etocifnumbered
                        {\etocpage}
                        {\ifextraiidone\else\etocpage\fi}}%
     \hskip-.2\linewidth
    }
    {}

    \newbox\forsectionnumbers
    \makeatletter
% 21 février 2013: je rajoute \color@begingroup et \color@endgroup
    \etocsetstyle{dummysection}
    {\setbox\forsectionnumbers=\hbox to .1\linewidth
        \bgroup\color@begingroup\hss\etocskipfirstprefix}
    {\@gobble}
    {\etocnumber---}
    {\etocnumber\color@endgroup\egroup
    % for reasons I do not quite understand, in some pdf viewers the dots
    % do not completely disappear if here \fboxsep0pt is used.
    % (problèmes liés à l'anti-aliasing, sur Mac OS X, Skim, Preview...)
    % (j'ai maintenu ici la méthode de mon post sur stackexchange, mais
    %  sans doute je pourrais réfléchir à une autre façon évitant d'avoir à
    %  « effacer ») 
        \fboxsep=.5pt\colorbox{white}{\box\forsectionnumbers}\par
        \ifextraiidone\else
            \begin{center}\bfseries Concord.\end{center}
            \noindent\makebox[.15\linewidth][r]{\textsc{\bfseries Lesson.}}\par
        \fi\extraiidonetrue
    }
    \makeatother

    \renewcommand{\etocinnertopsep}{0pt}

    \etocruledstyle[1]{%
        \parbox{\linewidth}{%
            \centering
            \textsc{\bfseries\LARGE\MakeUppercase{Table of Contents}}\\
            \rule{.2\linewidth}{2pt}}%
    }
        
    \etocsetnexttocdepth{dummysection}

    \tableofcontents
   

\makeatletter
    \def\adddummysection {\stepcounter{dummysection}%
      \addtocontents {toc}{\protect\contentsline 
          {dummysection}{\protect\numberline{\thedummysection}}%
                   {\the\dummypage }%
     \ifEtoc@hyperref{\@currentHref }\fi}}
 
    \def\adddummychapter #1{\stepcounter{dummychapter}%
      \advance\dummypage2
      \addtocontents {toc}{\protect\contentsline 
          {dummychapter}{\protect\numberline{\thedummychapter}#1}%
                   {\the\dummypage }%
     \ifEtoc@hyperref{\@currentHref }\fi}}


    \def\adddummychapno #1{\advance\dummypage2
      \addtocontents {toc}{\protect\contentsline 
          {dummychapter}{#1}{\the\dummypage }%
      \ifEtoc@hyperref{\@currentHref }\fi}}

    \def\adddummypart #1{\stepcounter{dummypart}%
       \advance\dummypage4
       \addtocontents {toc}{\protect\contentsline 
          {dummypart}{\protect\numberline{\Roman{dummypart}}#1}%
                     {\the\dummypage }%
       \ifEtoc@hyperref{\@currentHref }\fi}}
     
\makeatother
    
    \newcount\dummypage \dummypage-1

    \adddummypart {}
    

    \adddummychapno {Introductory}

    \newcount\tempcount

    \loop\advance\tempcount by 1
    \adddummysection
    \ifnum\tempcount<8
    \repeat

    \adddummychapter {Concord of Subject and Verb}

    \loop\advance\tempcount by 1
    \adddummysection
    \ifnum\tempcount<17
    \repeat

    \adddummychapter {Concord of Substantive and Adjective}

    \loop\advance\tempcount by 1
    \adddummysection
    \ifnum\tempcount<22
    \repeat

    \adddummychapno {Concord of Relative and its Antecedent}

    \loop\advance\tempcount by 1
    \adddummysection
    \ifnum\tempcount<25
    \repeat

    \adddummypart {Government}

    \adddummychapter {The Accusative Case}

    \adddummychapno {General uses}

    \loop\advance\tempcount by 1
    \adddummysection
    \ifnum\tempcount<30
    \repeat

    \adddummychapno {Particular uses}

    \loop\advance\tempcount by 1
    \adddummysection
    \ifnum\tempcount<37
    \repeat

    \adddummychapter {Verbs governing two Accusatives}

    \loop\advance\tempcount by 1
    \adddummysection
    \ifnum\tempcount<41
    \repeat

    \adddummychapter {The Causal}

    \loop\advance\tempcount by 1
    \adddummysection
    \ifnum\tempcount<49
    \repeat

    \adddummychapter {The Instrumental Case}

    \adddummychapno {General uses}

    \loop\advance\tempcount by 1
    \adddummysection
    \ifnum\tempcount<54
    \repeat

    \adddummychapno {Particular uses}

    \loop\advance\tempcount by 1
    \adddummysection
    \ifnum\tempcount<59
    \repeat

    \adddummychapter {The Dative Case}

    \adddummychapno {General uses}

    \loop\advance\tempcount by 1
    \adddummysection
    \ifnum\tempcount<65
    \repeat

    \adddummychapno {Particular uses}

    \loop\advance\tempcount by 1
    \adddummysection
    \ifnum\tempcount<71
    \repeat

    \adddummychapter {The Ablative Case}

    \adddummychapno {General uses}

    \loop\advance\tempcount by 1
    \adddummysection
    \ifnum\tempcount<75
    \repeat

    \adddummychapno {Particular uses}

    \loop\advance\tempcount by 1
    \adddummysection
    \ifnum\tempcount<86
    \repeat

    \adddummychapter {The Locative Case}

    \adddummychapno {General uses}

    \loop\advance\tempcount by 1
    \adddummysection
    \ifnum\tempcount<92
    \repeat

    \adddummychapno {Particular uses}

    \loop\advance\tempcount by 1
    \adddummysection
    \ifnum\tempcount<100
    \repeat
\endgroup

\section{Another compatibility mode}

As explained in \autoref{ssub:compat}, the commands
\csa{etocstandardlines} and \csa{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 \csa{etocsetstyle} commands
(and \csa{etocsettocstyle}) and is (supposedly...) in complete control.

Well, there is actually an alternative. It is possible to use the
\csa{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. One puts in the preamble:
\begin{verbatim}
\makeatletter
\newcommand{\MyStandardTOC}{%
  \begingroup
  \let\savedpartline\l@part
  \let\savedchapterline\l@chapter  %% remove if article/scrartcl class
  \let\savedsectionline\l@section
  \let\savedsubsectionline\l@subsection 
  % and so on if \subsubsection, etc... is used
  % 
  % for the book or article classes:
  \etocsetstyle{part}{}{}
    {\savedpartline{\etocnumber\hspace{1em}\etocname}{\etocpage}}{}%
  % for the scrbook or scrartcl classes:
  \etocsetstyle{part}{}{}
    {\savedpartline{\numberline{\etocnumber}\etocname}{\etocpage}}{}%
  % identical in book/article/scrbook/scrartcl classes:
  \etocsetstyle{chapter}{}{}   %%% only for book and scrbook
    {\savedchapterline{\numberline{\etocnumber}\etocname}{\etocpage}}{}%
  \etocsetstyle{section}{}{} 
    {\savedsectionline{\numberline{\etocnumber}\etocname}{\etocpage}}{}%
  \etocsetstyle{subsection}{}{}
    {\savedsubsectionline{\numberline{\etocnumber}\etocname}{\etocpage}}{}%
  % etc... if further sectioning units are used
  % (see the text for what to do with the memoir class)
  \etocstandarddisplaystyle % this is for the title, page-marks, etc...
  \tableofcontents     
  \endgroup}
\makeatother
\end{verbatim}
Of course 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 needs a bit more: each of the command \csa{booknumberline},
\csa{partnumberline} and \csa{chapternumberline} will have to be saved with a
\csa{let}, and, one then specifies:
\centeredline{%
\csa{etocsetstyle\{chapter\}\{\}\{\}\{\string\savedchapterline\{%
\string\savedchapternumberline}}
\hbox to \linewidth{\hfil\hfil \ttfamily 
        \{\csa{etocnumber}\}\csa{etocname}\}\{\csa{etocpage}\}\}\{\}\hfil} 
(and analogously for |part|, respectively |book|).}
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
\csa{etocnumber} with \csa{etocthenumber} will give a TOC where the numbers are
not links anymore, but the names still are. Or one may decide to use \csa{etocthename}
and keep an hyperlinked number with
\csa{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{verbatim}
\etocsetstyle{section}{}
  {\ifnum\etocthenumber=3
      \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}
       {}{}
       {\savedsubsectionline{\numberline{\etocnumber}\etocname}{\etocpage}}
       {}%
    \fi} 
  {\savedsectionline{\numberline{{\color{cyan}\etocthenumber}}\etocname}{\etocpage}}
  {}%
\end{verbatim}

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{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 \csa{tableofcontents} 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 \csa{etocnumber} and \csa{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
hyperlink information put by \etoc inside \csa{etocname}, etc\dots, is just a
pointer, not storable for later use; but the package provides
\csa{etocthelinkednumber}, \csa{etocthelinkedname}, and \csa{etocthelinkedpage}
whose contents contain the hyperlink in a form which can be stored and later
reused.

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|.

\newtoks\treetok
\newtoks\tmptok

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


% 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).

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

% 7 mars: j'utilise maintenant \etocthelinkedname
\newcommand*{\PrepareSubsectionNode}{%
  \tmptok {\raggedright}%  j'ai essayé aussi avec \sloppy
  \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{ ]}}


% 11 octobre
% forest ne veut pas @\the\treetok avec un \treetok vide, donc
% il faut lui donner une valeur par défaut.
\treetok{[{run latex again}]}

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

\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}}{},
                  % je trouve ce truc pour une position absolue. OK!
                  rectangle, thick, fill=cyan!5, inner sep=6pt,
     @\the\treetok 
     \end{forest}
     \centeredline{A table of contents displayed as a |forest| tree.}
\end{figure*}


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:
\begin{verbatim}
\newtoks\treetok
\newtoks\tmptok

\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{verbatim}

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 (see \autoref{ssec:tocastable});
  there we also will 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{ssec: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{verbatim}
% \newtoks\treetok % already done earlier
\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{ ;}}

% moved to the inside of the figure environment for correct \pageref{toc:molecule}
% \etocsetnexttocdepth{subsection}
% \tableofcontents \label{toc:molecule} \ref{toc:overview}
\end{verbatim}

\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}%
  \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*}[th!]\centering
\etocsetnexttocdepth{subsection}
   \tableofcontents \label{toc:molecule}\ref{toc:overview}
   \hypersetup{hidelinks}%
   \begin{tikzpicture}
              [grow cyclic,
               level 1/.style={level distance=4cm,sibling angle=90},
               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}
   \centeredline{A table of contents as a ``molecule.''}
\end{figure*}

% 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 (for the label of the
table of contents to certainly
refer 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}. Here is the code actually
producing it:
\begin{verbatim}
\begin{figure*}[th!]\centering
   \etocsetnexttocdepth{subsection}
   \tableofcontents \label{toc:molecule} \ref{toc:overview}
   \hypersetup{hidelinks}%
   \begin{tikzpicture}
              [grow cyclic,
               level 1/.style={level distance=4cm,sibling angle=90},
               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{verbatim}



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}

% \vfill\eject

\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 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}}

% \clearpage
\localtableofcontents \label{toc:a}

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

\subsection{The \csbhyp{etocname} and \csbhyp{etocpage} commands}
\label{etocname}
\label{etocpage}

Let us explain how \etoc was used to produce the table of
contents displayed at the beginning of this second part.
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{verbatim}
\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{verbatim}
\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.

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 mean-time 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 \marg{prefix} and \marg{contents} parts of the
\csa{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 \csa{etocname}, \csa{etocnumber} and
\csa{etocpage} (this last one will have a link only if |hyperref| was passed
option \emph{linktoc=all}.) 

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

The chosen |subsubsection| style also uses the command
\csb{etocskipfirstprefix}, which, if present, \emph{must} be
the very last one in the \emph{start} code. It instructs to not
use for the first item the specified ``prefix'' code.

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!

\subsection{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 \csa{etocnumber} we then used something like
|\fbox{\etocnumber}|. Note that \csa{etocnumber} is a robust
command which explains why it can be used inside the label specification
without needing an added |\protect|.


\subsubsection{The \csbhyp{etocifnumbered} switch}
\label{etocifnumbered}

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}|.

\subsection{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|.

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

The command \csb{etoclink}\marg{linkname} can be used in the line style
specifications in a manner analogous to the argument-less
commands \csa{etocname}, \csa{etocnumber} and \csa{etocpage}. It
creates a link (if such a link was added by |hyperref| to the
|.toc| file entry) whose destination is the corresponding document
unit and whose name is the given argument. 
Hence |\etoclink{\etocthename}| is like the original
|\etocname|.
Notice that if |hyperref| was not instructed to put a link in the page number
(via 
its option \emph{linktoc=all}) then \etoc's \csa{etocpage} contains no link
either, but |\etoclink{\etocthepage}| does. 


The command \csa{etoclink} is robust.

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


This is for advanced uses by advanced users. 
The \csa{etocthename} macro has
been mentioned before; using it in instructions such as
|\global\let\lastone\etocthename| in an \etoc line style will
define the macro |\lastone| to expand to the last name seen at the
corresponding level. But no facilities was previously available to
do the same with the link data.

The package now provides \csa{etocthelinkedname} to do the similar
thing, with the link data included. It was used in this
documentation when doing the
\hyperref[tocastree]{examples with trees}.

Also provided with the similar goal: \csa{etocthelinkednumber},
\csa{etocthelinkedpage} (which contains a link only if |hyperref|
added one to the page number) and \csa{etocthelink}\marg{linkname}
which allows to make a link with an arbitrary name.

All these commands are fragile.


\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 \csa{etocsetlevel}. For example:
\begin{verbatim}
\etocsetlevel{cell}{0}
\etocsetlevel{molecule}{1}
\etocsetlevel{atom}{2}
\etocsetlevel{nucleus}{3}
\end{verbatim}
Of course, in compatibility mode, it will be assumed here that the
macros |\l@cell|, |\l@molecule|, ..., pre-exist. If no table
of contents is typeset in compatibility mode, then all that
matters is that the line styles have been set. If for example
|section| is at level |1|, then there is no need to do a
\csa{etocsetstyle}|{molecule}| if \csa{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 \csa{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{verbatim}
\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{verbatim}
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.

The commands to be described next \csb{etocmulticolstyle},
\csb{etocruledstyle}, and \csb{etocframedstyle} all call
\csa{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 \csa{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{\csa{etocmulticol}\oarg{number\_of\_columns}\marg{heading}}
And there is also
\csa{etoclocalmulticol}\oarg{number\_of\_columns}\marg{heading}.

\subsubsection{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.

\paragraph{\texorpdfstring{\csbhyp{etoc\-toc\-style\-with\-marks}}{etoctocstylewithmarks}}%
\leavevmode\unskip{\color{blue}\oarg{kind}\marg{number\_of\_columns}\marg{title}\marg{mark}}
\label{etoctocstylewithmarks}
\label{etoctocstylewithmarksnouc}

\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{etoclocal\-ruled}}
\label{etocruledstyle}
\label{etocruled}
\label{etoclocalruled}

The general format of \csa{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{etoclocal\-framed}}
\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 \csa{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 \csa{etocframedstyle} or \csa{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
  \csa{etocoldpar} (= working \csa{par} in the argument to
  \csa{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 \csa{etocinnertopsep}. The command \csb{etocoldpar} can also be
used explicitely if needed in the mandatory argument to
\csa{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.

\subsection{The command \csbhyp{etoc\-inline}}
\label{etocinline}
\label{etocnopar}

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.

\section{Starred variants of the \csbhyp{tableofcontents}  etc... commands}
\label{tableofcontents*}
\label{localtableofcontents*}
\label{etocaftertitlehook}
\label{etocaftercontentshook}
\label{etocmemoirtoctotocfmt}

The \toc, \localtoc, \csa{etocmulticol}, and all their cousins and
variants have starred variants (the star must be before the other
arguments). For all but the |memoir| class, they are like the original.
For the |memoir| class, the original prints an entry in the |.toc| file,
as is the usage for the original \toc command in that class, whereas the
starred variants do not, as is the habit in that class.

As soon as one starts using local table of contents one
discovers that the default |memoir| thing which is to create a
|chapter| entry for each TOC is not convenient. The command
\csb{etocmemoirtoctotocfmt}\marg{kind}\marg{name} will change
the format (\meta{kind} is |chapter|, |section|, |subsection|... and
\meta{name} can be for example \csa{contentsname}.) The initial set-up
is with |chapter| and |\contentsname|. 

The format of the actual heading of the TOC should also be set
appropriately (for example with \csa{etoctocstyle}), to use the
identical division unit as in the first argument to
\csa{etocmemoirtoctotocfmt}. 

A weird situation arises when one has two successive
\csa{localtableofcontents} (obviously this is not a truly real
life situation), just after a \csa{part} for example. The first
one creates (if the default has not been modified as indicated
above) a Chapter heading which is
written to the |.toc|. Then the second one thinks to be local
to this chapter . . . and as a result it displays nothing. The
fix is to define the second one to be a clone of the first
one.

Independently of the situation with the |memoir| class there is
generally speaking a hook macro called
\csb{etocaftertitlehook} which is inhibited by using the
starred variants of the displaying commands. Except for the
|memoir| class, this hook is initially defined to do nothing.
There is also \csb{etocaftercontentshook},  similarly
defined to do nothing. They can be used for some special
effects.

\section{Table of contents for this part}


\subsection{Testing the compatibility mode}

As a third example we now print the local table of contents
for this part. 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 this \autoref{part:globalcmds}.
\begin{verbatim}
\KOMAoptions{toc=left}
\etocstandarddisplaystyle % necessary for the display to obey toc=left
\etocstandardlines
\tableofcontents \ref{toc:globalcmds}
\end{verbatim}
\KOMAoptions{toc=left}
\etocstandarddisplaystyle
\etocstandardlines
\tableofcontents \ref{toc:globalcmds}

\subsection{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}).\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.}

\begin{verbatim}
\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
\normalcolor % work-around to a bug involving color and multicols (and figure)
\tableofcontents \label{toc:b} \ref{toc:globalcmds}
\end{figure*}
\endgroup
\end{verbatim}


\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}{-.5\baselineskip\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
\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*

\subsection{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 taste in
many matters does not seem to be widely shared).

The code used:
\begin{verbatim}
\begingroup
\newsavebox{\forsubsections}
\etocsetstyle{part}{\upshape. \etocskipfirstprefix}{. \upshape}
                      {\bfseries\etocname:~~}{}
\etocsetstyle{section}{\itshape\etocskipfirstprefix}{, }
                      {\mdseries\etocname}{}
\etocsetstyle{subsection}
   {\begin{lrbox}{\forsubsections}\upshape\etocskipfirstprefix}
   {; }{\etocname}{\end{lrbox}\footnote{\unhbox\forsubsections.}}
\etocsetstyle{subsubsection}
  { (\itshape\etocskipfirstprefix}{, }{\etocname}{\/\upshape)}
\etocsettocstyle{Here is the inline table of contents. }{.\par}
\tableofcontents
\endgroup
\end{verbatim}

\clearpage
\begingroup
\newsavebox{\forsubsections}
\etocsetstyle{part}{\upshape. \etocskipfirstprefix}{. \upshape}{\bfseries\etocname:~~}{}
\etocsetstyle{section}{\itshape\etocskipfirstprefix}{, }{\mdseries\etocname}{}
\etocsetstyle{subsection}
   {\begin{lrbox}{\forsubsections}\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



\etocdepthtag.toc {custom}

\part{Using and customizing \etoc}
\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{\csa{etocthename}, \csa{etocthenumber}, \csa{etocthepage}, \csa{etoclink}\marg{linkname}}%
\framebox[\linewidth][c]
{\vbox{\hsize\wd0\normalcolor\noindent
\csa{etocsetstyle}\marg{levelname}%
  \marg{start}\marg{prefix}\marg{contents}\marg{finish}\\
\csa{etocname}, \csa{etocnumber}, \csa{etocpage},
\csa{etocifnumbered}\marg{A}\marg{B}\\
\csa{etocthename}, \csa{etocthenumber}, \csa{etocthepage}, \csa{etoclink}\marg{linkname}
}}}

\subsection{Setting up toc display styles}

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

\subsection{Displaying tables of contents}


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

\subsection{Labels and references}

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{\csa{etocname}, \csa{etocnumber},
    \csa{etocpage}, \csa{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\}|\\
      \hbox{}{\itshape\ttfamily\ \ \ \ similarly with\ }%
      \csa{etocmulticol}{\itshape\ttfamily\ etc . . . }
   }}}


\medskip 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}

Activating the use of the package default line styles is
done via \csa{etocdefaultlines}, or \csa{etoctoclines} if these styles have not
been modified with \csa{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
\csa{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 \csa{etocfontone} command for that. Also we use dot
leaders which are less spread out than in the package defautl.


\begin{verbatim}
\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{verbatim}

\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

\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}
\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{1ex plus .15ex minus .15ex} % modified in 1.07e
\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.~}
\newcommand*\etocpartname{\partname}  % utilisateurs de frenchb: attention
                                      % car donne "partie" sans majuscule.
\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
\csa{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
  \csa{etocstandarddisplaystyle} was apparently needed for the
  KOMA options |toc=left| to be active at the level of the line entries.}  


The \csa{etocstandardlines} compatibility mode will work also with
sectioning commands made known to \etoc via \csa{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 \csa{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} things are initially set to be
\csa{relax}, so there is no need to do \csa{usepackage}|{color}|
if the document does not use colors. If the scope of a change
to a color command such as \csa{etocbkgcolorcmd} has not
been limited to a group and one then wishes to let it again be
\csa{relax} one must use a \csa{renewcommand} 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 \csa{etocruledtoc} or
\csa{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 \csa{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{verbatim}
\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}{\hbox to 1.5cm{\hss\etocnumber\hskip.2cm}%
     \etocname\hfill\hbox{\etocpage\hskip.2cm}}\vskip6pt}
    {}

\etocframedstyle[1]{}
\tableofcontents \label{toc:clone} \ref{toc:globalcmds}
\endgroup
\end{verbatim}

% \clearpage

\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}{\hbox to 1.5cm{\hss\etocnumber\hskip.2cm}%
    \etocname\hfill\hbox{\etocpage\hskip.2cm}}\vskip6pt}
{}

\etocframedstyle[1]{}

\begin{figure*}[ht!]\centering
    \tableofcontents \label{toc:clone} \ref{toc:globalcmds}
\end{figure*}
\endgroup

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}

\subsection{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}


\subsection{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}
\etocmarkbothnouc{List of all subsections}
\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

\subsection{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{ssec:molecule}. We present also this second method.

But first, the code of \csa{thispartstats}:\par
\begin{verbatim}
\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{verbatim}

And now, the variant with macros rather than boxes (this variant as it
stands here is for using within a section).
\begin{verbatim}
\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{verbatim}

\subsection{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. So we simply added to this
source various \csb{etocdepthtag.toc} commands, and it is now just a matter to
set the levels for each one of these tags (as they were left undefined until
now, they were ignored in all previous 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:

%\clearpage

\etocsetnexttocdepth {all}
\begingroup
\parindent 0pt
\leftskip 0cm
\rightskip 0.75cm
\parfillskip -\rightskip
\newcommand*{\EndParWithPagenoInMargin}
    {\nobreak\hfill
     \nobreak\makebox[0.75cm][r]{\mdseries\normalsize\etocpage}%
     \par}
\renewcommand*\etoctoclineleaders
    {\hbox{\normalfont\normalsize\hbox to .75ex {\hss.\hss}}}
\newcommand*{\EndParWithPagenoInMarginAndLeaders}
    {\nobreak\leaders\etoctoclineleaders\hfill
     \nobreak\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}
\etocsettagdepth {surprising} {part}
\etocsettagdepth {linestyles} {part}
\etocsettagdepth {globalcmds} {paragraph}
\etocsettagdepth {custom}     {part}
\etocsettagdepth {tips}       {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

\begin{verbatim}
\etocsetnexttocdepth {all}
\begingroup 
\parindent 0pt \leftskip 0cm \rightskip .75cm \parfillskip -\rightskip
\newcommand*{\EndParWithPagenoInMargin}
    {\nobreak\hfill
     \nobreak\makebox[0.75cm][r]{\mdseries\normalsize\etocpage}%
     \par}
\renewcommand*\etoctoclineleaders
    {\hbox{\normalfont\normalsize\hbox to .75ex {\hss.\hss}}}
\newcommand*{\EndParWithPagenoInMarginAndLeaders}
    {\nobreak\leaders\etoctoclineleaders\hfill
     \nobreak\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}
\etocsettagdepth {surprising} {part}
\etocsettagdepth {linestyles} {part}
\etocsettagdepth {globalcmds} {paragraph}
\etocsettagdepth {custom}     {part}
\etocsettagdepth {tips}       {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{verbatim}
\endgroup

\subsection{Typesetting the TOC as a table}\label{ssec:tocastable}

Tabular cells create groups; definitions of |\etocname|, |\etocnumber|,
|\etocpage| made by \etoc are local, thus if the first cell of a row is
where the |.toc| file line is read and |\etocname| and |\etocnumber|
get defined, these definitions will be lost after the tabulation character |&|.
The source code of \etoc does allow the ``begin'' and ``finish'' parts of
the line styles to open or close groups, but the possibility of a group closed
by  a |&| for
example in the ``prefix'' part of the line style is not anticipated.
 
Another, similar, matter regards the redefinition of |\contentsline| made by
\etoc each time it typesets a TOC. It is done after the first argument to
\csb{etocsettocstyle} has been executed, hence if this argument opens a tabular,
the |etoc| redefinition of |\contentsline| will be done in the first cell of the
first row and get lost thereafter.

Thus one can not typeset a TOC directly as a tabular, with the opening and
closing specified via |\etocsettocstyle|, and using |&| and |\\| inside the
level styles.

The \etoc source code could be modified to make some relevant definitions
global, but I decided against it. Typesetting as a |tabular| (or, rather,
|longtable|) will appeal only to advanced users, and advanced users can employ
the technique explained in \autoref{tocastree}. Here is an example, giving again
a fully hyperlinked table of contents. The code follows, after the table.

\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
                      \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\\}% 
}

\newcommand*{\PrepareSubsection}{%
  \toks0 \expandafter{\etocthelinkednumber}%
  \toks2 \expandafter{\etocthelinkedname}%
  \toks4 \expandafter{\etocthelinkedpage}%
  \edef\toctablepiece{\noexpand\centering
                      \the\toks0 &\the\toks2 &\noexpand\itshape\the\toks4
                      \noexpand\\}%
}

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

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

\etocsetstyle{subsection}{}{}
  {\toctabletok\expandafter
     {\the\toctabletok &\small\begin{tabular}{@{}p{1cm}@{}p{5cm}r@{}}}%
   \PrepareSubsection\appendtotok\toctabletok\toctablepiece
   \toctabletok\expandafter{\the\toctabletok\end{tabular}&\\}}
  {}

\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

\begin{verbatim}
\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
                      \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\\}% 
}
\newcommand*{\PrepareSubsection}{%
  \toks0 \expandafter{\etocthelinkednumber}%
  \toks2 \expandafter{\etocthelinkedname}%
  \toks4 \expandafter{\etocthelinkedpage}%
  \edef\toctablepiece{\noexpand\centering\the\toks0 
                      &\the\toks2 &\noexpand\itshape\the\toks4 \noexpand\\}%
}
\etocsetstyle{part}{}{}
  {\PreparePart    \appendtotok\toctabletok\toctablepiece}{}
\etocsetstyle{section}{}{}
  {\PrepareSection \appendtotok\toctabletok\toctablepiece}{}
\etocsetstyle{subsection}{}{}
% each line does its own tabular, to allow page breaks in the long table
  {\toctabletok\expandafter
     {\the\toctabletok &\small\begin{tabular}{@{}p{1cm}@{}p{5cm}r@{}}}%
   \PrepareSubsection\appendtotok\toctabletok\toctablepiece
   \toctabletok\expandafter{\the\toctabletok\end{tabular}&\\}}
  {}

\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
\end{verbatim}

\subsection{Compatibility with other packages}
\label{etocaftertochook}


\etoc loads the package |multicol|. It is
|hyperref| aware and hopefully |hyperref| compatible! It
doesn't matter whether \etoc or |hyperref| is loaded first.

The contents of the |.toc| file (if it already exists) are read into memory by
\etoc once, at the time of \csa{usepackage\{etoc\}}. 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.

\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\mystuff}|}
    as this will make the |\label/\ref| mechanism impossible. Rather you may do
    \centeredline{|\renewcommand\etocaftertochook{\mystuff}|} 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.)
  \end{framed}
\footnotetext{contrarily to \csa{etocaftertochook},
      \csa{etocaftercontentshook} is not executed if the |tocdepth| did not
      allow the printing of the TOC.}

  \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| (done in
  the style above) 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.

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. The correct local table of
contents will be displayed only on the next |latex| run.

\etoc expects the document sectioning units to write their
data into the file having extension |.toc|, in the form of
lines containing the \csa{contentsline} command and its
arguments. The macros \csa{etocname}, \csa{etocnumber}, and
\csa{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 is possible to customize (using package |tocloft| for
example) throughout the document the macros \csa{l@section},
\csa{l@subsection} ... and the effect will be seen in the next
table of contents typeset by \etoc in compatibility mode.

It is possible to use simultaneously \etoc and 
{\color{niceone}|tableof|}\footnote{\url{http://ctan.org/pkg/tableof}}. For the
advanced uses such as what is done in \autoref{ssec:molecule} it is
  important 
to know that |tableof| adds one level of grouping inside the |.toc| file itself.
So when one needs to make some information \csa{global}, one can not wait to be
at the level of the second argument of \csa{etocsettocstyle}, as
|tableof| will already have closed the group then. The \csa{global} things (on
volatile data) must
be done at the latest in the \meta{finish} part of the top (or last) sectioning
  level used. 
This only applies of course to \csa{tableofcontents} or
  \csa{localtableofcontents} following the 
  \csa{nexttocwithtags}|{required}||{forbidden}| command from |tableof|.

And when the commands
  \csa{tableof} or \csa{tablenotof} of package 
  |tableof| are used,
  they typeset the table of contents according to the document class defaults:
  to benefit from the \etoc styles, it is mandatory to use either
  \csa{tableofcontents}, or \csa{localtableofcontents} or one of the other \etoc
  commands, and |tableof (v1.1)| will influence the outcome only if 
  \csa{nexttocwithtags}|{required}||{forbidden}| was added before the table of
  contents typesetting command.

\subsection{\TeX nical matters}

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

On the other hand \csa{etocthename}, \csa{etocthenumber},
\csa{etocthepage} do not represent |hyperref| links, and are
\emph{not} protected against expansion.

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

\subsection{Errors and catastrophes}

  After using \csa{etocsetstyle} for one level, the remaining
  uncustomized levels use the \etoc default styles (those
  which are activated by \csa{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 (but this should never be)
  these instructions should be done 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}

\section{Timestamp}

This is the documentation as of \texttt{\docdate}, printed from the source file
with the time stamp \texttt{\dtxtimestamp}. The package version is
\texttt{\jfbpkgversion}, of \texttt{\jfbpkgdate}.


\section{License, installation}

\begin{verbatim}
% Copyright (C) 2012-2013 by 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, either
%     version 1.3c of this license or (at your option) any later
%     version. 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. 
%
% This Work has the LPPL maintenance status Author-Maintained.
%
% 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.dvi, etoc.pdf, etoc.ins, etoc.tex
%
% Extraction of the package (.sty) and driver (.tex) files:
%  - if etoc.ins is present:   tex etoc.ins
%  - without etoc.ins:         tex etoc.dtx 
%
% It is also possible to run latex/pdflatex directly on etoc.dtx
%
% At least three ways to produce etoc.pdf:
%  (1) latex etoc.dtx (three times), then dvips, then ps2pdf
%  (2) pdflatex etoc.dtx (three times)
%  (3) latex etoc.tex (three times), then dvipdfmx
%
% Method (3) produces the smallest pdf files.
% Options can be set in etoc.tex:
%  - scrdoc class options (paper size, font size, ...) 
%  - with or without source code, 
%  - with dvipdfmx or with latex/pdflatex. 
%
% 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
%
% etoc.tex, etoc.ins, etoc.aux, etoc.toc, etc... may be discarded
%
\end{verbatim}



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

\section{Change history}

\setlength{\columnsep}{\etoccolumnsep}

\makeatletter

\def\jfverbatim{\@beginparpenalty \predisplaypenalty 
  \parindent \z@ 
  \parfillskip \@flushglue 
  \parskip \tw@\p@ plus 1fil\relax
  \let \do \@makeother \dospecials
  \catcode`\~\z@ 
  \footnotesize\normalfont\baselineskip10pt\relax
  \frenchspacing \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

\everypar{\leftskip\jfverbadim\bgroup
          \def\par{\egroup\jfverbadim\z@\@@par}%
          \def\jfverbaspace#1{\ifcat\noexpand#1\noexpand~\unskip\else\ \fi#1}}

\begingroup\obeyspaces\def\x{\endgroup%
\def {\ifvmode\advance\jfverbadim.5em\relax\else\expandafter\jfverbaspace\fi}}\x

\makeatother

\begin{multicols}{2}
\begin{jfverbatim}
v1.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).

v1.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).

v1.07h [2013/10/16]

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

v1.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).


v1.07f [2013/03/07]

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


v1.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.

v1.07d [2013/02/24]

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


v1.07b [2013/02/02]

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

   additional examples in the documentation.

   
v1.07 [2013/01/29]

   new commands:

      \etocthename, \etocthenumber, \etocthepage, \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.


v1.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.


v1.05 [2012/12/01]

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

   compatibility with KOMA-script and memoir document
   classes.


v1.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}

   
v1.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

% \def\MacroFont{\ttfamily\hyphenchar\font45 \baselineskip11pt\relax }

\section{Implementation}

\StopEventually{\normalsize\ifnum\NoSourceCode=1
   \texttt{%
     This documentation has been compiled without inclusion of the source
     code. To produce the documentation with source code included:\endgraf
     \ \ \ \ run latex on etoc.dtx (or on etoc.tex if available), \endgraf
     \ \ \ \ (or first run tex on etoc.ins if available to produce
     etoc.tex)\endgraf 
     \ \ \ \ then twice latex on etoc.tex,\endgraf 
     \ \ \ \ then dvipdfmx on etoc.dvi\endgraf}
\fi
\end{document}}

% Writing-up source code comments is hopefully for a future
% release. 

% 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.)
\makeatletter
\begingroup
\topsep\MacrocodeTopsep
\trivlist\parskip\z@\item[]
\macro@font
\leftskip\@totalleftmargin  \advance\leftskip\MacroIndent
\rightskip\z@  \parindent\z@  \parfillskip\@flushglue
\global\@newlistfalse \global\@minipagefalse
\ifcodeline@index
  \everypar{\global\advance\c@CodelineNo\@ne
  \llap{\theCodelineNo\ \hskip\@totalleftmargin}}%
\fi
\string\ProvidesPackage\string{\jfbpkgname\string}\par
\noindent\space [\jfbpkgdate\space\jfbpkgversion\space\jfbpkgdescription]\par
\nointerlineskip
\global\@inlabelfalse
\endtrivlist
\endgroup
\makeatother

% 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}
\RequirePackage{multicol}
\DeclareOption*{\PackageWarning{etoc}{Option `\CurrentOption' is unknown.}}
\ProcessOptions\relax
%    \end{macrocode}
% placeholder for comments
%    \begin{macrocode}
\newtoks\Etoc@toctoks
\def\Etoc@par{\par}
\def\etocinline{\def\Etoc@par{}}
\let\etocnopar\etocinline
\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@part 
%    \end{macrocode}
% placeholder for comments
%    \begin{macrocode}
\newif\ifEtoc@localtoc
\newif\ifEtoc@skipthisone
\newif\ifEtoc@stoptoc
\newif\ifEtoc@notactive
\newcounter{etoc@tocid}
\newif\ifEtoc@mustclosegroup
\def\etoc@{\etoc@}
%    \end{macrocode}
% |1.07g| uses a second counter; this could be avoided, but ok, let's not be
% that strict. 
%    \begin{macrocode}
\newcounter{etoc@tocdepth}% 1.07g
%    \end{macrocode}
% placeholder for comments
%    \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
\let\Etoc@localtop\Etoc@@minustwo@@
\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}
% placeholder for comments
%    \begin{macrocode}
\let\Etoc@levellist\@empty
\def\Etoc@newlevel#1{% 
    \def\Etoc@levellist@elt{\noexpand\Etoc@levellist@elt\noexpand}%
    \edef\Etoc@levellist{\Etoc@levellist\Etoc@levellist@elt#1}}
\def\etocsetlevel#1#2{%
 \expandafter\Etoc@newlevel\csname l@#1\endcsname
 \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}
% placeholder for comments
%    \begin{macrocode}
\def\Etoc@setflags #1{%
  \ifcase #1\relax
      \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
    \ifnum#1=\m@ne
      \global\Etoc@vfalse
      \global\Etoc@ivfalse
      \global\Etoc@iiifalse
      \global\Etoc@iifalse
      \global\Etoc@ifalse
      \global\Etoc@false
      \global\Etoc@jtrue
    \else
      \global\Etoc@vfalse
      \global\Etoc@ivfalse
      \global\Etoc@iiifalse
      \global\Etoc@iifalse
      \global\Etoc@ifalse
      \global\Etoc@false
      \global\Etoc@jfalse
      \global\Etoc@jjtrue
    \fi
  \fi}
%    \end{macrocode}
% placeholder for comments
%    \begin{macrocode}
\AtBeginDocument{%
\@ifpackageloaded{parskip}{\Etoc@parskiptrue}{}%
\@ifpackageloaded{hyperref}{\Etoc@hyperreftrue
                            \def\Etoc@et@hop#1#2#3#4#5{#1{#3}{#4}{#5}#2}%
                            \long\def\Etoc@gobblesixorfive#1#2#3#4#5#6{}}
                           {\def\Etoc@et@hop#1#2#3#4{#1{#3}{#4}#2}%
                            \long\def\Etoc@gobblesixorfive#1#2#3#4#5{}}%
}
%    \end{macrocode}
% placeholder for comments
%    \begin{macrocode}
\def\Etoc@swa#1{%
        \Etoc@et@hop 
          {\Etoc@savedcontentsline{#1}}
          {\Etoc@prefix\Etoc@contents}}
\def\Etoc@swb#1{%
        \Etoc@et@hop 
          {\Etoc@savedcontentsline{#1}}
          {\Etoc@contents}}
\let\etocskipfirstprefix\@thirdofthree 
%    \end{macrocode}
% placeholder for comments
%    \begin{macrocode}
\def\Etoc@etoccontentsline#1{%
  \global\expandafter\let\expandafter\Etoc@tmp\csname Etoc@#1@@\endcsname
  \Etoc@skipthisonefalse
  \let\Etoc@next\Etoc@gobblesixorfive
  \ifnum\Etoc@tmp=\Etoc@@six@@
      \Etoc@skipthisonetrue
  \else
    \ifEtoc@localtoc
      \let\Etoc@prenext\relax
      \ifEtoc@stoptoc 
        \Etoc@skipthisonetrue 
      \fi
      \ifnum\Etoc@tmp<\Etoc@localtop 
        \def\Etoc@prenext{\global\Etoc@stoptoctrue}%
        \Etoc@skipthisonetrue
      \fi
      \ifEtoc@notactive
        \def\Etoc@prenext{\Etoc@setflags{\Etoc@tmp}}%
        \Etoc@skipthisonetrue
      \fi
      \Etoc@prenext
    \fi
  \fi
  \ifnum\c@tocdepth<\Etoc@tmp\relax\else
  \ifEtoc@skipthisone\else
  \global\let\Etoc@next\relax  
  \ifcase\Etoc@tmp 
      \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@ \else \def\Etoc@next{\Etoc@begin@zero}\fi
      \def\Etoc@contents{\Etoc@contents@zero}%
      \def\Etoc@prefix{\Etoc@prefix@zero}%
  \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
      \ifEtoc@i \else \def\Etoc@next{\Etoc@begin@one}\fi
      \def\Etoc@contents{\Etoc@contents@one}%
      \def\Etoc@prefix{\Etoc@prefix@one}%
  \or
      \ifEtoc@v \Etoc@end@five\fi
      \ifEtoc@iv \Etoc@end@four\fi
      \ifEtoc@iii \Etoc@end@three\fi
      \ifEtoc@ii \else \def\Etoc@next{\Etoc@begin@two}\fi
      \def\Etoc@contents{\Etoc@contents@two}%
      \def\Etoc@prefix{\Etoc@prefix@two}%
  \or
      \ifEtoc@v \Etoc@end@five\fi
      \ifEtoc@iv \Etoc@end@four\fi
      \ifEtoc@iii \else \def\Etoc@next{\Etoc@begin@three}\fi
      \def\Etoc@contents{\Etoc@contents@three}%
      \def\Etoc@prefix{\Etoc@prefix@three}%
  \or 
      \ifEtoc@v \Etoc@end@five\fi 
      \ifEtoc@iv \else \def\Etoc@next{\Etoc@begin@four}\fi
      \def\Etoc@contents{\Etoc@contents@four}%
      \def\Etoc@prefix{\Etoc@prefix@four}%
  \or 
      \ifEtoc@v \else \def\Etoc@next{\Etoc@begin@five}\fi
      \def\Etoc@contents{\Etoc@contents@five}%
      \def\Etoc@prefix{\Etoc@prefix@five}%
  \else
    \ifnum\Etoc@tmp=\m@ne
      \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 \else \def\Etoc@next{\Etoc@begin@minusone}\fi
      \def\Etoc@contents{\Etoc@contents@minusone}%
      \def\Etoc@prefix{\Etoc@prefix@minusone}%
    \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 \else \def\Etoc@next{\Etoc@begin@minustwo}\fi
      \def\Etoc@contents{\Etoc@contents@minustwo}%
      \def\Etoc@prefix{\Etoc@prefix@minustwo}%
      \fi
  \fi
    \ifnum\Etoc@tmp=\m@ne\Etoc@parttrue\else\Etoc@partfalse\fi
    \Etoc@setflags{\Etoc@tmp}%
  \fi\fi
  \Etoc@next
  \@firstoftwo{\Etoc@swa{#1}}{\Etoc@swb{#1}}}
%    \end{macrocode}
% |[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 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.
%
% Then |1.07| added \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}. 
%
% One could now define \csa{etocname}, etc ... to be the robust versions of
% \csa{etocthelinkedname}, etc ..., but the original definitions are kept by
% sentimentalism. |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.
%    \begin{macrocode}
\def\Etoc@lxyz #1#2{% 
     \@namedef {etoclink }{\leavevmode}%        fall-back
     \let\etocthelink         \@empty  %        fall-back
     \@namedef {etocname }{\leavevmode #1}% fall-back (perhaps linked)
     \def\etocthename         {#1}%  (if link, will be removed later)
     \def\etocthelinkedname   {#1}%  will probably get redefined 
     \@namedef {etocpage }{\leavevmode #2}%      (perhaps linked)
   \Etoc@getthepage #2\etoc@ % defines also \etocthelinkedpage (and \etoclink)
   \Etoc@getnb #1\relax\relax\etoc@  % gets number *and* name, and \etoclink
   \ifEtoc@number\else               
      \ifEtoc@part 
        \Etoc@getit #1\hspace\relax\etoc@   % additional job for parts
      \fi
   \fi}
%    \end{macrocode}
% placeholder for comments
%    \begin{macrocode}
\def\Etoc@getthepage #1{%
  \let\Etoc@next\Etoc@getthepage@nohyp
  \ifEtoc@hyperref\ifx #1\hyper@linkstart
    \let\Etoc@next\Etoc@getthepage@hyp
  \fi\fi
  \Etoc@next #1%
}
\def\Etoc@getthepage@nohyp #1\etoc@ {%
    \def\etocthepage       {#1}%
    \def\etocthelinkedpage {#1}%
}
\def\Etoc@getthepage@hyp #1#2#3#4#5\etoc@ {%
  \@namedef{etoclink } ##1{\leavevmode #1{#2}{#3}{##1}#5}%
  \edef\etocthelink ##1{\noexpand\hyperlink {#3}{##1}}%
  \def\etocthepage {#4}%
  \toks@ {#4}%
  \edef\etocthelinkedpage {\noexpand\hyperlink {#3}{\the\toks@}}%
}
%
\def\Etoc@getnb #1{%
  \let\Etoc@next\Etoc@getnb@nohyp
  \ifEtoc@hyperref\ifx #1\hyper@linkstart
    \let\Etoc@next\Etoc@getnb@hyp
  \fi\fi
  \Etoc@next #1%
}
%
\def\Etoc@getit #1{%
  \let\Etoc@next\Etoc@getit@nohyp
  \ifEtoc@hyperref\ifx #1\hyper@linkstart
    \let\Etoc@next\Etoc@getit@hyp
  \fi\fi
  \Etoc@next #1%
}
%    \end{macrocode}
% placeholder for comments
%    \begin{macrocode}
\def\Etoc@getnb@nohyp #1#2#3\etoc@ {%
    \def\Etoc@getname ##1\relax\relax\etoc@ {%
      \@namedef {etocname }{\leavevmode ##1}%
      \def\etocthename       {##1}%
      \def\etocthelinkedname {##1}%
     }%
  \ifx #1\numberline
    \@namedef {etocnumber }{\leavevmode #2}%
    \def\etocthenumber       {#2}%
    \def\etocthelinkednumber {#2}%
    \Etoc@numbertrue
    \Etoc@getname #3\etoc@
  \else % then \etocthename and \etocthelinkedname already defined
    \@namedef {etocnumber }{\leavevmode}%
    \let\etocthenumber       \@empty
    \let\etocthelinkednumber \@empty
    \Etoc@numberfalse
  \fi
}
%    \end{macrocode}
% placeholder for comments
%    \begin{macrocode}
\def\Etoc@getnb@hyp #1#2#3#4#5#6\etoc@ {%
         \def\Etoc@getname ##1\relax\relax\etoc@ {%
          \@namedef {etocname }{\leavevmode #1{#2}{#3}{##1}#5}%
          \def\etocthename {##1}%
          \toks@           {##1}%
          \edef\etocthelinkedname {\noexpand\hyperlink {#3}{\the\toks@}}%
         }%
         \def\Etoc@getnbr ##1##2##3\etoc@ {%
          \ifx ##1\numberline
            \@namedef {etocnumber }{\leavevmode #1{#2}{#3}{##2}#5}%
            \def\etocthenumber {##2}%
            \toks@             {##2}%
            \edef\etocthelinkednumber {\noexpand\hyperlink {#3}{\the\toks@}}%
            \Etoc@numbertrue
            \Etoc@getname ##3\etoc@
          \else
            \@namedef {etocnumber }{\leavevmode}%
            \let\etocthenumber       \@empty
            \let\etocthelinkednumber \@empty
            \Etoc@numberfalse
            \def\etocthename {#4}%
            \toks@           {#4}%
            \edef\etocthelinkedname {\noexpand\hyperlink {#3}{\the\toks@}}%
          \fi
         }%
  \@namedef {etoclink }##1{\leavevmode #1{#2}{#3}{##1}#5}%
  \edef\etocthelink ##1{\noexpand\hyperlink {#3}{##1}}%
  \Etoc@getnbr #4\relax\relax\etoc@
}
%    \end{macrocode}
% placeholder for comments
%    \begin{macrocode}
\def\Etoc@getit@nohyp #1\hspace#2#3\etoc@ {%
    \def\Etoc@getname ##1\hspace\relax\etoc@ {%
       \@namedef {etocname }{\leavevmode ##1}%
       \def\etocthename       {##1}%
       \def\etocthelinkedname {##1}%
    }%
  \ifx\relax#2\else 
        \@namedef {etocnumber }{\leavevmode #1}%
        \def\etocthenumber       {#1}%
        \def\etocthelinkednumber {#1}%
        \Etoc@numbertrue
        \Etoc@getname #3\etoc@
  \fi
}
%    \end{macrocode}
% placeholder for comments
%    \begin{macrocode}
\def\Etoc@getit@hyp #1#2#3#4#5#6\etoc@ {%
    \def\Etoc@getname ##1\hspace\relax\etoc@ {%
       \@namedef {etocname }{\leavevmode #1{#2}{#3}{##1}#5}%
       \def\etocthename {##1}%
       \toks@           {##1}%
       \edef\etocthelinkedname {\noexpand\hyperlink {#3}{\the\toks@}}%
    }%
    \def\Etoc@getnbr ##1\hspace##2##3\etoc@ {%
       \ifx\relax##2\else
         \@namedef {etocnumber }{\leavevmode #1{#2}{#3}{##1}#5}%
         \def\etocthenumber {##1}%
         \toks@             {##1}%
         \edef\etocthelinkednumber {\noexpand\hyperlink {#3}{\the\toks@}}%
         \Etoc@numbertrue
         \Etoc@getname ##3\etoc@
       \fi
    }%
  \Etoc@getnbr #4\hspace\relax\etoc@
}
%    \end{macrocode}
% placeholder for comments
%    \begin{macrocode}
\let\etocthename   \@empty
\let\etocthenumber \@empty
\let\etocthepage   \@empty
\let\etocthelinkedname   \@empty
\let\etocthelinkednumber \@empty
\let\etocthelinkedpage   \@empty
\let\etocthelink   \@empty
\DeclareRobustCommand*{\etocname}  {}
\DeclareRobustCommand*{\etocnumber}{}
\DeclareRobustCommand*{\etocpage}  {}
\DeclareRobustCommand*{\etoclink}  {}
\DeclareRobustCommand*{\etocifnumbered}
   {\ifEtoc@number\expandafter\@firstoftwo\else\expandafter\@secondoftwo\fi}
%    \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
}
\Etoc@toctoks {}% (superfluous, but for clarity)
\IfFileExists{\jobname .toc}
    {{\endlinechar=-1 
      \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}
% placeholder for comments
%    \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
\ifEtoc@standard
    \etoc@setstyle{@minustwo}{}{}{}{}%
    \etoc@setstyle{@minusone}{}{}{}{}%
    \etoc@setstyle{@zero}{}{}{}{}%
    \etoc@setstyle{@one}{}{}{}{}%
    \etoc@setstyle{@two}{}{}{}{}%
    \etoc@setstyle{@three}{}{}{}{}%
    \etoc@setstyle{@four}{}{}{}{}%
    \etoc@setstyle{@five}{}{}{}{}%
\else
    \def\Etoc@levellist@elt##1{\let##1\Etoc@lxyz}%
    \Etoc@levellist
    \let\booknumberline\numberline
    \let\partnumberline\numberline
    \let\chapternumberline\numberline
\fi
\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}
% placeholder for comments
%    \begin{macrocode}
\def\etoc@@startlocaltoc#1#2{%
\let\Etoc@next\relax
    \ifEtoc@localtoc 
    \ifEtoc@notactive
        \ifnum #1=#2\relax
          \ifEtoc@jj  \let\Etoc@localtop\Etoc@@minusone@@ \fi
          \ifEtoc@j   \let\Etoc@localtop\Etoc@@zero@@  \fi
          \ifEtoc@    \let\Etoc@localtop\Etoc@@one@@   \fi
          \ifEtoc@i   \let\Etoc@localtop\Etoc@@two@@   \fi
          \ifEtoc@ii  \let\Etoc@localtop\Etoc@@three@@ \fi
          \ifEtoc@iii \let\Etoc@localtop\Etoc@@four@@  \fi
          \ifEtoc@iv  \let\Etoc@localtop\Etoc@@five@@  \fi
          \ifEtoc@v   \let\Etoc@localtop\Etoc@@six@@   \fi
          \def\Etoc@next{\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\fi
\Etoc@next}
\let\etoc@startlocaltoc\@gobble
%    \end{macrocode}
% |1.07g| suppresses the printing of |--unknown etoc ref: run latex again--| as
% sometimes one uses |\localtableofcontents| to prepare something else, and one
% does not want at any output of text at all even in an intermediate run.
% 
% Also |1.07g| adds |\etocaftertochook| to help with
% |\invisiblelocaltableofcontents| (and then I did |\etocsetnexttocdepth|).
% |1.07h| makes the hook used by |\etocsetnexttocdepth| private.
%    \begin{macrocode}
\def\Etoc@localtableofcontents#1{%
    \edef\Etoc@tmp{#1}%
    \ifnum\Etoc@tmp<\@ne
    \PackageWarning{etoc}
       {Unknown toc id: run LaTeX to get references right}% 
    \let\Etoc@next\@gobble\else\let\Etoc@next\@firstofone\fi
    \Etoc@next
    {\edef\etoc@startlocaltoc##1{%
         \noexpand\etoc@@startlocaltoc{##1}{#1}}
    \Etoc@localtoctrue
    \let\Etoc@localtop\Etoc@@minustwo@@
    \global\Etoc@stoptocfalse
    \global\Etoc@notactivetrue
    \Etoc@tableofcontents}%
    \endgroup\ifEtoc@mustclosegroup\endgroup\fi
    \Etoc@aftertochook % 1.07h
    \etocaftertochook % 1.07g
}
%    \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}
% placeholder for comments
%    \begin{macrocode}
\def\Etoc@t@bleofcontents{%
 \ifx\Etoc@nexttoken\label
    \def\Etoc@next{\expandafter\Etoc@label\@gobble}\else
 \ifx\Etoc@nexttoken\@sptoken
    \let\Etoc@next\Etoc@again\else
 \ifEtoc@tocwithid
    \def\Etoc@next{\Etoc@localtableofcontents{\c@etoc@tocid}}%
 \else
    \ifx\Etoc@nexttoken\ref
       \def\Etoc@next{\expandafter\Etoc@ref\@gobble}%
    \else
       \def\Etoc@next{\Etoc@localtocfalse
                      \global\Etoc@notactivefalse
                      \Etoc@tableofcontents
                      \endgroup
                      \ifEtoc@mustclosegroup\endgroup\fi
                      \Etoc@aftertochook % 1.07h
                      \etocaftertochook % 1.07g 
                      }%
    \fi
 \fi\fi\fi\Etoc@next}
%    \end{macrocode}
% |1.07g| for consistency Etoc@ prefix added.
%    \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{\arabic{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|.
%    \begin{macrocode}
\let\etocaftertitlehook    \@empty
\let\etocaftercontentshook \@empty
\def\etoctableofcontents{%
   \Etoc@openouttoc
   \Etoc@par
   \begingroup % closed in \Etoc@t@bleofcontents or \Etoc@localtableofcontents
     \def\etoc@startlocaltoc##1{\etoc@@startlocaltoc{##1}{\c@etoc@tocid}}%
     \@ifstar
     {\def\Etoc@aftertitlehook{}\Etoc@table@fcontents}
     {\let\Etoc@aftertitlehook\etocaftertitlehook\Etoc@table@fcontents}}
\let\tableofcontents\etoctableofcontents
\newcommand*\localtableofcontents{%
   \Etoc@openouttoc
   \Etoc@par
   \begingroup % closed in \Etoc@t@bleofcontents or \Etoc@localtableofcontents
     \@ifstar
     {\def\Etoc@aftertitlehook{}\Etoc@localtable@fcontents}
     {\let\Etoc@aftertitlehook\etocaftertitlehook\Etoc@localtable@fcontents}}
%    \end{macrocode}
% placeholder for comments.
%    \begin{macrocode}
\newcommand\etocsettocstyle[2]{%
\def\Etoc@tableofcontents
{\ifnum\c@tocdepth>\Etoc@minf
   \let\Etoc@@next\@firstofone\else
   \let\Etoc@@next\@gobble
\fi
\Etoc@@next{\Etoc@storetocdepth % 1.07g
            #1\ifEtoc@parskip\parskip\z@skip\fi %1.07d
              \Etoc@aftertitlehook
              \let\Etoc@savedcontentsline\contentsline
              \let\contentsline\Etoc@etoccontentsline 
              \Etoc@toctoc
              \let\Etoc@@next\relax
              \ifEtoc@tocwithid\else
                \ifEtoc@localtoc
                \ifEtoc@notactive
                  \def\Etoc@@next{\Etoc@localtocfalse
                           \global\Etoc@notactivefalse
                           \Etoc@toctoc}%
                \fi\fi
              \fi
            \Etoc@@next
            \Etoc@resettocdepth  % 1.07g
            \etocaftercontentshook
            #2\@nobreakfalse}}}  % 1.07d: \@nobreakfalse moved here
%    \end{macrocode}
% placeholder for comments
%    \begin{macrocode}
\def\etocsetstyle{\Etoc@standardfalse\etoc@setstyle}
\long\def\etoc@setstyle#1#2#3#4#5{%
\long\expandafter\def
     \csname Etoc@begin@\csname Etoc@#1@\endcsname\endcsname {#2}%
\long\expandafter\def
     \csname Etoc@prefix@\csname Etoc@#1@\endcsname\endcsname {#3}%
\long\expandafter\def
     \csname Etoc@contents@\csname Etoc@#1@\endcsname\endcsname {#4}%
\long\expandafter\def
     \csname Etoc@end@\csname Etoc@#1@\endcsname\endcsname {#5}}
%    \end{macrocode}
% placeholder for comments
%    \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.~}
\def\etocpartname       {\partname}
\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.
%
%    \begin{macrocode}
\def\etocdefaultlines{\Etoc@standardfalse % 
%% `book' in memoir class:
\etoc@setstyle{@minustwo}
  {\addpenalty\@M\etocskipfirstprefix}
  {\addpenalty\@secpenalty}
  {\begingroup 
   \etocfontminustwo
   \addvspace{\etocsepminustwo}%
   \parindent \z@ 
   \leftskip  \etocminustwoleftmargin
   \rightskip \etocminustworightmargin
   \parfillskip \@flushglue
   \vbox{\etocifnumbered{\etocbookname\enspace\etocnumber:\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{\etocpartname\enspace\etocnumber.\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}
   \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.
%    \begin{macrocode}
\newcommand\etocmulticolstyle[2][\etocdefaultnbcol]{%
\etocsettocstyle
   {\let\etocoldpar\par
    \addvspace{\etocabovetocskip}%
    \ifnum #1>\@ne\let\Etoc@next\@firstoftwo
         \else \let\Etoc@next\@secondoftwo\fi
    \Etoc@next{%
    \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\let\Etoc@next\@firstofone
         \else \let\Etoc@next\@gobble\fi
    \Etoc@next{\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\let\Etoc@next\@firstoftwo
         \else \let\Etoc@next\@secondoftwo\fi
    \Etoc@next
       {\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\let\Etoc@next\@firstofone
         \else \let\Etoc@next\@gobble\fi
    \Etoc@next{\end{multicols}}%
    \addvspace{\etocbelowtocskip}}}
%    \end{macrocode}
% placeholder for comments
%    \begin{macrocode}
\long\def\etocframedmphook{\relax}
\def\etocbkgcolorcmd{\relax}
\def\Etoc@relax{\relax}
\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\let\Etoc@next\@firstoftwo
    \else \let\Etoc@next\@secondoftwo\fi
        \Etoc@next
        {\multicolpretolerance\etocmulticolpretolerance
        \multicoltolerance\etocmulticoltolerance
        \setlength{\columnsep}{\etoccolumnsep}%
        \setlength{\multicolsep}{\etocmulticolsep}%
        \begin{multicols}{#1}}  
        {\pretolerance\etocmulticolpretolerance
         \tolerance\etocmulticoltolerance}}
     {\ifnum #1>\@ne\let\Etoc@next\@firstofone
         \else \let\Etoc@next\@gobble\fi
    \Etoc@next{\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
\def\etocmemoirtoctotocfmt #1#2{%
    \def\Etoc@addsuitablecontentsline{\addcontentsline {toc}{#1}{#2}}%
    \renewcommand*\etocaftertitlehook{%
      \ifmem@em@starred@listof
      \else\phantomsection\aftergroup\Etoc@addsuitablecontentsline\fi}}
\def\etocmemoirstyle{%
    \etocsettocstyle
        {\ensureonecol \par \begingroup \@nameuse {@tocmaketitle}
         \Etoc@aftertitlehook\let\Etoc@aftertitlehook\relax
         \parskip \cftparskip \@nameuse {cfttocbeforelisthook}}
        {\@nameuse {cfttocafterlisthook}\endgroup\restorefromonecol}}
%    \end{macrocode}
% placeholder for comments
%    \begin{macrocode}
\def\etocscrartclstyle{%
    \etocsettocstyle
        {\let\if@dynlist\if@tocleft
         \iftocfeature {toc}{onecolumn}
             {\iftocfeature {toc}{leveldown}
              {}
              {\if@twocolumn \aftergroup \twocolumn \onecolumn \fi }}
             {}%
         \tocbasic@listhead {\listoftocname}%
         \begingroup \expandafter \expandafter \expandafter 
         \endgroup \expandafter 
         \ifx 
             \csname microtypesetup\endcsname \relax 
         \else 
             \iftocfeature {toc}{noprotrusion}{}
                 {\microtypesetup {protrusion=false}%
                  \PackageInfo {tocbasic}%
                  {character protrusion at toc deactivated}}%
         \fi
         \setlength {\parskip }{\z@ }%
         \setlength {\parindent }{\z@ }%
         \setlength {\parfillskip }{\z@ \@plus 1fil}% 
         \csname tocbasic@@before@hook\endcsname
         \csname tb@toc@before@hook\endcsname}
        {\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}}{}
\@ifclassloaded{memoir}
    {\renewcommand*\etocfontone{\normalfont\normalsize}
     \etocmemoirtoctotocfmt{chapter}{\contentsname}%
     \renewcommand*\etocstandarddisplaystyle{\etocmemoirstyle}
     \Etoc@redefetocstyle{chapter}}{}
%    \end{macrocode}
% placeholder for comments
%    \begin{macrocode}
\def\Etoc@addtocontents #1#2%
    {\ifEtoc@hyperref
       \addtocontents {toc}{\protect\contentsline 
                {#1}{#2}%
                {\thepage }{\@currentHref }}%
     \else
       \addtocontents {toc}{\protect\contentsline 
          {#1}{#2}{\thepage }}%
     \fi}
\def\Etoc@addcontentsline@ #1#2#3%
    {\@namedef{toclevel@#1}{#3}%
     \addcontentsline {toc}{#1}{#2}}
\DeclareRobustCommand*{\etoctoccontentsline}
    {\@ifstar{\Etoc@addcontentsline@}{\Etoc@addtocontents}}
%    \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| 
% (|v1.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.
%
%    \begin{macrocode}
\def\Etoc@storetocdepth {\global\c@etoc@tocdepth\c@tocdepth }
\def\Etoc@resettocdepth {\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.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}}}
\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.
%    \begin{macrocode}
\def\Etoc@tocvsec@err #1{\PackageError {etoc}
        {the command \protect#1\space is incompatible with etoc} 
        {use \protect\etocsettocdepth.toc as replacement (check the manual)}%
}%
\AtBeginDocument {%
   \@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|
%    \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}}
     {\edef\Etoc@aftertochook {\global\c@tocdepth\the\c@tocdepth\space
                              \let\noexpand\Etoc@aftertochook\noexpand\@empty }%
       \global\c@tocdepth\csname Etoc@#1@@\endcsname}%
}%
%    \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 }{}}%
%    \end{macrocode}
% Initializations.
%    \begin{macrocode}
\def\etocstandardlines {\Etoc@standardtrue}
\def\etoctoclines      {\Etoc@standardfalse}
\etocdefaultlines
\etocstandardlines 
\etocstandarddisplaystyle
\etocobeytoctocdepth 
\etocobeydepthtags
\let\Etoc@aftertochook\@empty % private for \etocsetnexttocdepth
\let\etocaftertochook \@empty % public for end user.
\endinput
%    \end{macrocode}
% \MakePercentComment
\CharacterTable
 {Upper-case    \A\B\C\D\E\F\G\H\I\J\K\L\M\N\O\P\Q\R\S\T\U\V\W\X\Y\Z
  Lower-case    \a\b\c\d\e\f\g\h\i\j\k\l\m\n\o\p\q\r\s\t\u\v\w\x\y\z
  Digits        \0\1\2\3\4\5\6\7\8\9
  Exclamation   \!     Double quote  \"     Hash (number) \#
  Dollar        \$     Percent       \%     Ampersand     \&
  Acute accent  \'     Left paren    \(     Right paren   \)
  Asterisk      \*     Plus          \+     Comma         \,
  Minus         \-     Point         \.     Solidus       \/
  Colon         \:     Semicolon     \;     Less than     \<
  Equals        \=     Greater than  \>     Question mark \?
  Commercial at \@     Left bracket  \[     Backslash     \\
  Right bracket \]     Circumflex    \^     Underscore    \_
  Grave accent  \`     Left brace    \{     Vertical bar  \|
  Right brace   \}     Tilde         \~}

\CheckSum{2909}

\csname check@checksum\endcsname
\Finale
%%
%% End of file `etoc.dtx'.
