yasnippetで同じパターンを連続入力する

[2009/12/15]0.7.0に対応 id:hack-3 さん情報ありがとうございます。yasnippet-config.el (M-x install-elisp-from-emacswiki yasnippet-config.el) にはすでに対応してあるので更新は不要。

ぬぅ、半月以上あけてしまった。

Emacs界で定型文入力といえばyasnippet.elは有名だ。
しかし、同じパターンを数回だけ入力するのにわざわざsnippetを定義するのは面倒だ。

内部的にスニペット展開に使われている yas/expand-snippet をうまく活用すると、こういう場合でも楽に入力できる。
そこで、一度きりのスニペットを定義して、すかさず実行、繰り返し実行ができるようにしてみた。

(require 'yasnippet)
(defvar yas/oneshot-snippet nil)
(defun yas/register-oneshot-snippet (s e)
  (interactive "r")
  (setq yas/oneshot-snippet (buffer-substring-no-properties s e))
  (delete-region s e)
  (yas/expand-oneshot-snippet)
  (message "%s" (substitute-command-keys "Press \\[yas/expand-oneshot-snippet] to expand.")))

(defun yas/expand-oneshot-snippet ()
  (interactive)
  (if (string< "0.6" yas/version)
      (yas/expand-snippet yas/oneshot-snippet)
    (yas/expand-snippet (point) (point) yas/oneshot-snippet)))


M-wを2回押して一度きりのスニペットを登録・実行できるようにしてみた。
sequential-command.elを使って、こう設定している。

M-x install-elisp http://www.emacswiki.org/cgi-bin/wiki/download/sequential-command.el

(require 'sequential-command)
(define-sequential-command kill-ring-save-x
  kill-ring-save yas/register-oneshot-snippet)
(define-key esc-map "w" 'kill-ring-save-x) ; M-w
(define-key global-map "\C-x\C-y" 'yas/expand-oneshot-snippet)

で、再びスニペットを使いたくなったらC-x C-yを押せばよい。このキーバインドはなぜか空いてる。