无效字符错误:使用 pdflatex 和 xelatex 列出带有 unicode 字符的列表

无效字符错误:使用 pdflatex 和 xelatex 列出带有 unicode 字符的列表

以下代码在 xelatex 中运行良好。在 pdflatex 中,它会出现无效字符错误 ^^00。如果我注释掉该行,它就可以正常工作。可能是输入编码问题,但找不到答案。

% !TeX encoding = UTF-8
% !TeX program  = pdflatex
\documentclass{minimal}
\usepackage{iftex}
\ifxetex
    \usepackage{fontspec}
    \setmonofont{Fira Mono}
 \else
    \usepackage[utf8]{inputenc}
    \usepackage[T1]{fontenc}
\fi

\usepackage{listings}
\lstset{inputencoding=utf8, 
        extendedchars=true,
        basicstyle=\ttfamily}

\ifxetex
    \begingroup% ......... by Heiko Oberdiek
       \catcode0=12 %
       \makeatletter         
        \g@addto@macro\lst@DefEC{%
            \lst@CCECUse\lst@ProcessLetter
            μΔΩθφ% ... add Unicode characters
            ^^00%  ... end marker [This line cause error with pdflatex]
            }%
    \endgroup
\else
    \usepackage{textgreek}
    \lstset{literate= 
        {μ}{{\textmu}}1
        {Δ}{{\textDelta}}1
        {Ω}{{\textOmega}}1
        {θ}{{\texttheta}}1
        {φ}{{\textphi}}1
        {°}{{$^{\circ}$}}1}
\fi

\begin{document}
\begin{lstlisting}
  label = 'Δφ=6°'
\end{lstlisting}
\end{document}

答案1

我看到你把两个补丁合并到了listings以下软件包中

使其与 XeLaTeX 和 LuaLaTeX 兼容。


错误消息的原因是“显而易见的”(catcode 0 = 15 是非法的,并且此类字符不能出现在跳过的文本中),但需要了解 TeX 引擎的工作原理。(资源:例如我应该从哪里开始 LaTeX 编程?

无论如何,下面我给出了一个相当有效的解决方法:

%! TEX program = pdflatex

\documentclass{minimal}
\usepackage{iftex}
\ifxetex
    \usepackage{fontspec}
    %\setmonofont{Fira Mono}  % my machine doesn't have this font either
\else
    \usepackage[utf8]{inputenc}
    \usepackage[T1]{fontenc}
\fi

\usepackage{listings}
\lstset{inputencoding=utf8, 
        extendedchars=true,
        basicstyle=\ttfamily}


\ifxetex
    \begingroup
       \catcode0=12 %
       \catcode`!=7 %
       \makeatletter
        \g@addto@macro\lst@DefEC{%
            \lst@CCECUse\lst@ProcessLetter
            μΔΩθφ% ... add Unicode characters
            !!00%
            }%
    \endgroup
\else
    %\usepackage{textgreek}  % unfortunately on my machine this package doesn't exist so I use a rudimentary substitute below
    %\lstset{literate= 
    %   {μ}{{\textmu}}1
    %   {Δ}{{\textDelta}}1
    %   {Ω}{{\textOmega}}1
    %   {θ}{{\texttheta}}1
    %   {φ}{{\textphi}}1
    %   {°}{{$^{\circ}$}}1}
    % note that \lstset must be outside the group for it to be effective!
    \lstset{literate= 
        {μ}{{$\mu$}}1
        {Δ}{{$\Delta$}}1
        {Ω}{{$\Omega$}}1
        {θ}{{$\theta$}}1
        {φ}{{$\phi$}}1
        {°}{{$^{\circ}$}}1}
\fi



\begin{document}
\begin{lstlisting}
  label = 'Δφ=6°'
\end{lstlisting}
\end{document}

相关内容