# write contents of an environment to document and toc

I want to write the contents of an environment to the document and the toc. Here's a MWE hacked to look (almost) like what I need.

\documentclass[pdftex,12pt]{book}
\usepackage{hyperref}

\newenvironment{g}
{}
{\newline}

\begin{document}

\tableofcontents{}

\chapter{First}

\begin{g}
first goal first chapter
%\addtocontents{toc}{first goal first chapter} %% yields error message
\end{g}
\begin{g}
second goal first chapter
\end{g}

Chapter contents here \ldots

\chapter{Second}

\begin{g}
first goal second chapter
\end{g}

Chapter contents here \ldots

\end{document}


That produces this toc:

What I'd like is this (with no hyperref links for the extra lines):

Problems I don't know how to solve:

• Most important: how can I capture the write twice behavior in the environment definition so that I don't have to specify the extra toc line with cut and paste each time?

• Secondary: Why does \addtocontents produce an error when commented in? (An answer to this might solve the entry formatting and link problem.)

I can use the xparse package to define the environment if that makes for an easier solution.

-
The environ package gives you access to the body of the environment using a macro \BODY. You could use that to write the TOC line in the start or end code of the environment. –  Scott H. Jun 21 '12 at 18:59
@ScottH. Works like a charm almost. Solves the double write problem, but the second goal incarnation in the first chapter in the document has an extra indentation not in my MWE. The addtocontents error continues. You can post this as an answer I'd vote up, but not accept quite yet. –  Ethan Bolker Jun 21 '12 at 19:37
Edit your question and add the code you got with @ScottH. 's help so that others can build on it ;) –  tohecz Jun 21 '12 at 20:16
@tochecz egreg's answer below appeared before I saw this good idea, which I will remember. –  Ethan Bolker Jun 22 '12 at 0:55

\documentclass[12pt]{book}

\usepackage{environ}

\usepackage{hyperref}

\makeatletter
\newcommand\l@goal[1]{%
\vskip \z@ \@plus \p@
\begingroup
\parindent\z@
\rightskip\@pnumwidth
\parfillskip-\@pnumwidth
\leavevmode #1\nobreak\hfil\nobreak\null\par
\penalty\@highpenalty
\endgroup}
\newcommand{\goal}[1]{%
\NewEnviron{goal*}{\goal{\BODY}}
\makeatother

\begin{document}

\tableofcontents{}

\chapter{First}
\goal{first goal first chapter}
\goal{second goal first chapter}

\bigskip

Chapter contents here \ldots

\chapter{Second}
\begin{goal*}
first goal second chapter
\end{goal*}

\bigskip

Chapter contents here \ldots

\end{document}


If the goal text is not long, perhaps the command form is preferable. Otherwise use goal*.

The macro \goal writes to the .toc file using \addtocontents, because hyperref patches \addcontentsline so that it creates a link. We write \l@goal{<goal text>} and then the macro \l@goal does essentially the same as \l@chapter, which is responsible for typesetting the chapter title in the ToC.

-