6

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}

enter image description here

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

2 Answers 2

7

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}

Result

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$
9

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}
$ 
3
  • @cjorssen what do you mean?
    – touhami
    Sep 12, 2015 at 6:38
  • No hope to keep the test inside \write?
    – cjorssen
    Sep 12, 2015 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, 2015 at 6:51

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .