[Tex/LaTex] Uniform Unicode for text, math and listings

greeklistingsmath-modeunicodeunicode-math

What should I put in the preamble (preferably packages) for this to work as expected with its unicode characters?

\documentclass{article}
\usepackage{listings}
\begin{document}
  $α$ α
  \begin{lstlisting}
     α = 1.;
  \end{lstlisting}
\end{document}

Note that alpha (α) appears in three contexts: as text, as math and as code (listings).

(I can use lualatex if it simplifies things)


For a higher challenge, in this case I introduce a second level of difficulty, by introducing a second kind of alpha (𝛼: 0x1d6fc Mathematical italic small alpha vs. α: Greek small letter alpha). To see to what degree TeX can deal with the nuance (e.g. by make 𝛼 into $\alpha$, or by making 𝑝 –0x1D45D Mathematical italic small p– into $p$):

\documentclass[]{article}
\usepackage[]{listings}
\begin{document}
$α$ α $𝛼$ 𝛼 𝑝
\begin{lstlisting}
α = 1.
𝛼 = 2.
\end{lstlisting}
\end{document}

Best Answer

For the listings part of the question, you'll need something like the following (adapting the answers from the questions that @morbusg pointed to). This works in xelatex. I agree with @morbusg that the tricky part will be to find fonts that contain your glyphs, especially typewriter and math fonts.

\documentclass{article}
\usepackage{fontspec}
\setmainfont{FreeSerif}
\usepackage{listings}
\lstset{inputencoding=utf8,extendedchars=true}
\makeatletter
\lst@InputCatcodes
\def\lst@DefEC{%
 \lst@CCECUse \lst@ProcessLetter
  ^^^^03b1% α
  ^^^^^^01d6fc% 𝛼
  ^^^^^^01d45d% 𝑝
  ^^00}
\lst@RestoreCatcodes
\makeatother
\begin{document}
\begin{lstlisting}
α = 1.
𝛼 = 2.
𝑝 = 3.
\end{lstlisting}
\end{document}
Related Question