在emacs 23中将python缩进设置为2个空格?

dfr*_*kow 20 emacs python-mode

我在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)
Run Code Online (Sandbox Code Playgroud)

当我编辑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.
Run Code Online (Sandbox Code Playgroud)

也就是说,它是4,而不是2. Grr.我尝试自定义变量并保存,仍然是4.我尝试了自定义组缩进,仍然是4.

如何让emacs注意?

die*_*dha 17

在.emacs文件中或.emacs引用的文件中添加:

(setq-default indent-tabs-mode nil)
(setq-default tab-width 2)
Run Code Online (Sandbox Code Playgroud)

如果要进行本地化,可以放入钩子

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

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

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

对于这两个问题,我发现创建钩子并对变量进行本地化可能有所帮助.


小智 17

您可以将其放入.emacs文件中:

(add-hook 'python-mode-hook '(lambda () 
 (setq python-indent 2)))
Run Code Online (Sandbox Code Playgroud)

之所以

    (setq-default python-indent 2)
Run Code Online (Sandbox Code Playgroud)

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

但是,PEP 8 - Python代码样式指南推荐"每个缩进级别4个空格",我发现4个空格更易读.我实际上使用这段代码强制4个空格缩进.


bk1*_*k1e 15

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

See also `M-x python-guess-indent'
Run Code Online (Sandbox Code Playgroud)

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

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

(custom-set-variables
 '(python-guess-indent nil)
 '(python-indent 2))
Run Code Online (Sandbox Code Playgroud)

  • 现在,在 Emacs v26 中,python 模式变量的名称更长。我最终将其添加到我的自定义设置变量中。我只是想让它停止猜测并强制它为 4。 '(python-indent-guess-indent-offset nil) '(python-indent-offset 4) (2认同)