![](https://img.haomeiwen.com/i2678339/77afcfae7597a624.png)
使用到的包有 minted
、caption
和 currfile
。定义的辅助命令如下:
\usepackage{minted}
\usepackage{currfile}
\usepackage{caption}
\newenvironment{code}{\captionsetup{type=listing}}{}
\makeatletter
\renewcommand*{\thelisting}{\thesection.\arabic{listing}}
\@addtoreset{listing}{section}
\makeatother
\newcommand{\inputcode}[3]{
\begin{code}
\inputminted[mathescape,
linenos,
breaklines,
numbersep=5pt,
gobble=0,
tabsize=4,
fontsize=\footnotesize,
frame=lines,
framesep=2mm]{#1}{#2}%
\caption{#3}
\end{code}%
}
说明
- 代码的长度可能超过一页,所以不能用
float
。在这一情况下,为了能够添加题注,引入caption
包,并定义了code
环境用于包裹代码。- 更新了
\thelisting
命令,这里的效果是代码块的编号计数在每一节都自动重置。- 定义了
\inputcode
命令,其中使用了自定义的code
环境。命令有三个参数,第一个为语言名称(需要根据minted
文档来填写),第二个为代码文件的文件名,第三个为题注。\inputminted
中的配置选项可以根据文档自行调整。
在文件中的使用方式为:
\edef\CurrentFileDir{\currfiledir}
\inputcode{C}{\CurrentFileDir/abc.c}{用于计算 ABC 的代码}
这里使用 currfile
包解决相对路径问题,这样就可以在别的 .tex
文件中直接 \input
引入这里的内容,而代码文件的路径是相对于当前编写的这一个 .tex
文件的。这样只要保证这个文件和源代码文件的相对位置不变,任意移动也不会有影响。
实际效果如下图所示(实际的代码在文件 abc.c
中,而不在 .tex
文件中):
![](https://img.haomeiwen.com/i2678339/65b9859221ab358e.png)
网友评论