跳轉到內容

LaTeX/原始碼列表

來自華夏公益教科書,開放的書籍,開放的世界
(重定向自 LaTeX/Packages/Listings)

LaTeX

入門
  1. 簡介
  2. 安裝
  3. 安裝額外包
  4. 基礎
  5. 如何獲取幫助

常用元素

  1. 文件結構
  2. 文字格式
  3. 段落格式
  4. 顏色
  5. 字型
  6. 列表結構
  7. 特殊字元
  8. 國際化
  9. 旋轉
  10. 表格
  11. 標題建立
  12. 頁面佈局
  13. 自定義頁面頁首和頁尾‎
  14. 匯入圖形
  15. 浮動、圖形和標題
  16. 腳註和邊注
  17. 超連結
  18. 標籤和交叉引用
  19. 首字母

機制

  1. 錯誤和警告
  2. 長度
  3. 計數器
  4. 規則和支撐

技術文字

  1. 數學
  2. 高階數學
  3. 定理
  4. 化學圖形
  5. 演算法
  6. 原始碼列表
  7. 語言學

特殊頁面

  1. 索引
  2. 術語表
  3. 參考文獻管理
  4. 更多參考文獻

特殊文件

  1. 科學報告(學士報告、碩士論文、博士論文)
  2. 信件
  3. 簡報
  4. 教師專區
  5. 簡歷
  6. 學術期刊(MLA、APA 等)

建立圖形

  1. 介紹程式圖形
  2. MetaPost
  3. 圖片
  4. PGF/TikZ
  5. PSTricks
  6. Xy-pic
  7. 建立 3D 圖形

程式設計

  1. 純 TeX
  2. 建立包
  3. 建立包文件
  4. 主題

雜項

  1. 模組化文件
  2. 協作編寫 LaTeX 文件
  3. 匯出到其他格式

幫助和建議

  1. 常見問題解答
  2. 提示和技巧

附錄

  1. 作者
  2. 連結
  3. 包參考
  4. LaTeX 文件示例
  5. 索引
  6. 命令詞彙表

編輯此框編輯目錄


有很多包提供程式碼列表和高亮顯示,以下是比較流行的

  • listings
    • 非常有用且功能豐富,
  • minted
    • minted 是 listings 的替代方案,它越來越受歡迎。它使用外部 Python 庫 Pygments 進行程式碼高亮顯示,截至 2021 年 2 月,它支援超過 537 種語言和文字格式。由於該包依賴於外部 Python 程式碼,因此設定需要比一般的 LaTeX 包多一些步驟,請參考他們的 GitHub 倉庫 和他們的 手冊

使用 listings

[編輯 | 編輯原始碼]

使用 listings 包,您可以像使用 \begin{verbatim} 一樣新增非格式化文字,但它的主要目標是在您的文件中包含任何程式語言的原始碼。如果您希望包含虛擬碼或演算法,您可能會發現 演算法和虛擬碼 也很有用。

要使用該包,您需要

\usepackage{listings}

listings 包支援所有最常用語言的高亮顯示,並且高度可定製。如果您只想在文件中編寫程式碼,該包提供了 lstlisting 環境

\begin{lstlisting}
Put your code here.
\end{lstlisting}

另一種可能性是,如果您在一個或多個檔案中建立了一個程式並且仍在編輯它,那麼可以從原始碼本身匯入程式碼。這樣,如果您修改了原始碼,您只需重新編譯 LaTeX 程式碼,您的文件就會更新。命令是

\lstinputlisting{source_filename.py}

在示例中,有一個 Python 原始碼,但這並不重要:您可以包含任何檔案,但必須寫出完整的檔名。它將被視為純文字,並將根據您的設定進行高亮顯示,這意味著它不會自動識別程式語言。您可以使用以下命令在包含檔案時指定語言

\lstinputlisting[language=Python]{source_filename.py}

您也可以指定檔案的範圍。

\lstinputlisting[language=Python, firstline=37, lastline=45]{source_filename.py}

\lstinputlisting[language=Python, linerange={37-45,48-50}]{source_filename.py}

