Latex可以方便地支持多种代码高亮,办法如下:
用到的包
\usepackage{listings}
默认的高亮是关键词加粗
也可以自定义高亮格式,例如添加以下设置(为了能够使用\color,需引入包\usepackage{xcolor})
\lstset{
%backgroundcolor=\color{red!50!green!50!blue!50},%代码块背景色为浅灰色
rulesepcolor= \color{gray}, %代码块边框颜色
breaklines=true, %代码过长则换行
numbers=left, %行号在左侧显示
numberstyle= \small,%行号字体
%keywordstyle= \color{blue},%关键字颜色
commentstyle=\color{gray}, %注释颜色
frame=shadowbox%用方框框住代码块
}
添加代码块
\begin{lstlisting}[language={java}]
public class Main {
public static void main(String[] args)
{
System.out.println("Hello World");
}
}
\end{lstlisting}
--------------------------------------------------------------------------------
例子
\documentclass[GBK]{ctexart}
\usepackage{listings}
\usepackage{xcolor}
\lstset{
%backgroundcolor=\color{red!50!green!50!blue!50},%代码块背景色为浅灰色
rulesepcolor= \color{gray}, %代码块边框颜色
breaklines=true, %代码过长则换行
numbers=left, %行号在左侧显示
numberstyle= \small,%行号字体
%keywordstyle= \color{red},%关键字颜色
commentstyle=\color{gray}, %注释颜色
frame=shadowbox%用方框框住代码块
}
\begin{document}
%this is a fragment of java code
\begin{lstlisting}[language={java}]
//java code
public class Main{
public static void main(String[]args){
System.out.println("hello,world");
}
}
\end{lstlisting}
\end{document}