2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

yasnippet の新しいスニペットをリージョンから作成する

Posted at

yasnippet は Emacs でコードを書くときに便利なツール。短い文字列を定義されたスニペットに応じて展開してくれる。

この新しいスニペットを作成するために、関数 yas/new-snippet が用意されているのだが、コードを書いてる時に「ここをスニペットにしておくと今後便利かもしれない」と思うことがあると思う。そういう時のために、新規スニペット作成用のバッファにリージョンの内容を展開する Elisp を書いた。

(defun yas/new-snippet-region (&optional start end no-template)
  "Pops a new buffer for writing a snippet.

Expands a snippet-writing snippet, unless the optional prefix arg
NO-TEMPLATE is non-nil."
  (interactive "rP")
  (let ((yas/region-string (buffer-substring-no-properties start end))
        (guessed-directories (yas/guess-snippet-directories)))

    (switch-to-buffer "*new snippet*")
    (erase-buffer)
    (kill-all-local-variables)
    (snippet-mode)
    (yas/minor-mode 1)
    (set (make-local-variable 'yas/guessed-modes) (mapcar #'(lambda (d)
                                                              (intern (yas/table-name (car d))))
                                                          guessed-directories))
    (unless no-template (yas/expand-snippet (format "\
# -*- mode: snippet -*-
# name: $1
# key: ${2:${1:$(replace-regexp-in-string \"\\\\\\\\(\\\\\\\\w+\\\\\\\\).*\" \"\\\\\\\\1\" yas/text)}}
# --
%s$0" yas/region-string)))))

使い方は、リージョンを指定して M-x yas/new-snippet-region でOK。

「書いた」といっても、yas/new-snippet に (interactive "r") を追加してその間の文字列を文字列内に挿入しているだけ。また、自分は name: と key: 以外はスニペットに書くことがほとんどないので、テンプレートから残りの項目を削除している。必要なら最後の文字列を元の yas/new-snippet を参照して変更すればいい。

このコードは現在の最新版であるバージョン 0.7 の yas/new-snippet を参考に書いた。yasnippet はコロコロ仕様が変わるから、0.6 系だとおそらく動かない。

2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?