LaTeX 使用minted进行代码高亮 Code Highlighting

原  文:Code Highlighting with minted
译  者:Xovee
翻译时间:2022年10月2日

文章目录

  • LaTeX 使用minted进行代码高亮 Code Highlighting
  • 介绍
  • 基础用法
  • 从文件中引入代码
  • 单行代码
  • 自定义的词法分析器(Lexers)
  • 颜色和样式表
  • 代码标题、标签和目录
  • 参考指南

介绍

本文介绍如何使用minted包来对 LaTeX 文档中的代码进行样式自定义和高亮。我们首先来看一个例子:

\documentclass{article}
\usepackage{minted}
\begin{document}
\begin{minted}{python}
import numpy as npdef incmatrix(genl1,genl2):m = len(genl1)n = len(genl2)M = None #to become the incidence matrixVT = np.zeros((n*m,1), int)  #dummy variable#compute the bitwise xor matrixM1 = 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}

效果:
LaTeX 使用minted进行代码高亮 Code Highlighting-编程之家
这里面有两个很重要的命令。在preamble我们首先引入包:

\usepackage{minted}

然后我们使用\begin{minted}{python}\end{minted}标签来创建一个代码环境,在这个环境中,文字为等宽字体,注释、关键字和函数等会加上颜色。参数python定义了环境中所展示代码的语言。minted包支持超过150种编程语言和自定义样式。你可以在这个指南中找到所有支持的语言。

Note:如果你使用LaTeX本地分发版,那么你必须安装一个额外的程序Pygments(地址)。如果你使用Overleaf,那么这个程序已经帮你安装好了,非常方便。

基础用法

在下面的例子中,我们介绍如何使用各种minted环境的参数来自定义代码的样式。

\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 npdef incmatrix(genl1,genl2):m = len(genl1)n = len(genl2)M = None #to become the incidence matrixVT = np.zeros((n*m,1), int)  #dummy variable#compute the bitwise xor matrixM1 = 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}

效果:
LaTeX 使用minted进行代码高亮 Code Highlighting-编程之家
使用到的参数包括:

  • frame=lines:在代码的顶部和底部画两条线。你还可以使用leftline, topline, bottomline, single这几个参数。
  • frame=2mm:代码框架的间隔被设置为2mm,你也可以使用其他的长度单位。
  • baselinestretch=1.2:代码的行间距被设置为1.2
  • bgcolor=LightGray:代码框架的背景颜色被设置为LightGray,你需要引入xcolor包。你可以在[这篇文章]中查看如何在LaTeX中使用颜色。
  • fontsize=\footnotesize:设置代码的字体大小为fontnotesize,你也可以设置其他的字体大小。
  • linenos:启用行号。

其他一些有用的参数包括:

  • mathescape:在代码注释中启用数学环境
  • rulecolor:改变代码框架的颜色
  • showspaces:显示代码中的空格。

从文件中引入代码

如果我们可以从文件中引入写好的代码,那么将会非常方便:

\documentclass{article}
\usepackage{minted}
\title{Importing files using minted}
\begin{document}
The next code will be directly imported from a file:\inputminted{octave}{BitXorMatrix.m}
\end{document}

效果:
LaTeX 使用minted进行代码高亮 Code Highlighting-编程之家
命令\inputminted{octave}{BitXorMatrix.m}的作用是从BitXorMatrix.m文件中引入代码,参数octave是代码所属的编程语言。你也可以只引入文件中的一个代码区块,例如第2行到第12行:

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

单行代码

如果你只想显示一行代码,你可以使用下面的命令:

One-line code formatting also works with \texttt{minted}. For example, a small fragment of HTML like this:
\mint{html}|<h2>Something <b>here</b></h2>|
\noindent can be formatted correctly.

效果:
LaTeX 使用minted进行代码高亮 Code Highlighting-编程之家

间隔符|前的参数是代码所属的编程语言,之后是要显示的代码。

自定义的词法分析器(Lexers)

默认情况下minted只支持已经安装好的或者注册好的词法分析器(参考pygmentize)。如果你想用一个自定义的词法分析器,你可以使用这个方法

假设你在文件nl-lexer.py中定义了一个词法分析器,其中包含了一个NetLogo语言的类NetLogoLexer。那么你需要将这个文件上传到Overleaf,然后在使用minted的时候将nl-lexer.py:NetLogoLexer定义为“编程语言的名字”。例如:

