2

I have a snippet called struct. And I write text complex_struct in a snippet field. yasnippet will expand complex_struct with the snippet struct. I have to move backward one character to avoid this behavior.

So I hope there is an indicator like make cursor change color to red, and style. Or change text face etc.

Here is the snippet code:

# -*- mode: snippet -*-
# name: struct
# key: struct
# --
struct ${1:name} {
  $0
};


# -*- mode: snippet -*-
# name: complex_struct
# key: complex_struct
# --
complex struct ${1:name} {
  $0
};

When I type text like the following:

complex_struct|

The point is at position (|). It will be expanded from snippet struct instead of complex_struct. I don't want to change yasnippet expand detect characters list. Just want to show which text is expandable (Like struct in this case).

I have a demo code to change cursor style dynamically:

;; change cursor dynamically when prefix text is expandable.
(defun my-cursor-change-on-snippet ()
  ;; (yas-next-field-or-maybe-expand)
  (if (or yas-triggers-in-field ; FIXME: improve condition
          (yas-next-field-will-exit-p))
      (progn
        (set-cursor-color "red")
        (setq cursor-type 'hollow))
    (set-cursor-color "cyan")
    (setq cursor-type '(hbar . 2))
    )
  )

(add-hook 'post-command-hook #'my-cursor-change-on-snippet)
0

1 Answer 1

0

This can be implemented with yas--templates-for-key-at-point, that's an internal function so it's not guaranteed to keep working, but it should be fine for at least the next year or so.

(defvar-local yas--expandable-keys-overlay nil)

(defun yas-show-expand-keys ()
  "Put overlay on text which is an expandable snippet key.
This function is intended to be added to `post-command-hook'."
  (let ((keys-at-point (and yas-minor-mode (yas--templates-for-key-at-point)))
        (have-overlay (overlayp (buffer-local-value 'yas--expandable-keys-overlay (current-buffer)))))
    (if keys-at-point
        (let ((beg (nth 1 keys-at-point))
              (end (nth 2 keys-at-point)))
          (if have-overlay
              (move-overlay yas--expandable-keys-overlay beg end)
            (setq-local yas--expandable-keys-overlay
                        (make-overlay beg end)))
          (overlay-put yas--expandable-keys-overlay 'face '(:box t)))
      (when have-overlay
        (delete-overlay yas--expandable-keys-overlay)))))

(add-hook 'post-command-hook #'yas-show-expand-keys)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.