> For the complete documentation index, see [llms.txt](https://overleaf-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://overleaf-pro.ayaka.space/latex/zh-tw/ge-shi-hua/11-code-listing.md).

# 程式碼清單

## 簡介

LaTeX 在科學中被廣泛使用，而程式設計已成為科學多個領域中的重要一環，因此需要一個能正確顯示程式碼的工具。本文說明如何使用標準 **verbatim** 環境以及套件 **listings**，它們提供更進階的程式碼格式化功能。 [這篇獨立的文章](/latex/zh-tw/ge-shi-hua/12-code-highlighting-with-minted.md) 討論 `minted` 套件，它使用 Python 的 `僅支援已安裝或已向` 該函式庫。

## 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/c9fd761c6b74dacd83147bbdb0cf2f4a50755b38)

就像在前言中的範例一樣，所有文字都會在保留換行與空白的情況下輸出。這個指令也有一個帶星號的版本，其輸出會略有不同。

```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/2b4a1842358638384ba3963de6e4e04d2245df6d)

在這種情況下，空白會以特殊的「可見空白」字元強調： **`␣`**.

類似 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/c87a086bfcc227bc29691362734799ee487be02b)

命令 `\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 #將成為關聯矩陣
    VT = np.zeros((n*m,1), int)  #暫存變數

    #計算位元異或矩陣
    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}
```

[在 Overleaf 中開啟這個 `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/f1842458869ee606858883c1d9d74af3838e6abf)

在這個範例中，輸出會忽略所有 LaTeX 指令，並且文字會在保留輸入的所有換行與空白的情況下列印出來。讓我們看看第二個範例：

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

def incmatrix(genl1,genl2):
    m = len(genl1)
    n = len(genl2)
    M = None #將成為關聯矩陣
    VT = np.zeros((n*m,1), int)  #暫存變數

    #計算位元異或矩陣
    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}
```

[在 Overleaf 中開啟這個 `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/30e938e13362a6cfc5acf4ca1f9b8cc56bb7d428)

方括號中的附加參數 `[language=Python]` 可為此特定程式語言（Python）啟用程式碼上色，高亮顯示；特殊字詞會以粗體字型呈現，註解則會以斜體顯示。請參閱 [參考指南](#reference-guide) 以取得支援的程式語言完整清單。

## 從檔案匯入程式碼

程式碼通常儲存在原始檔中，因此一個能自動從檔案擷取程式碼的指令就非常方便。

```latex
接下來的程式碼將直接從檔案匯入

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

![CodeListingEx3.png](/files/8fc47c62f69dde81502debb260c4370726d28258)

命令 `\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/1ba8e2bd93f1e4dd738e9d8df853d89c23a60b71)

如你所見，程式碼的配色與樣式大幅提升了可讀性。

在這個範例中，套件 **xcolor** 被匯入，接著指令 `\definecolor{}{}{}` 用來定義稍後會使用的 RGB 格式新顏色。更多資訊請參閱： [在 LaTeX 中使用顏色](/latex/zh-tw/ge-shi-hua/13-using-colors-in-latex.md)

基本上有兩個指令可用來產生此範例的樣式：

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

定義一個名為「mystyle」的新程式碼列示樣式。第二組大括號內會傳入定義此樣式的選項；關於這些以及其他一些參數的完整說明，請參閱參考指南。

**\lstset{style=mystyle}**

啟用「mystyle」樣式。此指令可在文件中使用，以便在需要時切換到其他樣式。

## 標題與 Listings 清單

就像在浮動體（[表格](/latex/zh-tw/tu-biao-yu-biao-ge/01-tables.md) 和 [圖表](/latex/zh-tw/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 #將成為關聯矩陣
    VT = np.zeros((n*m,1), int)  #暫存變數

    #計算位元異或矩陣
    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}
```

[在 Overleaf 中開啟這個 `listings` Overleaf 上的範例](/latex/zh-tw/ge-shi-hua/11-code-listing.md)

上方程式碼會產生以下輸出：

![CodeListingEx5.png](/files/4ec92c3586ece46845f6b215dc24fab0bdcc7680)

加入以逗號分隔的參數 `caption=Python example` 放入方括號中即可啟用標題。之後這個標題可用於 Listings 清單。

```latex
\lstlistoflistings
```

![CodeListingEx6OLV2.png](/files/5e8b73c13e8ee785d8b9715c58fced512ccb6b50)

## 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）
* **數字** - 行號的位置（left/right/none，也就是不顯示行號）
* **prebreak** - 在換行的行尾顯示標記（例如 `prebreak=\raisebox{0ex}[0ex][0ex]{\ensuremath{\hookleftarrow}}`)
* **captionpos** - 標題的位置（t/b）
* **框線** - 在程式碼外顯示框線（none/leftline/topline/bottomline/lines/single/shadowbox）
* **breakatwhitespace** - 設定自動換行是否只在空白處發生
* **breaklines** - 自動換行
* **keepspaces** - 保留程式碼中的空白，對縮排很有用
* **tabsize** - 預設定位字元大小
* **escapeinside** - 指定從原始碼跳脫到 LaTeX 的字元（例如 `escapeinside={\%*}{*)}`)
* **rulecolor** - 指定框線方塊的顏色

## 延伸閱讀

詳情請見：

* [使用 minted 進行程式碼高亮](/latex/zh-tw/ge-shi-hua/12-code-highlighting-with-minted.md)
* [在 LaTeX 中使用顏色](/latex/zh-tw/ge-shi-hua/13-using-colors-in-latex.md)
* [目錄](/latex/zh-tw/wen-jian-jie-gou/02-table-of-contents.md)
* [大型專案中的管理](/latex/zh-tw/wen-jian-jie-gou/07-management-in-a-large-project.md)
* [多檔案 LaTeX 專案](/latex/zh-tw/wen-jian-jie-gou/08-multi-file-latex-projects.md)
* [字型大小、字族與樣式](/latex/zh-tw/zi-xing/01-font-sizes-families-and-styles.md)
* [字型字體](/latex/zh-tw/zi-xing/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://overleaf-pro.ayaka.space/latex/zh-tw/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.
