views:

31

answers:

2

I start by defining a command to store the string "Hello":

\newcommand{\textstring}{Hello}

I would like to append the string " world" but unfortunately this code causes an error:

\renewcommand{\textstring}{\textstring world}
+2  A: 

You can accomplish this by using \expandafter. For example:

% redefine \textstring by appending " world" to it
\expandafter\def\expandafter\textstring\expandafter{\textstring { }world}

If you don't use \expandafter then you end up with a recursion problem. You can read more about it here.

David Underhill
This method works fine (even when the appended text contains commands). But now I had another problem with it: when I use \textstring within my text it shows "Hello world" but I have to use it in \endnotetext[\value{enumi}]{\textstring} which generate an empty endnote.
flaflamm
A: 

The problem is that this overwrites the definition of \textstring, rather than referencing the old one. In order to append, the standard way is to use the TeX command \edef, which expands the definition before assigning something. Thus, if you have

\def\textstring{Hello} % Or with \newcommand
\edef\textstring{\textstring{} world}

LaTeX will change the right-hand side of the \edef into Hello world, and then reassign that to \textstring, which is what you want. Instead, in your current version, the \newcommand doesn't expand the right-hand side, so when you use \textstring, it expands to \textstring world, which itself expands to \textstring world world, which itself expands to… you get the idea.

Antal S-Z
This method seems to have problems when the text to add contains commands, it generated many errors.
flaflamm