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.
Use
Listings
package.Simple configuration for LaTeX header (before
\begin{document}
):You can change default language in the middle of document with
\lstset{language=Java}
.Example of usage in the document:
Here's the result:
Here is how to add inline code:
You can add inline code with
{\tt code }
or\texttt{ code }
. If you want to format the inline code, then it would be best to make your own commandAlso, note that code blocks can be loaded from other files with
breaklines
isn't required, but I find it useful. Be aware that you'll have to specify\usepackage{
listings}
for this one.You could also use the verbatim environment
Since it wasn't yet mentioned here, it may be worth to add one more option, package
spverbatim
(no syntax highlighting):Also, if syntax highlighting is not required, package
alltt
:Use Minted.
It's a package that facilitates expressive syntax highlighting in LaTeX using the powerful Pygments library. The package also provides options to customize the highlighted source code output using fancyvrb.
It's much more evolved and customizable than any other package!
Specialized packages such as
minted
, which relies on Pygments to do the formatting, offer various advantages over thelistings
package. To quote from theminted
manual,