You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 16 Next »


There are several methods for importing code to your project. We will here provide you with some of our different methods and styles, hopefully enabeling you to find or create the one you enjoy the most. As always, keep in mind that there are many other good tutorials online, covering both the methods we explain here, but also other methods. To improve the most, we highly recommend you to locate these!


The example code used on this page is written in C++, but the difference is negligible for other languages.

Page content

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.

The default input expression is \inputminted [ options ]{ language }{ filename } or

// Method 1 - Assumed that the code included in 'isPrime.cpp' is the same as in Method 2 
\inputminted{C++}{isPrime.cpp} 


// Method 2 
\begin{minted}{C++} 
#include <iostream>

bool isPrime() { 
	int number; 
	std::string question = "Please enter a number: "; 

	std::cout << question << std::endl; 
	std::cin >> number; 

	for (int i = 2; i < number; i++) { 
		if (number % i == 0) // If prime number 
			return false; 
	} 
	return true; 
} 
\end{minted}

Minted may also be applied to a single word or phrase in the middle of a text.

The default expression for mintinline is \mintinline[ options ]{ language }{ code }

The line \mintinline{C++}{#include iostream} is often found at the top of a file.

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}

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}





  • No labels