LaTeX listings排版代码与一些代码的格式(持续更新)

本文介绍了如何使用LaTeX的listings包进行代码排版,包括C/C++、Python和SQL代码的格式设定。内容来源于维基百科和Stack Overflow,提供了在正文中插入代码的方法,以避免长代码导致的浮动体混乱问题。
Python3.10

Python3.10

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

不需要特定的代码格式,用LaTeX排版代码:

\usepackage{listings}%排版代码的包

\begin{document}

\lstinputlisting{code/demo.c}%代码的文件名,源代码要utf-8,不然有中文的注释那些是乱码

\end{document}

需要特定的格式,代码格式找了很多地方,记录一些代码的格式。目前有C/C++,Python的listing格式。内容转自维基百科、Stack Overflow等地,稍有修改。

格式的定义放在导言区,先加排版代码的包:

\usepackage{listings}

然后定义语言的格式
C/C++:

\lstdefinestyle{customc}{% customc 是格式的名字
	belowcaptionskip=1\baselineskip,
	breaklines=true,
	frame=l,
	xleftmargin=\parindent,
	language=C,
	showstringspaces=false,
	basicstyle=\footnotesize\ttfamily,
	keywordstyle=\bfseries\color{green!40!black},
	commentstyle=\itshape\color{purple!40!black},
	identifierstyle=\color{blue},
	stringstyle=\color{orange},
	tabsize=2,
}

Python

\usepackage{color}
\definecolor{dkgreen}{rgb}{0,0.6,0}
\definecolor{gray}{rgb}{0.5,0.5,0.5}
\definecolor{mauve}{rgb}{0.58,0,0.82}


\lstdefinestyle{myPython}{% myPython是格式的名字
	frame=l,
	language=Python,
	aboveskip=3mm,
	belowskip=3mm,
	showstringspaces=false,
	columns=flexible,
	numberstyle=\small\color{red},
	basicstyle={\small\ttfamily},
	keywordstyle=\color{blue},
	commentstyle=\color{dkgreen},
	stringstyle=\color{mauve},
	breaklines=true,
	breakatwhitespace=true,
	tabsize=3
}

SQL:Stack Overflow地址

\definecolor{codegreen}{rgb}{0,0.6,0}
\definecolor{codegray}{rgb}{0.5,0.5,0.5}
\definecolor{codepurple}{HTML}{C42043}
\definecolor{backcolour}{HTML}{F2F2F2}
\lstdefinestyle{sql1}{% sql1 是格式的名字
	language=SQL,
	frame=l,
	backgroundcolor=\color{backcolour},   
	commentstyle=\color{codegreen},
	keywordstyle=\color{codepurple},
	numberstyle=\footnotesize\color{black},
	stringstyle=\color{codepurple},
	basicstyle=\footnotesize,
	breakatwhitespace=false, 
	breaklines=true,                 
	captionpos=b,                    
	keepspaces=true,                 
	numbers=left, 
	showspaces=false,                
	showstringspaces=false,
	showtabs=false,      
}

正文区要插入代码的地方这么写:

\begin{document}
...

\lstinputlisting[style=mystyle]{code/demo.c}%此处 mystyle 替换成上面定义的格式名字,花括号内是代码的路径(最好用相对路径)
%如果不知道相对路径是啥的:
% 1.在现在写的.tex文件旁边右键新建个“code”文件夹 
% 2. 把要排版的源代码文件放新建的文件夹里 
% 3.上面把demo.c 改成自己的源代码名
...
\end{document}

在实践中发现,如果代码太长,浮动体(图表)会插到代码中间,所以我在每次插入代码的地方都这么写:

\usepackage{placeins}%\FloatBarrier要的包

\begin{document}
...

\FloatBarrier
\lstinputlisting[style=mystyle]{code/demo.c}
\FloatBarrier
%这么做好处是不会打断代码,但图多的时候有可能排版不理想,目前没找到解决方法,先凑合着用

...
\end{document}

您可能感兴趣的与本文相关的镜像

Python3.10

Python3.10

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值