emacs 23 python.el 自动缩进样式——可以配置吗?

2024-02-18

我使用 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 自动缩进以实现我想要的样式?


您可以尝试这种和平的代码:

(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'
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

emacs 23 python.el 自动缩进样式——可以配置吗? 的相关文章

随机推荐