如果您確定檔案不會更改(至少在指定行之前),這將非常方便。您也可以省略 firstlinelastline 引數:這意味著從這一點開始或到這一點結束的所有內容

這是一個關於一些 Pascal 程式碼的基本示例

\documentclass{article}
\usepackage{listings}             % Include the listings-package
\begin{document}
\lstset{language=Pascal}          % Set your language (you can change the language for each code-block optionally)

\begin{lstlisting}[frame=single]  % Start your code-block
for i:=maxint to 0 do
begin
{ do nothing }
end;
Write('Case insensitive ');
Write('Pascal keywords.');
\end{lstlisting}

\end{document}

支援的語言

[編輯 | 編輯原始碼]

它支援以下程式語言

ABAP2,4, ACSL, Ada4, Algol4, Ant, Assembler2,4, Awk4, bash, Basic2,4, C#5, C++4, C4, Caml4, Clean, Cobol4, Comal, csh, Delphi, Eiffel, Elan, erlang, Euphoria, Fortran4, GCL, Go (golang), Gnuplot, Haskell, HTML, IDL4, inform, Java4, JVMIS, ksh, Lisp4, Logo, Lua2, make4, Mathematica1,4, Matlab, Mercury, MetaPost, Miranda, Mizar, ML, Modelica3, Modula-2, MuPAD, NASTRAN, Oberon-2, Objective C5 , OCL4, Octave, Oz, Pascal4, Perl, PHP, PL/I, Plasm, POV, Prolog, Promela, Python, R, Reduce, Rexx, RSL, Ruby, S4, SAS, Scilab, sh, SHELXL, Simula4, SQL, tcl4, TeX4, VBScript, Verilog, VHDL4, VRML4, XML, XSLT.

對於其中一些語言,支援多種方言。有關更多資訊,請參閱隨包附帶的文件,它應該在您的發行版中,名為listings-*.dvi.

注意
  1. 它僅在您使用純文字格式輸入時才支援 Mathematica 程式碼。您不能像其他程式語言一樣使用 \lstinputlisting{...} 包含 *.NB 檔案,但 Mathematica 可以匯出為漂亮格式的 LaTeX 原始碼。
  2. 對於這些語言,必須指定方言(例如 language={[x86masm]Assembler})。
  3. Modelica 透過 這裡 可用的 dtsyntax 包支援。
  4. 對於這些語言,支援多種方言。例如,C 有 ANSI、Handel、Objective 和 Sharp。請參閱 listings 手冊 第 12 頁的概述。
  5. 定義為另一種語言的方言

您可以修改幾個引數,這些引數會影響程式碼的顯示方式。您可以在文件中的任何位置放置以下程式碼(無論是在 \begin{{document}\end{document} 之前還是之後),根據您的需要進行更改。任何行的含義都在旁邊解釋。

\usepackage{listings}
\usepackage{color}

\definecolor{mygreen}{rgb}{0,0.6,0}
\definecolor{mygray}{rgb}{0.5,0.5,0.5}
\definecolor{mymauve}{rgb}{0.58,0,0.82}

\lstset{ 
  backgroundcolor=\color{white},   % choose the background color; you must add \usepackage{color} or \usepackage{xcolor}; should come as last argument
  basicstyle=\footnotesize,        % the size of the fonts that are used for the code
  breakatwhitespace=false,         % sets if automatic breaks should only happen at whitespace
  breaklines=true,                 % sets automatic line breaking
  captionpos=b,                    % sets the caption-position to bottom
  commentstyle=\color{mygreen},    % comment style
  deletekeywords={...},            % if you want to delete keywords from the given language
  escapeinside={\%*}{*)},          % if you want to add LaTeX within your code
  extendedchars=true,              % lets you use non-ASCII characters; for 8-bits encodings only, does not work with UTF-8
  firstnumber=1000,                % start line enumeration with line 1000
  frame=single,	                   % adds a frame around the code
  keepspaces=true,                 % keeps spaces in text, useful for keeping indentation of code (possibly needs columns=flexible)
  keywordstyle=\color{blue},       % keyword style
  language=Octave,                 % the language of the code
  morekeywords={*,...},            % if you want to add more keywords to the set
  numbers=left,                    % where to put the line-numbers; possible values are (none, left, right)
  numbersep=5pt,                   % how far the line-numbers are from the code
  numberstyle=\tiny\color{mygray}, % the style that is used for the line-numbers
  rulecolor=\color{black},         % if not set, the frame-color may be changed on line-breaks within not-black text (e.g. comments (green here))
  showspaces=false,                % show spaces everywhere adding particular underscores; it overrides 'showstringspaces'
  showstringspaces=false,          % underline spaces within strings only
  showtabs=false,                  % show tabs within strings adding particular underscores
  stepnumber=2,                    % the step between two line-numbers. If it's 1, each line will be numbered
  stringstyle=\color{mymauve},     % string literal style
  tabsize=2,	                   % sets default tabsize to 2 spaces
  title=\lstname                   % show the filename of files included with \lstinputlisting; also try caption instead of title
}
escapeinside

