像专业书籍中一样列出 LaTeX 源代码

标签 latex

latex 源代码列表应该是什么样子才能产生像已知书籍中那样的输出,例如 Spring 框架的输出?我尝试过使用 latex 列表包,但无法生成看起来像下面一样好的东西。因此,我主要对生成类似以下示例的格式说明感兴趣(来自 Manning 的 sample chapter Spring in Action):

From Manning's Spring in Action

编辑 特别是在 Tormod Fjeldskå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}}

在文档中使用它:

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

最佳答案

在我看来,您真正想要的是自定义标题的外观。使用 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}

结果:

Preview

关于像专业书籍中一样列出 LaTeX 源代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/741985/

相关文章:

html - 网络上的数学方程式

latex 彩色框内嵌文字

java - 将源代码转换为 LaTeX

latex - 添加情节 : set default domain

Latex - 未定义的控制序列\sym

latex - 尽管使用\centering,Latex 中的图形并未居中

r - Sweave 中的 xtable : specify toprule or midrule in a table + alignement

latex - 在 LaTeX Beamer 中有多个幻灯片模板

python - 将计算结果插入 LaTeX 文档

latex - 在 RMarkdown 表中引用