6

Using LuaLaTeX with TeXlive 2016, although I imagine that this question applies to nearly anything:

I know how to create a file using \immediate\write on a line-by-line basis. But I would like to do it for multiple lines, where the number of lines is not known in advance (it is the result of gathering text items in a macro). Something like this:

\newwrite\file
\immediate\openout\file=pickafilename.txt
\immediate\write\file{Hello! I am a new file.}
\immediate\write\file{\MacroContainingTextMacros}
\closeout\file

The \MacroContainingTextMacros has a few small macros within it, which I wish to expand as the file is written. Each of those small macros contains a few lines of plain text. So I cannot use verbatim, or filecontents.

Any ideas?

1 Answers1

8

You just need to write the \newlinechar which is pre-set to be ^^J in latex.

\def\MacroContainingTextMacros{
aa^^Jbb^^Jcc}
\newwrite\file
\immediate\openout\file=pickafilename.txt
\immediate\write\file{Hello!^^JI am a new file.}
\immediate\write\file{\MacroContainingTextMacros}
\closeout\file

\stop

produces

Hello!
I am a new file.
 aa
bb
cc
David Carlisle
  • 757,742
  • So simple! I always wondered what ^^J meant. I see it in code. I thought maybe it was a programmer's Smiley Face. –  Oct 21 '16 at 18:15
  • 1
    @RobtA it is control J that is ascii 10 (line feed), the ^^ is primitive TeX syntax for shifting the character code by 64 (which is what ctrl does, more or less) – David Carlisle Oct 21 '16 at 18:31
  • I bet you could get away with using ^^M as well -- for carriage return. – jpaugh Oct 21 '16 at 21:00
  • @jpaugh you can use any letter, such as a, if you want, it just depends on the value of \newlinechar which is 10 by default. using ^^M is tricky even if you set \newlinechar to 13 as it is \endlinechar and acts like a comment hiding the rest of the input line. – David Carlisle Oct 21 '16 at 21:09
  • @DavidCarlisle Thanks. I had forgotten about the special character mappings TeX has. – jpaugh Oct 21 '16 at 21:11
  • Hi @DavidCarlisle. This solution does not seem to work for mystrings defined as follows: \usepackage{xstring} \def\mystrings{\noindent\StrSubstitute{% B; new; test old; found people; sun; atom; number; life}% {; }{\noexpand\noexpand\noexpand\newline}} \mystrings. Should I ask a new question for this? – Krantz Oct 28 '23 at 13:14
  • @Krantz I can't see how that's related to the question or this answer, it doesn't use ^^J at all. – David Carlisle Oct 28 '23 at 13:25
  • Thanks @DavidCarlisle. I will open a new question then. – Krantz Oct 28 '23 at 13:27
  • Hi @DavidCarlisle. I would appreciate your help if possible: https://tex.stackexchange.com/questions/699750/how-to-immediate-write-multiple-lines-produced-with-newline-and-strsubstitute. Thanks – Krantz Oct 28 '23 at 13:32