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

标签 python emacs coding-style indentation

我已经使用 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'
}

关于python - emacs 23 python.el 自动缩进样式——可以配置吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5094649/

相关文章:

emacs - 如何检测 Emacs 是否以批处理模式运行?

Emacs 和公司自动补全。全局添加头目录

coding-style - Common Lisp 对象设置函数风格

python - tensorflow GPU安装问题

python - Scala 相当于 Python help()

vim - 艰难地学习 Emacs/Slime(来自 Vim 10 年)

python - 使用 MySQLdb 时如何使用 Python 列表理解(或类似的)来检索行?

python - Anaconda3 - 属性错误 : 'dict' object has no attribute 'rsplit'

python - Django:如何正确处理数据库连接错误

scala - 排除行为的首选方式是什么