[Tex/LaTex] Efficient way to write backslash to a file

external files

Say I have a writer and an environment (actually an Environ) defined as

\documentclass{article}
\usepackage{environ} % www.ctan.org/pkg/environ
\newwrite\mywriter
\NewEnviron{writethis}
    {\immediate\write\mywriter{\BODY}}
\begin{document}
\immediate\openout\mywriter=writehere.txt
...
\immediate\closeout\mywriter
\input{writehere.txt}
\begin{document}

What I want to do is copy everything in a writethis environment to writehere.txt and include it in the document later on.

It becomes problematic when I want to write a backslash. Not just a \textbackslash or $\backslash$ (in math mode) but one that can be used to write commands such as in \textbf{abc}. (The compiler refuses to write a \ via \textbackslash.)

I know of the solution

\makeatletter
\begin{writethis}\@backslashchar textbf{abc}\end{writethis}
\makeatother

but it would be really tedious to write \makeatletter...\makeatother every time I need a \. Somewhat naively, I tried to define a command to replace the above:

\newcommand\back
    {\makeatletter\@backslashchar\makeatother}

for the sake of writing simply

\begin{writethis}\back textbf{abc}\end{writethis}

but the compiler refuses. (It says Improper alphabetic constant. \spacefactor, I have no clue why this \spacefactor pops up.)

So here is my question:

Is there a way to write a \ to a file, shorter than \makeatletter\@backslashchar\makeatother?

This may have something to do with this question (perhaps even a duplicate?). I read it but didn't understand how to use Philippe Goutet's solution.

Best Answer

You want an “almost verbatim” write:

\documentclass{article}
\usepackage{environ} % www.ctan.org/pkg/environ

\newwrite\mywriter
\NewEnviron{writethis}
    {\immediate\write\mywriter{\unexpanded\expandafter{\BODY}}}
\begin{document}

\immediate\openout\mywriter=\jobname-later.tex
\begin{writethis}\textbf{abc}\end{writethis}
\immediate\closeout\mywriter

Something

\input{\jobname-later}
\end{document}

Here's the contents of \jobname-later (I use \jobname not to clobber my files, use whatever name you prefer):

\textbf {abc}

The space will be ignored in input.

If you want to add fixed text before and after the contents of the environment, do

\NewEnviron{writethis}{%
  \immediate\write\mywriter{%
    \unexpanded{<before>}%
    \unexpanded\expandafter{\BODY}}%
    \unexpanded{<after>}%
  }%
}

where <before> and <after> stand for arbitrary TeX code. You don't want \expandafter for them, in general, which is needed in the middle term in order to get the expansion of \BODY.