不需要特定的代码格式,用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}
本文介绍了如何使用LaTeX的listings包进行代码排版,包括C/C++、Python和SQL代码的格式设定。内容来源于维基百科和Stack Overflow,提供了在正文中插入代码的方法,以避免长代码导致的浮动体混乱问题。
1062

被折叠的 条评论
为什么被折叠?



