LaTeX 插入代码可以使用 verbatim 或者 fancyvrb 或者 listings 包。verbatim 没有语法高亮功能,只是显示一个等宽字体的输出。查看 Overleaf 示例
% Preamble
\usepackage{verbatim}
% Body
\begin{verbatim}
Text enclosed inside \texttt{verbatim} environment
is printed directly
and all \LaTeX{} commands are ignored.
\end{verbatim}
而 listings 则带有语法高亮、显示行号等功能。
% Preamble
\usepackage{xcolor} % 为了渲染颜色,需要使用 xcolor 包
\usepackage{listings} % 渲染代码块
% Body
% 定义颜色
\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}
% 定义 listings 风格,可以定义多个
\lstdefinestyle{mystyle}{
% backgroundcolor=\color{backcolour}, % 背景色
commentstyle= \color{red!50!green!50!blue!50}, % 注释的颜色
keywordstyle= \color{blue!70}, % 关键字/程序语言中的保留字颜色
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,
frame=single % [none | single | shadowbox] 显示边框
}
\lstset{style=mystyle} % 使用 listings 风格
\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}
标签:LaTeX,verbatim,color,代码,listings,插入,rgb,VT,np
From: https://www.cnblogs.com/Undefined443/p/18155226