[Tex/LaTex] Can the listings package automatically indent source code

indentationlistings

The listings package automatically highlights keywords in source code and makes it look nice. Is it possible to automatically indent the program? For example, in listings, if the following code is typed,

#include<stdio.h>
void main()
{
printf("\n Hello World");
}

the output should be

#include<stdio.h>

void main()
{
    printf("\n Hello World");
}

Can listings to do that, and if so, how should I configure it?

Best Answer

The listings package provides that functionality; see subsection 5.6 of the manual. Make sure the formats aspect is loaded, which can be done either by passing formats as a package option to listings,

\usepackage[formats]{listings}

or by using the \lstloadaspects macro after loading the listings package,

\usepackage{listings}
...
\lstloadaspects{formats}

Then, use the \lstdefineformat macro to define a "format", i.e. instructions about what listings should do upon encountering certain characters. The format definition shown below is taken straight from the manual.

Be aware that this feature remains experimental; according to the manual,

The automatic source code formatting is far away from being good. First of all, there are no general rules on how source code should be formatted. So ‘format definitions’ must be flexible. This flexibility requires a complex interface, a powerful ‘format definition’ parser, and lots of code lines behind the scenes. Currently, format definitions aren’t flexible enough (possibly not the definitions but the results).

Output

\documentclass{article}

\usepackage[formats]{listings}

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

\lstset{basicstyle=\ttfamily}

\usepackage{filecontents}
\begin{filecontents*}{sample.c}
#include<stdio.h>
void main()
{
printf("\n Hello World");
}
\end{filecontents*}

\begin{document}

\section*{``Raw'' listing}
\lstinputlisting{sample.c}

\section*{With automatic formatting}
\lstinputlisting[format=C]{sample.c}

\end{document}