在emacs 23中将python缩进设置为2个空格?
我正在Ubuntu 10.04上使用emacs 23.1.1。我希望在Python中使用两个空格的缩进进行编程。emacs看起来有一个python的默认模式(python.el?) 我在.emacs中添加了以下内容:在emacs 23中将python缩进设置为2个空格?,emacs,python-mode,Emacs,Python Mode,我正在Ubuntu 10.04上使用emacs 23.1.1。我希望在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)
;; 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缩进时,它会说:
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。Grr。我试着自定义变量并保存,仍然是4。我试过自定义组缩进,仍然是4
如何让emacs引起注意?在.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文件中:
(add-hook 'python-mode-hook '(lambda ()
(setq python-indent 2)))
原因是什么
(setq-default python-indent 2)
不工作可能是因为加载.emacs时此变量不退出。(但我是emacs的新手。我不确定我的解释。)
但是,建议“每个缩进级别4个空格”,我发现4个空格更具可读性。实际上,我使用这段代码强制执行4个空格的缩进。我自己也遇到了这个问题,我认为对
python缩进的帮助包含了一个其他人没有提到的重要线索:
See also `M-x python-guess-indent'
如果您没有通过将python guess indent设置为nil
来自定义python缩进,那么python.el
将自动为每个python缓冲区(包含缩进文本)设置python缩进
,使您的python缩进
自定义无效。(另一方面,在罗马……)
最后,这就是我的.emacs
文件中的内容(忽略所有其他自定义变量):
这个答案忽略了一个事实,即我在.emacs中已经有了tab width 2,并且没有解释我看到的任何内容。尽管如此,我的设置现在仍然有效(不知道为什么),所以我会接受。只是出于好奇,为什么要在(函数…)中包装(lambda…)?我以前没见过(功能…),手册上说没有必要。泰勒:从历史上看,它起了很大的作用。这不再是必要的,但对许多人来说仍然是一种习惯。有关详细信息,请参阅。python缩进为2,tab缩进为2,实际缩进为1。像这样的东西在emacs中是如此的挑剔,一点也不好。如果你用这段代码将缩进设置为与默认值相同,你确定它能工作吗?我实际上使用了Vulpecula的修复程序(我的制表符缩进为8)它解决了使用现有Python代码的问题,我需要将Python guess indent设置为nil,以便按照我希望的方式工作。但是,对于新的Python代码,它不是必需的。在我尝试此修复之前,这有点令人困惑。现在在Emacs v26中,python模式变量的名称更长。最后,我将其添加到我的自定义变量集中。我只是想让它停止猜测,把它改成4(python缩进猜测缩进偏移量nil)'(python缩进偏移量4)
(custom-set-variables
'(python-guess-indent nil)
'(python-indent 2))