listings技巧

\lstdefinestyle

参考 https://blog.csdn.net/ProgramChangesWorld/article/details/52142313

我们在使用listings的时候,需要设置语言和样式。用\lstset会设置全局的变量,如果我们文章中有多种代码,那么就需要\lstdefinestyle,设置多种样式,在使用的时候选择对应的样式。

% system=ubuntu
%soft=Tex Live2015
% complie=XeLaTeX
\documentclass[a4paper,UTF8]{article}
\usepackage{listings}
\usepackage{ctex}
\usepackage{color}
\definecolor{keywordcolor}{rgb}{0.8,0.1,0.5}
\definecolor{webgreen}{rgb}{0,.5,0}
\definecolor{bgcolor}{rgb}{0.92,0.92,0.92}

\lstdefinestyle{styleJ}{
    language=[AspectJ]Java,
    keywordstyle=\color{keywordcolor}\bfseries, 
    commentstyle=\color{blue} \textit, 
    showstringspaces=false,
    numbers=left,
    numberstyle=\small
}
\lstdefinestyle{styleP}{
    language=Python,
    numbers=right, 
    frame=single,
    numberstyle=\small ,
}
\begin{document}
\begin{lstlisting}[style=styleJ]
public int sum(int n){
    int sum = 0;
    for(int i=0;i<n;i++){  //开始的
        sum += i;         
    }
    return sum;
}
\end{lstlisting}

\begin{lstlisting}[style=styleP]
def fun():
    print('你好,世界') #我是注释
\end{lstlisting}

\end{document}

可以看到使用lstdefinestyle定义了两个样式,styleJ和styleP,分别是java和python的样式,在使用lstlisting环境的时候调设置了这两个样式。

如果不想把代码放在.tex文件里,也可以把代码放在单独的文件,然后使用下面的命令即可:

\lstinputlisting[style=styleJ]{code.java}

\listings样式1

参考 https://tex.stackexchange.com/questions/68091/how-do-i-add-syntax-coloring-to-my-c-source-code-in-beamer

\documentclass{beamer}
 \setbeamercovered{transparent}
\usepackage{listings}

\begin{document}

