LaTeX 入门 - 代码块 listings 宏包
listings
宏包用于设置代码块
1. 引入与使用
引入宏包
\usepackage{listings}
使用
- 常规使用代码块
\begin{lstlisting}
codes
\end{lstlisting}
- 从文件中导入代码块
\lstinputlisting[language=Python]{main.py}
\lstinputlisting[language=Python, firstline=2, lastline=12]{main.py}
- 行内代码
\lstinline|mycodes|
2. 设置命令
\lstset{
columns = fixed,
basicstyle = \linespread{0.8} \ttfamily, % 设置行距,字体
numbers = left, % 在左侧显示行号
numberstyle = \tiny \color{gray}, % 设定行号格式
keywordstyle = \bfseries \color[RGB]{40,40,255}, % 设定关键字颜色
numberstyle = \footnotesize \color{darkgray},
commentstyle = \color[RGB]{0,96,96}, % 设置代码注释的格式
stringstyle = \color[RGB]{128,0,0}, % 设置字符串格式
frame = single, % 不显示背景边框
backgroundcolor = \color[RGB]{245,245,244}, % 设定背景颜色
showstringspaces = false, % 不显示字符串中的空格
language=R % 设置语言
}
行号相关设置
参数 | 说明 | 可选值 |
---|---|---|
numbers |
行号 | left :左侧显示行号right :右侧显示行号none :不显示行号 |
stepnumber |
每隔多少行显示行号 | 整数 |
numbersep |
行号与代码内容的间隔 | |
firstnumber |
行号起始数字 | 整数:last :起始行数为上一段lstlisting 环境结尾的行数·` |
框架相关设置
参数 | 说明 | 可选值 |
---|---|---|
frame |
代码块边框设置 | topline :只有上侧有线rightline :只有右侧有线bottomline :只有底部有线leftline :只有左侧有线trbl ,tbl ,tb :按照top、right、bottom、left顺序,指定的任意方位设置边框TRBL ,TBl ,Tb :大写字母表示双竖线shadowbox :带有阴影none :不设置边框 |
frameround |
边框圆角 | fftt :边框右上角、右下角、左下角、左上角(顺时针方向)4个角的方角(f )或圆角(t ) |
rulecolor |
设置框架线条颜色 | |
rulesepcolor |
设置框架阴影颜色 | 只有当 frame=shadowbox 才会起作用 |
linewidth |
行宽 | 可与framexrightmargin 产生相同效果 |
framexleftmargin framexrightmargin framextopmargin framexbottommargin |
边框往左、右、上、下扩展的距离 仅改变框架,不会改变代码、行号的位置 |
距离:可以为正数、或负数,分别表示往外、或内扩展 |
xleftmargin xrightmargin xtopmargin xbottommargin |
调整框架整体(包括框架、代码、行号)往左、右、上、下扩展的距离。 | 距离:可以为正数、或负数,分别表示往外、或内扩展 |
aboveskip belowskip |
框架整体与上、下方的距离 | 距离: |
样式相关设置
参数 | 说明 | 可选值 |
---|---|---|
numberstyle |
行号样式 | |
keywordstyle |
关键字样式 | |
stringstyle |
字符串样式 | |
commentstyle |
注释样式 |
其他相关设置
参数 | 说明 | 可选值 |
---|---|---|
tabsize |
缩进空格数 | 整数: |
columns |
调整字母之间的距离 | fixed :flexible :fullflexible : |
firstline lastline |
只排版firstline 到lastline 的代码 |
整数: |
language |
程序语言 | Python ,R ,C++ ,Jave 等 |
3. 设置字体
- 将编译器(complier)改成 XeLaTex
- 引入宏包
fontspec
,并通过\setmonofont
命令设置等宽字体 - 在
lstset
或lstlisting
中设置basicstyle = \ttfamily
\usepackage{fontspec}
\setmonofont{Source Code Pro}
\begin{lstlisting}[basicstyle = \ttfamily]
codes
\being{lstlisting}
参考资料
[1] LaTeX listings 宏包使用说明(一), 知乎, 地址