29.3.12

Listings Package


Include source code in Latex with “Listings”


\usepackage{listings}

Basics


Now you have basically two possibilities. Either you type/copy your source code directly into the Latex document:

\begin{lstlisting}
place your source code here
\end{lstlisting
}

The other possibility is to directly include the source file:

\lstinputlisting{filename.java}

This is particularly useful if you are still editing your source code. Obviously, Latex will always include the latest version of the source while generating the PDF-file.


Supported languages

The listings package does not only support java source code, but there is an exhaustive list of languages which are known to the package:

ABAP (R/2 4.3, R/2 5.0, R/3 3.1, R/3 4.6C, R/3 6.10), ACSL Ada (83, 95), Algol (60, 68), Ant, Assembler (x86masm), Awk (gnu, POSIX), bash, Basic (Visual), C (ANSI, Handel, Objective, Sharp), C++ (ANSI, GNU, ISO, Visual), Caml (light, Objective), Clean, Cobol (1974, 1985, ibm), Comal 80, csh, Delphi, Eiffel, Elan, erlang, Euphoria, Fortran (77, 90, 95), GCL, Gnuplot, Haskell, HTML, IDL (empty, CORBA), inform, Java (empty, AspectJ), JVMIS, ksh, Lisp (empty, Auto), Logo, make (empty, gnu), Mathematica (1.0, 3.0), Matlab, Mercury, MetaPost, Miranda, Mizar, ML, Modula-2, MuPAD, NASTRAN, Oberon-2, OCL (decorative, OMG), Octave, Oz, Pascal (Borland6, Standard, XSC), Perl,PHP, PL/I,Plasm, POV,Prolog, Promela,Python, R,Reduce, Rexx,RSL, Ruby, S (empty, PLUS), SAS, Scilab, sh, SHELXL, Simula (67, CII, DEC, IBM), SQL, tcl (empty, tk), TeX (AlLaTeX, common, LaTeX, plain, primitive), VBScript, Verilog, VHDL (empty, AMS), VRML (97), XML, XSLT.

Custom code formatting

You can customise the way how your code is displayed by using:

\lstset{...}

The following is a list of parameters, which can be used inside the previous command
language=Octave -> choose the language of the code
basicstyle=\footnotesize -> the size of the fonts used for the code
numbers=left -> where to put the line-numbers
numberstyle=\footnotesize -> size of the fonts used for the line-numbers
stepnumber=2 -> the step between two line-numbers.
numbersep=5pt -> how far the line-numbers are from the code
backgroundcolor=\color{white} -> sets background color (needs package)
showspaces=false -> show spaces adding particular underscores
showstringspaces=false -> underline spaces within strings
showtabs=false -> show tabs within strings through particular underscores
frame=single -> adds a frame around the code
tabsize=2 -> sets default tab-size to 2 spaces
captionpos=b -> sets the caption-position to bottom
breaklines=true -> sets automatic line breaking
breakatwhitespace=false -> automatic breaks happen at whitespace
morecomment=[l]{//} -> displays comments in italics (language dependent)
If you are using several parameters, they have to be separated by commas.
Example:

\lstset{numbers=left, stepnumber=2, frame=single,}

You might want to have a caption as well as reference the listing later:

\lstset{language=Java, caption=Descriptive Caption Text, label=DescriptiveLabel}

Other example with matlab language:

\usepackage{listings}
\usepackage{color}
\usepackage{textcomp}
\definecolor{listinggray}{gray}{0.9}
\definecolor{lbcolor}{rgb}{0.9,0.9,0.9}
\lstset{
 backgroundcolor=\color{lbcolor},
 tabsize=4,
 rulecolor=,
 language=matlab,
        basicstyle=\scriptsize,
        upquote=true,
        aboveskip={1.5\baselineskip},
        columns=fixed,
        showstringspaces=false,
        extendedchars=true,
        breaklines=true,
        prebreak = \raisebox{0ex}[0ex][0ex]{\ensuremath{\hookleftarrow}},
        frame=single,
        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},
}

