Minted
Minted is a package that allows formatting and highlighting source code in LaTeX. Some minted documentation may be found at Overleaf or through the original package documentation. Most of the information we provide will be obtained from the package documentation.
Remember to include the Minted package: \usepackage{minted}
We will only use the option of including code through external files, but you may also include code directly. An example is shown below.
Minted may also be applied to a single word or phrase in the middle of a text.
Line breaks
To automatically break lines that are too long, include the option breaklines.
\inputminted[breaklines]{C++}{Breaklines.cpp} \inputminted{C++}{Breaklines.cpp}
Line numbering
To add line numbering to your code, include the option linenos.
Customized numbering
Using the option firstnumber we can specify where to start our numbering. This can for example be used to continue the numbering from where you last stopped.
\inputminted[linenos]{C++}{isPrime.cpp} \inputminted[linenos, firstnumber=last]{C++}{Linenumber.cpp}
Macro options
Using the commands \setminted[ language ]{ key=value,... } and \setmintedinline[ language ]{ key=value,... }, you may define general options for the entire document or for a specific language. However, individual options will still override the options set for the document or a language. The command is preferably included outside the document (in the setup), but may also be included inside.
\setminted[C++]{breaklines=true, mathescape=true, linenos=true} \inputminted{C++}{Math.cpp}
Mathematical symbols
Using the option mathescape, Minted has given us the possibility to include mathematical symbols within our code.
\inputminted[mathescape]{C++}{Math.cpp} --- Math.cpp --- // Calculate factorial of positive number // The factorial of 'n' is defined as $n! = \prod_{i = 1}^n i$ int factorial(int n) { int sum = 1; while (n != 1) { sum = sum * n--; } return sum; }
Styles
Minted offers a number of different styles. To change the style, include the command \usemintedstyle( style ) when including the package Minted. Different styles may be found at the Overleaf documentation linked above.
\usemintedstyle{borland} \inputminted{C++}{isPrime.cpp} \usemintedstyle{rrt} \inputminted{C++}{isPrime.cpp}