在Emacs Python模式中自定义多行语句缩进

16 投票
2 回答
1780 浏览
提问于 2025-04-16 07:41

我正在使用Emacs 23自带的python-mode。我想自定义多行语句的自动缩进方式。例如,目前Emacs更倾向于以下这种格式:

my_var = [
    'val1',
    'val2',
    'val3',
    ]

而我更希望看到的是:

my_var = [
    'val1',
    'val2',
    'val3',
]

另外,当我创建带有尾随列表或字典的函数时,Emacs更喜欢:

my_func('first_arg', 'another_arg', {
        'key1': val1,
        'key2': val2,
        })

我希望看到的是:

my_func('first_arg', 'another_arg', {
    'key1': val1,
    'key2': val2,
})

请问在Emacs的python-mode中,是否可以进行这些自定义设置?我找不到相关的文档来创建这些自定义。

2 个回答

1

你可以看看 python-mode.el 文件里的 py-indent-line 这个函数。

11

也许可以这样做?

(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)

可以看看这个类似的问题,里面讨论了一些在这个回答中用到的Emacs功能。

撰写回答