# \write and \\ command

Why I get some errors with the code below, and how can I fix that behaviour?

\documentclass{article}

\begin{document}
\newwrite\indexist
\immediate\openout\indexist=classic.ist
\immediate\write\indexist{\\}
\immediate\write\indexist{\catcode\{=11{\catcode\{=2 text}
\immediate\write\indexist{other text\catcode\}=11}\catcode\}=2}
\immediate\closeout\indexist
\end{document}

-
\string\\ (you're forgetting that \write does complete expansion). Why would you write on a .ist file? Isn't it easier writing it with an editor? – egreg Dec 3 '12 at 17:02
@egreg I have updated my question... I would to write on a .ist file because I want to automatize the procedure to get the index formatted correctly from the .ist file... – FormlessCloud Dec 3 '12 at 18:07
There's no point in writing an .ist file one line at a time with \write; the filecontents* environment may be much better for the task at hand. – egreg Dec 3 '12 at 18:50

The problem with \\ is already solved by egreg: \string\\. That prevents expansion and converts \\ to two \ tokens with catcode 12 (same catcode as digits).

The same is needed for unmatched { and }. However unmatched braces do not work inside \write. A trick is using macros that are defined via \edef (expanded def), then \leftbracechar and \rightbracechar contain the braces as tokens with catcode 12.

\documentclass{article}

\edef\leftbracechar{\string{}
\edef\rightbracechar{\string}}

\begin{document}
\newwrite\indexist
\immediate\openout\indexist=classic.ist
\immediate\write\indexist{\string\\}
\immediate\write\indexist{\leftbracechar text}
\immediate\write\indexist{other text\rightbracechar}
\immediate\closeout\indexist
\end{document}

-