# Change indentation depth when using spaces in lstlisting

I have an lstlisting that renders some lines of code. The code is indented by four spaces per indent. Is there any setting to change the indentation to only two spaces? I know that there is tabsize but that is obviously for tabs and I would like to avoid changing the code itself.

Any suggestions?

• It seems easier to use your editor to perform a search-and-replace, since you probably don't have consecutive spaces anywhere else in your code. Just a guess though. – Werner Dec 27 '13 at 21:08

One possible approach is to use the literate key to replace each occurence of two consecutives spaces by one space.

Caveats: this approach will

• perform such replacements "within" lines of code also (though not in string literals),
• interfere with the autogobble option (offered by the lstautogobble package), which is used to remove leading spaces in a listing.

\documentclass{article}

\setlength\parindent{0pt}

\usepackage{listings}
\usepackage{filecontents}

% code available at http://docs.python.org/2/tutorial/classes.html
\begin{filecontents*}{samplecode.py}
class MyClass:
"""A simple example     class"""
i = 12345
def f(self):
return 'hello world'
\end{filecontents*}

\lstdefinestyle{Python2}
{
language=Python,
literate = *{\ \ }{\ }1, %replaces each occurence of two consecutive spaces by one
}

\begin{document}
Indent = 4 spaces (as in the original listing)
\lstinputlisting[language=Python,frame=single]{samplecode.py}
Indent = 2 spaces
\lstinputlisting[style=Python2,frame=single]{samplecode.py}
\end{document}