[Tex/LaTex] Format code correctly in LaTeX

codeformattinglistings

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];
                            basicModel.addConstr(lhs == 0);
                        }
                    }
                }
            }
        }
\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 =)

Best Answer

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];
                            basicModel.addConstr(lhs == 0);
                        }
                    }
                }
            }
        }
\end{lstlisting}

\end{document}

screenshot

Related Question