LaTeX/原始碼列表
有很多包提供程式碼列表和高亮顯示,以下是比較流行的
使用 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}
|
如果您確定檔案不會更改(至少在指定行之前),這將非常方便。您也可以省略 firstline 或 lastline 引數:這意味著從這一點開始或到這一點結束的所有內容。
這是一個關於一些 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.
- 注意
- 它僅在您使用純文字格式輸入時才支援 Mathematica 程式碼。您不能像其他程式語言一樣使用
\lstinputlisting{...}包含 *.NB 檔案,但 Mathematica 可以匯出為漂亮格式的 LaTeX 原始碼。 - 對於這些語言,必須指定方言(例如
language={[x86masm]Assembler})。 - Modelica 透過 這裡 可用的 dtsyntax 包支援。
- 對於這些語言,支援多種方言。例如,C 有 ANSI、Handel、Objective 和 Sharp。請參閱 listings 手冊 第 12 頁的概述。
- 定義為另一種語言的方言
您可以修改幾個引數,這些引數會影響程式碼的顯示方式。您可以在文件中的任何位置放置以下程式碼(無論是在 \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 網站。

