[Tex/LaTex] Can listings automatically indent code?

indentationlistings

\documentclass[11pt,a4paper] {article}
%\usepackage{fontspec}
\usepackage{listings}
\usepackage{xcolor}
%\setmainfont[BoldFont=黑体]{宋体}
%\XeTeXlinebreaklocale "zh"
%\XeTeXlinebreakskip = 0pt plus 1pt minus 0.1pt
%\linespread{1.5}
\lstset{
numbers = left,
framexleftmargin=10mm,
frame=none,
backgroundcolor=\color[rgb]{245,245,244},
keywordstyle=\bf\color{blue},
identifierstyle=\bf,
numberstyle=\color[RGB]{0,192,192},
commentstyle=\it\color[RGB]{0,96,96},
stringstyle=\rmfamily\s1shape\color[RGB]{128,0,0},
showstringspaces=true
}
\begin {document}
\title{实验课}
\author{ coolwind}
\maketitle
\paragraph{}
你好,世界!

\begin{lstlisting}[language=C]

#include <stdio.h>

int main()
{
printf("Hello world!\n");

for (int i = 0; i < 100; i ++)
{
for (int j = 0; j < 100; j ++)
{
int tmp = i + j;
}
}
return 0;
}

\end{lstlisting}
\end {document}

Best Answer

Section 5.6 Automatic formatting of the listings package documentation describes how to get automatic indention. The idea is to define a format using \lstdefineformat (listings must be loaded with the formats option):

\documentclass[11pt,a4paper] {article}
\usepackage[formats]{listings}
\usepackage{xcolor}

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

\lstset{
numbers = left,
framexleftmargin=10mm,
frame=none,
backgroundcolor=\color[RGB]{245,245,244},
keywordstyle=\bfseries\color{blue},
identifierstyle=\bfseries,
numberstyle=\color[RGB]{0,192,192},
commentstyle=\it\color[RGB]{0,96,96},
stringstyle=\rmfamily\slshape\color[RGB]{128,0,0},
showstringspaces=true
}


\begin {document}

\begin{lstlisting}[language=C,format=C]

#include <stdio.h>

int main()
{
printf("Hello world!\n");

for (int i = 0; i < 100; i ++)
{
for (int j = 0; j < 100; j ++)
{
int tmp = i + j;
}
}
return 0;
}

\end{lstlisting}

\end{document}

enter image description here

I removed some lines if the original code not essential for the issue discussed; I also fixed an error in a color specification (changed from rgb to RGB)