I am trying to output some information to an auxiliary file using \write and among other things I have authors names that often include accented letters. If I use the string explicitly, the accented letters are expanded into TeX commands, but I can solve this by using \unexpanded. However, if the string is contained in a variable, and I use \unexpanded, I get the name of the variable instead of its content. The command \unexpanded works fine again if the variable is a command parameter, for example #1.
I don't have an understanding of expansion that is clear enough to sort this out, so any help is appreciated. All I want to do is to write the content of a variable holding a string with accented letters to the text file.
Here is a minimal example:
\documentclass{article}
\usepackage[utf8]{inputenc}
\newwrite\file
\immediate\openout\file=\jobname_extra.txt
\AtEndDocument{\closeout\file}
\begin{document}
\immediate\write\file{Test 1} % works fine
\immediate\write\file{José} % expands into TeX code
\immediate\write\file{\unexpanded{José}} % works fine
\def\mystring{José}
\immediate\write\file{\mystring} % expands into TeX code
\immediate\write\file{\unexpanded{\mystring}} % outputs \mystring literally
\newcommand{\writeaccented}[1]{
\immediate\write\file{\unexpanded{#1}}
}
\writeaccented{José} % works fine
\end{document}
EDIT: I received two answers to use either \expandafter\unexpanded\expandafter{\mystring} or \detokenize\expandafter{\mystring}. These work fine on the minimal example above, but not on the real example, making me think that the expansion in my case is happening earlier. Here is the new minimal example that is closer to my real case:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{xstring}
\newwrite\file
\immediate\openout\file=\jobname_extra.txt
\AtEndDocument{\closeout\file}
\begin{document}
\def\listofauthors{José Saramago, Luigi Pirandello and Władysław Reymont}
\makeatletter
\StrSubstitute[0]{\listofauthors}{, }{,}[\@cpauthors]
\StrSubstitute[0]{\@cpauthors}{ and }{,}[\@cpauthors]
\@for \@cpauthor:=\@cpauthors\do{%
\immediate\write\file{<author>\expandafter\unexpanded\expandafter{\@cpauthor}</author>}
}
\makeatother
\end{document}
EDIT 2: adding \usepackage[T1]{fontenc} prevents the expansion into TeX commands, but outputs accented letters in ISO-8859 encoding instead of unicode. I tried both with and without the proposed solutions.
EDIT 3: the solution that worked for me is in https://tex.stackexchange.com/a/390119/36823. Thank you!
\protected@write{\file}{}{content}but that will only be done after a shipout of page. – Sep 06 '17 at 15:18\StrSubstitutemust expand something before it can store it to another macro. – Sep 06 '17 at 16:53