PDA

Archiv verlassen und diese Seite im Standarddesign anzeigen : lstlisting [language = R] (Quellcode einfügen)



Kris
03-01-2011, 12:34
Hallo,

ich möchte gerne in latex ein Quellcode einfügen. Die Programmiersprache ist R (Statistiksoftware R). Weiß jemand wie man das in latex machen kann bzw. ein kleines Bsp.. habe schon im Internet gesucht aber kein passendes Bsp. gefunden.

LG Kris

Xenara
03-01-2011, 12:56
Was ist das Problem? "listings" kennt die Sprache (aber ich nicht, daher habe ich auf gut Glück diesen (http://www.mayin.org/ajayshah/KB/R/html/b1.html)Code hier geklaut):

\documentclass{scrreprt}
\usepackage[ngerman]{babel}
\usepackage[latin1]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{xcolor}
\usepackage{listings}

\usepackage{blindtext}

\begin{document}

\blindtext

\lstset{%
language=R,
keywordstyle=\color{blue},
identifierstyle=\color{orange},
commentstyle=\color{green},
stringstyle=\color{red},
}
\begin{lstlisting}
# Goals: A first look at R objects - vectors, lists, matrices, data frames.

# To make vectors "x" "y" "year" and "names"
x <- c(2,3,7,9)
y <- c(9,7,3,2)
year <- 1990:1993
names <- c("payal", "shraddha", "kritika", "itida")
# Accessing the 1st and last elements of y --
y[1]
y[length(y)]

# To make a list "person" --
person <- list(name="payal", x=2, y=9, year=1990)
person
# Accessing things inside a list --
person$name
person$x

# To make a matrix, pasting together the columns "year" "x" and "y"
# The verb cbind() stands for "column bind"
cbind(year, x, y)

# To make a "data frame", which is a list of vectors of the same length --
D <- data.frame(names, year, x, y)
nrow(D)
# Accessing one of these vectors
D$names
# Accessing the last element of this vector
D$names[nrow(D)]
# Or equally,
D$names[length(D$names)]
\end{lstlisting}

\blindtext

\end{document}

Weiteres in der listings-Doku, am Einfachsten zu erreichen (unter Windows) über Start -> Programme -> Zubehör -> Eingabeaufforderung
Eintippen: "texdoc listings"

Kris
03-01-2011, 13:08
Hallo,
bekomme jetzt leider immer den Fehler:

Package inputence Error: Keyboard character used is undefined
inputenc inputencoding 'latin1'.
See the inputenc package documentation for explanation

Kennt jemand eine Lösung

Xenara
03-01-2011, 13:12
Nimm utf8 oder ansinew oder wasauchimmer du sonst verwendest. Die Angabe des Betriebssystems könnte hilfreich sein.

Kris
03-01-2011, 13:32
Benutze Windows. Habe auch noch ein anderen Befehl für das Betriebssystem verwendet aber da bekomme ich auch einige Fehler.

Xenara
03-01-2011, 13:39
Welchen Befehl? Welche Fehler? Welcher Editor? Was für eine Anweisung für inputenc nimmst du normalerweise?
Win XP mit TeXnicCenter, genau den obigen Code kopiert, eingefügt, läuft einwandfrei.

Kris
03-01-2011, 13:55
Habe nochmal alles neu gemacht und bekomme jetzt den Fehler :
latex error : Option clash for package listings
Habe aber hier für noch keine Lösung gefunden.

Xenara
03-01-2011, 14:04
Option clash bedeutet hier afaik, dass bereits etwas für listings definiert wurde und später nochmal (anders) definiert wird, z.B. weil ein Paket mehrfach mit unterschiedlichen Optionen geladen wurde.

Kommt der Fehler, wenn du genau obigen Code versuchst zu kompilieren?
Wenn ja, wäre deine FileList interessant (\listfiles vor \documentclass... setzen, im .log-File erscheinen alle Pakete mit Versionsdaten).

Kris
03-01-2011, 14:13
Ich bin erstmal in meinen header gegangen und habe die Pakete
%Quellcode eingeben
\usepackage{listings}
\usepackage{blindtext}
geladen.

und da kam der Fehler auf. Ich habe mal in meinem Header was rot markiert, vermute, dass das Problem dort liegt.

Mein gesamter Header:

\documentclass[%
pdftex,% PDFTex verwenden
a4paper,% A4 Papier
oneside,% Einseitig
bibtotoc,% Literaturverzeichnis einfügen bibtotocnumbered: nummeriert
liststotoc,% Verzeichnisse einbinden in toc
idxtotoc,% Index ins Verzeichnis einfügen
halfparskip,% Europäischer Satz mit abstand zwischen Absätzen
% chapterprefix,% Kapitel anschreiben als Kapitel
headsepline,% Linie nach Kopfzeile
%footsepline,% Linie vor Fusszeile
pointlessnumbers,% Nummern ohne abschließenden Punkt
12pt% Grössere Schrift, besser lesbar am bildschrim
]{scrbook}

%
% Paket für Übersetzungen ins Deutsche
%
\usepackage[french,ngerman]{babel}

%Paket damit bilder in section bleiben
\usepackage[section]{placeins}
%
% Pakete um Latin1 Zeichnensätze verwenden zu können und die dazu
% passenden Schriften.
%
\usepackage[latin1]{inputenc}
\usepackage[T1]{fontenc}


%Tabelle über mehrer Seiten
\usepackage{longtable}
\usepackage{booktabs}
% Paket für Quotes
%
\usepackage[babel,french=guillemets,german=swiss]{csquotes}


%
% Paket zum Erweitern der Tabelleneigenschaften
%
\usepackage{array}

\usepackage{cite}

%
% Paket für schönere Tabellen
%
\usepackage{booktabs}

%
% Paket um Grafiken einbetten zu können
%
\usepackage{graphicx}
\usepackage{caption}
\usepackage{subfigure}
\usepackage{float}
%
% Spezielle Schrift im Koma-Script setzen.
%
\setkomafont{sectioning}{\normalfont\bfseries}
\setkomafont{captionlabel}{\normalfont\bfseries}
\setkomafont{pagehead}{\normalfont\bfseries} % Kopfzeilenschrift
\setkomafont{descriptionlabel}{\normalfont\bfserie s}

%
% Zeilenumbruch bei Bildbeschreibungen.
%
\setcapindent{0.5em}

%
%Paket für farbigen Hintergrund
\usepackage{color}
\usepackage{colortbl}
% Define user colors using the RGB model
\definecolor{dunkelgrau}{rgb}{0.8,0.8,0.8}
\definecolor{hellgrau}{rgb}{0.95,0.95,0.95}
% Kopf und Fußzeilen
%
\usepackage{scrpage2}
\pagestyle{scrheadings}

% Inhalt bis Section rechts und Chapter links
\automark[section]{chapter}
% Mitte: leer
\chead{}
\usepackage[multiple,bottom]{footmisc}
%
% mathematische symbole aus dem AMS Paket.
%
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{bbm}
%
%Quellcode eingeben
\usepackage{listings}
\usepackage{blindtext}
%Währungzeichen

% Type 1 Fonts für bessere darstellung in PDF verwenden.
%
%\usepackage{mathptmx} % Times + passende Mathefonts
%\usepackage[scaled=.92]{helvet} % skalierte Helvetica als \sfdefault
\usepackage{courier} % Courier als \ttdefault

%
% Paket um Textteile drehen zu können
%
\usepackage{rotating}

%
% Paket für Farben im PDF
%
\usepackage{color}

%
% Paket für Links innerhalb des PDF Dokuments
%
\definecolor{LinkColor}{rgb}{0,0,0.5}
\usepackage[%
pdftitle={Titel},% Titel der Diplomarbeit
pdfauthor={Autor},% Autor(en)
pdfcreator={LaTeX, LaTeX with hyperref and KOMA-Script},% Genutzte Programme
pdfsubject={Betreff}, % Betreff
pdfkeywords={Keywords}]{hyperref} % Keywords halt :-)
\hypersetup{colorlinks=true,% Definition der Links im PDF File
linkcolor=LinkColor,%
citecolor=LinkColor,%
filecolor=LinkColor,%
menucolor=LinkColor,%
pagecolor=LinkColor,%
urlcolor=LinkColor}

%
% Paket um LIstings sauber zu formatieren.

\usepackage[savemem]{listings}
\lstloadlanguages{TeX}
% Listing Definationen für PHP Code
%
\definecolor{lbcolor}{rgb}{0.85,0.85,0.85}
\lstset{language=[LaTeX]TeX,
numbers=left,
stepnumber=1,
numbersep=5pt,
numberstyle=\tiny,
breaklines=true,
breakautoindent=true,
postbreak=\space,
tabsize=2,
basicstyle=\ttfamily\footnotesize,
showspaces=false,
showstringspaces=false,
extendedchars=true,
backgroundcolor=\color{lbcolor}}
%
% ---------------------------------------------------------------------------
%

%
% Neue Umgebungen
\newenvironment{ListChanges}%
{\begin{list}{$\diamondsuit$}{}}%
{\end{list}}

% aller Bilder werden im Unterverzeichnis figures gesucht:
\graphicspath{{bilder/}}

%
% Literaturverzeichnis-Stil
\bibliographystyle{plain}

% Anführungsstriche mithilfe von \textss{-anzufuehrendes-}
\newcommand{\textss}[1]{"`#1"'}

% Strukturiertiefe bis subsubsection{} möglich
\setcounter{secnumdepth}{5}


% Dargestellte Strukturiertiefe im Inhaltsverzeichnis
\setcounter{tocdepth}{5}

Xenara
03-01-2011, 14:23
Wie vermutet, du lädst listings zweimal mit verschiedenen Optionen.
Wieso kompilierst du nicht erstmal den Code in einem eigenen Dokument?

pdftex als Option ist übrigens unnötig und fehleranfällig.

Kris
03-01-2011, 14:37
Ich kenne mich leider nicht so mit den packages und mit den Optionen aus. Habe von einer Freundin den Header sowie die restlichen Einstellungen bekommen (als Vorlage). Habe nur ab und zu mal ein package hinzugefügt.

Xenara
03-01-2011, 14:53
Vorlagen sind in LaTeX problematisch, vor allem, wenn man 1. nicht weiss, wozu was gut ist, und 2. etwas ändern will. Meistens ist es einfacher und lehrreicher, sich selbst für das jeweilige Dokument einen Header zu basteln und nur das aufzunehmen, was man braucht.

Läuft es denn jetzt bei dir?

Kris
03-01-2011, 15:10
Leider nicht. Habe auch schon versucht meine Freundin zu erreichen, da sie auch schon mal mit dem Befehl \lstlisting gearbeitet hat, aber leider geht sie nicht ans Handy.

Xenara
03-01-2011, 15:30
Du musst an Probleme strukturiert herangehen, dazu gehört auch, die Informationen zu liefern, die Helfer brauchen.

Wenn du meinen Code aus Posting #2 in ein leeres, neues Dokument kopierst und dieses kompilierst, funktioniert es?

Hast du in deinem Hauptdokument das doppelte \usepackage{listings} entfernt?

Wenn es dann immernoch nicht tut, musst du wohl oder übel auf Fehlersuche gehen. Da ich das Prozedere schonmal getippt habe, hier der Link:
http://www.mrunix.de/forums/showthread.php?t=66921

Darin ist beschrieben, wie du vorgehen musst, um zu sehen, an was es liegt.

Kris
03-01-2011, 15:34
Ja das doppelte \usepackage{listings} habe ich entfernt und es kommen immer noch die gleiche(n) Fehlermeldung(en). Danke für deine Hilfe!!! Ich werde ich mal auf Fehler suche begeben.

LG Kris

nixversteh
04-01-2011, 09:25
Ja das doppelte
\usepackage{listings} habe ich entfernt und es kommen immer noch die gleiche(n) Fehlermeldung(en). Danke für deine Hilfe!!! Ich werde ich mal auf Fehler suche begeben.

LG Kris

Hallo Kris,

vielleicht stellst du mal einen kleinen Teil deines Dokumentes mit ein, ich meine, etwas wie dies hier:

\begin{document}
\chapter{Test}
\end{document}
(von mir eingefügt)

[...] nachdem ich das doppelte
\usepackage{listings} und die Option pdftex sowie das doppelte
\usepackage{color} entfernt habe, läuft es bei mir fehlerfrei [...] aber auch sinnfrei ;-)

Viel Erfolg und ein gutes neues Jahr

Gruß

Martin

EDIT: schau mal diesen Code an
\documentclass[%
paper=a4, % A4 Papier
twoside=false, % Einseitig
bibliography=totoc, % Literaturverzeichnis einfügen bibtotocnumbered: nummeriert
listof=totoc, % Verzeichnisse einbinden in toc
index=totoc, % Index ins Verzeichnis einfügen
parskip=half, % Europäischer Satz mit abstand zwischen Absätzen% chapterprefix,% Kapitel anschreiben als Kapitel
headsepline, % Linie nach Kopfzeile
%footsepline, % Linie vor Fusszeile
numbers=noenddot, % Nummern ohne abschließenden Punkt
fontsize=12pt % Grössere Schrift, besser lesbar am bildschrim
]{scrbook}
% Paket für Übersetzungen ins Deutsche
\usepackage[ngerman]{babel}% wird french ben\"otigt?
%Paket damit bilder in section bleiben
\usepackage[section]{placeins}
% Pakete um Latin1 Zeichnensätze verwenden zu können und die dazu
% passenden Schriften.
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
%Tabelle über mehrer Seiten
\usepackage{longtable}
\usepackage{booktabs}
% Paket für Quotes
\usepackage[babel,french=guillemets,german=swiss]{csquotes}
% Paket zum Erweitern der Tabelleneigenschaften
\usepackage{array}
\usepackage{cite}
% Paket für schönere Tabellen
\usepackage{booktabs}
% Paket um Grafiken einbetten zu können
\usepackage{graphicx}
\usepackage{caption}
\usepackage{subfigure}
\usepackage{float}
\usepackage{scrhack}% Entfernt die Warnung:Class scrbook Warning: Usage of deprecated \float@addtolists! (scrbook) You should use the features of package `tocbasic' (scrbook) instead of \float@addtolists. (scrbook) Definition of \float@addtolists may be removed from (scrbook) KOMA-Script soon, so it should not be used on input line 2.
% Spezielle Schrift im Koma-Script setzen.
\setkomafont{sectioning}{\normalfont\bfseries}
\setkomafont{captionlabel}{\normalfont\bfseries}
\setkomafont{pagehead}{\normalfont\bfseries} % Kopfzeilenschrift
\setkomafont{descriptionlabel}{\normalfont\bfserie s}
% Zeilenumbruch bei Bildbeschreibungen.
\setcapindent{0.5em}
%Paket für farbigen Hintergrund
\usepackage{color}
\usepackage{colortbl}
% Define user colors using the RGB model
\definecolor{dunkelgrau}{rgb}{0.8,0.8,0.8}
\definecolor{hellgrau}{rgb}{0.95,0.95,0.95}
% Kopf und Fußzeilen
\usepackage{scrpage2}
\pagestyle{scrheadings}
% Inhalt bis Section rechts und Chapter links
\automark[section]{chapter}
% Mitte: leer
\chead{}
\usepackage[multiple,bottom]{footmisc}
% mathematische symbole aus dem AMS Paket.
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{bbm}
%Quellcode eingeben
\usepackage{listings}
\usepackage{blindtext}
% Type 1 Fonts für bessere darstellung in PDF verwenden.
\usepackage{courier} % Courier als \ttdefault
% Paket um Textteile drehen zu können
\usepackage{rotating}
% Paket für Links innerhalb des PDF Dokuments
\definecolor{LinkColor}{rgb}{0,0,0.5}
\usepackage[%
pdftitle={Titel},% Titel der Diplomarbeit
pdfauthor={Autor},% Autor(en)
pdfcreator={LaTeX, LaTeX with hyperref and KOMA-Script},% Genutzte Programme
pdfsubject={Betreff}, % Betreff
pdfkeywords={Keywords}]{hyperref} % Keywords halt :-)
\hypersetup{colorlinks=true,% Definition der Links im PDF File
linkcolor=LinkColor,%
citecolor=LinkColor,%
filecolor=LinkColor,%
menucolor=LinkColor,%
%pagecolor=LinkColor,%
urlcolor=LinkColor}

\definecolor{lbcolor}{rgb}{0.85,0.85,0.85}
\lstset{language=[LaTeX]TeX,
numbers=left,
stepnumber=1,
numbersep=5pt,
numberstyle=\tiny,
breaklines=true,
breakautoindent=true,
postbreak=\space,
tabsize=2,
basicstyle=\ttfamily\footnotesize,
showspaces=false,
showstringspaces=false,
extendedchars=true,
backgroundcolor=\color{lbcolor}}
% Neue Umgebungen
\newenvironment{ListChanges}%
{\begin{list}{$\diamondsuit$}{}}%
{\end{list}}
% aller Bilder werden im Unterverzeichnis figures gesucht:
\graphicspath{{bilder/}}
% Literaturverzeichnis-Stil
\bibliographystyle{plain}
% Anführungsstriche mithilfe von \textss{-anzufuehrendes-}
\newcommand{\textss}[1]{"`#1"'}
% Strukturiertiefe bis subsubsection{} möglich
\setcounter{secnumdepth}{5}
% Dargestellte Strukturiertiefe im Inhaltsverzeichnis
\setcounter{tocdepth}{5}
\begin{document}
\chapter{Test}
\end{document}


läuft auf Kubuntu 10.10, Texlive 2010

nixversteh
05-01-2011, 08:36
Hallo Kris,

habe mal etwas gewerkelt, hoffe, du kannst es gebrauchen:


\documentclass[%
paper=a4, % A4 Papier
twoside=false, % Einseitig
bibliography=totoc, % Literaturverzeichnis einfügen bibtotocnumbered: nummeriert
listof=totoc, % Verzeichnisse einbinden in toc
index=totoc, % Index ins Verzeichnis einfügen
parskip=half, % Europäischer Satz mit abstand zwischen Absätzen% chapterprefix,% Kapitel anschreiben als Kapitel
headsepline, % Linie nach Kopfzeile
%footsepline, % Linie vor Fusszeile
numbers=noenddot, % Nummern ohne abschließenden Punkt
fontsize=12pt % Grössere Schrift, besser lesbar am bildschrim
]{scrbook}
% Paket für Übersetzungen ins Deutsche
\usepackage[ngerman]{babel}% wird french ben\"otigt?
%Paket damit bilder in section bleiben
\usepackage[section]{placeins}
% Pakete um Latin1 Zeichnensätze verwenden zu können und die dazu
% passenden Schriften.
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
%Tabelle über mehrer Seiten
\usepackage{longtable}
\usepackage{booktabs}
% Paket für Quotes
\usepackage[babel,french=guillemets,german=swiss]{csquotes}
% Paket zum Erweitern der Tabelleneigenschaften
\usepackage{array}
\usepackage{cite}
% Paket für schönere Tabellen
\usepackage{booktabs}
% Paket um Grafiken einbetten zu können
\usepackage{graphicx}
\usepackage{caption}
\usepackage{subfigure}
\usepackage{float}
\usepackage{scrhack}% Entfernt die Warnung:Class scrbook Warning: Usage of deprecated \float@addtolists! (scrbook) You should use the features of package `tocbasic' (scrbook) instead of \float@addtolists. (scrbook) Definition of \float@addtolists may be removed from (scrbook) KOMA-Script soon, so it should not be used on input line 2.
% Spezielle Schrift im Koma-Script setzen.
\setkomafont{sectioning}{\normalfont\bfseries}
\setkomafont{captionlabel}{\normalfont\bfseries}
\setkomafont{pagehead}{\normalfont\bfseries} % Kopfzeilenschrift
\setkomafont{descriptionlabel}{\normalfont\bfserie s}
% Zeilenumbruch bei Bildbeschreibungen.
\setcapindent{0.5em}
%Paket für farbigen Hintergrund
\usepackage{color}
\usepackage{colortbl}
% Define user colors using the RGB model
\definecolor{dunkelgrau}{rgb}{0.8,0.8,0.8}
\definecolor{hellgrau}{rgb}{0.95,0.95,0.95}
% Kopf und Fußzeilen
\usepackage{scrpage2}
\pagestyle{scrheadings}
% Inhalt bis Section rechts und Chapter links
\automark[section]{chapter}
% Mitte: leer
\chead{}
\usepackage[multiple,bottom]{footmisc}
% mathematische symbole aus dem AMS Paket.
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{bbm}
%Quellcode eingeben
\usepackage{listings,relsize}
\lstloadlanguages{R}
\newcommand{\lil}[1]{\lstinline|#1|}

% Type 1 Fonts für bessere darstellung in PDF verwenden.
\usepackage{courier} % Courier als \ttdefault
% Paket um Textteile drehen zu können
\usepackage{rotating}
% Paket für Links innerhalb des PDF Dokuments
\definecolor{LinkColor}{rgb}{0,0,0.5}
\usepackage[%
pdftitle={Titel},% Titel der Diplomarbeit
pdfauthor={Autor},% Autor(en)
pdfcreator={LaTeX, LaTeX with hyperref and KOMA-Script},% Genutzte Programme
pdfsubject={Betreff}, % Betreff
pdfkeywords={Keywords}]{hyperref} % Keywords halt :-)

\hypersetup{colorlinks=true,% Definition der Links im PDF File
linkcolor=LinkColor,%
citecolor=LinkColor,%
filecolor=LinkColor,%
menucolor=LinkColor,%
%pagecolor=LinkColor,%
urlcolor=LinkColor}

\definecolor{lbcolor}{rgb}{0.85,0.85,0.85}
\setcounter{tocdepth}{5}
\begin{document}
\lstset{language=R,basicstyle=\smaller,commentstyl e=\rmfamily\smaller,
showstringspaces=false,%
xleftmargin=4ex,literate={<-}{{$\leftarrow$}}1 {~}{{$\sim$}}1}
\lstset{escapeinside={(*}{*)}} % for (*\ref{ }*) inside lstlistings (S code)
\begin{lstlisting}
a <- b # this is a test line
if(i==3) { # another line, for y^2
y <- 3^3
z <- 'this string'
qqcat <- y ~ pol(x,2)
} else y <- 4
\end{lstlisting}

\end{document}
\chapter{Test}
\end{document}

Viel Erfolg

Gruß

Martin

nixversteh
05-01-2011, 09:40
Hallo Kris,

habe noch eine weitere Möglichkeit gefunden, schau mal:


%%
%% This is file `mcode.sty'
%%
%% It is supposed to help you easily include MATLAB source code
%% into LaTeX document, but have it nicely highlighted, using
%% the great listings package.
%%
%% For a demo document, please see
%% http://www.knorn.org/misc_files/mcode_demo.zip
%%
%% PLEASE NOTE that this package does nothing but save you from
%% figuring out some configurations in setting up the listings
%% package. ALL the work is done by that package! Thus, refer
%% your questions to the listings package documentation.
%%
%% Usage: You have three ways of including your MATLAB code. As
%% environment, as inline object and directly from an external
%% file.
%%
%% 1) Environment:
%%
%% \begin{lstlisting}
%% YOUR CODE HERE
%% \end{lstlisting}
%%
%%
%% 2) Inline object:
%%
%% Bla bla \mcode{CODEFRAGMENT} bla bla.
%%
%%
%% 3) Include external file (in environment form)
%%
%% \lstinputlisting{YOUR-FILE.m}
%%
%%
%% For your convenience this package has the following options:
%%
%% - bw if you intend to print the document (highlighting done
%% via text formatting (bold, italic) and shades of gray)
%%
%% - numbered if you want line numbers
%%
%% - framed if you want a frame around the source code blocks
%%
%% - final if you have ``gloablly'' set the draft option, the
%% listings package will not output the code at all. to
%% force it to do so anyway, load this package with the
%% final option (passes the ``final'' on to listings).
%%
%% For example, you may use \usepackage[numbered,framed]{mcode}
%% in your document preamble.
%%
%% Note: Inside code blocks you can escape to LaTeX text mode
%% using §...§. For ex. §text and some math: $x^2$§, which is
%% especially useful in comments for putting nicely typeset
%% equations etc. To get the same colour/style as in the rest
%% of the comment use \mcommentfont, i.e. §\mcommentfont $x^2$§
%%
%% A nice feature of the listings package is that you can re-
%% place certain strings by LaTeX strings; this is used for
%% some relation symbols, see below...
%%
%% To change the font used, edit the first line in the "custo-
%% mise below" section. And feel free to edit other things as
%% well. Refer to the documentation of the listings package to
%% see what else you could do. If an extra small font is re-
%% quired, use {\fontfamily{pcr}\fontsize{3}{4.6}\selectfont}
%% in the definition of \lstbasicfont.
%%
%% Author: Florian Knorn | floz@gmx.de | www.florian-knorn.com
%%
%% Version history:
%% 1.9 -- Fixed minus being replaced by math minus
%% 1.8 -- Fixed typo in documentation regarding §...§
%% 1.7 -- Added MATLAB block comment syntax %{ ...... %}
%% 1.6 -- Added some infos, dealing with keyword ``end''
%% 1.5 -- Tweaked check to see wether textcomp is loaded
%% 1.4 -- Fixed misconfig (mathescape now set to false)
%% 1.3 -- Purely cosmetic (tabs replaced by spaces)
%% 1.2 -- Added \lstset{showstringspaces=false}
%% 1.1 -- Added \mcode command and [final] option
%% 1.0 -- Release


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%
% D O N ' T T O U C H T H I S %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%
\def\fileversion{1.9}
\def\filedate{2010/05/04}

