当前位置: 代码迷 >> 综合 >> LaTex:插入代码的listings包和lstlisting环境
  详细解决方案

LaTex:插入代码的listings包和lstlisting环境

热度:91   发布时间:2023-12-11 20:45:08.0

典型的应用示例代码:

% LaTex中插入高亮显示的代码需以下设定% 注意,代码中不能含有中文,否则为无法编译。
\usepackage[utf8]{inputenc}
%\usepackage[T1]{fontenc}
%\usepackage{textcomp}
\usepackage{listings}
% 在LaTex中添加代码
\usepackage{color}\definecolor{codegreen}{rgb}{0,0.6,0}
\definecolor{codegray}{rgb}{0.5,0.5,0.5}
\definecolor{codepurple}{rgb}{0.58,0,0.82}
\definecolor{backcolour}{rgb}{0.95,0.95,0.92}\lstdefinestyle{mystyle}{backgroundcolor=\color{backcolour},   commentstyle=\color{codegreen},keywordstyle=\color{magenta},numberstyle=\tiny\color{codegray},stringstyle=\color{codepurple},basicstyle=\footnotesize,breakatwhitespace=false,         breaklines=true,                 captionpos=b,                    keepspaces=true,                 numbers=left,                    numbersep=5pt,                  showspaces=false,                showstringspaces=false,showtabs=false,                  tabsize=2
}
\end{lstlisting}...
\begin{lstlisting}[language=C++]
#include <iostream>
using namespace std;
int main(){cout << "Hello world!" << endl;
}
\end{lstlisting}
</iostream>

效果如下:


如果lstlisting环境中含有中文等其它语言字符,pdfLaTex或LaTex编译时会有如下报错:

Package inputenc error unicode char u8:字 not set up for use with LaTex.

确实需要在lstlisting环境中插入中文的话,可设置“逃逸”字串,临时从lstlisting环境跳回到LaTex环境,从而显示相应的中文:

\lstset{style=mystyle, escapeinside=``}
\begin{lstlistings}
`我就要用中文`
\end{lstlistings}

或者,也可以用XeLaTex来编译,同样可以正常显示。

但是,有一种情况:如果你的lstlisting环境是跨页显示的,而恰好你又有含中文字符的页眉或页脚。这时,LaTex编译同样会报错,错误好像就出在页眉页脚也被纳入了lstlisting环境。这时你可以敲入s并回车以忽略这一系列错误强行编译,至少目前看来得到的PDF效果一样;但如果你跟主页菌一样是个完美主义者,偏想将这个错误完全解决掉,那请与我一起期待有经验者能在此倾囊相授。因为主页菌也还未找到有效办法。