viernes, 23 de octubre de 2009

insert code listings in latex



I've been strugling with it for last 2 days, and finally found a solution (I should have googled before , and not so much blind guessing).

Depending on what you're writing about, you probably will have to put code in your documents. Inserting code in latex is not that trivial, because you have to tell latex that a given block has to be left 'as is' (that means not formating it, not squeezing the newlines, indenting it correctly, and syntax highlighting it).

My first attempts where quite hand-crafted solutions, mixing a verbatim environment and fitting it into a table with just one row and one column.

Then I found a package called listings. It's a farily complex package, with lots of options and parameters, but for me, I just can use it nearly vanilla.

\usepackage{listings}
\usepackage{textcomp}
\usepackage[]{color}

\lstset{language=c++,
tabsize=4}
\lstset{commentstyle=\textit}



If you want, you can use pretty complex configurations:

\lstset{ language=C++,
keywordstyle=\bfseries\ttfamily\color[rgb]{0,0,1},
identifierstyle=\ttfamily,
commentstyle=\color[rgb]{0.133,0.545,0.133},
stringstyle=\ttfamily\color[rgb]{0.627,0.126,0.941},
showstringspaces=false,
basicstyle=\small,
numberstyle=\footnotesize,
numbers=left,
stepnumber=1,
numbersep=10pt,
tabsize=2,
breaklines=true,
prebreak = \raisebox{0ex}[0ex][0ex]{\ensuremath{\hookleftarrow}},
breakatwhitespace=false,
aboveskip={1.5\baselineskip},
columns=fixed,
upquote=true,
extendedchars=true,
% frame=single,
% backgroundcolor=\color{lbcolor},
}

Then, you just embed your code inside a lstlisting environment


\begin{lstlisting}[frame=trbl]{}
class Funcio{
private:
map dict;
public:
Funcio(){};
~Funcio(){};
operator()(int param1){
if( dict.exist(param1)){
return dict[param1];
}
double resultat;
// calcular i omplir resultat ...

dict[param1]=resultat;
return resultat;
}
}

\end{lstlisting}


With this you can paste codes with a great look.

As always, here are the sources I read to write this howto.

Ah, I know the code in the screenshot does not work, but it's just a kind of pseudocode to illustrate memoize, closures, and the c++ functors aproach (a half-solution to emulate closures and stateful functions in c++)

Bye!