LaTeX代码宏包listings的使用

LaTeX代码宏包listings的使用

1 需求

LaTeX \LaTeX LATEX适合用来进行结构化文档的编辑。如今,在科技论文写作上, LaTeX \LaTeX LATEX是最常用的标准化工具。对于程序员来说,当文档中需要插入代码段时,如何像Visual Studio或者PyCharm这样的IDE一样,使代码中的关键字高亮显示呢?

这就是今天我们想要讨论和实现的需求。

以下特别说明:

在兼并了ShareLaTeX之后,OverLeaf是如今最为主流的在线LaTeX编辑环境。本文也是在OverLeaf上进行相关的编辑。

本文参考的文献地址为https://www.overleaf.com/learn/latex/Code_listing#Using_listings_to_highlight_code
它介绍了 LaTeX \LaTeX LATEX中verbatim环境和listings宏包的使用方式。

2 verbatim环境简介

LaTeX \LaTeX LATEX中默认用来显示代码的工具是verbatim,这是一个用monospaced字体显示代码的工具。它的基本使用方式是:

\documentclass{article}
\begin{document}
\begin{verbatim}
Text enclosed inside \texttt{verbatim} environment 
is printed directly 
and all \LaTeX{} commands are ignored.
\end{verbatim}
\end{document}

以上代码显示的效果如下:

在这里插入图片描述

就像在引言中的示例一样,打印所有文本时都保留换行符和空格。这段代码还有一个带星标的版本,其输出和上面的例子略有不同。

\documentclass{article}
\begin{document}
\begin{verbatim*}
Text enclosed inside \texttt{verbatim} environment 
is printed directly 
and all \LaTeX{} commands are ignored.
\end{verbatim*}
\end{document}

在这里插入图片描述

在带星标的版本中,空格以一种可见的方式得到了强调。
下面让我们看看如何在行内插入代码:

\documentclass{article}
\begin{document}
In the directory \verb|C:\Windows\system32| you can find a lot of Windows 
system applications. 
 
The \verb+\ldots+ command produces \ldots
\end{document}

以上的代码生成的结果如下所示:
在这里插入图片描述

命令\verb|C:\Windows\system32|verbatim格式下,使用|作为分隔符。实际上,除字母和*以外的任意字符,都可以作为分隔符。在本例中,\verb+\ldots+使用+作为分隔符。

3 listings设置代码高亮

要使用listings环境,必须要先把以下行添加到文档的序言中:

\usepackage{listings}

下面是一个使用listings宏包中lstlisting环境的例子:

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

上述实例的结果为:
在这里插入图片描述

对于这一段Python代码,可以看到输出结果保留了原样的缩进效果,但除此以外,没有关键字高亮效果。
稍微修改一下代码:

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

上述代码的效果如下:

在这里插入图片描述

代码中仅添加了一个参数说明,即[language=Python],则可以看到,所有Python关键字都得到了自动加粗效果。

从文件中读取代码:

由于代码通常存储在源文件中,所以如果有一条命令,能够从源文件中自动读取代码就好了!
LaTeX \LaTeX LATEX通过listings包满足你!

The next code will be directly imported from a file:

%Importing code from file
\lstinputlisting[language=Octave]{BitXorMatrix.m}

代码的效果如下:

在这里插入图片描述

\lstinputlisting[language=Octave]{BitXorMatrix.m}BitXorMatrix.m文件中直接导入了源码。\lstinputlisting指令完成了这一工作。BitXorMatrix.m是一个Octave语言编写的代码(其实就是MatLab的在线版本语言)。
如果只需要截取源码中的一段,那么只需要通过两个参数firstlinelastline进行行控制即可:

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

4 代码样式和颜色

以下代码,通过调用listings宏包及颜色宏包,可以达到非常完美的效果:

\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}
The next code will be directly imported from a file

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

上述代码的效果如下:

在这里插入图片描述

可以看到关键字都得到了高亮的效果,且添加了行号,代码的背景也非常合适。
如此,代码的着色和样式大大提高了可读性。

