Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to lookup a snippet by key? #1201

Open
ghost opened this issue Aug 22, 2024 · 1 comment
Open

How to lookup a snippet by key? #1201

ghost opened this issue Aug 22, 2024 · 1 comment

Comments

@ghost
Copy link

ghost commented Aug 22, 2024

I'm writing some code to auto insert a snippet into files by major-mode. I have an alist for major-mode -> snippet name, but it seems like the snippet keys are a more straightforward way to identify a snippet... except I can't find a function to lookup a snippet by key. Is there such a thing, something like yas-lookup-snippet?
Also if someone's already done this, feel free to point me in that direction.

FYI, here's my current code:

;; Define an alist mapping file extensions to yasnippet names (*not* keys!)
(defvar my-extension-snippet-alist
  '(("cpp" . "C++ CPP source file header")
    ("cxx" . "C++ CPP source file header")
    ("h" . "C++ CPP header file header")
    ("hpp" . "C++ CPP header file header")
    ("hxx" . "C++ CPP header file header"))
  "Alist mapping file extensions to yasnippet names.")

(defun my-auto-insert-snippet ()
  "Automatically insert a specific yasnippet when creating a new file based on its extension."
  (when (and buffer-file-name
             (zerop (buffer-size)))
    (let* ((file-extension (file-name-extension buffer-file-name))
           (snippet-name (assoc-default file-extension my-extension-snippet-alist)))
      (condition-case err
          (when snippet-name
            (yas-expand-snippet (yas-lookup-snippet snippet-name))) ;;; here's where I'd like to look up by key instead
        (error
         ;; maybe no such snippet
         (message (error-message-string err))
         nil)
        ))))

(add-hook 'find-file-hook 'my-auto-insert-snippet)
@reinierkof
Copy link

reinierkof commented Feb 20, 2025

I wrote this function, based on the source code i found for the yas-lookup-snippet function.
If you are using it locally you can also opt to remove the mode and just paste major-mode in there

(defun yas--lookup-snippet-by-key  (key mode)
  "Get the snippet with KEY in MODE's tables."
  (interactive)
  (let ((yas-choose-tables-first nil)
        (yas-choose-keys-first nil))
    (cl-find key (yas--all-templates
                  (yas--get-snippet-tables mode))
             :key #'yas--template-key :test #'string=))
  )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant