343

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 for Spring in Action):

From Manning's Spring in Action

EDIT With the help especially of Tormod Fjeldskår 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}
6
  • Please be more precise. To me the listing I posted “looks like in professional books” and “looks as nice” as the one you posted. Apr 12, 2009 at 16:47
  • 2
    Please use the sample posted in form of a screenshot as the result i want to archieve.
    – Mork0075
    Apr 12, 2009 at 17:08
  • 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. Oct 12, 2009 at 22:55
  • 1
    Great work! I had to add \usepackage{caption} and \usepackage{graphics} though and it seems to convert single quotes.
    – hakunin
    Mar 21, 2011 at 12:19
  • Hi mork where do I have to place the source file? In your example Hello.java Apr 4, 2011 at 23:11

8 Answers 8

196

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). 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

14
  • 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
    Apr 12, 2009 at 20:20
  • 1
    Try /captionsetup[lstlisting]{your options} Apr 12, 2009 at 21:26
  • 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
    Apr 13, 2009 at 8:01
  • 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
    Jan 25, 2011 at 7:33
  • 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
    Mar 18, 2015 at 9:38
52

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}
3
  • 1
    @lamba: if I remember correctly, it tells Latex to place the it at the top of the page. Apr 1, 2012 at 5:28
  • 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
    Jan 11, 2015 at 21:01
  • 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. Jan 12, 2015 at 10:06
34

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}
4
  • 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? Apr 13, 2009 at 12:12
  • 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
    Apr 13, 2009 at 13:45
  • I was thinking the same thing, but so far all my listings looked good. Apr 13, 2009 at 14:22
  • 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
    May 14, 2013 at 13:17
31

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

$ 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
  • 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
    Jul 30, 2016 at 18:34
21

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.

1
  • Thanks. I'am still aware of the listings package, but not able to format like my sample. This is the real question.
    – Mork0075
    Apr 12, 2009 at 16:32
9

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

2
  • 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
    Apr 12, 2009 at 16:26
  • 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
    Apr 12, 2009 at 16:35
8

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}
1
  • 2
    I believe that in \keywordstyle and \tabsize the backslash should be removed as it wouldn't work this way. Nonetheless very helpful!
    – Xiphias
    Nov 28, 2013 at 15:06
2

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

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.