# Format code correctly in LaTeX

I am pasting some code I have developed for a project from Visual Studio 2019 to LaTeX for a report, however upon pasting the horizontal spacing is far too large and runs off the page. Currently I am using the lstlisting environment:

The LaTeX code is as follows:

\begin{lstlisting}
for (int i = 0; i < numBuses; i++) {
for (int h = 0; h < maxRoute; h++) {
for (int j = 0; j < numStops; j++) {
for (int k = 0; k < numStops; k++) {
if (j == k) {
GRBLinExpr lhs = 0;
lhs += X[i][h][j][k];
}
}
}
}
}
\end{lstlisting}


While i can edit this problem manually the code is hundreds of lines thus this seems impractical. Notice that the spacing become far too large. Could anyone offer any advice on how to fix this problem. Many thanks in advance =)

• You must be using TABs to indent your code. listings provides an option to set tabsize. Try tabsize = 2 as part of your options (you can also set tab to something else). – Werner Sep 9 '19 at 18:22
• Many thanks for all the help, I came across this which really helped as well: tex.stackexchange.com/questions/81834/… – sam Sep 9 '19 at 18:50

As @Werner mentioned in his comment, you could use tabsize to adjust the indentation if you are using tabs in your source code.

However, a more robust solution, that works for both tabs and spaces, is to use the formats feature of listings package. It allows you to define custom formatting rules. For your case, something as simple as the following suffices:

\lstdefineformat{C}{%
\{=\space\string\newline\indent,%
\}=\newline\noindent\string\newline%
}


The first line says that whenever we see an open brace {, we should place a space before it, then print it, then place a newline and finally indent.

The second line says that whenever we see a close brace }, we should place a newline before it, remove indentation, then print it and finally print a newline.

You can read Section 5.6 of the listings package documentation for more details on how to use lstdefineformat.

The full working example is:

\documentclass[en,12pt]{article}

\usepackage[formats]{listings}

\lstdefineformat{C}{%
\{=\space\string\newline\indent,%
\}=[;]\newline\noindent\string\newline%
}

\begin{document}

\begin{lstlisting}[language=C,format=C]
for (int i = 0; i < numBuses; i++) {
for (int h = 0; h < maxRoute; h++) {
for (int j = 0; j < numStops; j++) {
for (int k = 0; k < numStops; k++) {
if (j == k) {
GRBLinExpr lhs = 0;
lhs += X[i][h][j][k];