\typeout{-- Package: `mcode' \fileversion\space <\filedate> --}
\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{mcode}[\filedate\space\fileversion]

% for bw-option
\newif\ifbw
\DeclareOption{bw}{\bwtrue}

% numbered option
\newif\ifnumbered
\DeclareOption{numbered}{\numberedtrue}

% final option
\newif\iffinal
\DeclareOption{final}{\finaltrue}

% for framed option
\newif\ifframed
\DeclareOption{framed}{\framedtrue}

\DeclareOption*{% default
\PackageWarning{mcode}{Unknown option `\CurrentOption' !}%
}
\ProcessOptions

\ifbw\typeout{ - settings optimized for printing (bw formating)}
\else\typeout{ - settings optimized for display (colour formating)}\fi
\ifnumbered\typeout{ - line numbering enabled}\else\fi
\ifframed\typeout{ - framed listings}\else\fi

% This command allows you to typeset syntax highlighted Matlab
% code ``inline''. The font size \small seems to look best...
\newcommand{\mcode}[1]{\lstinline[basicstyle=\lstbasicfont\small]|#1|}

% check if color command exists
\ifx\color\undefined%
\RequirePackage{xcolor}%
\fi

% check if listings has been loaded
\ifx\lstset\undefined%
\iffinal
\RequirePackage[final]{listings}
\else
\RequirePackage{listings}
\fi
\fi

% Check if textcomp has been loaded (this package is needed for
% upright quotes '' (instead of typographic ones `´)...
\ifx\textquotesingle\undefined%
\RequirePackage{textcomp}%
\fi

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%
% C U S T O M I S E B E L O W %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%

% define the wanted font for all highlightings here
\def\lstbasicfont{\fontfamily{pcr}\selectfont\foot notesize}

% now let's define our own version of matlab highlighting
\lstdefinelanguage{matlabfloz}{%
alsoletter={...},%
morekeywords={% % keywords
break,case,catch,continue,elseif,else,end,for,func tion,global,%
if,otherwise,persistent,return,switch,try,while,.. .},%
comment=[l]\%,% % comments
morecomment=[l]...,% % comments
morecomment=[s]{\%\{}{\%\}}, % block comments
morestring=[m]',% % strings
}[keywords,comments,strings]%

% define the colours

\ifbw % use font formating and gray 'colors'
\def\mcommentfont{\color[gray]{.75}\itshape} %comments light gray and italic
\lstset{language=matlabfloz, % use our version of highlighting
keywordstyle=\bfseries, % keywords in bold
commentstyle=\mcommentfont, % comments
stringstyle=\color[gray]{0.5} % strings darker gray
}
\else% notbw => use colors : )
\def\mcommentfont{\color[rgb]{.133,.545,.133}} %comments in green
\lstset{language=matlabfloz, % use our version of highlighting
keywordstyle=\color[rgb]{0,0,1}, % keywords in blue
commentstyle=\mcommentfont, % comments
stringstyle=\color[rgb]{.627,.126,.941} % strings in purple
}
\fi%bw

\lstset{%
basicstyle={\lstbasicfont}, % set font
showstringspaces=false, % do not emphasize spaces in strings
tabsize=4, % number of spaces of a TAB
mathescape=false,escapechar=§, % escape to latex with §...§
upquote=true, % upright quotes
aboveskip={1.5\baselineskip}, % a bit of space above listings
columns=fixed, % nice spacing
%
% the following is for replacing some matlab relations like >= or ~=
% by the corresponding LaTeX symbols, which are much easier to read ...
literate=%
{~}{{$\neg$}}1 % \neg
{-}{{-}}1 % prevent ``-'' being replaced by math minus
{<=}{{\tiny$\leq$}}1 % \leq
{>=}{{\tiny$\geq$}}1 % \geq
{~=}{{\tiny$\neq$}}1 % \neq
{delta}{{\tiny$\Delta$}}1% \Delta
{iend}{{\fontfamily{pcr}\selectfont end}}3% end when indexing matrix elements
}

\ifnumbered% numbered option
\lstset{%
numbersep=3mm, numbers=left, numberstyle=\tiny, % number style
}
\fi

\ifframed% framed option
\lstset{%
frame=single, % frame
}
\ifnumbered%
\lstset{%
framexleftmargin=6mm, xleftmargin=6mm % tweak margins
}
\fi
\fi

\endinput
%% End of file `mcode.sty'.

erstelle eine Datei namens *mcode.sty* und lege sie in deinen Ordner, indem du auch die Texdateien hast.

Nun die Hauptdatei:

\documentclass{article}
\usepackage[framed,numbered]{mcode}
\setlength{\parindent}{0pt}
\setlength{\parskip}{18pt}

% .................................................. ...................................
\begin{document}
\begin{lstlisting}
a <- b # this is a test line
if(i==3) { # another line, for y^2
y <- 3^3
z <- 'this string'
qqcat <- y ~ pol(x,2)
} else y <- 4
\end{lstlisting}

Quelle: Florian Knorn

\end{document}

Viel Erfolg

Gruß

Martin