Insert yasnippet by name
Asked Answered
O

4

6

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.

Orangy answered 18/4, 2012 at 14:38 Comment(0)
D
5

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)))))
Devote answered 18/4, 2012 at 15:58 Comment(0)
N
3

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")
Neddra answered 28/4, 2012 at 19:14 Comment(2)
Perhaps that would be a worthwhile addition to the package?Narcho
Actually, I'd love to hear about the data structures, though I don't think this answer/comments are the proper place.Orangy
O
2

I'm just getting into yasnippet and I wanted to automatically insert one of my snippets upon opening a new file for certain modes. That led me to here but I've generated a slightly different solution. Providing yet another alternative: ("new-shell" is the name of my personal snippet for providing a new shell script template)

(defun jsm/new-file-snippet (key)
  "Call particular yasnippet template for newly created
files. Use by adding a lambda function to the particular mode
hook passing the correct yasnippet key"
  (interactive)
  (if (= (buffer-size) 0)
      (progn
        (insert key)
        (call-interactively 'yas-expand))))

(add-hook 'sh-mode-hook '(lambda () (jsm/new-file-snippet "new-shell")))

IMO, my solution is a tad less susceptible to breaking should yasnippet change dramatically.

Ochone answered 26/4, 2014 at 3:48 Comment(0)
N
2

This is 2022 now, so we can simply do the following :

(yas-expand-snippet (yas-lookup-snippet "name-of-your-snippet"))

See the documentation

Nope answered 6/10, 2022 at 7:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.