# Can the listings package automatically indent source code?

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?

-

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}
...


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).

\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}

-
@ManuelKuehner Thanks for the edit. –  Jubobs Mar 20 '14 at 14:43
I would like to develop a patch for this @Jubobs –  subham soni Mar 20 '14 at 17:46
@subhamsoni Do you mean that you would like to extend that functionality? If so, that's great and I encourage you to get in touch with the maintainer of listings. –  Jubobs Mar 20 '14 at 18:28