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.
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.
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.
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.
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} .
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With