且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Latex文档中高亮显示代码

更新时间:2021-11-17 04:00:14

准备

  • 所需Latex库包:\usepackage{minted}
  • minted库依赖程序:一个python程序-pygmentize。若没有,可直接用命令安装:pip install pygmentize

使用

\usepackage{minted}

\begin{document}

\begin{minted}{c}
    int main() {
        printf("hello, world");
        return 0;
    }
\end{minted}

\end{document}

编译命令

附加参数: --shell-escape, texstudio一般使用xelatex,参数截图如下

Latex文档中高亮显示代码
编译参数

效果

Latex文档中高亮显示代码
代码高亮:简单效果

奇怪的tab符号

上图中的tab缩进居然显示为奇怪的^^I,不能忍!查了官方文档可知,是因为xelatex的原因。修正方法是再加一个编译命令:-8bit:

Latex文档中高亮显示代码
编译命令:修正tab显示错误

修正后的效果

Latex文档中高亮显示代码
Tab显示正常

更多选项配置

比如:

\begin{minted}[bgcolor=white,breaklines=True,firstline=1,lastline=6,firstnumber=last,
                        frame=none,highlightlines={1,3,5},linenos=true,showtabs=false,
                        tabsize=4]{c}
int main() 
{
    printf("hello, world");
    printf("hello, A subsection can be created just before a set of slides with a common theme further break down your presentation into chunks");
    return 0;
}
\end{minted}

这些选项显而易见,此处省略解释!效果:

Latex文档中高亮显示代码
高级配置效果

还有更多其他选项,请参阅官方文档