Emacs ruby-mode indentation behavior

久未见 提交于 2019-11-28 21:27:49

This hack should work in the majority of cases.

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

Example:

class Comment < ActiveRecord::Base
  after_create :send_email_to_author,
               :if => :author_wants_emails?,
               :unless => Proc.new { |comment| comment.post.ignore_comments? }
end

From Remi (in comments): Note that Emacs will correctly indent class Foo attr_accessor(:a, :time, # ms since epoch :b, :c) end – Rémi Dec 11 '10 at 8:50

You can add parens and have it indent properly -- I'm adding this here because I'm looking for unanswered questions, and this one comes up (incorrectly, since it has been answered in the comments).

When using Emacs 24.4 or newer, your example will be indented like this by default.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!