跳至內容

LaTeX/原始碼列表

來自華夏公益教科書

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. 方框
  5. 規則和支撐線

技術文字

  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

[edit | edit source]

使用包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}

支援的語言

[edit | edit source]

它支援以下程式語言

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 程式碼。您無法包含 *.NB 檔案 \lstinputlisting{...},就像您可以使用任何其他程式語言一樣,但 Mathematica 可以匯出為格式精美的 LaTeX 原始碼。
  2. 對於這些語言,必須指定方言(例如,language={[x86masm]Assembler})。
  3. Modelica 透過 此處提供的 dtsyntax 包支援。
  4. 對於這些語言,支援多種方言。例如,C 有 ANSI、Handel、Objective 和 Sharp。有關概述,請參閱 listings 手冊 的第 12 頁。
  5. 定義為另一種語言的方言

設定

[edit | edit source]

您可以修改影響程式碼顯示方式的多個引數。您可以將以下程式碼放在文件中的任何位置(無論是在 \beginspan class="nb">{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}

還有更多選項,請檢視官方文件。

樣式定義

[edit | edit source]

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

示例

\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 部分將列印為

自動包含檔案

[edit | edit source]

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

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

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

\lstlistoflistings

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

有關更多詳細資訊,請參見

編碼問題

[edit | edit source]

預設情況下,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{listings}(在序言中)替換為\usepackage{listingsutf8},但這隻對\lstinputlisting{...}有效。

自定義標題

[edit | edit source]

您可以使用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}

參考文獻

[edit | edit source]

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

關於 Listings 包的詳細資訊和文件可以在其 CTAN 網站上找到。


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