elken / yasnippet-capf

Completion-At-Point Extension for YASnippet
GNU General Public License v3.0
40 stars 9 forks source link

completing based on snippet's "name" instead of "key" #2

Closed kings2u closed 1 year ago

kings2u commented 1 year ago

I would like to be able to search for and expand yasnippets not only by looking up their "key" property in the snippet (as this capf currently does) but also by simply looking up the full name of the yasnippet via corfu completion. Do you know how that would be possible? I was thinking modifying the :exit-function of this capf to expand based on the name of the final string chosen, in addition to the shorter "key" that a user defines in a yasnippet, but I not an elisp expert. My config right now offers the names of yasnippets in the options to complete against, but when I choose it, it just inserts the name as plain text rather than expanding the yasnsippet.

Any help would be much appreciated. Thanks so much for this package!

elken commented 1 year ago

Duplicate of #1, but I've also forgotten to look into it so thanks

kings2u commented 1 year ago

I’m sure there’s a more elegant way that you will write, but for the time being this is working for me to complete against Yasnippet names rather than keys:

(require 'yasnippet)

(defun my/generate-yas-capf-candidates ()
  "Dynamically generate list of candidates of yasnippets for the current mode(s)."
  (let ((yasTemplates (yas--all-templates (yas--get-snippet-tables))))
    (mapcar
     (lambda (yasTemplate) 
       (yas--template-name yasTemplate))
     yasTemplates)))

(defvar-local my-yas-capf-candidates nil) 

(defun my/cape-yasnippet-capf ()
  "Function to be used for the hook `completion-at-point-functions'."
  (interactive)
  (let ((start (save-excursion (skip-syntax-backward "w_") 
                               (point)))
        (end (point)))
    (list start end
          (if (not my-yas-capf-candidates)
              (setq my-yas-capf-candidates (my/generate-yas-capf-candidates)) 
            my-yas-capf-candidates)
          :exclusive 'no
          :annotation-function (lambda (_) " YAS")
          :exit-function (lambda (str status)
                           (delete-char (* -1 (length str))) 
                           (yas-expand-snippet (yas-lookup-snippet str))))))

(add-hook 'prog-mode-hook
          (lambda () (setq-local completion-at-point-functions
                                 (list (cape-super-capf
                                        #'my/cape-yasnippet-capf
                                        #'cape-symbol
                                        #'cape-dabbrev)))))
elken commented 1 year ago

Added in c33e8bd63d867ed40b5f3037b62b46c98f9674db, not keen on the delete-char but I don't have time to come up with a cleaner impl myself atm.

In future, when someone marks an issue as duplicate and closes it don't try to necro bump it :)