# \write and \ifmmode

This is related to a previous question of mine (if I understand correctly, \write works a bit like \edef).

Consider the following code:

\documentclass[varwidth,convert={size=640}]{standalone}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage{fancyvrb}
\begin{document}

\newwrite\foo
\immediate\openout\foo=foo.txt
$\immediate\write\foo{\ifmmode\noexpand\true\else\noexpand\false\fi}$
\immediate\closeout\foo

\VerbatimInput{foo.txt}

\end{document}


I'd like to write \true to the file. How can I do?

Some variations.

## The fun of \expandafter:

\documentclass[varwidth,convert={size=640}]{standalone}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage{fancyvrb}
\begin{document}

\newwrite\foo
\immediate\openout\foo=foo.txt
$\immediate\expandafter\write\expandafter\foo\expandafter{% \ifmmode\noexpand\true\else\noexpand\false\fi}$
\immediate\closeout\foo

\VerbatimInput{foo.txt}

\end{document}


The \expandafter expands \ifmmode while in math mode, before \write is executed.

## Expanded macro definitions:

$\edef\result{\ifmmode\string\true\else\string\false\fi} \immediate\write\foo{\result}$


Or the whole expression can be put in an \edef:

$\edef\next{% \immediate\write\foo{\ifmmode\string\true\else\string\false\fi}% }\next$


Inside a \write, TeX is in 'no mode', not in hmode, math mode, etc. Thus you have to move the test outside of the \write

$\ifmmode \immediate\write\foo{\string\true}% \else \immediate\write\foo{\string\false}% \fi}$

• @cjorssen what do you mean? – touhami Sep 12 '15 at 6:38
• No hope to keep the test inside \write? – cjorssen Sep 12 '15 at 6:39
• @cjorssen No: you can't set the mode yourself other than locally redefining the meaning of \ifmmode, \ifhmode and \ifvmode, which of course will have unwanted consequences: if you set \ifmmode to \iftrue and you have in the argument to \write something like \hbox{\foo}, where \foo expands to \ifmmode a\else b\fi, the result will be wrong. – egreg Sep 12 '15 at 6:51