在 lstlisting 中使用空格時變更縮排深度

在 lstlisting 中使用空格時變更縮排深度

我有一個lstlisting可以呈現一些程式碼行的程式。該代碼每次縮排四個空格。是否有任何設定可以將縮排更改為僅兩個空格?我知道有,tabsize但這顯然是針對選項卡的,我想避免更改程式碼本身。

有什麼建議麼?

答案1

一種可能的方法是使用literate金鑰將每次出現的兩個連續空格替換為一個空格。

注意事項: 這種方法將

  • 也在程式碼行「內」執行此類替換(儘管不是在字串文字中),
  • 幹擾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}

相關內容