前言

最近在写 表达与交流 这门课的论文。我肯定不会用Word的,毕竟太烦了。 但是Markdown+Typora的方案对于复杂的论文格式来说有点力不从心,遂作罢,选择LaTeX。

感谢Rei Suzunami自制的Overleaf模板!

listing+minted

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
\usepackage{minted}% 语法高亮和代码样式设置方面更加强大和灵活
\usepackage{listings}% 引入listings包,用于在文档中插入代码,并可自定义代码样式
\usepackage{xcolor}

\begin{document}

\begin{listing}[htb]
\caption{判断质数}
\label{code:2}
\begin{minted}{cpp}
#include<stdio.h>
int main()
{
int a,b;
scanf("%d%d",&a,&b);
printf("%d",a+b);
return 0;
}
\end{minted}
\end{listing}

\end{document}

但是没有行号,而且无法进行自动换行。也可能我设置的不对。遂作罢。

lstlisting

网上查到的教程,大多都是使用lstlisting而非listing

参考文章:LaTeX listings 宏包使用说明 - 知乎

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
\usepackage{listings}
\usepackage{xcolor}
\setmonofont{JetBrains Mono}

\lstdefinestyle{mystyle}{
backgroundcolor=\color{backcolour},
commentstyle=\color{codegreen},
keywordstyle=\color{magenta},
numberstyle=\tiny\color{codegray}\ttfamily,
stringstyle=\color{codepurple},
basicstyle=\footnotesize\ttfamily,
breakatwhitespace=false,
breaklines=true,
captionpos=b,
keepspaces=true,
numbers=left, %行号
stepnumber=5, %每五行标号一次
numbersep=5pt,
showspaces=false,
showstringspaces=false, %去掉空格时产生的下划的空格标志, 设置为true则出现
showtabs=false,
tabsize=2,
xleftmargin=1em %整体距离左边边距一个字符
}

\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}

效果很好,前面可以显示行号,并且有最低限度的代码高亮。唯一的小缺点是行号会超出正文的宽度。现在在研究如何调整边距。

将相关注释写在上面了。