如果上一行以逗号结尾,则缩进

时间:2014-08-05 13:42:15

标签: ruby emacs elisp

编写ruby代码时,Emacs不会在以逗号结尾的行后缩进该行:

attr_accessor :a, :b,
:c

我希望将以下行缩进一级:

attr_accessor :a, :b,
  :c

阅读ruby-mode.el后,我认为这不容易。有没有办法做到这一点?

2 个答案:

答案 0 :(得分:0)

好的,感谢this post我找到了办法:

(defadvice ruby-indent-line (after line-up-args activate)
  (let (indent prev-indent arg-indent)
    (save-excursion
      (back-to-indentation)
      (when (zerop (car (syntax-ppss)))
        (setq indent (current-column))
        (skip-chars-backward " \t\n")
        (when (eq ?, (char-before))
          (ruby-backward-sexp)
          (back-to-indentation)
          (setq prev-indent (current-column))
          (skip-syntax-forward "w_.")
          (skip-chars-forward " ")
          (setq arg-indent (+ (ruby-current-indentation) ruby-indent-level))))) ;; (current-column)
    (when prev-indent
      (let ((offset (- (current-column) indent)))
        (cond ((< indent prev-indent)
               (indent-line-to prev-indent))
              ((= indent prev-indent)
               (indent-line-to arg-indent)))
        (when (> offset 0) (forward-char offset))))))

答案 1 :(得分:0)

我一直在创建一个库以定制缩进的需求,它仍在使用中,但我自己用于Erlang模式,也许你想查看它。我不认为这是一个合适的解决方案,但它可能适合你。

https://github.com/AtticHacker/indent-of-doom

这是一个自定义缩进的DSL,根据您的需要,这是您想要添加到您的emacs中的内容:

(setq tab-width 2) ; Set default tab with to 2
(setq doom-indent-fallback t) ; If no rules match, use default tab
(setq doom-use-tab-cycle nil) ; Don't use tab cycling
(setq my-doom '(
    ; Rules for ruby mode
    (ruby-mode . (
        ; When previous line ends on "," and starts with "attr_accessor"
        ; indent the current line as previous + 1 tab
        ((and (prev 'ends-on ",") (prev 'starts-with "attr_accessor")) (prev 'indent 1)))
    )
))