ChatGPT解决这个技术问题 Extra ChatGPT

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

https://i.stack.imgur.com/GhMUK.png

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}
Please be more precise. To me the listing I posted “looks like in professional books” and “looks as nice” as the one you posted.
Please use the sample posted in form of a screenshot as the result i want to archieve.
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.
Great work! I had to add \usepackage{caption} and \usepackage{graphics} though and it seems to convert single quotes.
Hi mork where do I have to place the source file? In your example Hello.java

T
Tormod Fjeldskår

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:

https://i.stack.imgur.com/WmL2j.png


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?
Try /captionsetup[lstlisting]{your options}
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.
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.
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.
B
Bastien Léonard

I am happy with the listings package:

https://i.imgur.com/f90FB.png

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}

@lamba: if I remember correctly, it tells Latex to place the it at the top of the page.
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: yeah, I think I changed it later. It looked OK on this listing but not at all on others with more indentation/nesting.
J
JasonMArcher

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}

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?
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).
I was thinking the same thing, but so far all my listings looked good.
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.
H
Hans Ott

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:

https://i.stack.imgur.com/5yBe8.png

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

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.
a
avakar

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


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.
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.
k
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}

I believe that in \keywordstyle and \tabsize the backslash should be removed as it wouldn't work this way. Nonetheless very helpful!
p
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

https://i.stack.imgur.com/7PEEB.jpg


关注公众号,不定期副业成功案例分享
Follow WeChat

Success story sharing

Want to stay one step ahead of the latest teleworks?

Subscribe Now