Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert yasnippet by name

I want to insert a specific yasnippet as part of a function in emacs-lisp. Is there a way to do that?

The only command that seems related is yas/insert-snippet, but it simply opens a popup with all the options and the documentation doesn't say anything about bypassing the popup by specifing the snippet name.

like image 825
Malabarba Avatar asked Apr 18 '12 14:04

Malabarba


2 Answers

yas/insert-snippet is indeed just a thin wrapper around yas/expand-snippet for interactive use. However, the internal structures are... interesting. Judging from the source code the following does work for me when I want to expand the "defun" snippet in elisp-mode:

(yas/expand-snippet
  (yas/template-content (cdar (mapcan #'(lambda (table)
                                          (yas/fetch table "defun"))
                                      (yas/get-snippet-tables)))))
like image 115
Moritz Bunkus Avatar answered Sep 28 '22 01:09

Moritz Bunkus


As the author of yasnippet, I think you'd rather not rely on internal details of yasnippet's interesting data structures, which may change in the future. I would do this based on the documentation of yas/insert-snippet and yas/prompt-functions:

(defun yas/insert-by-name (name)
  (flet ((dummy-prompt
          (prompt choices &optional display-fn)
          (declare (ignore prompt))
          (or (find name choices :key display-fn :test #'string=)
              (throw 'notfound nil))))
    (let ((yas/prompt-functions '(dummy-prompt)))
      (catch 'notfound
        (yas/insert-snippet t)))))

(yas/insert-by-name "defun")
like image 30
Joao Tavora Avatar answered Sep 28 '22 02:09

Joao Tavora