i am using lstinputlisting in a latex document to include some source code. When I am giving a specific line range or firstline to start with there is a cryptic line added directly before my code looking like that:
code line added by latex
My latex code:
\lstset{ % Konfiguration
xleftmargin=0.5cm,
language=C++, % C++ als Sprache vordefinieren. Optional überschreiben
basicstyle=\small,
backgroundcolor=\color{lgray},
keywordstyle=\color{black}\bfseries,
commentstyle=\color{black}\small,
showstringspaces=false,
numbers=left,
numberstyle=\tiny,
numbersep=5pt,
breaklines=true,
tabsize=4,
showtabs=false,
}
\lstinputlisting[linerange=739-745]{Marlin/Configuration.h}
Does someone know where this line comes from and how to fix it?
Minimal example:
\documentclass[12pt, ngerman]{scrreprt}
\usepackage{listings}
\begin{document}
\lstinputlisting[linerange={740-745}]{example.h}
\end{document}
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
Can anyone recommend me a good template to include C source code with line numbering
in Latex? For example, taking the classical Hello world program, I would like to make it look as follows:
(1) /* Hello World program */
(2)
(3) #include<stdio.h>
(4)
(5) main()
(6) {
(7) printf("Hello World");
(8) }
Typicall, I always used the verbatim environment, but I am wondering if there is a better and nicer way to do that.
Thanks so much
Richard
As others have said, the listings package will probably do what you want using something like the following:
\lstset{
language=C, % choose the language of the code
numbers=left, % where to put the line-numbers
stepnumber=1, % the step between two line-numbers.
numbersep=5pt, % how far the line-numbers are from the code
backgroundcolor=\color{white}, % 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
tabsize=2, % sets default tabsize to 2 spaces
captionpos=b, % sets the caption-position to bottom
breaklines=true, % sets automatic line breaking
breakatwhitespace=true, % sets if automatic breaks should only happen at whitespace
title=\lstname, % show the filename of files included with \lstinputlisting;
}
\lstinputlisting{HelloWorld.c}
A more powerful alternative would be to use the minted package, although this will do much more than what you're currently asking, as it uses/requires pygments to be installed on your system so that it can fully tokenize the code you give it.
You might want to have a look at the listings package. It is very flexible and easy to use.
Take a look at Code listings in LaTeX. You'll find a couple of alternatives there. Some options are:
listings
minted
lgrind
Use lgrind package for latex. It converts your code into a .tex file
CWEB had a nice C formatter.
Why does the following command not produce a horizontal rule filling the space until the end of the line?
Hello \rule[0.5em]{\fill}{1pt}
It is my understanding that this should print the text “Hello” followed by a horizontal rule that extends until the end of the line, analogously to the macro \hfill which is effectively equivalent to \hspace\fill. – But in effect, this command just produces the text “Hello”, no rule.
I am aware that the effect can be produced by \hrulefill but it can’t be used here because I want a raised rule and \hrulefill doesn’t work together with \raisebox and I want my rule to hang above the baseline (at best in the middle of the line).
I don't have a satisfying answer as to why the command you presented doesn't work, but I can offer an effective workaround. Put
% Raised Rule Command:
% Arg 1 (Optional) - How high to raise the rule
% Arg 2 - Thickness of the rule
\newcommand{\raisedrule}[2][0em]{\leaders\hbox{\rule[#1]{1pt}{#2}}\hfill}
into your document's preface, and then you can accomplish what you were hoping to with:
Hello \raisedrule[0.5em]{1pt}
The horizontal rule of 1pt height and raised by 1.5pt.
Hello \leaders\vrule height 2.5pt depth -1.5pt \hfill \null
There is a package called ulem which does this
% !TEX encoding = UTF-8 Unicode
% !TEX TS-program = xelatex
\documentclass{article}
\usepackage[normalem]{ulem}
\begin{document}
normal text \uline{\textit{underline text}\hfill}
\end{document}
which will produce
For your curiosity, the option normalem for package ulem prevents ulem to produce extra underline with \em or \emph.
You can do this with the command \hrulefill
see http://en.wikibooks.org/wiki/LaTeX/Lengths#Fill_the_rest_of_the_line
% I did it!
%
\documentclass{article}
\usepackage[normalem]{ulem}
\begin{document}
\uline{Some text \hfill\phantom{.}}
\end{document}
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