# Understanding titletoc example (and vertical alignment on line)

EDIT: TLDR summary (as I wrote in comments): What I want from this question (and couple of others referenced herein) is: -- section number (label) to be top-aligned with the title + AND I want the title bottom-aligned with the page number - on the same line -- when a TOC entry is typeset (I've used frames just for visual debugging).

I asked Changing vertical alignment of items in middle of line (for ToC entry), and got a suggestion there that I should try titletoc. And indeed, indeed, in the documentation, pg. 14, there is an example that looks like exactly what I want (the emphasized part):

... however, I simply cannot get a working example for this.

First problem is I don't really understand where are those particular <left> and <right> (and in the PDF, I cannot search for the brackets included), or how I can change them. Closest I can see in the manual for now is these definitions:

\titlecontents{ <section> }[ <left> ]{ <above-code> }
{ <numbered-entry-format> }{ <numberless-entry-format> }
{ <filler-page-format> }[ <below-code> ]

\contentsmargin[ <correction> ]{ <right> }


... so apparently, I set <left> in \titlecontents - and I set <right> in \contentsmargin; correct ?!

In particular, the manual continues:

All you need is to put these elements in the right way. If you have reserved the space with \hspace*{-2pc}, simply put a box 2 pc width containing the section label or page so that this space will be retrieved; ...

... but I don't understand two things:

• Where is this reservation of space with \hspace*{-2pc} done? (in \titlecontents?)
• Where should this box 2 pc width be put? (in \titlecontents? or in the \addtocontents line?)

I'm trying to build an example based on this (MWE below), and closest I can get is to an analysis of this snippet (where letters are added for visual debugging purposes):

\contentsmargin{-4em}
\titlecontents{part}[2.3em]
{A}
{B\filbreak C\contentslabel{2.3em}D}
{E\fbox{\hspace*{2.3em}F\rule{2.3em}{2pt}}}
{G\titlerule*[1pc]{.}H\contentspage I\nobreak}


... which results with:

... and all I can say is that:

• TOC entry starts with A (<above-code>)
• B, C, D are ignored (<numbered-entry-format>)
• E starts right after (F also shown), until the section number is typeset (<numberless-entry-format>)
• Title is typeset as is; if there is no paragraph environment with defined width (in \addtocontents), a long line will not break (the manual is not clear on this, when giving the illustration)
• If I use a minipage to set the width of the entry - then again everything is centered, and I get back to the same problem as in original question
• G is printed before the leader dots - H (and, I guess, also I) are printed after the leader dots, but before page number (<filler-page-format>);
• I don't get what \contentspage is supposed to do there

... and thats about all I can understand; and I don't really see how and would help me get the TOC entry format I want.

Even worse, when I build the MWE with pdflatex, it notifies of this:

(./test.aux) )
(see the transcript file for additional information)pdfTeX warning (dest): name
{\040\\unhbox\040\\voidb@x\040\\setbox\040\\@tempboxa\040\\hbox\040{\\color@beg
ingroup\040\\kern\040\\fboxsep\040{\040part.III}\\kern\040\\fboxsep\040\\endgra
r\040\\@tempdima\040\\hbox\040{\\vbox\040{\\hrule\040height\\fboxrule\040\\hbox
\040{\\vrule\040width\\fboxrule\040\\relax\040\\vbox\040{\\vskip\040\\fboxsep\0
40\\box\040\\@tempboxa\040\\vskip\040\\fboxsep\040}\\relax\040\\vrule\040width\
\fboxrule\040}\\hrule\040height\\fboxrule\040}}}\040} has been referenced but d
oes not exist, replaced by a fixed one

pdfTeX warning (dest): name{\040...{\040part.II}...\040}
has been referenced but does not exist, replaced by a fixed one

pdfTeX warning (dest): name{\040...{\040part.I}...\040}
has been referenced but does not exist, replaced by a fixed one


... so something is obviously wrong - even if the run completes (and a PDF is generated).

So, does anyone know of an existing MWE that implements the illustration on pg 13/14 of the titletoc manual? Alternatively, could anyone help fix the MWE so it implements the same example?

The MWE code is here:

\documentclass{book}

\usepackage{hyperref}
\usepackage{titletoc}

