Latex插入代码并高亮显示

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} 

效果

  • 8
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值