\begin{minted}{nl-lexer.py:NetLogoLexer -x}... your code here ...
\end{minted}

颜色和样式表

代码所使用的各种高亮颜色定义在样式表中。你可以创建自定义的样式表,或者使用安装好的其他样式表。本文末尾介绍了Overleaf中所支持的样式表。

\documentclass{article}
\usepackage{minted}
\usemintedstyle{borland}
\begin{document}
\begin{minted}{python}
import numpy as npdef incmatrix(genl1,genl2):m = len(genl1)n = len(genl2)M = None #to become the incidence matrixVT = np.zeros((n*m,1), int)  #dummy variable#compute the bitwise xor matrixM1 = 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}

使用borland样式表的效果:

LaTeX 使用minted进行代码高亮 Code Highlighting-编程之家

设置颜色样式非常简单,例如,命令\usemintedstyle{borland}使用了borland颜色样式来对代码进行着色。

代码标题、标签和目录

minted创建的代码可以被嵌套在浮动元素中,就像表格和图片一样。你可以给代码设置标题和标签(label),然后在其他地方引用它们。

\documentclass{article}
\usepackage{minted}
\title{Listing code examples}
\begin{document}
\begin{listing}[!ht]
\inputminted{octave}{BitXorMatrix.m}
\caption{Example from external file}
\label{listing:1}
\end{listing}\begin{listing}[!ht]
\begin{minted}{c}
#include <stdio.h>
int main() {printf("Hello, World!"); /*printf() outputs the quoted string*/return 0;
}
\end{minted}
\caption{Hello World in C}
\label{listing:2}
\end{listing}\begin{listing}[!ht]
\begin{minted}{lua}
function fact (n)--defines a factorial functionif n == 0 thenreturn 1elsereturn n * fact(n-1)end
endprint("enter a number:")
a = io.read("*number") -- read a number
print(fact(a))
\end{minted}
\caption{Example from the Lua manual}
\label{listing:3}
\end{listing}
\noindent\texttt{minted} makes a nice job of typesetting listings \ref{listing:1}, \ref{listing:2} and \ref{listing:3}.
\renewcommand\listoflistingscaption{List of source codes}
\listoflistings
\end{document}

效果:
LaTeX 使用minted进行代码高亮 Code Highlighting-编程之家

显示代码目录的命令为\listoflistings。在下面的代码中,我们将默认的标题修改为List of source codes

\renewcommand\listoflistingscaption{List of source codes}
\listoflistings % Now typeset the list

LaTeX 使用minted进行代码高亮 Code Highlighting-编程之家

参考指南

minted支持的颜色样式:

参数 效果 参数 效果
main LaTeX 使用minted进行代码高亮 Code Highlighting-编程之家 fruity LaTeX 使用minted进行代码高亮 Code Highlighting-编程之家
rrt LaTeX 使用minted进行代码高亮 Code Highlighting-编程之家 autumn LaTeX 使用minted进行代码高亮 Code Highlighting-编程之家
perldoc LaTeX 使用minted进行代码高亮 Code Highlighting-编程之家 bw LaTeX 使用minted进行代码高亮 Code Highlighting-编程之家
borland LaTeX 使用minted进行代码高亮 Code Highlighting-编程之家 emacs LaTeX 使用minted进行代码高亮 Code Highlighting-编程之家
colorful LaTeX 使用minted进行代码高亮 Code Highlighting-编程之家 vim LaTeX 使用minted进行代码高亮 Code Highlighting-编程之家
murphy LaTeX 使用minted进行代码高亮 Code Highlighting-编程之家 pastie LaTeX 使用minted进行代码高亮 Code Highlighting-编程之家
vs LaTeX 使用minted进行代码高亮 Code Highlighting-编程之家 friendly LaTeX 使用minted进行代码高亮 Code Highlighting-编程之家
trac LaTeX 使用minted进行代码高亮 Code Highlighting-编程之家 native LaTeX 使用minted进行代码高亮 Code Highlighting-编程之家
tango LaTeX 使用minted进行代码高亮 Code Highlighting-编程之家 monokai LaTeX 使用minted进行代码高亮 Code Highlighting-编程之家

有些样式需要你设置深色的背景才能让代码显示清楚

支持的编程语言请见这里