いくつかのコード行をレンダリングする がありますlstlisting
。コードは 1 インデントあたり 4 つのスペースでインデントされています。インデントを 2 つのスペースのみに変更する設定はありますか? あることは知っていますtabsize
が、それは明らかにタブ用であり、コード自体の変更は避けたいと思います。
助言がありますか?
答え1
1 つの方法としては、literate
キーを使用して、連続する 2 つのスペースをそれぞれ 1 つのスペースに置き換えることが考えられます。
注意点:このアプローチは
- このような置換をコード行内でも実行する(ただし文字列リテラル内では実行しない)。
- リストの先頭のスペースを削除するために使用される
autogobble
オプション (パッケージによって提供される)を妨害します。lstautogobble
\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}