3

I want to create a control sequence using expl3 to write file content while obeying whitespace. So far I have the following MWE which does write to file, but ignores whitespace.

\documentclass[]{article}

\usepackage{expl3}

\ExplSyntaxOn

\iow_new:N \g_mwe_stream

\cs_new:Nn \write_whitespace:n {
  \iow_open:Nn \g_mwe_stream { mwe.txt }
  \iow_now:Nn \g_mwe_stream { #1 }  
  \iow_close:N \g_mwe_stream
}

\write_whitespace:n {
abc def
123 456
}

\ExplSyntaxOff

\begin{document}
\end{document}

The MWE creates the file mwe.txt which contains

abcdef123456

instead of the desired

abc def
123 456

I know I can use ~ and ^^J to manually create spaces and line breaks, but I want to avoid this. In LaTeX2 there is the \obeyspaces and \obeylines macros, but I have not found equivalents for LaTeX3.

1
  • The expl code environment is not really for 'data' (beyond short strings such as error messages). You could of course manually \char_set_catcode_space:n { `\~ } or similar, but normally I'd use a function that reads the argument outside of the code environment.
    – Joseph Wright
    Feb 12, 2019 at 16:34

1 Answer 1

3

You should do the writing outside the scope of \ExplSyntaxOn.

\documentclass{article}

\usepackage{xparse}

\ExplSyntaxOn

\iow_new:N \g_slo_output_stream
\seq_new:N \l__slo_output_seq

\NewDocumentCommand{\writefile}{O{\\}mm}
 {% #1 = line separator, #2 = file name, #3 = text
  \iow_open:Nn \g_slo_output_stream { #2 }
  \seq_set_split:Nnn \l__slo_output_seq { #1 } { #3 }
  \seq_map_inline:Nn \l__slo_output_seq
   {
    \iow_now:Nn \g_slo_output_stream { ##1 }
   }
  \iow_close:N \g_slo_output_stream
}

\ExplSyntaxOff

\writefile{\jobname.txt}{
  abc def \\
  123 456
}

{\obeylines
\writefile[^^M]{\jobname.tx2}{% <-- don't forget
  abc def
  123 456
}}

\stop

I recommend not using the second way.

The first file will not have an empty final line. Apart from this, they'll contain

abc def
123 456

You must log in to answer this question.

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