Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I trigger an event when a Yasnippet macro can fire?

I love yasnippet, but it requires time to memorize. What I'd like to do is change the cursor color when I am at a point that can expand a macro (and back again when there is no macro). However, from what I remember about how yasnippet works, that might not exactly be performant.

A friend suggested that what I want here is a yasnippet-can-fire-p, but I'm still not sure as to the best way to go about doing this. What's the cleanest path towards implementing this that won't drive my sistem to a grinding halt?

like image 592
angelixd Avatar asked Jan 10 '13 17:01

angelixd


1 Answers

Took some time to find the function that did the checking whether or not it can expand, but was 'lucky' enough to find it eventually.

The key is that this function would normally expand, or otherwise, perform the fallback behavior. I cloned this function and set the cursor colors in those places instead.

And, surprisingly, it actually does not slow down at all.

;; It will test whether it can expand, if yes, cursor color -> green.
(defun yasnippet-can-fire-p (&optional field)
  (interactive)
  (setq yas--condition-cache-timestamp (current-time))
  (let (templates-and-pos)
    (unless (and yas-expand-only-for-last-commands
                 (not (member last-command yas-expand-only-for-last-commands)))
      (setq templates-and-pos (if field
                                  (save-restriction
                                    (narrow-to-region (yas--field-start field)
                                                      (yas--field-end field))
                                    (yas--current-key))
                                (yas--current-key))))

  (set-cursor-color (if (and templates-and-pos (first templates-and-pos)) 
                        "green" "red"))))

; As pointed out by Dmitri, this will make sure it will update color when needed.
(add-hook 'post-command-hook 'yasnippet-can-fire-p)

Added this to my lisp collection (I was actually thinking that this would be useful as well).


Update: In latest version of yasnippet [from august 2014, from 0.8.1], yas--current-key function has been renamed into yas--templates-for-key-at-point. cf Issue

like image 134
PascalVKooten Avatar answered Oct 11 '22 14:10

PascalVKooten