如何在 Latext 中的代码列表(lstlisting)中写瑞典字母?

如何在 Latext 中的代码列表(lstlisting)中写瑞典字母?

我正在 lstlisting 中编写 R 代码:

\documentclass{article} 
\usepackage{listings}
\usepackage[swedish,english]{babel}
\usepackage{xcolor}
\usepackage{color}
\definecolor{ForestGreen}{rgb}{0.0, 0.5, 0.0}
\lstset{language=R,
basicstyle=\small\ttfamily,
stringstyle=\color{ForestGreen},
otherkeywords={0,1,2,3,4,5,6,7,8,9},
morekeywords={TRUE,FALSE},
deletekeywords={data,frame,length,as,character},
keywordstyle=\color{blue},
commentstyle=\color{ForestGreen},
breaklines=true,
postbreak=\mbox{\textcolor{red}{$\hookrightarrow$}\space},
}

\begin{document}
\begin{lstlisting}
   studentsNames = c("Björn","Hökan")
\end{lstlisting}
\end{document}

但是 latex 返回错误,无法在 lstlisting 中显示瑞典字母 (ö、å、ä)。有什么解决办法吗?

答案1

您可以通过关键字定义一些UTF-8字符(由两个或多个字节编码)literate

\documentclass{article} 
\usepackage{listings}
\usepackage[swedish,english]{babel}
\usepackage{xcolor}
\usepackage{color}
\definecolor{ForestGreen}{rgb}{0.0, 0.5, 0.0}
\lstset{language=R,
basicstyle=\small\ttfamily,
stringstyle=\color{ForestGreen},
otherkeywords={0,1,2,3,4,5,6,7,8,9},
morekeywords={TRUE,FALSE},
deletekeywords={data,frame,length,as,character},
keywordstyle=\color{blue},
commentstyle=\color{ForestGreen},
breaklines=true,
postbreak=\mbox{\textcolor{red}{$\hookrightarrow$}\space},
}

\lstset{
  literate=
  {á}{{\'a}}1 {é}{{\'e}}1 {í}{{\'i}}1 {ó}{{\'o}}1 {ú}{{\'u}}1
  {Á}{{\'A}}1 {É}{{\'E}}1 {Í}{{\'I}}1 {Ó}{{\'O}}1 {Ú}{{\'U}}1
  {à}{{\`a}}1 {è}{{\`e}}1 {ì}{{\`i}}1 {ò}{{\`o}}1 {ù}{{\`u}}1
  {À}{{\`A}}1 {È}{{\'E}}1 {Ì}{{\`I}}1 {Ò}{{\`O}}1 {Ù}{{\`U}}1
  {ä}{{\"a}}1 {ë}{{\"e}}1 {ï}{{\"i}}1 {ö}{{\"o}}1 {ü}{{\"u}}1
  {Ä}{{\"A}}1 {Ë}{{\"E}}1 {Ï}{{\"I}}1 {Ö}{{\"O}}1 {Ü}{{\"U}}1
  {â}{{\^a}}1 {ê}{{\^e}}1 {î}{{\^i}}1 {ô}{{\^o}}1 {û}{{\^u}}1
  {Â}{{\^A}}1 {Ê}{{\^E}}1 {Î}{{\^I}}1 {Ô}{{\^O}}1 {Û}{{\^U}}1
  {œ}{{\oe}}1 {Œ}{{\OE}}1 {æ}{{\ae}}1 {Æ}{{\AE}}1 {ß}{{\ss}}1
  {ç}{{\c c}}1 {Ç}{{\c C}}1 {ø}{{\o}}1 {å}{{\r a}}1 {Å}{{\r A}}1
  {€}{{\texteuro}}1 {£}{{\pounds}}1
  {«}{{<<}}1 {»}{{>>}}1
  {°}{{\up{o}}}1
}

\begin{document}
\begin{lstlisting}
   studentsNames = c("Björn","Hökan")
\end{lstlisting}
\end{document}

答案2

当我使用 XeLaTeX 运行你的代码时,一切正常,但在 pdfLaTeX 中我得到了:

! Package inputenc Error: Invalid UTF-8 byte sequence.

不同之处在于 pdfLaTeX 并不真正理解 UTF-8,而且由于lstlisting每次解析输入的一个字符,这是差异所在。Unicode 引擎 XeLaTeX 和 LuaLaTeX 理解这0xC3 0xB6是一个字符,但 pdfLaTeX 会很乐意将其拆分,然后对结果感到不满。

相关内容