> For the complete documentation index, see [llms.txt](https://ayakaleaf-pro.ayaka.space/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ayakaleaf-pro.ayaka.space/latex/zh-cn/ge-shi-hua/11-code-listing.md).

# 代码列表

## 引言

LaTeX 在科学领域被广泛使用，而编程已成为科学多个领域中的一个重要方面，因此需要一款能够正确显示代码的工具。本文介绍如何使用标准 **verbatim** 环境以及宏包 **listings**，它们提供更高级的代码格式化功能。 [这篇单独的文章](/latex/zh-cn/ge-shi-hua/12-code-highlighting-with-minted.md) 讨论了 `minted` 宏包，它使用 Python 的 `pygmentize` 库。

## verbatim 环境

LaTeX 中用于显示代码的默认工具是 `verbatim`，它会生成等宽字体的输出。

```latex
\begin{verbatim}
包在 \texttt{verbatim} 环境中的文本
会直接打印
，并且所有 \LaTeX{} 命令都会被忽略。
\end{verbatim}
```

[在 Overleaf 中打开此示例](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=verbatim+text+example\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cbegin%7Bdocument%7D%0A%5Cbegin%7Bverbatim%7D%0AText+enclosed+inside+%5Ctexttt%7Bverbatim%7D+environment+%0Ais+printed+directly+%0Aand+all+%5CLaTeX%7B%7D+commands+are+ignored.%0A%5Cend%7Bverbatim%7D%0A%5Cend%7Bdocument%7D)

上面的代码会生成如下输出：

![Verbatim1.png](/files/3fadbf196b0b27f0e04d79aa3ad911f89ee803f8)

正如引言中的示例一样，所有文本都会在保留换行和空白的情况下打印出来。这个命令还有一个带星号的版本，其输出略有不同。

```latex
\begin{verbatim*}
包在 \texttt{verbatim} 环境中的文本
会直接打印
，并且所有 \LaTeX{} 命令都会被忽略。
\end{verbatim*}
```

[在 Overleaf 中打开此示例](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=verbatim+text+example\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cbegin%7Bdocument%7D%0A%5Cbegin%7Bverbatim%2A%7D%0AText+enclosed+inside+%5Ctexttt%7Bverbatim%7D+environment+%0Ais+printed+directly+%0Aand+all+%5CLaTeX%7B%7D+commands+are+ignored.%0A%5Cend%7Bverbatim%2A%7D%0A%5Cend%7Bdocument%7D)

上面的代码会生成如下输出：

![Verbatim2.png](/files/89c67d874a17e8d70c0f620f46533ac3d901e46c)

在这种情况下，空格会通过一个特殊的“可见空格”字符来强调： **`␣`**.

类似 verbatim 的文本也可以通过以下方式在段落中使用： `\verb` 该命令。

```latex
在目录 \verb|C:\Windows\system32| 中，你可以找到许多 Windows
系统应用程序。

\verb+\ldots+ 命令会生成 \ldots
```

[在 Overleaf 中打开此示例](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=using+the+%5Cverb+command\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cbegin%7Bdocument%7D%0AIn+the+directory+%5Cverb%7CC%3A%5CWindows%5Csystem32%7C+you+can+find+a+lot+of+Windows+%0Asystem+applications.+%0A+%0AThe+%5Cverb%2B%5Cldots%2B+command+produces+%5Cldots%0A%5Cend%7Bdocument%7D)

上面的代码会生成如下输出：

![Verbatim3OLV2.png](/files/868e701e51f734a9abb7c421906785d20740d3dc)

命令 `\verb|C:\Windows\system32|` 会以 verbatim 格式打印分隔符内的文本 `|` 。除了字母和 `*`之外，任何字符都可以用作分隔符。例如 `\verb+\ldots+` 使用 `+` 作为分隔符。

## 使用 listings 对代码进行高亮

要使用 `lstlisting` 环境，你需要在文档导言区添加下面这一行：

```latex
\usepackage{listings}
```

下面是一个使用 `lstlisting` 环境的 `listings` 宏包的示例代码：

```latex
\begin{lstlisting}
import numpy as np

def incmatrix(genl1,genl2):
    m = len(genl1)
    n = len(genl2)
    M = None #to become the incidence matrix
    VT = np.zeros((n*m,1), int)  #dummy variable

    #compute the bitwise xor matrix
    M1 = bitxormatrix(genl1)
    M2 = np.triu(bitxormatrix(genl2),1)

    for i in range(m-1):
        for j in range(i+1, m):
            [r,c] = np.where(M2 == M1[i,j])
            for k in range(len(r)):
                VT[(i)*n + r[k]] = 1;
                VT[(i)*n + c[k]] = 1;
                VT[(j)*n + r[k]] = 1;
                VT[(j)*n + c[k]] = 1;

                if M is None:
                    M = np.copy(VT)
                else:
                    M = np.concatenate((M, VT), 1)

                VT = np.zeros((n*m,1), int)

    return M
\end{lstlisting}
```

[打开此 `listings` Overleaf 上的示例](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=listings+package+example\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cusepackage%7Blistings%7D%0A%5Cbegin%7Bdocument%7D%0A%5Cbegin%7Blstlisting%7D%0Aimport+numpy+as+np%0A++++%0Adef+incmatrix%28genl1%2Cgenl2%29%3A%0A++++m+%3D+len%28genl1%29%0A++++n+%3D+len%28genl2%29%0A++++M+%3D+None+%23to+become+the+incidence+matrix%0A++++VT+%3D+np.zeros%28%28n%2Am%2C1%29%2C+int%29++%23dummy+variable%0A++++%0A++++%23compute+the+bitwise+xor+matrix%0A++++M1+%3D+bitxormatrix%28genl1%29%0A++++M2+%3D+np.triu%28bitxormatrix%28genl2%29%2C1%29+%0A%0A++++for+i+in+range%28m-1%29%3A%0A++++++++for+j+in+range%28i%2B1%2C+m%29%3A%0A++++++++++++%5Br%2Cc%5D+%3D+np.where%28M2+%3D%3D+M1%5Bi%2Cj%5D%29%0A++++++++++++for+k+in+range%28len%28r%29%29%3A%0A++++++++++++++++VT%5B%28i%29%2An+%2B+r%5Bk%5D%5D+%3D+1%3B%0A++++++++++++++++VT%5B%28i%29%2An+%2B+c%5Bk%5D%5D+%3D+1%3B%0A++++++++++++++++VT%5B%28j%29%2An+%2B+r%5Bk%5D%5D+%3D+1%3B%0A++++++++++++++++VT%5B%28j%29%2An+%2B+c%5Bk%5D%5D+%3D+1%3B%0A++++++++++++++++%0A++++++++++++++++if+M+is+None%3A%0A++++++++++++++++++++M+%3D+np.copy%28VT%29%0A++++++++++++++++else%3A%0A++++++++++++++++++++M+%3D+np.concatenate%28%28M%2C+VT%29%2C+1%29%0A++++++++++++++++%0A++++++++++++++++VT+%3D+np.zeros%28%28n%2Am%2C1%29%2C+int%29%0A++++%0A++++return+M%0A%5Cend%7Blstlisting%7D%0A%5Cend%7Bdocument%7D)

上面的代码会生成如下输出：

![CodeListingEx1.png](/files/0dcd016a04ce6c507411d84540d6eb8fde4fa0d0)

在这个示例中，输出会忽略所有 LaTeX 命令，并且文本会在保留输入的所有换行和空白的情况下打印出来。让我们看第二个示例：

```latex
\begin{lstlisting}[language=Python]
import numpy as np

def incmatrix(genl1,genl2):
    m = len(genl1)
    n = len(genl2)
    M = None #to become the incidence matrix
    VT = np.zeros((n*m,1), int)  #dummy variable

    #compute the bitwise xor matrix
    M1 = bitxormatrix(genl1)
    M2 = np.triu(bitxormatrix(genl2),1)

    for i in range(m-1):
        for j in range(i+1, m):
            [r,c] = np.where(M2 == M1[i,j])
            for k in range(len(r)):
                VT[(i)*n + r[k]] = 1;
                VT[(i)*n + c[k]] = 1;
                VT[(j)*n + r[k]] = 1;
                VT[(j)*n + c[k]] = 1;

                if M is None:
                    M = np.copy(VT)
                else:
                    M = np.concatenate((M, VT), 1)

                VT = np.zeros((n*m,1), int)

    return M
\end{lstlisting}
```

[打开此 `listings` Overleaf 上的示例](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=Python+listings+package+example\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cusepackage%7Blistings%7D%0A%5Cbegin%7Bdocument%7D%0A%5Cbegin%7Blstlisting%7D%5Blanguage%3DPython%5D%0Aimport+numpy+as+np%0A++++%0Adef+incmatrix%28genl1%2Cgenl2%29%3A%0A++++m+%3D+len%28genl1%29%0A++++n+%3D+len%28genl2%29%0A++++M+%3D+None+%23to+become+the+incidence+matrix%0A++++VT+%3D+np.zeros%28%28n%2Am%2C1%29%2C+int%29++%23dummy+variable%0A++++%0A++++%23compute+the+bitwise+xor+matrix%0A++++M1+%3D+bitxormatrix%28genl1%29%0A++++M2+%3D+np.triu%28bitxormatrix%28genl2%29%2C1%29+%0A%0A++++for+i+in+range%28m-1%29%3A%0A++++++++for+j+in+range%28i%2B1%2C+m%29%3A%0A++++++++++++%5Br%2Cc%5D+%3D+np.where%28M2+%3D%3D+M1%5Bi%2Cj%5D%29%0A++++++++++++for+k+in+range%28len%28r%29%29%3A%0A++++++++++++++++VT%5B%28i%29%2An+%2B+r%5Bk%5D%5D+%3D+1%3B%0A++++++++++++++++VT%5B%28i%29%2An+%2B+c%5Bk%5D%5D+%3D+1%3B%0A++++++++++++++++VT%5B%28j%29%2An+%2B+r%5Bk%5D%5D+%3D+1%3B%0A++++++++++++++++VT%5B%28j%29%2An+%2B+c%5Bk%5D%5D+%3D+1%3B%0A++++++++++++++++%0A++++++++++++++++if+M+is+None%3A%0A++++++++++++++++++++M+%3D+np.copy%28VT%29%0A++++++++++++++++else%3A%0A++++++++++++++++++++M+%3D+np.concatenate%28%28M%2C+VT%29%2C+1%29%0A++++++++++++++++%0A++++++++++++++++VT+%3D+np.zeros%28%28n%2Am%2C1%29%2C+int%29%0A++++%0A++++return+M%0A%5Cend%7Blstlisting%7D%0A%5Cend%7Bdocument%7D)

上面的代码会生成如下输出：

![CodeListingEx2.png](/files/461f0a330d73b5c1df2329a47c335e714b97fbce)

方括号中的附加参数 `[language=Python]` 可为该特定编程语言（Python）启用代码高亮，关键字会以粗体显示，注释会以斜体显示。请参见 [参考指南](#reference-guide) 以查看支持的编程语言完整列表。

## 从文件导入代码

代码通常存储在源文件中，因此一个能自动从文件中提取代码的命令会非常方便。

```latex
下面的代码将直接从文件

\lstinputlisting[language=Octave]{BitXorMatrix.m}
```

![CodeListingEx3.png](/files/117373d11fbe7f81f74fdfb098498d738321ee5a)

命令 `\lstinputlisting[language=Octave]{BitXorMatrix.m}` 从文件 *BitXorMatrix.m*导入；方括号中的附加参数可为 Octave 编程语言启用高亮。如果你只需要导入文件的一部分，可以在方括号中指定两个以逗号分隔的参数。例如，要导入第 2 行到第 12 行的代码，前面的命令变为

```latex
\lstinputlisting[language=Octave, firstline=2, lastline=12]{BitXorMatrix.m}
```

如果 `firstline` 或 `lastline` 被省略时，则分别默认取文件开头或文件结尾。

## 代码样式与颜色

使用 **listing** 宏包进行代码格式化具有很高的可定制性。让我们看一个示例

```latex
\documentclass{article}
\usepackage{listings}
\usepackage{xcolor}

\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=\ttfamily\footnotesize,
    breakatwhitespace=false,
    breaklines=true,
    captionpos=b,
    keepspaces=true,
    numbers=left,
    numbersep=5pt,
    showspaces=false,
    showstringspaces=false,
    showtabs=false,
    tabsize=2
}

\lstset{style=mystyle}

\begin{document}
下面的代码将直接从文件

\lstinputlisting[language=Octave]{BitXorMatrix.m}
\end{document}
```

上面的代码会生成如下输出：

![CodeListingEx4.png](/files/7ae3136039169e9e129994375df871f0fe32836c)

如你所见，代码着色和样式显著提高了可读性。

在这个示例中，宏包 **xcolor** 被导入，然后命令 `\definecolor{}{}{}` 用于定义后续会使用的 rgb 格式新颜色。更多信息请参见： [在 LaTeX 中使用颜色](/latex/zh-cn/ge-shi-hua/13-using-colors-in-latex.md)

这个示例的样式生成主要有两个命令：

**\lstdefinestyle{mystyle}{...}**

定义一个名为 “mystyle” 的新代码列表样式。在第二对花括号中传入定义该样式的选项；有关这些参数以及其他一些参数的完整说明，请参阅参考指南。

**\lstset{style=mystyle}**

启用 “mystyle” 样式。必要时，可以在文档中使用此命令切换到不同的样式。

## 标题与 Listings 列表

就像在浮动体（[表](/latex/zh-cn/tu-xing-he-biao-ge/01-tables.md) 和 [图](/latex/zh-cn/geng-duo-zhu-ti/27-inserting-images.md)），标题也可以添加到列表中，以便更清晰地展示。

```latex
\begin{lstlisting}[language=Python, caption=Python example]
import numpy as np

def incmatrix(genl1,genl2):
    m = len(genl1)
    n = len(genl2)
    M = None #to become the incidence matrix
    VT = np.zeros((n*m,1), int)  #dummy variable

    #compute the bitwise xor matrix
    M1 = bitxormatrix(genl1)
    M2 = np.triu(bitxormatrix(genl2),1)

    for i in range(m-1):
        for j in range(i+1, m):
            [r,c] = np.where(M2 == M1[i,j])
            for k in range(len(r)):
                VT[(i)*n + r[k]] = 1;
                VT[(i)*n + c[k]] = 1;
                VT[(j)*n + r[k]] = 1;
                VT[(j)*n + c[k]] = 1;

                if M is None:
                    M = np.copy(VT)
                else:
                    M = np.concatenate((M, VT), 1)

                VT = np.zeros((n*m,1), int)

    return M
\end{lstlisting}
```

[打开此 `listings` Overleaf 上的示例](/latex/zh-cn/ge-shi-hua/11-code-listing.md)

上面的代码会生成如下输出：

![CodeListingEx5.png](/files/16dd0138b55e8c1950f34851138cca207d6bf598)

添加逗号分隔的参数 `caption=Python example` 到方括号中，即可启用标题。之后，这个标题还可用于 Listings 列表。

```latex
\lstlistoflistings
```

![CodeListingEx6OLV2.png](/files/681929d58b9c761cad68b84798efa3bfb66f519c)

## Overleaf 示例项目

打开此链接以 [试用 `listings` 宏包示例（Overleaf 上）。](https://www.overleaf.com/project/new/template/20053?id=68266290\&templateName=listings+package+demo\&latexEngine=pdflatex\&texImage=texlive-full%3A2020.1\&mainFile=)

## 参考指南

### 支持的语言

**支持的语言（如果可能，也包括其方言；方言在括号中指定，默认方言以斜体显示）：**

|                                                        |                                                  |
| ------------------------------------------------------ | ------------------------------------------------ |
| ABAP (R/2 4.3, R/2 5.0, R/3 3.1, R/3 4.6C, *R/3 6.10*) | ACSL                                             |
| Ada (*2005*, 83, 95)                                   | Algol (60, *68*)                                 |
| Ant                                                    | Assembler (Motorola68k, x86masm)                 |
| Awk (*gnu*, POSIX)                                     | bash                                             |
| Basic (Visual)                                         | C (*ANSI*, Handel, Objective, Sharp)             |
| C++ (ANSI, GNU, *ISO*, Visual)                         | Caml (*light*, Objective)                        |
| CIL                                                    | Clean                                            |
| Cobol (1974, *1985*, ibm)                              | Comal 80                                         |
| command.com (*WinXP*)                                  | Comsol                                           |
| csh                                                    | Delphi                                           |
| Eiffel                                                 | Elan                                             |
| erlang                                                 | Euphoria                                         |
| Fortran (77, 90, *95*)                                 | GCL                                              |
| Gnuplot                                                | Haskell                                          |
| HTML                                                   | IDL (empty, CORBA)                               |
| inform                                                 | Java (empty, AspectJ)                            |
| JVMIS                                                  | ksh                                              |
| Lingo                                                  | Lisp (empty, Auto)                               |
| Logo                                                   | make (empty, gnu)                                |
| Mathematica (1.0, 3.0, *5.2*)                          | Matlab                                           |
| Mercury                                                | MetaPost                                         |
| Miranda                                                | Mizar                                            |
| ML                                                     | Modula-2                                         |
| MuPAD                                                  | NASTRAN                                          |
| Oberon-2                                               | OCL (decorative, *OMG*)                          |
| Octave                                                 | Oz                                               |
| Pascal (Borland6, *标准版*, XSC)                          | Perl                                             |
| PHP                                                    | PL/I                                             |
| Plasm                                                  | PostScript                                       |
| POV                                                    | Prolog                                           |
| Promela                                                | PSTricks                                         |
| Python                                                 | R                                                |
| Reduce                                                 | Rexx                                             |
| RSL                                                    | Ruby                                             |
| S (empty, PLUS)                                        | SAS                                              |
| Scilab                                                 | sh                                               |
| SHELXL                                                 | Simula (*67*, CII, DEC, IBM)                     |
| SPARQL                                                 | SQL                                              |
| tcl (empty, tk)                                        | TeX (AlLaTeX, common, LaTeX, *plain*, primitive) |
| VBScript                                               | Verilog                                          |
| VHDL (empty, AMS)                                      | VRML (*97*)                                      |
| XML                                                    | XSLT                                             |

### 自定义代码列表样式的选项

* **backgroundcolor** - 背景颜色。需要外部 ***color*** 或 ***xcolor*** 宏包。
* **commentstyle** - 源语言中注释的样式。
* **basicstyle** - 源代码的字号/字体族等（例如 `basicstyle=\ttfamily\small`)
* **keywordstyle** - 源语言中关键字的样式（例如 `keywordstyle=\color{red}`)
* **numberstyle** - 行号使用的样式
* **numbersep** - 行号与代码之间的距离
* **stringstyle** - 源语言中字面字符串的样式
* **showspaces** - 强调代码中的空格（true/false）
* **showstringspaces** - 强调字符串中的空格（true/false）
* **showtabs** - 强调代码中的制表符（true/false）
* **numbers** - 行号的位置（left/right/none，即不显示行号）
* **prebreak** - 换行末尾显示的标记（例如 `prebreak=\raisebox{0ex}[0ex][0ex]{\ensuremath{\hookleftarrow}}`)
* **captionpos** - 标题的位置（t/b）
* **frame** - 在代码外显示边框（none/leftline/topline/bottomline/lines/single/shadowbox）
* **breakatwhitespace** - 设置自动断行是否只在空白处发生
* **breaklines** - 自动换行
* **keepspaces** - 保留代码中的空格，对缩进很有用
* **tabsize** - 默认制表符宽度
* **escapeinside** - 指定从源代码转义到 LaTeX 的字符（例如 `escapeinside={\%*}{*)}`)
* **rulecolor** - 指定框线的颜色

## 进一步阅读

更多信息请参见：

* [使用 minted 进行代码高亮](/latex/zh-cn/ge-shi-hua/12-code-highlighting-with-minted.md)
* [在 LaTeX 中使用颜色](/latex/zh-cn/ge-shi-hua/13-using-colors-in-latex.md)
* [目录](/latex/zh-cn/wen-dang-jie-gou/02-table-of-contents.md)
* [大型项目中的管理](/latex/zh-cn/wen-dang-jie-gou/07-management-in-a-large-project.md)
* [多文件 LaTeX 项目](/latex/zh-cn/wen-dang-jie-gou/08-multi-file-latex-projects.md)
* [字体大小、字体族和样式](/latex/zh-cn/zi-ti/01-font-sizes-families-and-styles.md)
* [字体类型](/latex/zh-cn/zi-ti/02-font-typefaces.md)
* [**listings** 包文档](https://texdoc.org/serve/listings/0)
* [**listings** CTAN 网站](http://www.ctan.org/pkg/listings)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://ayakaleaf-pro.ayaka.space/latex/zh-cn/ge-shi-hua/11-code-listing.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