escapeinside 行需要解釋。選項 escapeinside={A}{B} 將定義轉義到 LaTeX 程式碼的定界符,,字串“A”和“B”之間的所有程式碼都將被解析為當前listings樣式上的 LaTeX 程式碼。在上面的示例中,Octave 的註釋以 % 開頭,並且它們將被列印在文件中,除非它們以 %* 開頭,在這種情況下,它們將被解析為 LaTeX(執行所有 LaTeX 命令),直到它們被另一個 *) 關閉。如果您添加了上面的段落,可以使用以下方法在程式碼中更改設定

\lstset{language=C,caption={Descriptive Caption Text},label=DescriptiveLabel}

還有很多其他選項,請檢視官方文件。

樣式定義

[編輯 | 編輯原始碼]

該包允許您定義樣式,指定一組設定的配置檔案。

示例

\lstdefinestyle{customc}{
  belowcaptionskip=1\baselineskip,
  breaklines=true,
  frame=L,
  xleftmargin=\parindent,
  language=C,
  showstringspaces=false,
  basicstyle=\footnotesize\ttfamily,
  keywordstyle=\bfseries\color{green!40!black},
  commentstyle=\itshape\color{purple!40!black},
  identifierstyle=\color{blue},
  stringstyle=\color{orange},
}

\lstdefinestyle{customasm}{
  belowcaptionskip=1\baselineskip,
  frame=L,
  xleftmargin=\parindent,
  language=[x86masm]Assembler,
  basicstyle=\footnotesize\ttfamily,
  commentstyle=\itshape\color{purple!40!black},
}

\lstset{escapechar=@,style=customc}

在我們的示例中,我們只全域性設定了兩個選項:預設樣式和跳脫字元。用法

\begin{lstlisting}
#include <stdio.h>
#define N 10
/* Block
 * comment */

int main()
{
    int i;

    // Line comment.
    puts("Hello world!");
    
    for (i = 0; i < N; i++)
    {
        puts("LaTeX is also great for programmers!");
    }

    return 0;
}
\end{lstlisting}

\lstinputlisting[caption=Scheduler, style=customc]{hello.c}

C 部分將列印為

自動包含檔案

[編輯 | 編輯原始碼]

如果您有一堆要包含的原始檔,您可能會發現自己一遍又一遍地做同樣的事情。這就是宏顯示其真正力量的地方。

