share
Stack OverflowLaTeX source code listing like in professional books
[+343] [8] Mork0075
[2009-04-12 16:15:51]
[ latex ]
[ https://stackoverflow.com/questions/741985/latex-source-code-listing-like-in-professional-books ]

How should a latex source code listing look like to produce an output like in known books, for example one for the Spring Framework? I've tried with the latex listings package but wasn't able to produce something that looked as nice as the one below. So I'm primarely interested in the formatting instructions to produce something like the sample below (from Manning's sample chapter [1] for Spring in Action):

From Manning's Spring in Action

EDIT With the help especially of Tormod Fjeldskår [2] here's the complete snippet to produce the desired look:

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

Use it with this in your document:

\lstinputlisting[label=samplecode, caption=A sample]{sourceCode/HelloWorld.java}
Please be more precise. To me the listing I posted “looks like in professional books” and “looks as nice” as the one you posted. - Bastien Léonard
(2) Please use the sample posted in form of a screenshot as the result i want to archieve. - Mork0075
(8) For the sake of completeness you may want to add \usepackage{color} to the tex you posted. Took me a moment before I noticed it was missing. - Robert Massaioli
(1) Great work! I had to add \usepackage{caption} and \usepackage{graphics} though and it seems to convert single quotes. - hakunin
Hi mork where do I have to place the source file? In your example Hello.java - RoflcoptrException
When I tried to do this, my caption appears at the bottom of the source code, how can I fix this? - lamba
[+196] [2009-04-12 17:13:51] Tormod Fjeldskår [ACCEPTED]

It seems to me that what you really want, is to customize the look of the captions. This is most easily done using the caption package. For instructions how to use this package, see the manual (PDF) [1]. You would probably need to create your own custom caption format, as described in chapter 4 in the manual.

Edit: Tested with 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}

Result:

Preview

[1] http://tug.ctan.org/tex-archive/macros/latex/contrib/caption/caption-eng.pdf

(1) I would like to redefine the caption format only for things in the \lstinputlisting section (something like myCaption). Have you got any hint how to do that? - Mork0075
(1) Try /captionsetup[lstlisting]{your options} - Tormod Fjeldskår
This works great, thank you. Have you got an idea how to realize the gray background behind the caption (like in my initial posts sample)? Cant find anything in the documentation. - Mork0075
I think \colorbox{gray}{\parbox{\textwidth}{\textcolor{white}{text goes here}}} would be somewhere near your initial post sample. - Tormod Fjeldskår
Wow, if you can say how to apply this to the caption, you're my hero of the day :) \colorbox{gray}{\parbox{\textwidth}{\textcolor{white}{text goes here}}} \lstinputlisting[label=beispielcode,caption=Ein Beispiel]{sourceCode/HelloWorld.java} - Mork0075
Thats it, thanks a lot :) Have you also any idea how to indent the text inside the caption? - Mork0075
The margin option, explained in Section 2.4 of the manual, should do the trick. - Tormod Fjeldskår
No, this also indents the whole surrounding colorbox. - Mork0075
Ah, of course... Try adding \hspace{1cm} before #1#2#3 in the DeclareCaptionFormat statement. - Tormod Fjeldskår
(2) This looks nice, but my caption box gets indented (not the text, the box itself). I don't know why, since the listing isn't indented either. - Johan
I included 2 pieces source code in a later chapter (chapter 6), the caption says something like "listing 6.1", "listing 6.2" is there a way to change this caption to say "listing 1" and "listing 2"? Thanks - lamba
@lamba Have you tried setting the numberbychapter key to False? That should cause your listings to be numbered sequentially throughout your document, rather than subnumbered by your chapters. - Tormod Fjeldskår
I like this snippet, but accents like é in 'caption' make error. - Sergey Vakulenko
(1) In case anybody wants to have the listings' background colored as well, you will notice that the caption is wider than the listing. Look here tex.stackexchange.com/q/233717/30325 for a solution. - efie
1
[+52] [2009-04-12 16:28:18] Bastien Léonard

I am happy with the listings package:

Listing example

Here is how I configure it:

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

I use it like this:

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

(1) @lamba: if I remember correctly, it tells Latex to place the it at the top of the page. - Bastien Léonard
(8) Urgh, listings in proportional font are so massively ugly. (Plus, for cultural reasons, they are hard to read for some (at least many Japanese, maybe also other Asian) people.) - mirabilos
(2) @mirabilos: yeah, I think I changed it later. It looked OK on this listing but not at all on others with more indentation/nesting. - Bastien Léonard
2
[+34] [2009-04-12 17:11:57] zvrba

And please, whatever you do, configure the listings package to use fixed-width font (as in your example; you'll find the option in the documentation). Default setting uses proportional font typeset on a grid, which is, IMHO, incredibly ugly and unreadable, as can be seen from the other answers with pictures. I am personally very irritated when I must read some code typeset in a proportional font.

Try setting fixed-width font with this:

\lstset{basicstyle=\ttfamily}

(3) I personnally use columns=fullflexible with basicstyle=\small\sffamily, as in the example I posted above. The characters aren't vertically aligned, but I think they look better than with \ttfamily. Do you find the sample I posted above ugly? - Bastien Léonard
Your particular example looks fine. However, I would hate it with nested compound statements where a proper indentation (column alignment) is a big help to seeing the extent of a compound statement ({} block). - zvrba
I was thinking the same thing, but so far all my listings looked good. - Bastien Léonard
(1) Nested compound statements are a red herring. Since the indentations all consist of spaces, the indentations will line up regardless of the width of other characters. - jwg
3
[+32] [2015-05-27 15:08:29] Hans Ott

I wonder why nobody mentioned the Minted [1] package. It has far better syntax highlighting than the LaTeX listing package. It uses Pygments [2].

$ pip install Pygments

Example in 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}

Which results in:

enter image description here

You need to use the flag -shell-escape with the pdflatex command.

For more information: https://www.sharelatex.com/learn/Code_Highlighting_with_minted

[1] https://github.com/gpoore/minted
[2] http://pygments.org/

(3) +1. Minted is THE package for typesetting source code in LaTeX. Not only is it easy to use, feature-rich and well documented, but it also has no problems with Unicode characters in source code (unlike listings). - ScumCoder
4
[+21] [2009-04-12 16:27:45] Markus

Have a try on the listings package. Here is an example of what I used some time ago to have a coloured Java listing:

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

You may want to customize that. There are several references of the listings package. Just google them.


Thanks. I'am still aware of the listings package, but not able to format like my sample. This is the real question. - Mork0075
5
[+9] [2009-04-12 16:22:26] avakar

Take a look at algorithms [1] package, especially the algorithm environment.

[1] http://www.ctan.org/tex-archive/macros/latex/contrib/algorithms/algorithms.pdf

(1) Thanks. This package seems to be very strong in more theoretical algirthm discussion, i know it from many math books. But i wont emphasize this so much (prerequsites, if, else), i would like to have a formatting like the one above. - Mork0075
(4) I was only talking about the algorithm environment, not algorithmic. algorithm is a floating container, which looks pretty nice. You can put whatever you'd like inside, even the listing mentioned elsethread. - avakar
6
[+8] [2010-05-20 15:23:32] kahen

There are several other things you can do, such as selecting new fonts:

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

(2) I believe that in \keywordstyle and \tabsize the backslash should be removed as it wouldn't work this way. Nonetheless very helpful! - Xiphias
7
[+2] [2016-06-23 20:40:06] pachadotdev

For R code I use

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

And it looks exactly like this

enter image description here


8