> 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/texlive/zh-cn/yu-bao-xiang-guan/minted.md).

# {Minted}

本文演示如何使用 [`minted` 宏包](https://ctan.org/pkg/minted?lang=en) 在 LaTeX 文档中格式化并高亮显示编程语言源代码，先从一个示例开始：

```latex
\documentclass{article}
\usepackage{minted}
\begin{document}
\begin{minted}{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{minted}
\end{document}
```

此示例产生以下输出：

<p align="center"><img src="https://sharelatex-wiki-cdn-671420.c.cdn77.org/learn-scripts/images/f/f0/OLV2minted.png" alt="Example displaying the output of the minted package"></p>

这里有两个重要的命令。在导言区通过写入来导入宏包

```latex
\usepackage{minted}
```

然后标签 `\begin{minted}{python}` 和 `\end{minted}` 界定了一个将文本逐字打印为等宽字体并且对注释、关键字和函数应用颜色的环境。参数 `python` 是源代码所使用的编程语言。 `minted` 支持 150 多种编程和标记语言以及配置文件，详见 [参考指南](https://www.overleaf.com/learn/latex/Code_Highlighting_with_minted#Reference_guide) 以获取支持语言的列表。

**注意**： 对于 `minted` 能在你的 *本地* LaTeX 发行版上工作，还必须安装一个名为 [Pygments](https://pygments.org/) 的附加程序。 [Overleaf](https://www.overleaf.com/) 可以为你省去安装它以及运行特殊命令来编译文档的麻烦——在 Overleaf 上，使用 `minted` 的文档将可以“开箱即用”。

### 基本用法

如下面的示例所示， `minted` 环境可以配置以修改已排版代码的视觉呈现。在这里， `minted` 环境使用了几项以逗号分隔的参数，形式为 `key=value`:

```latex
\documentclass{article}
\usepackage{minted}
\usepackage{xcolor} % to access the named colour LightGray
\definecolor{LightGray}{gray}{0.9}
\begin{document}
\begin{minted}
[
frame=lines,
framesep=2mm,
baselinestretch=1.2,
bgcolor=LightGray,
fontsize=\footnotesize,
linenos
]
{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{minted}
\end{document}
```

此示例产生以下输出：

<p align="center"><img src="https://sharelatex-wiki-cdn-671420.c.cdn77.org/learn-scripts/images/f/ff/OLV2minted2.png" alt="Example applying formatting to typeset code produced by the minted package"></p>

本例中使用的参数有：

* `frame=lines`： 绘制两条线，一条在代码顶部一条在底部以给代码加框。其他可能的值有 `leftline`, `topline`, `bottomline` 和 `single`.
* `framesep=2mm`： 框与代码的间距设置为 2mm。其他 [长度单位](https://www.overleaf.com/learn/latex/Lengths_in_LaTeX) 也可以使用。
* `baselinestretch=1.2`： 将代码的行间距设置为 1.2。
* `bgcolor=LightGray`： 背景颜色设为 `LightGray`。 要使其工作，需要导入 `xcolor` 宏包。参见 [在 LaTeX 中使用颜色](https://www.overleaf.com/learn/latex/Using_colours_in_LaTeX) 以了解有关颜色操作的更多信息。
* `fontsize=\footnotesize`： 字体大小设置为 `footnotesize`。 可以设置任何其他 [字体大小](https://www.overleaf.com/learn/latex/Font_sizes_and_kinds%23Reference_guide) 。
* `linenos`： 启用行号。

其他可能有用的选项有：

* `mathescape`： 在代码注释中启用数学模式。
* `rulecolor`： 更改框线的颜色。
* `showspaces`： 启用特殊字符以使空格可见。

### 从文件包含代码

代码通常存储在源文件中，因此一个可自动从文件导入代码的命令非常方便，如下面的示例所示：

```latex
\documentclass{article}
\usepackage{minted}
\title{Importing files using minted}
\begin{document}
下面的代码将直接从文件中导入：

\inputminted{octave}{BitXorMatrix.m}
\end{document}
```

此示例产生以下输出：

<img src="https://sharelatex-wiki-cdn-671420.c.cdn77.org/learn-scripts/images/c/c8/OLV2mintedinput.png" alt="使用 minted 导入代码文件" height="392" width="600">

命令 `\inputminted{octave}{BitXorMatrix.m}` 从文件中导入代码 `BitXorMatrix.m`，参数 `octave` 告诉 LaTeX 代码的编程语言。该命令可以接受两个额外参数以仅导入文件的一部分；例如，要导入第 2 行到第 12 行的代码，命令变为：

```latex
\inputminted[firstline=2, lastline=12]{octave}{BitXorMatrix.m}
```

### 单行代码

如果你只需要输入一行代码，命令 `\mint`（其语法在下一个示例中给出）就可以做到。

{% code overflow="wrap" %}

```latex
单行代码格式化也适用于 \texttt{minted}。例如，像这样的一个小片段 HTML：
\mint{html}|<h2>Something <b>here</b></h2>|
\noindent 可以正确地格式化。
```

{% endcode %}

此示例产生以下输出：

<img src="https://sharelatex-wiki-cdn-671420.c.cdn77.org/learn-scripts/images/d/d9/OLV2mintedHTML.png" alt="使用 minted 的单行代码示例" height="112" width="600">

大括号之间的参数设置编程语言（在此情况为`html` 标记语言），实际要被格式化的文本由 '|' 字符界定。

### 自托管 Overleaf 的问题

如果你正在使用沙箱编译并且还使用一个 Overleaf 服务器来部署 Overleaf，minted 可能无法正常工作。有关详细信息，你可以查看： [issues/131](https://github.com/yu-i-i/overleaf-cep/issues/131)。 你需要启用 ARM 指令配置文件和某些系统调用以使 minted 工作。


---

# 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/texlive/zh-cn/yu-bao-xiang-guan/minted.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.
