[Tex/LaTex] The ‘listings’ package and UTF-8

listingsunicodexetex

Please, do you know if there's any possibility how to use the listings package together with XeLaTeX? I have to use XelaTeX and therefore I have UTF-8 encoded files. This is not compatible with listings which allows one-byte encoding. (I know there is listingsutf8 package, but it converts files from UTF-8 which I don't need.)

The listings package works somehow, bu I only can use English letters. I've fond some solution like a list of special characters ( Having problems with listings and UTF-8. Can it be fixed? ) but it seems it works only for some letters. It there anything that would support UTF-8 in listing 'naturally'?

Best Answer

The link you are mentioning is for 8-bit engines like pdflatex, it will not work with xetex or luatex.

With xelatex + lualatex chars with unicode positions below 256 will work out of the box:

\documentclass{article}
\usepackage{listings,fontspec}
\begin{document}
\begin{lstlisting}
öäü é è ß 
\end{lstlisting}
\end{document}

Things get more complicated if you want to use chars above 256. E.g. an € or the french "oe" or greek etc. In this case you will have to add them to the processing list of listings first and use extendedchars=true. Here an example which adds the euro and the french oe and Oe (the middle listings shows the problems without the extended definitions):

\documentclass{article}
\usepackage{fontspec}
\usepackage{listings}

\makeatletter
\lst@InputCatcodes
\def\lst@DefEC{%
 \lst@CCECUse \lst@ProcessLetter
  ^^80^^81^^82^^83^^84^^85^^86^^87^^88^^89^^8a^^8b^^8c^^8d^^8e^^8f%
  ^^90^^91^^92^^93^^94^^95^^96^^97^^98^^99^^9a^^9b^^9c^^9d^^9e^^9f%
  ^^a0^^a1^^a2^^a3^^a4^^a5^^a6^^a7^^a8^^a9^^aa^^ab^^ac^^ad^^ae^^af%
  ^^b0^^b1^^b2^^b3^^b4^^b5^^b6^^b7^^b8^^b9^^ba^^bb^^bc^^bd^^be^^bf%
  ^^c0^^c1^^c2^^c3^^c4^^c5^^c6^^c7^^c8^^c9^^ca^^cb^^cc^^cd^^ce^^cf%
  ^^d0^^d1^^d2^^d3^^d4^^d5^^d6^^d7^^d8^^d9^^da^^db^^dc^^dd^^de^^df%
  ^^e0^^e1^^e2^^e3^^e4^^e5^^e6^^e7^^e8^^e9^^ea^^eb^^ec^^ed^^ee^^ef%
  ^^f0^^f1^^f2^^f3^^f4^^f5^^f6^^f7^^f8^^f9^^fa^^fb^^fc^^fd^^fe^^ff%
  ^^^^20ac^^^^0153^^^^0152% nouveau pour xetex
  ^^00}
\lst@RestoreCatcodes
\makeatother
\begin{document}
\begin{lstlisting}[extendedchars=true]%default je pense
bœuf BŒeuf a€e
Dès Noël où un zéphyr haï me
vêt de glaçons würmiens je
dîne d'exquis rôtis de bœuf
au kir à l'aÿ d'âge mûr \& cætera!
\end{lstlisting}

\begin{lstlisting}[extendedchars=false]
bœuf BŒeuf a€e
Dès Noël où un zéphyr haï me
vêt de glaçons würmiens je
dîne d'exquis rôtis de bœuf
au kir à l'aÿ d'âge mûr \& cætera!
\end{lstlisting}


\begin{lstlisting}[language=XML]
bœuf BŒeuf a€e
Dès Noël où un zéphyr haï me
vêt de glaçons würmiens je
dîne d'exquis rôtis de bœuf
au kir à l'aÿ d'âge mûr \& cætera!
\end{lstlisting}
\end{document}

Output:

enter image description here