Malabarba
Malabarba

Reputation: 4553

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.

Upvotes: 6

Views: 1376

Answers (4)

learner
learner

Reputation: 391

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

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

See the documentation

Upvotes: 3

jonEbird
jonEbird

Reputation: 418

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.

Upvotes: 2

joao
joao

Reputation: 3566

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")

Upvotes: 3

user507077
user507077

Reputation:

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

Upvotes: 5

Related Questions