# LaTeX/Source Code Listings

* LaTeX
* Getting Started
* Introduction
* Installation
* Installing Extra Packages
* Basics
* How to get help
* Common Elements
* Document Structure
* Text Formatting
* Paragraph Formatting
* Colors
* Fonts
* List Structures
* Special Characters
* Internationalization
* Rotations
* Tables
* Title creation
* Page Layout
* Customizing Page Headers and Footers‎
* Importing Graphics
* Floats, Figures and Captions
* Footnotes and Margin Notes
* Hyperlinks
* Labels and Cross-referencing
* Initials
* Mechanics
* Errors and Warnings
* Lengths
* Counters
* Boxes
* Rules and Struts
* Technical Text
* Mathematics
* Advanced Mathematics
* Theorems
* Chemical Graphics
* Algorithms
* Source Code Listings
* Linguistics
* Special Pages
* Indexing
* Glossary
* Bibliography Management
* More Bibliographies
* Special Documents
* Scientific Reports (Bachelor Report, Master Thesis, Dissertation)
* Letters
* Presentations
* Teacher's Corner
* Curriculum Vitae
* Academic Journals (MLA, APA, etc.)
* Creating Graphics
* Introducing Procedural Graphics
* MetaPost
* Picture
* PGF/TikZ
* PSTricks
* Xy-pic
* Creating 3D graphics
* Programming
* Macros
* Plain TeX
* Creating Packages
* Creating Package Documentation
* Themes
* Miscellaneous
* Modular Documents
* Collaborative Writing of LaTeX Documents
* Export To Other Formats
* Help and Recommendations
* FAQ
* Tips and Tricks
* Appendices
* Authors
* Links
* Package Reference
* Sample LaTeX documents
* Index
* Command Glossary
There are many packages providing code listings and highlighting, below are most popular:
* listings
** very useful and functionality rich,
* minted
** minted is an alternative to listings which has become popular. It uses the external Python library Pygments for code highlighting, which as of February 2021 boasts over 537 supported languages and text formats. As the package relies on external Python code, the setup require a few more steps than a usual LaTeX package, so please have a look at their GitHub repo and their manual.

## Using the listings package

Using the package listings you can add non-formatted text as you would do with \begin{verbatim} but its main aim is to include the source code of any programming language within your document. If you wish to include pseudocode or algorithms, you may find Algorithms and Pseudocode useful also.
To use the package, you need:
* \usepackage{listings}
The listings package supports highlighting of all the most common languages and it is highly customizable. If you just want to write code within your document the package provides the lstlisting environment:
* \begin{lstlisting}
* Put your code here.
* \end{lstlisting}
Another possibility, that is very useful if you created a program on several files and you are still editing it, is to import the code from the source itself. This way, if you modify the source, you just have to recompile the LaTeX code and your document will be updated. The command is:
* \lstinputlisting{source_filename.py}
in the example there is a Python source, but it doesn't matter: you can include any file but you have to write the full file name. It will be considered plain text and it will be highlighted according to your settings, that means it doesn't recognize the programming language by itself. You can specify the language while including the file with the following command:
* \lstinputlisting[language=Python]{source_filename.py}
You can also specify a scope for the file.
* \lstinputlisting[language=Python, firstline=37, lastline=45]{source_filename.py}
Or
* \lstinputlisting[language=Python, linerange={37-45,48-50}]{source_filename.py}
This comes in handy if you are sure that the file will not change (at least before the specified lines). You may also omit the firstline or lastline parameter: it means everything up to or starting from this point.
This is a basic example for some Pascal code:

### Supported languages

It supports the following programming languages:
ABAP$^{2,4}$, ACSL, Ada$^4$, Algol$^4$, Ant, Assembler$^{2,4}$, Awk$^4$, bash, Basic$^{2,4}$, C#$^5$, C++$^4$, C$^4$, Caml$^4$, Clean, Cobol$^4$, Comal, csh, Delphi, Eiffel, Elan, erlang, Euphoria, Fortran$^4$, GCL, Go (golang), Gnuplot, Haskell, HTML, IDL$^4$, inform, Java$^4$, JVMIS, ksh, Lisp$^4$, Logo, Lua$^2$, make$^4$, Mathematica$^{1,4}$, Matlab, Mercury, MetaPost, Miranda, Mizar, ML, Modelica$^3$, Modula-2, MuPAD, NASTRAN, Oberon-2, Objective C$^5$ , OCL$^4$, Octave, Oz, Pascal$^4$, Perl, PHP, PL/I, Plasm, POV, Prolog, Promela, Python, R, Reduce, Rexx, RSL, Ruby, S$^4$, SAS, Scilab, sh, SHELXL, Simula$^4$, SQL, tcl$^4$, TeX$^4$, VBScript, Verilog, VHDL$^4$, VRML$^4$, XML, XSLT.
For some of them, several dialects are supported. For more information, refer to the documentation that comes with the package, it should be within your distribution under the name listings-*.dvi.

#### Notes

