2

I'd like to append code to a file containing latex code... So I tried the solution proposed here, but unfortunately it fails when there are backslash in the file: How can I open a file in "append" mode?

So I tried to adapt it with \unexpand\expandafter{\filecontent}#2, but it adds spaces after "commands", which is really annoying:

enter image description here

MWE:

\documentclass{article}
\usepackage{verbatim}

\usepackage{catchfile}

\newwrite\appendwrite
\newcommand*\appendtofile[2]{%
    \begingroup
    \IfFileExists{#1}%
      {\CatchFileDef{\filecontent}{#1}{\endlinechar=`^^J\catcode\endlinechar=12\relax}}% keep existing end-of-lines
      {\let\filecontent\empty}%
    \immediate\openout\appendwrite=#1\relax
    \immediate\write\appendwrite{\unexpanded\expandafter{\filecontent}#2}%
    \immediate\closeout\appendwrite
    \endgroup
}

\newcounter{mycounter}
\begin{document}

\appendtofile{\jobname.test}{\string\Mycode\themycounter}

First, everything is good:\\
\verbatiminput{\jobname.test}

\appendtofile{\jobname.test}{Second line}

Second, see how the spaces are added:\\
\verbatiminput{\jobname.test}

\end{document}
  • The behaviour is by-design: you'll have to go for a token-by-token conversion to a string to avoid it – Joseph Wright Apr 11 at 17:42
  • @JosephWright I have no idea how to do that (LaTeX is still a mystery for me), could you provide an example please? – tobiasBora Apr 11 at 17:55
  • This happens because when TeX reads the file the \ is the control character thus \Mycode is a control sequence and TeX adds a space after that, as Joseph said, by-design. You can do \let\do\@makeother\dospecials before \CatchFileDef then the file would be read verbatim and \Mycode0 would be just a sequence of 8 characters. – Phelype Oleinik Apr 11 at 17:56
4

You can read the file back with a verbatim \

enter image description here

\documentclass{article}
\usepackage{verbatim}

\usepackage{catchfile}

\newwrite\appendwrite
\newcommand*\appendtofile[2]{%
    \begingroup
    \IfFileExists{#1}%
      {\CatchFileDef{\filecontent}{#1}{\catcode`\\=12 \endlinechar=`^^J\catcode\endlinechar=12\relax}}% keep existing end-of-lines
      {\let\filecontent\empty}%
    \immediate\openout\appendwrite=#1\relax
    \immediate\write\appendwrite{\detokenize\expandafter{\filecontent}#2}%
    \immediate\closeout\appendwrite
    \endgroup
}

\newcounter{mycounter}
\begin{document}

\appendtofile{\jobname.test}{\string\Mycode\themycounter}

First, everything is good:\\
\verbatiminput{\jobname.test}

\appendtofile{\jobname.test}{Second line}

Second, see how the spaces are added:\\
\verbatiminput{\jobname.test}

\end{document}

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.