8

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]

I suspect that this is caused by the fact that, when \renewcommand{\storedContent}{#1} is applied the second time, it operates recursively on itself. Probably, the argument of the \renewcommand must be expanded in order to first retrieve the content of the previous \storedContent, but I just can't figure out how to do it...

  • 2
    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. – Manuel Dec 4 '15 at 10:45
8

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.

enter image description here

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

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
     \g@addto@macro\storedContent{#1}%
    \else
     \g@addto@macro\storedContent{, #1}%
    \fi 
}
\makeatother
\begin{document}
    \mySection{one}
    \mySection{two}
    \mySection{three}
\storedContent    
\end{document}

enter image description here

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.