\newcommand{\includecode}[2][c]{\lstinputlisting[caption=#2, escapechar=, style=custom#1]{#2}<!---->}
% ...

\includecode{sched.c}
\includecode[asm]{sched.s}
% ...

\lstlistoflistings

在這個例子中,我們建立一個命令來簡化原始碼的包含。我們將預設樣式設定為customc。所有列表將以其名稱作為標題:由於宏的存在,我們不必兩次寫入檔名。最後,我們使用listings包的此命令列出所有列表。

有關詳細資訊,請參閱

編碼問題

[編輯 | 編輯原始碼]

預設情況下,listings不支援原始碼的多位元組編碼。 extendedchar選項僅適用於latin1等8位編碼。

要處理UTF-8,您應該告訴listings如何解釋特殊字元,方法是像這樣定義它們

\lstset{literate=
  {á}{{\'a}}1 {é}{{\'e}}1 {í}{{\'i}}1 {ó}{{\'o}}1 {ú}{{\'u}}1
  {Á}{{\'A}}1 {É}{{\'E}}1 {Í}{{\'I}}1 {Ó}{{\'O}}1 {Ú}{{\'U}}1
  {à}{{\`a}}1 {è}{{\`e}}1 {ì}{{\`i}}1 {ò}{{\`o}}1 {ù}{{\`u}}1
  {À}{{\`A}}1 {È}{{\`E}}1 {Ì}{{\`I}}1 {Ò}{{\`O}}1 {Ù}{{\`U}}1
  {ä}{{\"a}}1 {ë}{{\"e}}1 {ï}{{\"i}}1 {ö}{{\"o}}1 {ü}{{\"u}}1
  {Ä}{{\"A}}1 {Ë}{{\"E}}1 {Ï}{{\"I}}1 {Ö}{{\"O}}1 {Ü}{{\"U}}1
  {â}{{\^a}}1 {ê}{{\^e}}1 {î}{{\^i}}1 {ô}{{\^o}}1 {û}{{\^u}}1
  {Â}{{\^A}}1 {Ê}{{\^E}}1 {Î}{{\^I}}1 {Ô}{{\^O}}1 {Û}{{\^U}}1
  {ã}{{\~a}}1 {}{{\~e}}1 {ĩ}{{\~i}}1 {õ}{{\~o}}1 {ũ}{{\~u}}1
  {Ã}{{\~A}}1 {}{{\~E}}1 {Ĩ}{{\~I}}1 {Õ}{{\~O}}1 {Ũ}{{\~U}}1
  {œ}{{\oe}}1 {Œ}{{\OE}}1 {æ}{{\ae}}1 {Æ}{{\AE}}1 {ß}{{\ss}}1
  {ű}{{\H{u}}}1 {Ű}{{\H{U}}}1 {ő}{{\H{o}}}1 {Ő}{{\H{O}}}1
  {ç}{{\c c}}1 {Ç}{{\c C}}1 {ø}{{\o}}1 {Ø}{{\O}}1 {å}{{\r a}}1 {Å}{{\r A}}1
  {}{{\euro}}1 {£}{{\pounds}}1 {«}{{\guillemotleft}}1
  {»}{{\guillemotright}}1 {ñ}{{\~n}}1 {Ñ}{{\~N}}1 {¿}{{?`}}1 {¡}{{!`}}1 
}

上面的表格將涵蓋拉丁語中的大多數字符。有關literate選項使用情況的更詳細說明,請檢視Listings 文件中的第5.4節。

另一種方法是將(在前言中)替換為\usepackage{listingsutf8},但這僅適用於\lstinputlisting{...}

自定義標題

[編輯 | 編輯原始碼]

您可以使用caption包為您的列表建立花哨的標題(或標題)。以下是一個針對listings的示例。

\usepackage{caption}
\usepackage{listings}

\DeclareCaptionFont{white}{ \color{white} }
\DeclareCaptionFormat{listing}{
  \colorbox[cmyk]{0.43, 0.35, 0.35,0.01 }{
    \parbox{\textwidth}{\hspace{15pt}#1#2#3}
  }
}
\captionsetup[lstlisting]{ format=listing, labelfont=white, textfont=white, singlelinecheck=false, margin=0pt, font={bf,footnotesize} }

% ...

\lstinputlisting[caption=My caption]{sourcefile.lang}

參考文獻

[編輯 | 編輯原始碼]

更多詳細資訊可以在Carsten Heinz 和 Brooks Moses 編寫的 PDF中找到。

有關 Listings 包的詳細資訊和文件,請訪問其 CTAN 網站


上一頁:演算法 索引 下一頁:語言學
華夏公益教科書