3

I'm writing the document title to a file using the command \immediate\write\myfile{\@title}, but it fails if the title contains newlines \\.

How can I strip newlines (or even better any kind of formatting, ~ included) from \@title? I've tried solutions like this one and this one, but without success.

Thanks in advance for any clue.

mmj
  • 1,702
  • Many more things will fail this way: accented letters, for instance. What \\ should be replaced with? – egreg May 27 '18 at 09:32
  • 1
    @egreg Newlines should be replaced with a long hypen (the same generated by --). If it fails with accented letters would be a problem too. – mmj May 27 '18 at 09:35

1 Answers1

5

Many more things will fail with \immediate\write.

I suggest getting an “immediate” version of \protected@write:

\documentclass{article}
\usepackage{xpatch}

\makeatletter
% get a copy of `\protected@write
\let\protected@iwrite\protected@write
% patch the copy to add \immediate
\xpatchcmd{\protected@iwrite}{\write}{\immediate\write}{}{}
\makeatother

\newwrite\titlefile


\begin{document}

\author{A. Uthor}
\title{A title with \'accent \\ and new~line}

\immediate\openout\titlefile=\jobname.title
\makeatletter
\protected@iwrite\titlefile{\def\\{--}\def~{ }}{\@title}
\immediate\closeout\titlefile
\makeatother

\maketitle

\end{document}

See https://tex.stackexchange.com/a/110885/4427 for further information.

With this setup, the file \jobname.title will contain

A title with \'accent -- and new line
egreg
  • 1,121,712
  • Tha solution is excellent, and it would be perfect if only it could save accented letters directly to file. – mmj May 27 '18 at 10:59
  • @mmj That possibility depends on several factors. With pdflatex and UTF-8 it's going to be quite difficult. – egreg May 27 '18 at 12:05
  • Would it be possible with XeTeX or other TeX processor? – mmj May 27 '18 at 13:36
  • 1
    @mmj Yes, with XeTeX or LuaTeX you can input directly the accented character and no transformation is performed. – egreg May 27 '18 at 13:37