% like definition for \phantomsection, but for part
% "Re: documentation for \phantomsection"
% http://newsgroups.derkeiler.com/Archive/Comp/comp.text.tex/2006-01/msg01612.html
\makeatletter
\def\phantompart{%
\stepcounter{part}%
\xdef\@currentHref{part.\thepart}%
}
\makeatother

\fboxsep=0pt % for framebox

\contentsmargin{-4em}
\titlecontents{part}[2.3em]
{A}
{B\filbreak C\contentslabel{2.3em}D}
{E\fbox{\hspace*{2.3em}F\rule{2.3em}{2pt}}}
{G\titlerule*[1pc]{.}H\contentspage I\nobreak}

\begin{document}

\tableofcontents

\phantompart %
\protect\contentsline{part}{%
\thepart\hspace{1em}\ignorespaces %
\protect\fbox{ %
A Short Entry %
} %
} %
{ \protect\fbox{ \thepage } }
{ \protect\fbox{ part.\thepart } }% fbox doesn't show!
} %

\phantompart %
\protect\contentsline{part}{%
\thepart\hspace{1em}\ignorespaces %
%     \contentslabel{2pc} %
\protect\fbox{ %
\textbf{A longer entry here...} \\ %
Maybe something more written in this entry here, %
just to show as an illustration ... %
%       \protect\end{minipage} %
} %
} %
{ \protect\fbox{ \thepage } }
{ \protect\fbox{ part.\thepart } }% fbox doesn't show!
} %

\phantompart %
\protect\contentsline{part}{%
\thepart\hspace{1em}\ignorespaces %
\protect\fbox{ %
\protect\begin{minipage}{0.5\textwidth} %
\textbf{Another longer entry here...} \\ %
Still, some more content entered here; %
just to show as an illustration ... %
\protect\end{minipage} %
} %
} %
{ \protect\fbox{ \thepage } }
{ \protect\fbox{ part.\thepart } }% fbox doesn't show!
} %

\vspace{0.2\textheight}
Some extra text...

\end{document}

-
I don't understand your question. Do you want to draw a frame around the title? (This isn't trivial, indeed.) – Javier Bezos Jun 10 '12 at 10:05
Hi @JavierBezos - please see answer; I want: -- section number (label) to be top-aligned with the title + and I want the title bottom-aligned with the page number -- when a TOC entry is typeset (frames I've used just for visual debugging). Cheers! – sdaau Jun 10 '12 at 10:39
But frames (and boxes) spoil the format of entries! For example, lines are not broken inside \fbox'es. Don't use frames for your tests. – Javier Bezos Jun 10 '12 at 10:53
@JavierBezos - indeed, and I do I intend to remove the frames :) but they are actually a great tool to see if lines are broken as intended - which is why in the solution minipages are used :) I leave the removal of frames as exercise to the reader :) - what is difficult here is top-top-bottom alignment of entries on the same line, when a TOC line is typeset. Cheers! – sdaau Jun 10 '12 at 10:57

Holy mackerel - this must be one of the most complicated Latex problems I've ever encountered! However, I think I finally got somewhere - though I didn't quite expect it to be so involved. Anyway, the obligatory output for the MWE (posted way below) is here:

The part ("section") number is top aligned to the minipage content; and the page number and leaders are bottom aligned to the minipage content.

## Discussion

I don't know even where to start from, there were so many problems for me :)

The first problem is my choice of "part" as a sectioning command to work with. Originally, the OP code started with article document class, where "part" is not used for sectioning; so I though I may just as well work with it as a custom section. Since then, I moved to class book (as in the OP) - but there "\part" is actually defined and used! That makes understanding of the code much more complicated, since I couldn't tell if something refers to the "default" "\part" - or to the custom one.

Turns out, \part is handled specially, and a closer look to the titlesec/titletoc manual refers to that often:

(titletoc) This package is a companion to the titlesec package and it handles toc entries. However, it is an independent package and you can use it alone. ...
Standard parts write the toc entry number in a non standard way. You may change that with newparttoc so that titletoc or a similar package can manipulate the entry. (That works only if \part has been redefined.)

Note, however, that newparttoc is (somewhat surprisingly) an option for titleSEC - not titleTOC - package (this confusion caused me to waste time on quite a bit of useless grepping)

