Insert yasnippet by name

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

The only command that seems to be related is yas/insert-snippet, but it just opens a popup window with all the options, and the documentation says nothing about going around the popup window, specifying the name of the fragment.

+5
source share
3 answers

yas/insert-snippet- This is a really thin wrapper around yas/expand-snippetfor interactive use. However, the internal structures ... are interesting. Judging by the source code, the following works 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)))))
+5
source

yasnippet, , yasnippet, . yas/insert-snippet 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")
+3

I just got into yasnippet and I wanted to automatically insert one of my fragments when opening a new file for certain modes. This brought me here, but I created a slightly different solution. Providing another alternative: ("new-shell" is the name of my personal fragment to provide a new script shell 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 decision is a little less susceptible to hacking if the lynx changes dramatically.

+1
source

All Articles