在此示例中,导入包xcolor,然后使用命令definecolor{}{}{}定义稍后将使用的rgb格式的新颜色。

对于此示例,基本上有两个命令可以生成样式:
lstdefinestyle{mystyle}{...}
定义一个名为"mystyle"的新代码列表样式。在第二对大括号内传递定义此样式的选项。其中的参数比较多,请参阅第7节。

\lstset{style=mystyle}
这条指令使能了样式"mystyle",如果需要的话,可以在文档中使用此命令切换到其他样式。

5 为listings添加题注

和浮动体(如图片和表格)一样,可以为代码添加题注。

\documentclass{article}
\usepackage{listings}

\usepackage{xcolor}

%New colors defined below
\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}

%Code listing style named "mystyle"
\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
}

%"mystyle" code listing set
\lstset{style=mystyle}
\begin{document}
\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}
\end{document}

以上代码的效果如下所示:
在这里插入图片描述

这是一段Python代码,编辑的风格也遵循了Python的经典配色及缩进。
并且在代码框的底部添加了题注。

6 listings支持的语言格式

以下表格记录了所有支持的语言类型:

支持的语言支持的语言
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)
AntAssembler (Motorola68k, x86masm)
Awk (gnu, POSIX)bash
Basic (Visual)C (ANSI, Handel, Objective, Sharp)
C++ (ANSI, GNU, ISO, Visual)Caml (light, Objective)
CILClean
Cobol (1974, 1985, ibm)Comal 80
command.com (WinXP)Comsol
cshDelphi
EiffelElan
erlangEuphoria
Fortran (77, 90, 95)GCL
GnuplotHaskell
HTMLIDL (empty, CORBA)
informJava (empty, AspectJ)
JVMISksh
LingoLisp (empty, Auto)
Logomake (empty, gnu)
Mathematica (1.0, 3.0, 5.2)Matlab
MercuryMetaPost
MirandaMizar
MLModula-2
MuPADNASTRAN
Oberon-2OCL (decorative, OMG)
OctaveOz
Pascal (Borland6, Standard, XSC)Perl
PHPPL/I
PlasmPostScript
POVProlog
PromelaPSTricks
PythonR
ReduceRexx
RSLRuby
S (empty, PLUS)SAS
Scilabsh
SHELXLSimula (67, CII, DEC, IBM)
SPARQLSQL
tcl (empty, tk)TeX (AlLaTeX, common, LaTeX, plain, primitive)
VBScriptVerilog

7 附录 listings样式的自定义参数

  • backgroundcolor - 背景色. 需要外部宏包 colorxcolor .
  • commentstyle - 源语言中的注释样式.
  • basicstyle - 源码的字体、字号/family/等. (例如 basicstyle=\ttfamily\small)
  • keywordstyle - 源代码中关键字的样式 (e.g. keywordstyle=\color{red})
  • numberstyle - 行号的样式.
  • numbersep - 行号与代码的间距.
  • stringstyle - 源代码中的字符串样式.
  • showspaces - 强调代码中的空格 (true/false).
  • showstringspaces - 强调代码中的字符串 (true/false)
  • showtabs - 强调代码中的tab (true/false)
  • numbers - 行号及位置 (left/right/none, i.e. no line numbers)
  • prebreak - 分行后显示换行符 (e.g. prebreak=\raisebox{0ex}[0ex][0ex]{\ensuremath{\hookleftarrow}})
  • captionpos - 题注的位置 (t/b)
  • frame - 在代码之外显示边框 (none/leftline/topline/bottomline/lines/single/shadowbox)
  • breakatwhitespace - 设置后将只会在空格处换行
  • breaklines - 自动换行
  • keepspaces - 保持空格,对于缩进代码有效
  • tabsize - 默认的tab间隔
  • escapeinside - 特定的字符,退出源码模式到LaTeX模式 (例如 escapeinside={\%*}{*)})
  • rulecolor - 指定边框的颜色
    在这里插入图片描述
  • 12
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值