This question is a possible solution to question Code fails with Emergency stop, when using \expandafter\csname and such in listings, though not really an answer.
I have defined a command which may contain up to hundred lines of code including paragraph lines breaks, but basically it is just a lot of LaTeX Code. Let's assume this command is called \printhis
Now I want to export the content of \printthis into a file, which can be loaded by listings afterwards.
I have not worked before with any tex code that exports something to a file. If anyone can provide and example or link to a tutorial that would be great.
EDIT: Approach using answer package.
\documentclass{scrbook}
\makeatletter
\providecommand{\packagename}{templatedemo}
\RequirePackage{etoolbox}
\RequirePackage{answers}
\providecommand\demo@filename{demofile}
\providecommand\AddDemo[2]{%
% #1 : package/identifier
% #2 : content
\ifcsdef{demo@content@#1}{
\expandafter\renewcommand\csname demo@content@#1\endcsname{#2}%
}{
\expandafter\newcommand\csname demo@content@#1\endcsname{#2}%
}
}
\providecommand{\demo@printhis}{}
\newcommand{\outputtofile}[1]{
\Opensolutionfile{\demo@filename}
\scantokens{\begin{Filesave}{\demo@filename}#1\end{Filesave}}
\Closesolutionfile{\demo@filename}
}
\providecommand\PrintDemo[1]{%
\ifcsdef{demo@content@#1}%
{ % print
\renewcommand{\demo@printhis}{\csuse{demo@content@#1}}
To file: \demo@printhis
\outputtofile{\demo@printhis}
}%
{ % error if not defined
}
}
\AddDemo{text}{Sample text in file}%
\makeatother
\listfiles
\begin{document}
\PrintDemo{text}\par
From File: \IfFileExists{demofile.tex}{\input{demofile.tex}}{}
\end{document}
\pars, but the whole thing would be one single but very long source line. The actual writing could be done using\immediate\write\filehandle{\expandafter\unexpanded\expandafter{\printthis}}. After\newwrite\filehandleand\immediate\openout\filehandle=yourname.tex. – Martin Scharrer♦ Sep 23 '11 at 14:09