emacs 23 python.el 自动缩进风格 -- 可以配置吗?

13 投票
3 回答
1531 浏览
提问于 2025-04-16 12:24

我已经使用 emacs 23(python.el)一个多月了,但对默认的自动缩进设置不太满意。

现在,我的 Python 文件的自动缩进是这样的:

x = a_function_with_dict_parameter({
                                   'test' : 'Here is a value',
                                   'second' : 'Another value',
                                   })
a_function_with_multiline_parameters(on='First', line='Line',
                                     now_on='Second', next_line='Line',
                                     next='Third', finally='Line')

我希望能设置自动缩进,这样同样的代码可以更容易地格式化:

x = a_function_with_dict_parameter({
    'test' : 'Here is a value',
    'second' : 'Another value',
})
a_function_with_multiline_parameters(on='First', line='Line',
    now_on='Second', next_line='Line', next='Third', finally='Line')

我想要的自动缩进逻辑是:

如果上一行最后一个非注释和空格的字符是冒号(:),那么缩进级别增加 1。否则,保持相同的缩进级别。

但按照这个逻辑,按下 TAB 键时,应该真的增加当前行的缩进级别。(现在,TAB 只是把这一行移动到自动缩进的级别)

有没有人知道我该如何修改 emacs 的自动缩进,以达到我想要的风格?

3 个回答

-1

在你的编辑器里,输入“M-x customize-group”,然后按回车键(RET),接着再输入“python”,再按一次回车键(RET)。

1

试试fgallina最新的 python.el 版本。这个版本包含了很多其他的 改进

我用的就是这个版本,TAB 的功能正是你想要的,不过我对python.el做了一些修改,所以我不能保证你会得到一样的效果。如果你得到了,请告诉我。

3

你可以试试这段代码:

(require 'python)

; indentation
(defadvice python-calculate-indentation (around outdent-closing-brackets)
  "Handle lines beginning with a closing bracket and indent them so that
  they line up with the line containing the corresponding opening bracket."
(save-excursion
  (beginning-of-line)
  (let ((syntax (syntax-ppss)))
    (if (and (not (eq 'string (syntax-ppss-context syntax)))
             (python-continuation-line-p)
             (cadr syntax)
             (skip-syntax-forward "-")
             (looking-at "\\s)"))
        (progn
          (forward-char 1)
          (ignore-errors (backward-sexp))
          (setq ad-return-value (current-indentation)))
      ad-do-it))))

(ad-activate 'python-calculate-indentation)

现在,一个简单的 Python 字典像这样:

a = {'foo': 'bar',
     'foobar': 'barfoo'
    }

变成了...

a = {'foo': 'bar',
     'foobar': 'barfoo'
}

撰写回答