【问题标题】:LaTeX source code listing like in professional books专业书籍中的 LaTeX 源代码列表
【发布时间】:2010-10-19 00:35:31
【问题描述】:

latex 源代码列表应该如何产生类似于已知书籍中的输出,例如 Spring 框架的输出?我已经尝试过使用乳胶列表包,但无法制作出看起来像下面这样漂亮的东西。因此,我主要对生成以下示例的格式说明感兴趣(来自 Manning 的 sample chapterSpring in Action):

编辑 尤其是在 Tormod Fjeldskår 的帮助下,这里是完整的 sn-p 以产生所需的外观:

\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}}

在您的文档中使用它:

\lstinputlisting[label=samplecode, caption=A sample]{sourceCode/HelloWorld.java}

【问题讨论】:

  • 请更准确。对我来说,我发布的列表“看起来像在专业书籍中”并且“看起来和您发布的一样好”。
  • 请使用以截图形式发布的示例作为我要归档的结果。
  • 为了完整起见,您可能需要将 \usepackage{color} 添加到您发布的 tex 中。我花了一点时间才发现它不见了。
  • 干得好!我不得不添加 \usepackage{caption} 和 \usepackage{graphics} 虽然它似乎转换单引号。
  • 嗨,我必须将源文件放在哪里?在您的示例中 Hello.java

标签: latex


【解决方案1】:

对于我使用的 R 代码

\usepackage{listings}
\lstset{
language=R,
basicstyle=\scriptsize\ttfamily,
commentstyle=\ttfamily\color{gray},
numbers=left,
numberstyle=\ttfamily\color{gray}\footnotesize,
stepnumber=1,
numbersep=5pt,
backgroundcolor=\color{white},
showspaces=false,
showstringspaces=false,
showtabs=false,
frame=single,
tabsize=2,
captionpos=b,
breaklines=true,
breakatwhitespace=false,
title=\lstname,
escapeinside={},
keywordstyle={},
morekeywords={}
}

它看起来就像这样

【讨论】:

    【解决方案2】:

    我想知道为什么没有人提到 Minted 包。它比 LaTeX 列表包有更好的语法高亮。它使用Pygments

    $ pip install Pygments
    

    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}
    

    结果:

    您需要在 pdflatex 命令中使用标志 -shell-escape

    欲了解更多信息:https://www.sharelatex.com/learn/Code_Highlighting_with_minted

    【讨论】:

    • +1。 Minted 是用于在 LaTeX 中排版源代码的软件包。它不仅易于使用、功能丰富且文档齐全,而且源代码中的 Unicode 字符也没有问题(与 listings 不同)。
    【解决方案3】:

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

    尝试用这个设置固定宽度的字体:

    \lstset{basicstyle=\ttfamily}
    

    【讨论】:

    • 我个人使用 columns=fullflexible 和 basicstyle=\small\sffamily,就像我在上面发布的示例一样。字符不是垂直对齐的,但我认为它们看起来比 \ttfamily 更好。你觉得我上面贴的样本丑吗?
    • 您的特定示例看起来不错。但是,我会讨厌嵌套复合语句,其中适当的缩进(列对齐)是查看复合语句({}块)范围的帮助。
    • 我也在想同样的事情,但到目前为止我所有的列表看起来都不错。
    • 嵌套复合语句是一个红鲱鱼。由于缩进全部由空格组成,因此无论其他字符的宽度如何,缩进都会对齐。
    【解决方案4】:

    在我看来,您真正想要的是自定义字幕的外观。使用caption 包最容易做到这一点。有关如何使用此软件包的说明,请参阅the manual (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}
    

    结果:

    【讨论】:

    • 我想只为 \lstinputlisting 部分(类似于 myCaption)中的内容重新定义标题格式。你有什么提示吗?
    • 试试 /captionsetup[lstlisting]{your options}
    • 这很好用,谢谢。您知道如何实现标题背后的灰色背景(就像我最初的帖子示例中一样)吗?在文档中找不到任何内容。
    • 这看起来不错,但是我的标题框缩进了(不是文本,而是框本身)。我不知道为什么,因为列表也没有缩进。
    • 如果有人想同时为列表的背景着色,您会注意到标题比列表宽。在这里查看tex.stackexchange.com/q/233717/30325 的解决方案。
    【解决方案5】:

    试试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}
    

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

    【讨论】:

    • 谢谢。我仍然知道列表包,但无法像我的示例那样格式化。这是真正的问题。
    【解决方案6】:

    我对@9​​87654322@ 包很满意:

    这是我的配置方式:

    \lstset{
    language=C,
    basicstyle=\small\sffamily,
    numbers=left,
    numberstyle=\tiny,
    frame=tb,
    columns=fullflexible,
    showstringspaces=false
    }
    

    我是这样使用的:

    \begin{lstlisting}[caption=Caption example.,
      label=a_label,
      float=t]
    // Insert the code here
    \end{lstlisting}
    

    【讨论】:

    • @lamba:如果我没记错的话,它会告诉 Latex 将它放在页面顶部。
    • 呃,比例字体的列表非常丑陋。 (另外,出于文化原因,某些(至少很多日本人,也许还有其他亚洲人)很难阅读它们。)
    • @mirabilos:是的,我想我后来改了。在这个列表上看起来不错,但在其他有更多缩进/嵌套的列表上就不行了。
    【解决方案7】:

    您还可以做其他几件事,例如选择新字体:

    \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}
    

    【讨论】:

    • 我相信在 \keywordstyle 和 \tabsize 中应该删除反斜杠,因为它不会以这种方式工作。尽管如此非常有帮助!
    【解决方案8】:

    看看algorithms 包,尤其是algorithm 环境。

    【讨论】:

    • 谢谢。这个包在更理论的算法讨论中似乎非常强大,我从许多数学书籍中都知道。但我不会过多强调这一点(前提条件、if、else),我希望采用上述格式。
    • 我只是在谈论algorithm 环境,而不是algorithmicalgorithm 是一个浮动容器,看起来很漂亮。你可以在里面放任何你想要的东西,即使是 listing 提到的 elsethread。
    猜你喜欢
    • 1970-01-01
    • 2011-03-24
    • 1970-01-01
    • 2011-02-11
    • 1970-01-01
    • 1970-01-01
    • 2011-05-25
    • 2021-09-30
    • 2013-05-22
    相关资源
    最近更新 更多