There are three classes: page is like the book \part, in a single page, top is like \chapter, which begins a page and places the title at the top, and straight is intended for titles in the middle of text ...
If you do not use the optional argument, you just change the class of name . For example: \titleclass{\part}{straight} makes part of straight class.

Yes - but this talks about the default \part; and since I've reprogrammed "part" down to \addcontentsline, this actually doesn't apply to my example (I think :))

There are two sectioning commands which perform some extra actions depending of its name and ignoring the class:
• \chapter logs the string defined in \chaptertitlename and the matter is taken into account.
• \part does not encapsulates the label in the toc entry, except if you use the newparttoc option.

Note here that \part does not apply to my example, but this is still an important issue: what does "does not encapsulates the label" mean? Which label?

It turns out: what tocloft calls "section number" (snum); - in titletoc is called a "label" - of a TOC entry. Now, the "encapsulating the label" actually ties into why the (<numbered-entry-format>) in the OP is ignored; from the manual for \titlecontents:

• is in horizontal mode and it will be used just before the entry title. As in \titleformat, the last command can take an argument with the title.
• is like the above if there is, well, no label.

Ok, so no label == numberless. But that means "part" in the OP has no label == is numberless; why? There are obviously part numbers shown, and a part counter kept?

To answer that, one needs to dig a bit through the definition of \titlecontents:

\$ texdef -t latex -p titletoc titlecontents -f
\titlecontents first defined in "titletoc.sty".

\titlecontents:
\long macro:->\@ifstar {\ttl@contents {\z@ }}{\ttl@contents {\@ne }}

# through searching/grepping through kpsewhich titletoc.sty:

