LaTeX源代码列表,如专业书籍

Mor*_*075 323 latex

乳胶源代码列表应如何生成类似于已知书籍的输出,例如Spring Framework的输出?我尝试过使用乳胶列表包,但是无法生成看起来像下面那样漂亮的东西.所以我的格式化指令产生类似下面的样品(来自曼宁primarely感兴趣的样章春天在行动):

从曼宁的春天在行动

编辑TormodFjeldskår的帮助下,这里有完整的片段,可以产生所需的外观:

\usepackage{listings}
\usepackage{courier}
\lstset{
    basicstyle=\footnotesize\ttfamily, % Default font
    % numbers=left,              % Location of line numbers
    numberstyle=\tiny,          % Style of line numbers
    % stepnumber=2,              % Margin between line numbers
    numbersep=5pt,              % Margin between line numbers and text
    tabsize=2,                  % Size of tabs
    extendedchars=true,
    breaklines=true,            % Lines will be wrapped
    keywordstyle=\color{red},
    frame=b,
    % keywordstyle=[1]\textbf,
    % keywordstyle=[2]\textbf,
    % keywordstyle=[3]\textbf,
    % keywordstyle=[4]\textbf,   \sqrt{\sqrt{}}
    stringstyle=\color{white}\ttfamily, % Color of strings
    showspaces=false,
    showtabs=false,
    xleftmargin=17pt,
    framexleftmargin=17pt,
    framexrightmargin=5pt,
    framexbottommargin=4pt,
    % backgroundcolor=\color{lightgray},
    showstringspaces=false
}
\lstloadlanguages{ % Check documentation for further languages ...
     % [Visual]Basic,
     % Pascal,
     % C,
     % C++,
     % XML,
     % HTML,
     Java
}
% \DeclareCaptionFont{blue}{\color{blue}} 

% \captionsetup[lstlisting]{singlelinecheck=false, labelfont={blue}, textfont={blue}}
\usepackage{caption}
\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}}
Run Code Online (Sandbox Code Playgroud)

在文档中使用它:

\lstinputlisting[label=samplecode, caption=A sample]{sourceCode/HelloWorld.java}
Run Code Online (Sandbox Code Playgroud)

Tor*_*kår 184

在我看来,你真正想要的是定制字幕的外观.使用该caption包最容易完成.有关如何使用此包的说明,请参阅手册(PDF).您可能需要创建自己的自定义标题格式,如手册第4章所述.

编辑:使用MikTex测试:

\documentclass{report}

\usepackage{color}
\usepackage{xcolor}
\usepackage{listings}

