Skip to content

Instantly share code, notes, and snippets.

@unhammer
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save unhammer/dca17d8678153848ea0f to your computer and use it in GitHub Desktop.
Save unhammer/dca17d8678153848ea0f to your computer and use it in GitHub Desktop.
(defvar-local dix-yas-key-rex ""
"Used by `dix-yas-update-key-rex' for caching the regex-opt of
possible snippet keys.")
(defvar-local dix-yas-key-rex-tables nil
"Used by `dix-yas-update-key-rex' for checking if we need to
update `dix-yas-key-rex'.")
(defun dix-yas-update-key-rex ()
"Update `dix-yas-key-rex', used by `dix-yas-skip-backwards-to-key'."
(let ((tables (yas--get-snippet-tables)))
(unless (equal tables dix-yas-key-rex-tables)
;; Only update key-rex if tables changed (but is this equal test slow?):
(setq dix-yas-key-rex-tables tables)
(setq dix-yas-key-rex
(let (keys) (mapc
(lambda (table)
(let* ((keyhash (yas--table-hash table)))
(when keyhash
(maphash (lambda (k v) (push k keys)) keyhash))))
dix-yas-key-rex-tables)
(concat (regexp-opt keys) "$"))))))
(defun dix-yas-skip-backwards-to-key ()
"Skip backwards to the first possible yasnippet key.
This is meant to be used in `yas-key-syntaxes', since the
defaults don't let you expand e.g. \"<s>\" without having
whitespace before it. To use this function, put the following in
your init file:
(eval-after-load 'yasnippet
'(add-to-list 'yas-key-syntaxes 'dix-yas-skip-backwards-to-key))
Only has an effect in `dix-mode' so the above shouldn't change
how yasnippet expansion works in other modes."
(when dix-mode
(dix-yas-update-key-rex)
(let ((haystack (buffer-substring-no-properties (line-beginning-position) (point))))
(when (string-match dix-yas-key-rex haystack)
(goto-char (+ (line-beginning-position) (match-beginning 0)))))))
@npostavs
Copy link

;; Only update key-rex if tables changed (but is this equal test slow?):

I think equal is equivalent to eq for hashtables, so it will be fast, but it won't detect changes to the tables themselves (only changes to the list of active tables).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment