21

How can the special characters { and } be written literally to an external file in LaTeX, without being balanced?

Obviously the following does not work:

 \immediate\write\my@outfile{{}
 \immediate\write\my@outfile{}}
Martin Scharrer
  • 262,582
Romildo
  • 4,093

3 Answers3

30

Writing balanced braces doesn't require anything special, as the following transcript of an interactive TeX session shows:

$ tex
This is TeX, Version 3.1415926 (TeX Live 2011)
**\relax
*\newwrite\mywr
*\immediate\openout\mywr=temp.dat
*\immediate\write\mywr{{}}
*\bye
No pages of output.
Transcript written on texput.log.
$ cat temp.dat
{}

If you want to write unbalanced braces you can do with

\begingroup
\catcode`<=1 \catcode`>=2
\catcode`{=12 \catcode`}=12
\gdef\wbgroup<{>
\gdef\wegroup<}>
\endgroup

\newwrite\mywr
\immediate\openout\mywr=temp.dat

\immediate\write\mywr{\wbgroup}
\immediate\write\mywr{\wegroup}

\bye

that is, using \wbgroup and \wegroup for writing open and close brace respectively. The contents of temp.dat will be

{
}

Notice that LaTeX already has equivalents of \wbgroup and \wegroup that are called \@charlb and \@charrb, which actually expand to category code 11 characters.

Alternative definitions for \wbgroup and \wegroup that expand to category code 12 characters are

\begingroup\lccode`?=`\{ \lccode`!=`\}
\lowercase{\endgroup\def\wbgroup{?}\def\wegroup{!}}

or

\edef\wbgroup{\iftrue\string{\else}\fi}
\edef\wegroup{\iffalse{\else\string}\fi}
egreg
  • 1,121,712
14

In order to write unbalanced braces you should use macros which hold them as verbatim characters instead. These will be expanded when written to the file. LaTeX2e defines \@charlb (left brace) and \@charrb (right brace) which require \makeatletter .. \makeatother of course. You can find these listed in source2e or better macros2e.

\immediate\write\my@outfile{\@charlb}
\immediate\write\my@outfile{\@charrb}

You can also define you own macro easily with \Verbdef from my newverbs package (not to be confused with \verbdef from the verbdef package). Macros define this way are usable to be written to an external file (in contrast to \verbdef which macros them typsetable).

\usepackage{newverbs}
\Verbdef\leftbrace|{|
\Verbdef\rightbrace|}|
% ...

\immediate\write\myoutfile{\leftbrace}
\immediate\write\myoutfile{\rightbrace}
Martin Scharrer
  • 262,582
  • The \Verbdef-Methode doesn't seem to work any more: "\protected" is inserted into the output (it worked well with TL2020 but not after I switched to TL2021). Edit: @charlb also doesn't seem to work. egreg's anwers works well. – lAtExFaN May 25 '21 at 12:17
3

Depends what you want to do, you can try escaping it

\newwrite\temp
\immediate\openout\temp=temp.dat
\immediate\write\temp{\}}
\bye

This will write \delimiter "5267309 in the temp.dat file or you can write \string\}, which will write \} in the file.

yannisl
  • 117,160