LaTeX source code listing like in professional books - latex
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):
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}
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:
I am happy with the listings package:
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}
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 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:
You need to use the flag -shell-escape with the pdflatex command.
For more information: https://www.sharelatex.com/learn/Code_Highlighting_with_minted
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.
Take a look at algorithms package, especially the algorithm environment.
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}
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
Related
LaTex how to edit this equation?
I'm having issues turning this word equation into a LaTex equation. It's coming out looking dodgy, please help! I added a screen shot of the equation I want, and what I end up getting when I copy and paste into LaTex: WORD: LATEX CODE: \mathrm{=\ }\mathrm{C}_\mathrm{0}\mathrm{[1-}6(Dt)1/2aπ2-3Dta2] + 12(Dt)1/2an = 1∞exp(na(Dt)1/2) and therefore nothing comes out and LaTex doesn't let me run it.
This is absolutely not a proper LaTeX equation code. I don't know what you know about LaTeX, but you cannot just copy and paste from Word or any software to you LaTex editor. Plus, you need to provide your full code for anyone being able to help you. Anyway, running this MWE should work : \documentclass[11pt, a4paper, twoside]{report} % ===== PACKAGES DECLARATION ===== \usepackage{mathtools} % Replaces amsmaths + more features \usepackage{amsfonts} % Maths fonts package % ===== DOCUMENT BODY ===== \begin{document} \begin{equation} % optional : use the "equation*" environment to remove equation number % optional : use traditional math font by removing the \mathrm{} command \mathrm{X = C_0 \left[ 1 - \frac{6(Dt)^{1/2}}{a \pi^2} - \frac{3Dt}{a^2}\right] + \frac{12(Dt)^{1/2}}{a} \sum_{n=1}^\infty \exp\left(\frac{na}{(Dt)^{1/2}} \right)} % optional : remove auto-sized brackets by removing the \left and \right commands \end{equation} \end{document} As written in the code, you may want to remove the equation number and the big auto-sized brackets (that are more readable in my opinion). Just remove the corresponding commands. Also, you should consider using the "normal" math font and not the roman one that is clearly different from the text and helps the reader to separate equations from inline small expressions you could insert in your document.
One first sketch: \documentclass{article} \begin{document} \[ C_0\left[1-\frac{6(Dt)^{\frac{1}{2}}}{a\pi^2}-\frac{3Dt}{a^2}\right]+% \frac{12(Dt)^{\frac{1}{2}}}{a}\sum^{\infty}_{n=1}% \exp\left(\frac{na}{(Dt)^{\frac{1}{2}}}\right) \] \end{document} No packages required. The output: Than you can tune the math fonts and anything else.
How to prefix a refence in LaTex?
so I have figures like this: \begin{figure}[h]{} \includegraphics[width=\textwidth]{./assets/demo/identify-usecases/DomainSplitt-1.jpg} \caption{Identifying Domains: Match History with Filter} \centering \label{fig:domainsplitt-one} \end{figure} and I reference them like this: \ref{fig:domainsplitt-one}. In the generated PFD, the images have the caption like this Figure 4.13: Identifying Domains: Match History with Filter. But the reference in the text only has the number 4.13. I have something similar for code: \begin{code} \captionof{listing}{Custom Element listening to global custom events} \label{code:listening-custom-event} \begin{minted}{JavaScript} Here, the code has the prefix Source Code but in the reference is only the number. The rule I use for this is \usepackage[newfloat]{minted} \usepackage{caption} \newenvironment{code}{\captionsetup{type=listing}}{} \SetupFloatingEnvironment{listing}{name=Source Code} So what I need is, that the reference also have this prefix in the text. Since I'm really new to latex may question is: How do I do this? edit: here is a link with a replica: https://github.com/adrian-goe/latex-replica
The cleveref package will do all the work for you: % !TeX program = txs:///arara % arara: pdflatex: {synctex: on, interaction: nonstopmode, shell: yes} % Preamble %\documentclass[11pt]{article} % Packages \documentclass[12pt,DIV12,BCOR0mm,twoside,openright,headings=normal, numbers=noenddot,headsepline,headinclude]{scrreprt} \usepackage[automark,headsepline]{scrlayer-scrpage} \usepackage{scrhack} % to avoid KOMA-Script warning \usepackage[utf8]{inputenc} % UTF8 encoding \usepackage[T1]{fontenc} \usepackage{txfonts} % Postscript fonts \usepackage[ngerman,english]{babel} \usepackage[style=numeric-comp,giveninits=true,maxnames=10,sorting=none]{biblatex} \usepackage{graphicx} \usepackage[usenames]{xcolor} \usepackage[pdftex]{hyperref} \usepackage{wallpaper} \usepackage[newfloat]{minted} \usepackage{caption} \newenvironment{code}{\captionsetup{type=listing}}{} \SetupFloatingEnvironment{listing}{name=Code} \usemintedstyle{manni} \usepackage[noabbrev]{cleveref} \crefname{listing}{code}{code} \Crefname{listing}{Code}{Code} % Document \begin{document} this is my sample text and i want to reference \cref{code:update-a-attribute} and the \cref{fig:image} \begin{figure}[h]{} \includegraphics[width=\textwidth]{./img.png} \caption{some image} \centering \label{fig:image} \end{figure} \begin{code} \captionof{listing}{Update a Attribute} \label{code:update-a-attribute} \begin{minted}{JavaScript} const fragment = document.querySelector(".fragment"); fragment.setAttribute("data", 2) \end{minted} \end{code} \end{document} (please note that you can only have one single documentclass)
non-ASCII characters in Julia sourcefiles (e.g. θ) come out mojibake (e.g. Îÿ) using '\lstinputlisting{}' in LaTeX
I would like to include some Julia source in a LaTeX doc. I am familiar with the 'listings' package, and have crafted a decent 'lstdefinelanguage'. But I am having trouble with non-ASCII characters in the jl. I have played around with various 'lstset' and 'inputenc' options like 'extendedchars' and 'utf8' to no avail. I am using TeXShop on a Mac. Has anyone cracked this?
You can use literate option although it requires some set-up work. Here is a MWE: \documentclass{article} \usepackage{listings} \usepackage{courier} \lstset{basicstyle=\ttfamily} \lstset{literate= {δ}{{$\delta$}}1 {ϵ}{{$\epsilon$}}1 } \begin{document} \begin{lstlisting} function f() ϵϵϵϵϵ = 1 xxxxx = 3 δδδδδ = 2 ϵ + x + δ end \end{lstlisting} \end{document}
part lettering Latex
I am trying to get my document parts to show up as: A. Narrative % \part{Narrative} Intro %\section{Intro} main text... B. Appendix % \part{Appendix} Derivations % \section{Derivations} appendix text... I have seen others use: \renewcommand{\thepart}{\Alph{part}} However this is not working for me for some reason. My parts are showing up as: Part A Narrative Intro main text... Part B Appendix Derivations appendix text... Any ideas anyone?
The minimal example below updates \part to set its numbering differently. More specifically, it removes the \partname - Part - prefix and keeps the title on the same line. Fonts are also updated to set the part using \LARGE\bfseries in both \part and \part*. All of the above updates are done using etoolbox's \patchcmd{<cmd>}{<search>}{<replace>}{<success>}{<failure>} macro that performs a <search>-and-<replace> within <cmd>. \documentclass{article} \usepackage{lipsum,etoolbox} \renewcommand{\thepart}{\Alph{part}} \makeatletter % Change part display; also uniform size of \LARGE\bfseries \patchcmd{\#part}% <cmd> {\Large\bfseries \partname\nobreakspace\thepart \par\nobreak}% <search> {\LARGE\bfseries \thepart.\quad}% <replace> {}{}% <success><failure> \patchcmd{\#part}{\huge}{\LARGE}{}{} \patchcmd{\#spart}{\huge}{\LARGE}{}{} \renewcommand{\#seccntformat}[1]{\csname the#1\endcsname.\quad} % \#addtoreset{section}{part} % Reset section counter with every part \makeatother \begin{document} \part{Narrative} \section{Intro} \lipsum[1] \part{Appendix} \section{Derivations} \lipsum[2] \end{document} If you wish to have the \section numbers reset with every new \part, uncomment the line referencing that in the preamble.
Your idea is right, but you also redefine the titleformat. From the following link: \usepackage{titlesec} \renewcommand{\thepart}{\Alph{part}} \makeatletter \titleformat{\part}[display] {\Huge\scshape\filright} {\thepart~\partname} {20pt} {\thispagestyle{plain}} \makeatother
Latex + Source Code Import
I'm using Latex to write a program listing all my code and I am following this: http://texblog.wordpress.com/2008/04/02/include-source-code-in-latex-with-listings/ It works, but my code runs of the side of the page. How can I fix this? Additional question: How can I get it to highlight syntax? I do have lang set to Java.
Try something like this: \documentclass{article} \usepackage{listings} \usepackage{color} \usepackage{textcomp} \definecolor{listinggray}{gray}{0.9} \definecolor{lbcolor}{rgb}{0.9,0.9,0.9} \lstset{ language=c, basicstyle=\scriptsize, upquote=true, aboveskip={1.5\baselineskip}, columns=fullflexible, showstringspaces=false, extendedchars=true, breaklines=true, showtabs=false, showspaces=false, showstringspaces=false, identifierstyle=\ttfamily, keywordstyle=\color[rgb]{0,0,1}, commentstyle=\color[rgb]{0.133,0.545,0.133}, stringstyle=\color[rgb]{0.627,0.126,0.941}, } \begin{document} \begin{lstlisting} #include <stdio.h> int main() { // A line comment printf("A really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, REALLY long line. && & \n"); return 0; } \end{lstlisting} \end{document} which produces: alt text http://img260.imageshack.us/img260/1608/codes.png
Did you consider \lstset{...} breaklines=true -> sets automatic line breaking breakatwhitespace=false -> automatic breaks happen at whitespace ?
You want to turn on line breaking with \lstset{breaklines=true} in the command options. Now you might no like its choices but that is another question.
Instead of including the source directly, include it from a file: \lstinputlisting{/Volumes/docs/p2k_files_in_qt.sh} You'll save lots of work doing it that way. Alternatively, if you have to include source into the file, there's lgrind. \lstset{ % language=C, % choose the language of the code basicstyle=\footnotesize, % the size of the fonts that are used for the code numbers=left, % where to put the line-numbers numberstyle=\footnotesize, % the size of the fonts that are used for the line-numbers stepnumber=1, % the step between two line-numbers. If it's 1 each line will be numbered numbersep=5pt, % how far the line-numbers are from the code %backgroundcolor=\color{Blue}, % choose the background color. You must add \usepackage{color} showspaces=false, % show spaces adding particular underscores showstringspaces=false, % underline spaces within strings showtabs=false, % show tabs within strings adding particular underscores frame=single, % adds a frame around the code tabsize=2, % sets default tabsize to 2 spaces captionpos=b, % sets the caption-position to bottom breaklines=true, % sets automatic line breaking breakatwhitespace=false, % sets if automatic breaks should only happen at whitespace escapeinside={\%*}{*)}, % if you want to add a comment within your code % size, font commentstyle=\fontsize{7}{7}\selectfont, basicstyle=\ttfamily\fontsize{7}{7}\selectfont, keywordstyle=\color{red}, commentstyle=\color{blue}, stringstyle=\color{green} }
Use breaklines=true e. g.: \lstnewenvironment{bash} {\lstset{language=bash,breaklines=true,frame=trBL}} {}