Appending a command with evaluated parameters to a macro

I'm trying to have a command \appendtocmd that does that:

\def\contents{Files:}
\def\value{yo man}
\appendcmdto{contents}{section}{\value}


contents contains now "Files: \section{yo man}" so when I evaluate it anywhere, it will show "Files:" and create a section. Note also that #3 of the macro is FULLY evaluated when it is called.

I was trying to make it with \expandafter, \expandnext, \csname, etc., but to no avail. If you know a solution, I would also appreciate an explanation, WHY it works :).

It's not very clear what you want to achieve, but here's a definition for \appendcmdto and \xappendto; the latter does complete expansion on the third argument.

\documentclass{article}

\newcommand{\appendcmdto}[3]{%
\edef#1{%
\unexpanded\expandafter{#1}%
\space
\expandafter\noexpand\csname #2\expandafter\endcsname
\expandafter{\expandafter\unexpanded\expandafter{#3}}%
}%
}

\makeatletter
\newcommand{\xappendcmdto}[3]{%
\protected@edef#1{%
\unexpanded\expandafter{#1}%
\space
\expandafter\noexpand\csname #2\expandafter\endcsname{#3}%
}%
}
\makeatletter

\def\contents{Files:}
\def\somevalue{yo man}
\def\someothervalue{Ehi! \textbf{\somevalue}}

\appendcmdto{\contents}{section}{\somevalue}

\show\contents

\xappendcmdto{\contents}{subsection}{\someothervalue}

\show\contents

\stop


Running this with LaTeX will show on the terminal

> \contents=macro:
->Files: \section {yo man}.
l.28 \show\contents

?
> \contents=macro:
->Files: \section {yo man} \subsection {Ehi! \protect \textbf  {yo man}}.
l.32 \show\contents

?

• This is almost what I want! One issue though: the macro in #3 is not fully expanded as can be shown by running: \appendcmdto{\contents}{section}{\somevalue\somevalue}. Only the first \somevalue is expanded. I already fixed it myself and I'll be happy to accept your answer if you fix it (and I'm pretty sure you can do it, considering that I was able to :) ). I think that I understand why it works, but \expandafters make me dizzy. – tombuc Oct 23 '14 at 14:18
• @tombuc If you want full expansion you should tell so in your question. – egreg Oct 23 '14 at 14:19
• I added "FULLY" to the question text. – tombuc Oct 23 '14 at 14:25
• @tombuc OK, and I added the trick. – egreg Oct 23 '14 at 14:29
• Ok, accepted, it does precisely what I want. Why did you use \protected@edef in the second version? – tombuc Oct 23 '14 at 14:34

(don't redefine \value in LaTeX but...)

\def\contents{Files:}
\def\value{yo man}
\def\tmp{\appendcmdto{contents}{section}}
\expandafter\tmp\expandafter{\value}


This is assuming \appendcmdto is defined somewhere (your question didn't make that clear)

or just

\makeatletter
\def\contents{Files:}
\def\value{yo man}