\usepackage{caption}
\DeclareCaptionFont{white}{\color{white}}
\DeclareCaptionFormat{listing}{\colorbox{gray}{\parbox{\textwidth}{#1#2#3}}}
\captionsetup[lstlisting]{format=listing,labelfont=white,textfont=white}

% This concludes the preamble

\begin{document}

\begin{lstlisting}[label=some-code,caption=Some Code]
public void here() {
    goes().the().code()
}
\end{lstlisting}

\end{document}
Run Code Online (Sandbox Code Playgroud)

结果:

预习

  • 这看起来不错,但我的标题框缩进(不是文本,框本身).我不知道为什么,因为列表也没有缩进. (2认同)

Bas*_*ard 48

我对listings包裹感到满意:

清单示例

这是我配置它的方式:

\lstset{
language=C,
basicstyle=\small\sffamily,
numbers=left,
numberstyle=\tiny,
frame=tb,
columns=fullflexible,
showstringspaces=false
}
Run Code Online (Sandbox Code Playgroud)

我这样使用它:

\begin{lstlisting}[caption=Caption example.,
  label=a_label,
  float=t]
// Insert the code here
\end{lstlisting}
Run Code Online (Sandbox Code Playgroud)

  • Urgh,比例字体列表非常丑陋.(另外,由于文化原因,一些人(至少很多日本人,也许还有其他亚洲人)很难阅读.) (6认同)
  • @mirabilos:是的,我想我后来改了。在此列表中看起来不错,但在具有更多缩进/嵌套的其他列表中则完全不同。 (2认同)

zvr*_*rba 31

并且,无论你做什么,配置列表包使用固定宽度字体(如在您的示例中;您将在文档中找到该选项).默认设置在网格上使用比例字体排版,即恕我直言,令人难以置信的难看和难以理解,从其他答案与图片可以看出.当我必须阅读比例字体中的一些代码排版时,我个人非常恼火.

尝试使用以下方法设置固定宽度字体:

\lstset{basicstyle=\ttfamily}
Run Code Online (Sandbox Code Playgroud)

  • 我个人使用columns = fullflexible和basicstyle =\small\sffamily,就像我上面发布的例子一样.字符不是垂直对齐的,但我认为它们看起来比使用\ ttfamily更好.你发现我上面发布的样本难看吗? (3认同)

小智 23

我想知道为什么没人提到Minted包.它具有比LaTeX列表包更好的语法突出显示.它使用Pygments.

$ pip install Pygments
Run Code Online (Sandbox Code Playgroud)

LaTeX中的示例:

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}

\usepackage{minted}

\begin{document}
\begin{minted}{python}
import numpy as np

def incmatrix(genl1,genl2):
    m = len(genl1)
    n = len(genl2)
    M = None #to become the incidence matrix
    VT = np.zeros((n*m,1), int)  #dummy variable

    #compute the bitwise xor matrix
    M1 = bitxormatrix(genl1)
    M2 = np.triu(bitxormatrix(genl2),1) 

    for i in range(m-1):
        for j in range(i+1, m):
            [r,c] = np.where(M2 == M1[i,j])
            for k in range(len(r)):
                VT[(i)*n + r[k]] = 1;
                VT[(i)*n + c[k]] = 1;
                VT[(j)*n + r[k]] = 1;
                VT[(j)*n + c[k]] = 1;

                if M is None:
                    M = np.copy(VT)
                else:
                    M = np.concatenate((M, VT), 1)

                VT = np.zeros((n*m,1), int)

    return M
\end{minted}
\end{document}
Run Code Online (Sandbox Code Playgroud)

结果如下:

在此输入图像描述

您需要使用-shell-escapepdflatex命令的标志.

有关更多信息,请访问:https://www.sharelatex.com/learn/Code_Highlighting_with_minted

  • +1.Minted是用于在LaTeX中排版源代码的包.它不仅易于使用,功能丰富且文档齐全,而且源代码中的Unicode字符也没有问题(与`listing`不同). (2认同)

Mar*_*Lux 21

试试listings包裹.这是我前一段时间使用彩色Java列表的例子:

\usepackage{listings}

[...]

\lstset{language=Java,captionpos=b,tabsize=3,frame=lines,keywordstyle=\color{blue},commentstyle=\color{darkgreen},stringstyle=\color{red},numbers=left,numberstyle=\tiny,numbersep=5pt,breaklines=true,showstringspaces=false,basicstyle=\footnotesize,emph={label}}

[...]

\begin{lstlisting}
public void here() {
    goes().the().code()
}

[...]

\end{lstlisting}
Run Code Online (Sandbox Code Playgroud)

您可能想要自定义它.列表包有几个参考.只是谷歌他们.


ava*_*kar 9

看看algorithms包装,特别是algorithm环境.

  • 我只谈论`algorithm`环境,而不是'算法'.`algorithm`是一个浮动容器,看起来很漂亮.你可以在里面放任何你想要的东西,甚至是提到的elsethread的`listing`. (4认同)

kah*_*hen 8

您还可以执行其他一些操作,例如选择新字体:

\documentclass[10pt,a4paper]{article}
% ... lots of packages e.g. babel, microtype, fontenc, inputenc &c.
\usepackage{color}    % Leave this out if you care about B/W printing, obviously.
\usepackage{upquote}  % Turns curly quotes in verbatim text into straight quotes. 
                      % People who have to copy/paste code from the PDF output 
                      % will love you for this. Or perhaps more accurately: 
                      % They will not hate you/hate you less.
\usepackage{beramono} % Or some other package that provides a fixed width font. q.v.
                      % http://www.tug.dk/FontCatalogue/typewriterfonts.html
\usepackage{listings} 
\lstset {                 % A rudimentary config that shows off some features.
    language=Java,
    basicstyle=\ttfamily, % Without beramono, we'd get cmtt, the teletype font.
    commentstyle=\textit, % cmtt doesn't do italics. It might do slanted text though.
    \keywordstyle=        % Nor does cmtt do bold text.
        \color{blue}\bfseries,
    \tabsize=4            % Or whatever you use in your editor, I suppose.
}
\begin{document} 
\begin{lstlisting}
public final int ourAnswer() { return 42; /* Our final answer */ }
\end{lstlisting} 
\end{document}
Run Code Online (Sandbox Code Playgroud)

  • 我相信在\ keywordstyle和\ tabsize中应该删除反斜杠,因为它不会以这种方式工作.尽管如此,非常有帮助! (2认同)