LaTeX nice listing code

by GarciaPL on Monday 9 July 2012

I'm very fascinated about document markup language and preparation system for the TeX typesetting program called LaTeX. I wrote using it my BSc thesis, curriculum vitae, cover letters, laboratory reports and many many more :-). Furthermore I am currently working on my MSc thesis of course writing it in LaTeX.


It has a lot of advantages - it is absolutely free, cross-platform, open-source (LPPL licence), automation generation components such as table of contents, bibliography, index etc., very good support for mathematical formulas and from community and obviously it can create documents look very nice and professionally in many widely known formats e.g. PDF, PostScript, HTML, DVI etc.


So, I am gona to show some piece of code which helps you create wonderful listing of your code in LaTeX ;) which is widely used for instance in books :

LaTeX code listing
LaTeX code listing

Copy and paste this style to your LaTeX project :

\usepackage{listings}
\usepackage{courier}
\lstset{
  basicstyle=\footnotesize\ttfamily, % Standardschrift
  %numbers=left, % Ort der Zeilennummern
  numberstyle=\tiny, % Stil der Zeilennummern
  %stepnumber=2, % Abstand zwischen den Zeilennummern
  numbersep=5pt, % Abstand der Nummern zum Text
  tabsize=2, % Groesse von Tabs
  extendedchars=true, %
  breaklines=true, % Zeilen werden Umgebrochen
  keywordstyle=\color{red},
    frame=b,
  % keywordstyle=[1]\textbf, % Stil der Keywords
  % keywordstyle=[2]\textbf, %
  % keywordstyle=[3]\textbf, %
  % keywordstyle=[4]\textbf, \sqrt{\sqrt{}} %
  stringstyle=\color{white}\ttfamily, % Farbe der String
  showspaces=false, % Leerzeichen anzeigen ?
  showtabs=false, % Tabs anzeigen ?
  xleftmargin=17pt,
  framexleftmargin=17pt,
  framexrightmargin=5pt,
  framexbottommargin=4pt,
  %backgroundcolor=\color{lightgray},
  showstringspaces=false % Leerzeichen in Strings anzeigen ?
}

\lstloadlanguages{% Check Dokumentation 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}}


Then use this code in LaTeX to invoke source code listing :


\lstinputlisting[label=samplecode,caption=Description]{code/foo.java}


Reference :
[1] MHK's Blog
[2] LaTeX source code listing like in professional books (Stackoverflow)