* It supports Mathematica code only if you are typing in plain text format. You can't include *.NB files \lstinputlisting{...} as you could with any other programming language, but Mathematica can export in a pretty-formatted LaTeX source.
* Specification of the dialect is mandatory for these languages (e.g. language={[x86masm]Assembler}).
* Modelica is supported via the dtsyntax package available here.
* For these languages, multiple dialects are supported. C, for example, has ANSI, Handel, Objective and Sharp. See p. 12 of the listings manual for an overview.
* Defined as a dialect of another language

### Settings

You can modify several parameters that will affect how the code is shown. You can put the following code anywhere in the document (it doesn't matter whether before or after \begin{document}), change it according to your needs. The meaning is explained next to any line.
It would be helpful to categorize the properties based upon their functions.
| | Keyword | Explanation |
| General ||||
| | language=Python, | The programming language in the listing, e.g., Python. |
| | title=\lstname | If a file is inputted using command \lstinputlisting{FNAME.PY} then by default title is file name, i.e. FNAME.PY |
| | captionpos=b, | The caption-position for the listing is set to bottom. |
| | backgroundcolor=\color{white}, | Background color; you must add \usepackage{color} or \usepackage{xcolor}; should come as last argument |
| | basicstyle=\footnotesize, | The size of the fonts that are used for the code |
| | breaklines=true, | Sets automatic line breaking |
| Tabs and Space settings ||||
| | breakatwhitespace=false, | Sets if automatic breaks should only happen at whitespace |
| | showspaces=false, | show spaces everywhere adding particular underscores; it overrides 'showstringspaces' |
| | showtabs=false, | show tabs within strings adding particular underscores |
| | keepspaces=true, | keeps spaces in text, useful for keeping indentation of code (possibly needs columns=flexible) |
| | tabsize=2, | Sets default tabsize to 2 spaces |
| Frame setting ||||
| | frame=single, | Adds a frame around the code |
| | rulecolor=\color{black}, | if not set, the frame-color may be changed on line-breaks within not-black text (e.g. comments (green here)) |
| Numbering code line ||||
| | firstnumber=1, | The counting for line number in each listing will start with this value. |
| | stepnumber=2, | Interval at which the numbers should be printed. |
| | numbers=left, | Place the numbering on left side of the code |
| | numberstyle=\tiny\color{mygray}, | Style for the line-numbers |
| | numbersep=10pt | Space between the code and line numbering. |
| Keywords ||||
| | otherkeywords={++, --} | |
| | morekeywords={self, __init__} | |
| | keywordstyle=\color{blue}, | Keyword style |
| | deletekeywords={...}, | If you want to delete keywords from the given language |
| Strings ||||
| | stringstyle=\color{mymauve}, | String literal style |
| | showstringspaces=false, | Underline spaces within strings only |
| Comments ||||
| | commentstyle=\color{mygreen}, | The comments in the code shall be shown in this color/formatting |
| Emphasize ||||
| | emph={__init__,self,}, | To emphasize on these extra words |
| | emphstyle=\color{blue}, | color, style for the words to be emphasize |
| Escape sequence ||||
| | escapeinside={(*}{*)}, | If you want to execute the latex commands within listing environment. The latex code shall be wrapped as following. (* LATEX CODE *)| Here (* and *) are escape sequences marking the beginning and end of the latex code. You may define them as per your convenience as shown in the left coloumn. |
| Special ||||
| | extendedchars=true, | It lets you use non-ASCII characters; for 8-bits encodings only, does not work with UTF-8 |
| | autogobble=true, | |
| | upquote=true, | Forces the quote symbol to be vertical. |

#### escapeinside

The escapeinside line needs an explanation. The option escapeinside={A}{B} will define delimiters for escaping into LaTeX code, i.e. all the code between the string "A" and "B" will be parsed as LaTeX over the current listings style. In the example above, the comments for Octave start with %, and they are going to be printed in the document unless they start with %*, in which case they are read as LaTeX (with all LaTeX commands fulfilled) until they're closed with another *). If you add the above paragraph, the following can be used to alter the settings within the code:
* \lstset{language=C,caption={Descriptive Caption Text},label=DescriptiveLabel}
There are many more options, check the official documentation.

### Style definition

The package lets you define styles, i.e. profiles specifying a set of settings.
Example
In our example, we only set two options globally: the default style and the escape character. Usage:
The C part will print as

### Automating file inclusion

If you have a bunch of source files you want to include, you may find yourself doing the same thing over and over again. This is where macros show their real power.
In this example, we create one command to ease source code inclusion. We set the default style to be customc. All listings will have their name as caption: we do not have to write the file name twice thanks to the macro. Finally we list all listings with this command from the listings package.
See Macros for more details.

### Encoding issue

By default, listings does not support multi-byte encoding for source code. The extendedchar option only works for 8-bits encodings such as latin1.
To handle UTF-8, you should tell listings how to interpret the special characters by defining them like so
The above table will cover most characters in latin languages. For a more detailed explanation of the usage of the literate option check section 5.4 in the Listings Documentation.
Another possibility is to replace \usepackage{listings} (in the preamble) with \usepackage{listingsutf8}, but this will only work for \lstinputlisting{...}.

### Customizing captions

You can have fancy captions (or titles) for your listings using the caption package. Here is an example for listings.

## References

A lot more detailed information can be found in a PDF by Carsten Heinz and Brooks Moses.
Details and documentation about the Listings package can be found at its CTAN website.