おもしろwebサービス開発日記

Ruby や Rails を中心に、web技術について書いています

ruby-mode のインデントをいい感じにする

僕はこれまで下記のようなインデントで ruby のコードを書いてきました。

SuperLongClassName.super_long_name_method(hoge: 'fuga',
                                          foo: 'bar',
                                          baka: 'aho')

理由は、Emacs の ruby-mode による標準インデントが上記のような形になっているからです。今ひとつだなーと思いながら幾年月。すばらしい設定を発見しました。

(setq ruby-deep-indent-paren-style nil)

とすると下記のようにインデントできます。

SuperLongClassName.super_long_name_method(
  hoge: 'fuga',
  foo: 'bar',
  baka: 'aho'
  )

おお!すばらしい…かと思ったら閉じ括弧が微妙ですね。ぐぐったらこんな設定を見つけました。

(defadvice ruby-indent-line (after unindent-closing-paren activate)
  (let ((column (current-column))
        indent offset)
    (save-excursion
      (back-to-indentation)
      (let ((state (syntax-ppss)))
        (setq offset (- column (current-column)))
        (when (and (eq (char-after) ?\))
                   (not (zerop (car state))))
          (goto-char (cadr state))
          (setq indent (current-indentation)))))
    (when indent
      (indent-line-to indent)
      (when (> offset 0) (forward-char offset)))))

上記の設定を追加することで最終的にこうなります。

SuperLongClassName.super_long_name_method(
  hoge: 'fuga',
  foo: 'bar',
  baka: 'aho'
)

やりましたね!

参考

Emacs Ruby method parameter indentation - Stack Overflow