Thre examples with Fortran language:

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{xcolor}
\usepackage{lmodern}
\usepackage{listings}
\lstset{language=[90]Fortran,
  basicstyle=\ttfamily,
  keywordstyle=\color{red},
  commentstyle=\color{green},
  morecomment=[l]{!\ }% Comment only with space after !
}
\begin{document}
\begin{lstlisting}
! Der folgende Fortran-Code ist bei Wikipedia geklaut.
SUBROUTINE test( Argument1, Argument2, Argument3 )
   REAL,              INTENT(IN) :: Argument1
   CHARACTER(LEN= *), INTENT(IN) :: Argument2
   INTEGER,           INTENT(IN), OPTIONAL :: Argument3
   ! This makes sense
END SUBROUTINE\end{lstlisting}
\end{document}

\documentclass[11pt]{article}
%\usepackage{geometry}            % See geometry.pdf to learn the layout options. There are lots.
%\geometry{letterpaper}           % ... or a4paper or a5paper or ...
%\geometry{landscape}             % Activate for for rotated page geometry
%\usepackage[parfill]{parskip}    % Activate to begin paragraphs with an empty line rather than an indent
%\usepackage{graphicx}
%\usepackage{amssymb}
%\usepackage{epstopdf}
\usepackage{listings}
\lstset{ %
language= Fortran,              % choose the language of the code
basicstyle=\footnotesize,       % the size of the fonts that are used for the code
basicstyle=\scriptsize,
numbers=left,                   % where to put the line-numbers
numberstyle=\footnotesize,      % the size of the fonts that are used for the line-numbers
numberstyle=\scriptsize,        % the size of the fonts that are used for the line-numbers
stepnumber=2,                   % 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{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
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
title=\lstname,                 % show the filename of files included with \lstinputlisting; also try caption instead of title
escapeinside={\%*}{*)}          % if you want to add a comment within your code
%morekeywords={*,...}            % if you want to add more keywords to the set
}
%\DeclareGraphicsRule{.tif}{png}{.png}{`convert #1 `dirname #1`/`basename #1 .tif`.png}

\title{Brief Article}
\author{The Author}
%\date{}                                           % Activate to display a given date or no date

\begin{document}
\maketitle
%\section{}
%\subsection{}

\lstinputlisting[language=Fortran]{pGrand_hsnj.f}
\lstinputlisting[language=Fortran]{pHydroTort_FT_F.f90}

\end{document}
There are several alternative packages for syntax highlighting. With fortran there seems to be even a package to print Fortran programs. But I've never used this, it cannot be used for syntax highlighting and was made to be used with plainTeX. So maybe if you want to try an alternative, e.g., highlight would be ab better suggestion.

\documentclass{article}

\usepackage{amsmath}
\usepackage{amsthm}
\usepackage[latin1]{inputenc}
\usepackage[normalbf,normalem]{ulem}
\usepackage{titlesec}
\usepackage{titletoc}
\usepackage{amsbsy}
\usepackage{multicol}
\usepackage{fancyhdr}
\usepackage{extramarks}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{times}
\usepackage[activeacute,spanish]{babel}

\usepackage{color}

\usepackage{verbatim}
\usepackage{listings}
\definecolor{gray97}{gray}{.97}
\definecolor{gray85}{gray}{.95}
\definecolor{gray75}{gray}{.75}
\definecolor{gray45}{gray}{.45}
\definecolor{yellow57}{rgb}{1.00,1.00,0.84}
\lstset{ frame=Ltb,
     framerule=0pt,
     aboveskip=0.5cm,
     framextopmargin=3pt,
     framexbottommargin=3pt,
     framexleftmargin=0.4cm,
     framesep=0pt,
     rulesep=.4pt,
     backgroundcolor=\color{gray97},
     rulesepcolor=\color{black},
     %
     stringstyle=\ttfamily,
     showstringspaces = false,
     basicstyle=\small\ttfamily,
     commentstyle=\color{gray45},
     keywordstyle=\bfseries,
     %
     numbers=left,
     numbersep=15pt,
     numberstyle=\tiny,
     numberfirstline = false,
     breaklines=true,
   }
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% minimizar fragmentado de listados
\lstnewenvironment{listing}[1][]
   {\lstset{#1}\pagebreak[0]}{\pagebreak[0]}

\lstdefinestyle{consola}
   {basicstyle=\scriptsize\bf\ttfamily,
    backgroundcolor=\color{blue57},
   }

\lstdefinestyle{L}
   {language=TeX,
   }
% y en la derecha la composici'on.
%
% \begin{example}
% \Large Esto es grande
% \end{example}
%
% Esta parte procede de verbaim.sty de FMi
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\makeatletter
\newwrite\solution@stream
\openout\solution@stream=\jobname.solutions
\newcounter{problem}
\newcommand*{\problemname}{Problem}
\newcommand{\problem}[1]{%
  \refstepcounter{problem}%
  \problemname~\theproblem:\enskip#1\par

}

\newcommand{\solution}[1]{%
  \protected@write\solution@stream{}{%
    \protect\print@solution{\theproblem}{#1}%
  }%

}

\newcommand*{\printsolutions}{%
  \closeout\solution@stream
  \makeatletter
  \InputIfFileExists{\jobname.solutions}{}{}%
  \makeatother

}

\newcommand*{\solutionname}{Solution}
\newcommand{\print@solution}[2]{%
  \solutionname~#1:\enskip#2\par

}

%\makeatother

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%\makeatletter
%\def\ThisFile{\yorname}
%\let\OldInput\input
%\renewcommand{\input}[1]{%
%  \renewcommand{\ThisFile}{#1}%
%  \OldInput{#1}%
%}
\newwrite\ejercicio@out
\newenvironment{ejercicio}%
 {\begingroup% Lets Keep the Changes Local
  \@bsphack
  \immediate\openout \ejercicio@out \jobname.exa
  \let\do\@makeother\dospecials\catcode`\^^M\active
  \def\verbatim@processline{%
    \immediate\write\ejercicio@out{\the\verbatim@line}}%
  \verbatim@start}%
 {\immediate\closeout\ejercicio@out\@esphack\endgroup%
%
% Y aqu'i lo que se ha a~nadido
%
  \par\small\addvspace{3ex plus 1ex}\vskip -\parskip
  \noindent
  \makebox[0.45\linewidth][l]{%
  \begin{minipage}[t]{0.45\linewidth}
    \vspace*{-2ex}
    \setlength{\parindent}{0pt}
    \setlength{\parskip}{1ex plus 0.4ex minus 0.2ex}
    \begin{trivlist}

      \item\input{\jobname.exa}

    \end{trivlist}
  \end{minipage}}%
  \hfill%
  \makebox[0.5\linewidth][l]{%
  \begin{minipage}[t]{0.50\linewidth}
    \vspace*{-1ex}
    \verbatiminput{\jobname.exa}
  \end{minipage}}
  \par\addvspace{3ex plus 1ex}\vskip -\parskip
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\newwrite\example@out
\newenvironment{example}%
 {\begingroup% Lets Keep the Changes Local
  \@bsphack
  \immediate\openout \example@out \jobname.exa
  \let\do\@makeother\dospecials\catcode`\^^M\active
  \def\verbatim@processline{%
    \immediate\write\example@out{\the\verbatim@line}}%
  \verbatim@start}%
 {\immediate\closeout\example@out\@esphack\endgroup%
\makeatother
%% Y aqu'i lo que se ha a~nadido
%
  \par\small\addvspace{3ex plus 1ex}\vskip -\parskip
  \noindent
  \makebox[0.5\linewidth][l]{%
  \hspace*{+2ex}
  \setlength{\parindent}{0pt}
    \setlength{\parskip}{1ex plus 0.4ex minus 0.7ex}
  \begin{minipage}[t]{0.50\linewidth}
   % \vspace*{-1ex}
   \vspace*{-2ex}

        \lstinputlisting[style=L, basicstyle=\scriptsize\bf\ttfamily,
    backgroundcolor=\color{yellow57},]{\jobname.exa}
    %\verbatiminput{\jobname.exa}
     \end{minipage}}
  \hfill
  \hspace{10pt}%
  \makebox[0.45\linewidth][l]{%
  \begin{minipage}[t]{0.45\linewidth}
    \vspace*{-2ex}
    \setlength{\parindent}{0pt}
    \setlength{\parskip}{1ex plus 0.4ex minus 0.7ex}
    \begin{trivlist}
      \item\input{\jobname.exa}
    \end{trivlist}
  \end{minipage}}%
  \par\addvspace{3ex plus 1ex}\vskip -\parskip
}




\begin{document}
aaaaa
\begin{example}
$\sum $
\end{example}

\begin{lstlisting}[style=L]
  \begin{trivlist}
      \item\input{\jobname.exa}
      \end{trivlist}
    \end{lstlisting}
\begin{ejercicio}
 Este es un ejemplo con un
parrrafo m\'{a}s grande
que , por c i e r t o , tambi \'{e}n
es mucho m\'{a}s i n te re sa
n te . Recuerda que un p\'{a} r ra fo
debe expresar una idea
completa y coherente . Justo como este
 p \'{a} r ra fo que nos ha
servido como un ejemplo genial . Observa
que los p \'{a} r ra fo s
en \ LaTeX { } forman l a unidad
e s t r u c t u r a l m\'{a}s
pequeña dent ro de los documentos .
 Recuerda que es tu responsabilidad
  e l contenido de estos
párrafos , y de \ LaTeX { } e l
que se vean boni tos .

\end{ejercicio}
\begin{example}
 Este es un ejemplo con un
p á r ra fo m\'{a}s grande
que , por c i e r t o , tambi \'{e}n
es mucho m\'{a}s i n te re sa
n te . Recuerda que un p\'{a} r ra fo
debe expresar una idea
completa y coherente . Justo como este
 p \'{a} r ra fo que nos ha
servido como un ejemplo genial . Observa
que los p \'{a} r ra fo s
en \ LaTeX { } forman l a unidad
e s t r u c t u r a l m\'{a}s
peque~na dent ro de los documentos .
 Recuerda que es tu responsabilidad
  e l contenido de estos
párrafos , y de \ LaTeX { } e l
que se vean boni tos .
\end{example}
\begin{example}
\begin{equation}
\forall x \in \mathbf{R}:
\qquad x^{2} \geq 0
\end{equation}
\end{example}
\begin{example}
\begin{displaymath}
x^{2} \geq 0\qquad
\textrm{para todo }x\in\mathbb{R}
\end{displaymath}
\end{example}

\end{document}



An example with XML language

\usepackage{listings}
\usepackage{color}
\definecolor{gray}{rgb}{0.4,0.4,0.4}
\definecolor{darkblue}{rgb}{0.0,0.0,0.6}
\definecolor{cyan}{rgb}{0.0,0.6,0.6}
\lstset{
  basicstyle=\ttfamily,
  columns=fullflexible,
  showstringspaces=false,
  commentstyle=\color{gray}\upshape
}
\lstdefinelanguage{XML}
{
  morestring=[b]",
  morestring=[s]{>}{<},
  morecomment=[s]{}{?>},
  stringstyle=\color{black},
  identifierstyle=\color{darkblue},
  keywordstyle=\color{cyan},
  morekeywords={xmlns,version,type}% list your attributes here
}


Other example with octave language:

\usepackage{listings}
\usepackage{color}
 
\definecolor{dkgreen}{rgb}{0,0.6,0}
\definecolor{gray}{rgb}{0.5,0.5,0.5}
\definecolor{mauve}{rgb}{0.58,0,0.82}
 
\lstset{ %
  language=Octave,                % 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=\tiny\color{gray},  % the style that is used for the line-numbers
  stepnumber=2,                   % 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{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
  frame=single,                   % adds a frame around the code
  rulecolor=\color{black},        % if not set, the frame-color may be changed on line-breaks within not-black text (e.g. commens (green here))
  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
  title=\lstname,                 % show the filename of files included with \lstinputlisting;
                                  % also try caption instead of title
  keywordstyle=\color{blue},      % keyword style
  commentstyle=\color{dkgreen},   % comment style
  stringstyle=\color{mauve},      % string literal style
  escapeinside={\%*}{*)},         % if you want to add a comment within your code
  morekeywords={*,...}            % if you want to add more keywords to the set
}


The escapeinside line needs an explanation. You need it if you want to add some text within the code that will not be printed. Note that, by default, comments of the language you are inserting will be printed; the command escapeinside={A}{B} will define comments for listings only. All the code between the string "A" and "B" will be ignored. In the example above, the comments for Octave start with %, and they are going to be printed in the document unless they start with %*, but you have to remember to "close" the comment with another "*".
If you add the above paragraph, the following can be used to alter the settings within the code:
\lstset{language=C,caption={Descriptive Caption Text},label=DescriptiveLabel}


A lot more detailed information can be found in a PDF by Carsten Heinz and Brooks Moses .     

For an exhaustive list of available options to customize your included source code, refer to the documentation on CTAN.

A very short example is:


\documentclass{article}
\usepackage{listings}
\begin{document}
 
\begin{lstlisting}[language=C]
#include 
int main(int argc, char* argv[]) {
  puts("Hola mundo!");
}
\end{lstlisting}
 
\end{document}

and we get





Other example with more details is:

\documentclass{article}
 
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[spanish]{babel}
\usepackage{times}
 
\usepackage{color}
\definecolor{gray97}{gray}{.97}
\definecolor{gray75}{gray}{.75}
\definecolor{gray45}{gray}{.45}
 
\usepackage{listings}
\lstset{ frame=Ltb,
     framerule=0pt,
     aboveskip=0.5cm,
     framextopmargin=3pt,
     framexbottommargin=3pt,
     framexleftmargin=0.4cm,
     framesep=0pt,
     rulesep=.4pt,
     backgroundcolor=\color{gray97},
     rulesepcolor=\color{black},
     %
     stringstyle=\ttfamily,
     showstringspaces = false,
     basicstyle=\small\ttfamily,
     commentstyle=\color{gray45},
     keywordstyle=\bfseries,
     %
     numbers=left,
     numbersep=15pt,
     numberstyle=\tiny,
     numberfirstline = false,
     breaklines=true,
   }
 
% minimizar fragmentado de listados
\lstnewenvironment{listing}[1][]
   {\lstset{#1}\pagebreak[0]}{\pagebreak[0]}
 
\lstdefinestyle{consola}
   {basicstyle=\scriptsize\bf\ttfamily,
    backgroundcolor=\color{gray75},
   }
 
\lstdefinestyle{C}
   {language=C,
   }
 
\begin{document}
 
\noindent
Escribe el siguiente código en un fichero llamado \texttt{hello.c}:
 
\begin{lstlisting}[style=C]
#include 
int main(int argc, char* argv[]) {
  puts("Hola mundo!");
}
\end{lstlisting}
 
\noindent
Ahora compila usando \texttt{gcc}:
 
\begin{listing}[style=consola, numbers=none]
$ gcc  -o hello hello.c
\end{listing}
 
\end{document}
And we get




With caption personal
\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}

Tricks


The following will draw a frame around your source code with a blue shadow (you will need the color-package).

\lstset{frame=shadowbox, rulesepcolor=\color{blue}}


If you want closed frames on each page, use the following command sequence:

\begin{framed}
\begin{lstlisting}...\end{lstlisting}
or \lstinputlisting{...}
\end{framed}

No hay comentarios:

Publicar un comentario