24

我在 Ubuntu 10.04 上使用 emacs 23.1.1。我希望在 Python 中使用 2 个空格缩进进行编程。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 个空格缩进。当我尝试 Ch 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。我尝试自定义组缩进,仍然是 4。

如何让emacs关注?

4

3 回答 3

22

你可以把它放到你的 .emacs 文件中:

(add-hook 'python-mode-hook '(lambda () 
 (setq python-indent 2)))

之所以

    (setq-default python-indent 2)

不起作用可能是因为加载 .emacs 时此变量不会退出。(但我是emacs新手。我不确定我的解释。)

但是,PEP 8 -- Style Guide for Python Code建议“每个缩进级别 4 个空格”,我发现 4 个空格更具可读性。我实际上使用这段代码来强制缩进 4 个空格。

于 2010-12-13T03:33:35.047 回答
18

在您的 .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))))

编辑:我发现以下问题可能会影响我的设置:

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

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

于 2010-11-22T23:43:09.627 回答
15

我自己也遇到了这个问题,我认为帮助python-indent包含一个没有其他人提到的重要线索:

See also `M-x python-guess-indent'

如果您不python-guess-indent通过将其设置为 进行自定义nilpython.el则将自动python-indent为每个 Python 缓冲区(包含缩进文本)设置,使您的python-indent自定义无效。(另一方面,在罗马时......)

最后,这就是我的.emacs文件中的内容(忽略所有其他自定义变量):

(custom-set-variables
 '(python-guess-indent nil)
 '(python-indent 2))
于 2011-11-17T04:04:58.483 回答