如何在emacs 23中将Python缩进设置为2个空格?

24

我正在使用Ubuntu 10.04上的emacs 23.1.1。我希望使用2个空格进行Python编程。emacs似乎有一个默认的Python模式(python.el?)。

我在我的.emacs文件中添加了以下内容:

    ;; Only spaces, no tabs
    (setq indent-tabs-mode nil)

    ;; Always end a file with a newline
    (setq require-final-newline nil)

    ;; Don't know which of these might work
    (setq-default tab-width 2)
    (setq-default python-indent 2)
    (setq-default py-indent-offset 2)

当我编辑Python文件时,它使用4个空格缩进。当我尝试C-h v python-indent时,它会显示:

    python-indent's value is 4
    Local in buffer webpage_cache.py; global value is 2

        This variable is safe as a file local variable if its value
        satisfies the predicate `integerp'.

    Documentation:
    Number of columns for a unit of indentation in Python mode.
    See also `M-x python-guess-indent'

    You can customize this variable.

也就是说,它是4而不是2。我尝试自定义变量并保存,但仍然是4。我尝试使用customize-group indent,但仍然是4。

我该如何让emacs注意到这个问题?

3个回答

23
你可以把这个放进你的 .emacs 文件里:
(add-hook 'python-mode-hook '(lambda () 
 (setq python-indent 2)))

为什么

    (setq-default python-indent 2)

可能不起作用是因为当加载.emacs文件时,该变量还不存在。(但我是一个Emacs新手,对我的解释不太确定。)

然而,PEP 8 -- Python代码风格指南建议 "每个缩进级别使用4个空格" ,我发现4个空格更易读。我实际上使用这段代码来强制执行4个空格的缩进。


如果您使用此代码将缩进设置为与默认值相同,您确定它有效吗? - bk1e
我实际上使用了 Vulpecula 的修复方法(我的制表符缩进宽度为8),这解决了问题。 - arthur johnston

19

在你的 .emacs 文件中或被你的 .emacs 引用的文件中添加以下内容:

(setq-default indent-tabs-mode nil)
(setq-default tab-width 2)

如果您想本地化,可以使用钩子

;; Python Hook
(add-hook 'python-mode-hook
          (function (lambda ()
                      (setq indent-tabs-mode nil
                            tab-width 2))))

编辑:我发现以下问题会干扰我的设置:

  • 在库加载之前设置变量
  • 其他软件包/配置文件重置全局变量

对于这两个问题,我发现创建钩子和本地化变量可以有所帮助。


这个回答忽略了我在.emacs中已经设置了tab宽度为2,也没有解释我当时所看到的情况。不过,我的设置现在可以工作了(不知道为什么),所以我接受了这个答案。 - dfrankow
只是出于好奇,为什么要在(function ...)中包装(lambda ...)?我以前没有看到过(function ...),手册建议不必要。 - Tyler
1
Tyler:从历史上看,这是有区别的。现在已经不再必要了,但对许多人来说仍然是一种习惯。请参阅https://dev59.com/xXI-5IYBdhLWcg3wcn3m获取详细信息。 - phils
我将python-indent设置为2,tab-indent也设置为2,但实际缩进仍为1。在emacs中这种事情如此微妙,这一点都不好。 - Samantha Atkins

15

我也遇到了这个问题,但我认为 python-indent 帮助文档中提供的线索是其他人没有提到的重要提示:

See also `M-x python-guess-indent'
如果您不通过将其设置为nil来自定义python-guess-indent,那么python.el将自动为每个包含缩进文本的Python缓冲区设置python-indent,使您的python-indent自定义无效。(另一方面,入乡随俗......)最终,以下是我放入我的.emacs文件中的内容(忽略所有其他自定义变量):
(custom-set-variables
 '(python-guess-indent nil)
 '(python-indent 2))

为了处理现有的Python代码,我需要将python-guess-indent设置为nil,以便按照我想要的方式工作。但对于新的Python代码,这并不是必需的。在尝试了这个修复方法之前,这有点令人困惑。 - andybauer
2
现在在Emacs v26中,python-mode变量的名称更长了。我最终将以下内容添加到我的custom-set-variables中。我只是想让它停止猜测并强制将其设置为4。 '(python-indent-guess-indent-offset nil) '(python-indent-offset 4) - IcarusNM

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接