\titlecontents{ <section> }[ <left> ]{ <above-code> }
{ <numbered-entry-format>  #5 }{ <numberless-entry-format> #6 }
{ <filler-page-format> }[ <below-code> ]
....
\newcommand\titlecontents{%
-> \def\ttl@contents#1#2{%
-> \def\ttl@contents@i#1#2[#3]#4#5#6#7{%
-> \ttl@tocentry{#1}{#2}{#3}{#4} {{#5}{#6}} {#7}
...
\def\numberline##1{\ignorespaces}%
\ifttl@label
{\leavevmode\strut\@firstoftwo#5{#7}\strut\kern\z@}%
\else
{\leavevmode\strut\@secondoftwo#5{#7}\strut\kern\z@}%
\fi
{#6}%
...
.. the decision ttl@label a bit above:
...
\global\ttl@labelfalse
\sbox\z@{%  Unused box. It just catch the numberline
\def\numberline##1{\global\ttl@labeltrue\gdef\thecontentslabel{##1}}%
#7}%    \ttl@b = current     \ttl@a = previous


First of all, here one must recall that building of a TOC is a two-step process in Latex:

• First latex pass: \addcontentsline calls are saved to a file ".toc";
• in the ".toc" file, \contentsline commands are saved
• Second latex pass: \contentsline entries from ".toc" are read back in, and TOC is typeset

With that in mind, the above search actually tells us (even though it's a bit hard to read) that - the macro \titlesec actually "greps" for the actual string "\numberline" in the ".toc" file; if it finds it, then the entry is declared "numbered" numbered (or with label) - if not, then it is declared without label (or numberless).

Thus - since in the OP, I wasn't emitting myself any \numberline from my \addcontentsline - all my custom parts were considered "numberless"; hence the (<numbered-entry-format>) is skipped; and (<numberless-entry-format>) is applied instead.

Note that because of this two step process, you must compile twice to get the TOC typeset; and since I frequently forgot that (esp. after crashes), I used this command line to build my example (called a.tex):

rm a.toc ; pdflatex a.tex && pdflatex a.tex


Also, those commands that are fragile and added as part of \addcontentsline, will get expanded when written to the ".toc" file; for the most part, that is unwanted, so \protect has to be issued in specific places; one has to freqently check the .toc file content after the first texing, to make sure that there are no unexpected expansions.

One last thing to point out is the \titleformat command:

\titleformat{ command }[ shape ]{ format }{ label }{ sep }{ before-code }[ after-code ] ... before-code is code preceding the title body. The very last command can take an argument, which is the title text. However, with the package option explicit the title must be given explicitly with #1 (see below).

This sounds interesting - because looking at \titlesection, you can specifically change the label (section number) and the page number formatting - but nothing is said specifically about the "title" (the body of the TOC entry). And the #1 mentioned there actually does provide the title - however, \titleformat has nothing to do with typesetting of TOC entries; it typesets the "Part 1. Test", "Section 1. Test" texts in the document, when \part{Test} or \section{Test} are encountered (quite some time wasted on figuring this out, too :))

### Back to alignment

With the above about the titletoc behavior in mind, we can go back to the vertical alignment problem.

The most important note here is that the accepted answer of "Changing minipage vertical alignment in mid-line?" uses something like this for top-top-bottom vertical alignment on a single line:

\begin{tabular}[b]{lll}
\begin{minipage}[t]{100pt} \end{minipage}
\begin{minipage}[t]{100pt} \end{minipage}
\end{tabular}
\begin{tabular}[b]{ll}
\begin{minipage}[t]{100pt} \end{minipage}
\end{tabular}


This posting to the same question, however, notes that it's the first tabular wrapping the minipages which is responsible for the top alignment: if one breaks that up - in three tabulars, so that each minipage has it's own tabular - it becomes impossible to achieve again the top-top-bottom alignment, just by using the [t] and [b] options (of either minipage or tabular).

And that is the problem here - effectively, to have top-top-bottom typeset in TOC, we'd need to reconstruct this tabular/minipage hierarchical relationship in the \titlecontents formatting call; however, the \titlecontents gives separate command arguments for at least the "section number" and "page number" formats - and sticking a \begin{environment} in the one, and \end{environment} in the other doesn't seem to work (think "! Missing } inserted."; seemingly, this problem is of the same nature as the top-top-bottom alignment problem with tocloft, too).

However, the same posting also states that it is possible to achieve top-top-bottom alignment, also with three independent tabulars (one for each minipage) - if all tabulars are kept [b] aligned, and \raisebox is used in the first one to "lift" the contents up. However yet again, this requires also that the minipage in the second tabular - the one with the largest expected height - has its height measured for each entry; so the section number can be "lifted" up accordingly.

And this means we need to:

• put the second minipage in \savebox,
• and then \usebox and measure with \ht and \dp
• NOTE that just \settoheight is NOT enough to get the actual height; it is \ht + \dp
• ... and that means you also need to include package calc to find the real height
• make sure { <section> } of \titlecontents has access to this height as a number, so it can \raisebox - even if, in principle, the "section number" is typeset before the title text in the TOC (so in principle this height is "not available yet")
• make sure all this survives the roundtrip through the .toc file and the two latex calls

All in all taken, that's quite of a mouthful; and my MWE solution below adresses it through definition of three macros to handle the formatting:

• \tctitleformat - called from \addcontentsline; then calls:
• \tcboxtitleformat - , emits \protected code to .toc file; also the one which upon rereading and expanding recalculates the height
• it accepts an argument, which is the title for the TOC entry (available during \addcontentsline, first pass)
• It creates the minipage box by defining a \tcboxTF macro, whose only purpose is to allow "re-instantiation" of the minipage box without an argument - so it can be called from the { <section> } piece of \titlecontents
• \tclabelformat - for the section number label piece of TOC - called from { <section> } of \titlecontents (to make it even more confusing, as an argument of \contentslabel[ARG]{2.3em})
• this handles the \raisebox; and expects that the respective height is already globally available
• \tcpageformat - for the page number piece of TOC - would be called from { <filler-page-format> }, but there's no need for it (left it for archival)

One final issue is to mention the "pdfTeX warning" from the OP. Basically, it turns out that the final argument of the \addtocontents call:

\addtocontents{toc}{%
% .... ....
{part.\thepart}%
}


... MUST be in the form {part.\thepart} - NO spaces or any other characters are allowed; any such apparently cause the parsing of the entry numbering to fail, which then doesn't leave a working reference for the entry. Note that in the MWE below, as an example, { \protect\fbox{ part.\thepart } } is deliberately left in that position - as a result, when texing, you should see only one "pdfTeX warning" in the terminal output, related to that entry.

Well, I guess that is all that there is to it - would certainly love to hear if there is a simpler solution, though :)

## MWE code

\documentclass{book}

% \def\thepart{\arabic{part}} % no real need for this

\usepackage{calc}
\usepackage{hyperref}
\usepackage[explicit,newparttoc]{titlesec}
\usepackage{titletoc}
\usepackage{trace}

% like definition for \phantomsection, but for part
% "Re: documentation for \phantomsection"
% http://newsgroups.derkeiler.com/Archive/Comp/comp.text.tex/2006-01/msg01612.html
\makeatletter
\def\phantompart{%
\stepcounter{part}%
\xdef\@currentHref{part.\thepart}%
}
\makeatother

\fboxsep=0pt % for framebox

\documentclass{book}

% \def\thepart{\arabic{part}} % no real need for this

\usepackage{calc}
\usepackage{hyperref}
\usepackage[explicit,newparttoc]{titlesec}
\usepackage{titletoc}
\usepackage{trace}

% like definition for \phantomsection, but for part
% "Re: documentation for \phantomsection"
% http://newsgroups.derkeiler.com/Archive/Comp/comp.text.tex/2006-01/msg01612.html
\makeatletter
\def\phantompart{%
\stepcounter{part}%
\xdef\@currentHref{part.\thepart}%
}
\makeatother
% note \baselineskip dissapears (is 0) in tabular!
% so save the default \baselineskip in
% another variable:
\typeout{\the\baselineskip} %
\newlength{\oldbaselineskip}
\setlength{\oldbaselineskip}{\baselineskip}

% we must save the title format minipage;
% so we can extract its typeset height
\global\newsavebox\mybox
\global\newlength{\miniheight}

% save long minipage for \tctitleformat (tabular 2)
% into a box, so we can measure its height;
% we must make this into a command;
% since the title text will be passed as an argument;
% re-calc the height here too?
%  must use the package calc, to use + as addition
%  operator in the \setlength{\miniheight}... stanza
% ( \tctitleformat goes into addtocontents! )
\def\tcboxtitleformat#1{
\protect\gdef\protect\tcboxTF{  % inner gdef, so we can call it
% from titlecontents without an argument
\protect\begin{lrbox}{\mybox} %
\protect\begin{minipage}[t]{0.5\textwidth} %
#1 %
\protect\end{minipage} %
\protect\end{lrbox} % ... also recalc:
\global\protect\settoheight{\miniheight}{\protect\usebox\mybox} %
\global\protect\setlength{\miniheight}{\ht\mybox+\dp\mybox+1em-1.411\oldbaselineskip} %
} %
\protect\tcboxTF{}%             % now that we have inner def,
%   must call it separately to instantiate
\protect\typeout{----minihg-tocfile--\protect\the\miniheight-\protect\the\mybox} %
}

% \global doesn't help here;
% tocfile seems to kick in first, though;
% but only way to retrieve values, is with
% with inner gdef \tcboxTF called in \titlecontents:
% ----minihg-tocfile  --39.50452pt-27 39.50452pt-27
% ----minihg-tcA      --0.0pt-27      0.0pt-27
% ----minihg-tcAA     --0.0pt-27      39.50452pt-27
% ----minihg-tclabelf --0.0pt-27      39.50452pt-27

\documentclass{book}

% \def\thepart{\arabic{part}} % no real need for this

\usepackage{calc}
\usepackage{hyperref}
\usepackage[explicit,newparttoc]{titlesec}
\usepackage{titletoc}
\usepackage{trace}

% like definition for \phantomsection, but for part
% "Re: documentation for \phantomsection"
% http://newsgroups.derkeiler.com/Archive/Comp/comp.text.tex/2006-01/msg01612.html
\makeatletter
\def\phantompart{%
\stepcounter{part}%
\xdef\@currentHref{part.\thepart}%
}
\makeatother
% {minipage}[t] inside {tabular} no work here.
% must do shifting with raisebox;
\def\tclabelformat{ %
%\settoheight{\miniheight}{\usebox\mybox} % nope
\typeout{----minihg-tclabelf--\the\miniheight-\the\mybox} %
\fbox{%
\begin{tabular}[b]{l} %
\raisebox{-\miniheight}{M}  % works from here ONLY; it does
%   *not* work from anywhere in
%   \titlecontents: {B\filbreak C\... D} !!
\thecontentslabel %
\\[0pt] %
\end{tabular} %
} %
}

% \tctitleformat goes into addtocontents!
\def\tctitleformat#1{%
\tcboxtitleformat{#1} \\[0pt] % we let this command expand when written
%   to tocfile (its insides are protected);
%   it just saves the box contents,
%   but doesn't actually use it!
%\tcboxTF{}                    % tcboxTF not used here
%
% use - inside the tabular:
\protect\begin{tabular}[b]{l} %
\protect\usebox\mybox %     % this is also saved in toc;
%   but when contents read back from toc and ran,
%   previous command 'expands' the minipage box and
%   recalcs the height; and this command
%   can just use (typeset) the \mybox...
\\[0pt] %                   % do NOT forget the linebreak! ( else,
%   there will be no [b]ottom alignment of
%   tabulars for the \raisebox thing!
% \protect\begin{minipage}[t]{0.5\textwidth} %
% #1 %
% \protect\end{minipage} \\[0pt] %
% \protect\traceon % no
\protect\end{tabular} %
}

\def\tcpageformat#1{ %
\fbox{ %
\protect\begin{tabular}[b]{l} %
\protect\begin{minipage}[b]{0.3\textwidth} %
#1 %
\protect\end{minipage} \\[0pt] %
\protect\end{tabular} %
}}

\let\tcboxTF\relax  % must do this before \titlecontents is first called;
%   if we don't give it a default value;
%   \titlecontents will crash at first
%   ( ! Undefined control sequence. )
%   because -tcA-- may run first without a \tcboxTF run
%   ( if a "real" \part was called, not a custom one )
\contentsmargin{-4em}
\titlecontents{part}[2.3em]%
{%
A%
\typeout{----minihg-tcA--\the\miniheight-\the\mybox}%
\tcboxTF{}%                                 % call again to reinstantiate box,
%   ( and retrieve values )
% \settoheight{\miniheight}{\usebox\mybox}  % no need - \tcboxTF also recalcs now
\typeout{----minihg-tcAA--\the\miniheight-\the\mybox}%
}
{B\filbreak C\fbox{\contentslabel[\tclabelformat]{2.3em}}D}
{E\fbox{\hspace*{2.3em}F\rule{2.3em}{2pt}}}
%   {\tcpageformat{G\titlerule*[1pc]{.}H\contentspage I}\nobreak} % box too wide
%   {G\titlerule*[1pc]{.}\tcpageformat{H\contentspage }I\nobreak} % rule lost
%   {G\titlerule*[1pc]{.}H\contentspage\tcpageformat{ }I\nobreak} % rule appears
{G\titlerule*[1pc]{.} \fbox{H} \contentspage \nobreak I}  % is bottom aligned fine,
% so no need for \tcpageformat
% (note: cannot \fbox \titlerule)

\begin{document}

% \traceon
\tableofcontents

% for debugging:
% \section{Whatever section}
% \part{Whatever part}

\phantompart %
\protect\contentsline{part}{%
\thepart\hspace{1em}\ignorespaces %
\protect\fbox{ %
A Short Entry %
} %
} %
{ \protect\fbox{ \thepage } }
{ \protect\fbox{ part.\thepart } }% fbox doesn't show!
} %

\phantompart %
\protect\contentsline{part}{%
\protect\numberline{\thepart}\ignorespaces %
\protect\fbox{ %
\tctitleformat{ %
\textbf{A longer entry here...} \\ %
Maybe something more written in this entry here, %
just to show as an illustration ... %
} %
} %
} %
{ \protect\fbox{ \thepage } }
{part.\thepart}% { \protect\fbox{ part.\thepart } }% fbox doesn't show!
} %

\phantompart %
\protect\contentsline{part}{%
\protect\numberline{\thepart}\ignorespaces %
\protect\fbox{ %
\tctitleformat{ %
\textbf{Another longer entry here...} \\ %
Still, some more content entered here; %
just to show as an illustration ... %
} %
} %
} %
{ \protect\fbox{ \thepage } } %
{part.\thepart}   % { part.\thepart }% { \protect\fbox{ part.\thepart } }% fbox doesn't show! %
%   also: - if just *one* space left before part.\thepart;
%   then ->> "pdfTeX warning (dest): name {\040part.III} has been
%   referenced but does not exist, replaced by a fixed one"
} %

\vspace{0.2\textheight}
Some extra text...

\end{document}

-