Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting code in this LaTeX document with indentation

Tags:

latex

How do I insert code into a LaTeX document? Is there something like:

\begin{code}## Heading ## ... \end{code} 

The only thing that I really need is indentation and a fixed width font. Syntax highlighting could be nice although it is definitely not required.

like image 512
sixtyfootersdude Avatar asked Jul 04 '10 15:07

sixtyfootersdude


People also ask

How to insert code in a LaTeX document?

Creating Source Code The command \usepackage[margin=2.5cm]{geometry} affects the printed source code's layout. The command \usepackage{listings} informs LaTeX to include the source code in the document. The command \usepackage{hyperref} is needed for adding links in the text.

How to display code in LaTeX?

The default tool to display code in LaTeX is verbatim , which generates an output in monospaced font. Just as in the example at the introduction, all text is printed keeping line breaks and white spaces. There's a starred version of this command whose output is slightly different.

How to Set paragraph indent in LaTeX?

To indent subsequent lines of a paragraph, use the TeX command \hangindent . (While the default behaviour is to apply the hanging indent after the first line, this may be changed with the \hangafter command.) An example follows. \hangindent=0.7cm This paragraph has an extra indentation at the left.

How do you put an appendix code in LaTeX?

Referencing an appendix in LaTeX is as easy as any other chapter or object. You just have to put an anchor to it using \label{name} and then you can reference the appendix using \ref{name} .


1 Answers

Use listings package.

Simple configuration for LaTeX header (before \begin{document}):

\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{frame=tb,   language=Java,   aboveskip=3mm,   belowskip=3mm,   showstringspaces=false,   columns=flexible,   basicstyle={\small\ttfamily},   numbers=none,   numberstyle=\tiny\color{gray},   keywordstyle=\color{blue},   commentstyle=\color{dkgreen},   stringstyle=\color{mauve},   breaklines=true,   breakatwhitespace=true,   tabsize=3 } 

You can change default language in the middle of document with \lstset{language=Java}.

Example of usage in the document:

\begin{lstlisting} // Hello.java import javax.swing.JApplet; import java.awt.Graphics;  public class Hello extends JApplet {     public void paintComponent(Graphics g) {         g.drawString("Hello, world!", 65, 95);     }     } \end{lstlisting} 

Here's the result:

Example image

like image 116
Cloudanger Avatar answered Sep 26 '22 10:09

Cloudanger