LoginSignup
4
2

More than 5 years have passed since last update.

Emacsでintellij風のbackspaceを実現する

Last updated at Posted at 2017-08-23

やりたいこと

普段AndroidStudioを使っていて便利だなあと思うのが、コードのインデントに合わせて最適なbackspaceをしてくれることなのですが、それをEmacsで実現できないかなと思っていました。Hungry deleteというパッケージがよさそうだと思って試したのですが、ほんとに全部のホワイトスペースを削除してしまいやりすぎ。
EmacsLispを勉強したのでせっかくだし書いてみることにしました。

できた

  (defun smart-backspace ()
    (interactive)
    (let* ((current (save-excursion
                      (point)))
           (beginning (save-excursion
                        (beginning-of-line)
                        (point))))
      (if (string-match "^[ \t]*$" (buffer-substring beginning current))
          (progn
            (kill-line 0)
            (delete-backward-char 1)
            (indent-for-tab-command))
        (delete-backward-char 1))))

おもいのほか簡単にかけました。使い方は下のように好きなキーにキーバインドをあてるだけ。
(global-set-key (kbd "backspace") 'smart-backspace)
自分はC-hにもbackspaceをあてたかったので
(global-set-key (kbd "C-h") 'smart-backspace)
としてみたのですが、これでは補完の際にhelpがでてしまいうまく行きませんでした。
仕方がないのでbackspaceにキーバインドを当ててkey-translation-mapでC-hにも同じキーバインドを適用することにして一件落着となりました。
最終的な使い方はこんな感じです。

(global-set-key [?\C-?] 'smart-backspace)
(define-key key-translation-map [?\C-h] [?\C-?])

まだElisp初心者なので修正点などあればぜひ教えてください。

2017/10/14 追記

パッケージ化してmelpaに登録しました。-> https://github.com/itome/smart-backspace

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2