Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 14 down vote accepted

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}
share|improve this answer
    
@ManuelKuehner Thanks for the edit. –  Jubobs Mar 20 at 14:43
    
I would like to develop a patch for this @Jubobs –  subham soni Mar 20 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 at 18:28

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.