% Using typewriter font: \ttfamily inside \lstset
\begin{frame}[fragile]
\frametitle{Inserting source code}
\lstset{language=C++,
                basicstyle=\ttfamily,
                keywordstyle=\color{blue}\ttfamily,
                stringstyle=\color{red}\ttfamily,
                commentstyle=\color{green}\ttfamily,
                morecomment=[l][\color{magenta}]{\#}
}
\begin{lstlisting}
    #include<stdio.h>
    #include<iostream>
    // A comment
    int main(void)
    {
    printf("Hello World\n");
    return 0;
    }
\end{lstlisting}
\end{frame}

\begin{frame}[fragile]
\frametitle{Inserting source code without setting typewriter}
\lstset{language=C++,
                keywordstyle=\color{blue},
                stringstyle=\color{red},
                commentstyle=\color{green},
                morecomment=[l][\color{magenta}]{\#}
}
\begin{lstlisting}
    #include<stdio.h>
    #include<iostream>
    // A comment
    int main(void)
    {
    printf("Hello World\n");
    return 0;
    }
\end{lstlisting}
\end{frame}
\end{document}

第一种使用了\ttfamily,这个是一种打印机字体。

参考 https://www.tug.org/pracjourn/2006-1/schmidt/schmidt.pdf

https://tug.org/FontCatalogue/typewriterfonts.html

\ttfamilyselects a monospaced (“typewriter”) font family

listings样式2

参考 https://tex.stackexchange.com/questions/409705/c-code-change-the-font

\documentclass{article}
\usepackage{xcolor}
\usepackage{listings}

\colorlet{mygray}{black!30}
\colorlet{mygreen}{green!60!blue}
\colorlet{mymauve}{red!60!blue}

\lstset{
  backgroundcolor=\color{gray!10},  
  basicstyle=\ttfamily,
  columns=fullflexible,
  breakatwhitespace=false,      
  breaklines=true,                
  captionpos=b,                    
  commentstyle=\color{mygreen}, 
  extendedchars=true,              
  frame=single,                   
  keepspaces=true,             
  keywordstyle=\color{blue},      
  language=c++,                 
  numbers=none,                
  numbersep=5pt,                   
  numberstyle=\tiny\color{blue}, 
  rulecolor=\color{mygray},        
  showspaces=false,               
  showtabs=false,                 
  stepnumber=5,                  
  stringstyle=\color{mymauve},    
  tabsize=3,                      
  title=\lstname                
}

\begin{document}

\begin{lstlisting}
#include <tesseract/baseapi.h>
#include <leptonica/allheaders.h>

int main()
{
    char *outText;

    tesseract::TessBaseAPI *api = new tesseract::TessBaseAPI();
    // Initialize tesseract-ocr with English, without specifying tessdata path
    if (api->Init(NULL, "eng")) {
        fprintf(stderr, "Could not initialize tesseract.\n");
        exit(1);
    }

    // Open input image with leptonica library
    Pix *image = pixRead("/usr/src/tesseract/testing/phototest.tif");
    api->SetImage(image);
    // Get OCR result
    outText = api->GetUTF8Text();
    printf("OCR output:\n%s", outText);

    // Destroy used object and release memory
    api->End();
    delete [] outText;
    pixDestroy(&image);

    return 0;
}
\end{lstlisting}

\end{document}

换行

有时候会出现不换行的情况,比如我们需要用bash来展示一些命令操作,有可能不会被认为bash,所以比较长的内容,并不会换行,而是超出显示边界,而被阶段,这时候可以在设置里面增加一个breaklines,这个对所有语言有效,用于自动换行。

设置字体大小

basicstyle=\ttfamily\zihao{6}

可以在设置字体的后面加zihao来设置字体大小

增加对json的支持

https://tex.stackexchange.com/questions/83085/how-to-improve-listings-display-of-json-files

\usepackage{bera}% optional: just to have a nice mono-spaced font
\usepackage{listings}
\usepackage{xcolor}

\definecolor{eclipseStrings}{RGB}{42,0.0,255}
\definecolor{eclipseKeywords}{RGB}{127,0,85}
\colorlet{numb}{magenta!60!black}

\lstdefinelanguage{json}{
    basicstyle=\normalfont\ttfamily,
    commentstyle=\color{eclipseStrings}, % style of comment
    stringstyle=\color{eclipseKeywords}, % style of strings
    numbers=left,
    numberstyle=\scriptsize,
    stepnumber=1,
    numbersep=8pt,
    showstringspaces=false,
    breaklines=true,
    frame=lines,
    backgroundcolor=\color{gray}, %only if you like
    string=[s]{"}{"},
    comment=[l]{:\ "},
    morecomment=[l]{:"},
    literate=
        *{0}{{{\color{numb}0}}}{1}
         {1}{{{\color{numb}1}}}{1}
         {2}{{{\color{numb}2}}}{1}
         {3}{{{\color{numb}3}}}{1}
         {4}{{{\color{numb}4}}}{1}
         {5}{{{\color{numb}5}}}{1}
         {6}{{{\color{numb}6}}}{1}
         {7}{{{\color{numb}7}}}{1}
         {8}{{{\color{numb}8}}}{1}
         {9}{{{\color{numb}9}}}{1}
}
\begin{lstlisting}[language=json,firstnumber=1]
{"menu": {
  "id": "file",
  "value": "File",
  "popup": {
    "menuitem": [
      {"value": "New", "onclick": "CreateNewDoc()"},
      {"value": "Open", "onclick": "OpenDoc()"},
      {"value": "Close", "onclick": "CloseDoc()"}
    ]
  }
}}
0123456789
\end{lstlisting}

双引号中的空格显示

https://tex.stackexchange.com/questions/77743/why-does-latex-replace-some-spaces-with-brackets-or-underscores-in-the-listings
https://tex.stackexchange.com/questions/483927/treatment-of-space-in-quotation-marks-in-listings
在listings中,如果代码内容被双引号""括起来,里面的空格会显示出来,如图
这时需要在listings中增加showstringspaces=false

\begin{lstlisting}[showstringspaces=false]
\end{lstlisting}
posted @   秋来叶黄  阅读(1623)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
点击右上角即可分享
微信分享提示