# Recursive use of \renewcommand: How to make it work?

I am trying to define a command that is able to store the content of a section and accumulate it as new sections are created. My current attempt is the following:

\documentclass{article}

\newcommand{\storedContent}{}

\newcommand{\mySection}[1]{
\section*{#1}
\renewcommand{\storedContent}{#1}
}

\begin{document}
\mySection{one}
\mySection{\storedContent~two}
%    \mySection{\storedContent~three}
\end{document}


In practive, I would like it to display:

one
one two
one two three

However, it only works up to one one two. When \mySection is called the third time, LaTeX throws the error:

TeX capacity exceeded, sorry [input stack size=5000]


• Use \csname protected@edef\endcsname\storedContent instead of \renewcommand{\storedContent}. \protected@edef is the LaTeX version of \edef which, as you say, expands the argument first. Dec 4 '15 at 10:45

You can add the item before doing \section:

\documentclass{article}
\usepackage{etoolbox}

\newcommand{\storedContent}{}
\newcommand{\mySection}[1]{%
\ifdefempty{\storedContent}
{\gappto\storedContent{#1}}
{\gappto\storedContent{~#1}}%
\section*{\storedContent}
}

\begin{document}

\mySection{one}

\mySection{two}

\mySection{three}

\end{document}


Using etoolbox is just for convenience; the same could be done without packages.

• Thanks, this perfectly fits my needs! Thanks for your help. Dec 4 '15 at 23:26

One way would be this (there are others). The comma is only there to show you, how you can do something different with the second, third occurance than with the first.

\documentclass{article}

\newcommand{\storedContent}{}
\makeatletter
\let\storedContent\@empty
\newcommand{\mySection}[1]{%
\section*{#1}
\ifx\storedContent\@empty
\else
\fi
}
\makeatother
\begin{document}
\mySection{one}
\mySection{two}
\mySection{three}
\storedContent
\end{document}


• Thanks for your answer! Very nice workarround to my problem, while avoiding a more troublesome recursive solution. Thanks! Dec 4 '15 at 23:24