]> code.delx.au - gnu-emacs-elpa/blob - yasnippet.el
Revert "inhibit change hooks during (insert content)"
[gnu-emacs-elpa] / yasnippet.el
1 ;;; yasnippet.el --- Yet another snippet extension for Emacs.
2
3 ;; Copyright (C) 2008-2013 Free Software Foundation, Inc.
4 ;; Authors: pluskid <pluskid@gmail.com>, João Távora <joaotavora@gmail.com>
5 ;; Maintainer: João Távora <joaotavora@gmail.com>
6 ;; Version: 0.8.0
7 ;; Package-version: 0.8.0
8 ;; X-URL: http://github.com/capitaomorte/yasnippet
9 ;; Keywords: convenience, emulation
10 ;; URL: http://github.com/capitaomorte/yasnippet
11 ;; EmacsWiki: YaSnippetMode
12
13 ;; This program is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
17
18 ;; This program is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
25
26 ;;; Commentary:
27 ;;
28 ;; Basic steps to setup:
29 ;;
30 ;; (add-to-list 'load-path
31 ;; "~/path-to-yasnippet")
32 ;; (require 'yasnippet)
33 ;; (yas-global-mode 1)
34 ;;
35 ;;
36 ;; Interesting variables are:
37 ;;
38 ;; `yas-snippet-dirs'
39 ;;
40 ;; The directory where user-created snippets are to be
41 ;; stored. Can also be a list of directories. In that case,
42 ;; when used for bulk (re)loading of snippets (at startup or
43 ;; via `yas-reload-all'), directories appearing earlier in
44 ;; the list shadow other dir's snippets. Also, the first
45 ;; directory is taken as the default for storing the user's
46 ;; new snippets.
47 ;;
48 ;; The deprecated `yas/root-directory' aliases this variable
49 ;; for backward-compatibility.
50 ;;
51 ;; `yas-extra-modes'
52 ;;
53 ;; A local variable that you can set in a hook to override
54 ;; snippet-lookup based on major mode. It is a list of
55 ;; symbols that correspond to subdirectories of
56 ;; `yas-snippet-dirs' and is used for deciding which
57 ;; snippets to consider for the active buffer.
58 ;;
59 ;; Major commands are:
60 ;;
61 ;; M-x yas-expand
62 ;;
63 ;; Try to expand snippets before point. In `yas-minor-mode',
64 ;; this is normally bound to TAB, but you can customize it in
65 ;; `yas-minor-mode-map'.
66 ;;
67 ;; M-x yas-load-directory
68 ;;
69 ;; Prompts you for a directory hierarchy of snippets to load.
70 ;;
71 ;; M-x yas-insert-snippet
72 ;;
73 ;; Prompts you for possible snippet expansion if that is
74 ;; possible according to buffer-local and snippet-local
75 ;; expansion conditions. With prefix argument, ignore these
76 ;; conditions.
77 ;;
78 ;; M-x yas-visit-snippet-file
79 ;;
80 ;; Prompts you for possible snippet expansions like
81 ;; `yas-insert-snippet', but instead of expanding it, takes
82 ;; you directly to the snippet definition's file, if it
83 ;; exists.
84 ;;
85 ;; M-x yas-new-snippet
86 ;;
87 ;; Lets you create a new snippet file in the correct
88 ;; subdirectory of `yas-snippet-dirs', according to the
89 ;; active major mode.
90 ;;
91 ;; M-x yas-load-snippet-buffer
92 ;;
93 ;; When editing a snippet, this loads the snippet. This is
94 ;; bound to "C-c C-c" while in the `snippet-mode' editing
95 ;; mode.
96 ;;
97 ;; M-x yas-tryout-snippet
98 ;;
99 ;; When editing a snippet, this opens a new empty buffer,
100 ;; sets it to the appropriate major mode and inserts the
101 ;; snippet there, so you can see what it looks like. This is
102 ;; bound to "C-c C-t" while in `snippet-mode'.
103 ;;
104 ;; M-x yas-describe-tables
105 ;;
106 ;; Lists known snippets in a separate buffer. User is
107 ;; prompted as to whether only the currently active tables
108 ;; are to be displayed, or all the tables for all major
109 ;; modes.
110 ;;
111 ;; If you have `dropdown-list' installed, you can optionally use it
112 ;; as the preferred "prompting method", putting in your .emacs file,
113 ;; for example:
114 ;;
115 ;; (require 'dropdown-list)
116 ;; (setq yas-prompt-functions '(yas-dropdown-prompt
117 ;; yas-ido-prompt
118 ;; yas-completing-prompt))
119 ;;
120 ;; Also check out the customization group
121 ;;
122 ;; M-x customize-group RET yasnippet RET
123 ;;
124 ;; If you use the customization group to set variables
125 ;; `yas-snippet-dirs' or `yas-global-mode', make sure the path to
126 ;; "yasnippet.el" is present in the `load-path' *before* the
127 ;; `custom-set-variables' is executed in your .emacs file.
128 ;;
129 ;; For more information and detailed usage, refer to the project page:
130 ;; http://github.com/capitaomorte/yasnippet
131
132 ;;; Code:
133
134 (require 'cl)
135 (require 'easymenu)
136 (require 'help-mode)
137
138 (defvar yas--editing-template)
139 (defvar yas--guessed-modes)
140 (defvar yas--indent-original-column)
141 (defvar yas--scheduled-jit-loads)
142 (defvar yas-keymap)
143 (defvar yas-selected-text)
144 (defvar yas-verbosity)
145 (defvar yas--current-template)
146
147 \f
148 ;;; User customizable variables
149
150 (defgroup yasnippet nil
151 "Yet Another Snippet extension"
152 :group 'editing)
153
154 (defvar yas--load-file-name load-file-name
155 "Store the filename that yasnippet.el was originally loaded from.")
156
157 (defcustom yas-snippet-dirs (remove nil
158 (list "~/.emacs.d/snippets"
159 (when yas--load-file-name
160 (concat (file-name-directory yas--load-file-name) "snippets"))))
161 "Directory or list of snippet dirs for each major mode.
162
163 The directory where user-created snippets are to be stored. Can
164 also be a list of directories. In that case, when used for
165 bulk (re)loading of snippets (at startup or via
166 `yas-reload-all'), directories appearing earlier in the list
167 shadow other dir's snippets. Also, the first directory is taken
168 as the default for storing the user's new snippets."
169 :type '(choice (string :tag "Single directory (string)")
170 (repeat :args (string) :tag "List of directories (strings)"))
171 :group 'yasnippet
172 :require 'yasnippet
173 :set #'(lambda (symbol new)
174 (let ((old (and (boundp symbol)
175 (symbol-value symbol))))
176 (set-default symbol new)
177 (unless (or (not (fboundp 'yas-reload-all))
178 (equal old new))
179 (yas-reload-all)))))
180
181 (defun yas-snippet-dirs ()
182 "Return `yas-snippet-dirs' (which see) as a list."
183 (if (listp yas-snippet-dirs) yas-snippet-dirs (list yas-snippet-dirs)))
184
185 (defvaralias 'yas/root-directory 'yas-snippet-dirs)
186
187 (defcustom yas-new-snippet-default "\
188 # -*- mode: snippet -*-
189 # name: $1
190 # key: ${2:${1:$(yas--key-from-desc yas-text)}}${3:
191 # binding: ${4:direct-keybinding}}${5:
192 # expand-env: ((${6:some-var} ${7:some-value}))}${8:
193 # type: command}
194 # --
195 $0"
196 "Default snippet to use when creating a new snippet.
197 If nil, don't use any snippet."
198 :type 'string
199 :group 'yasnippet)
200
201 (defcustom yas-prompt-functions '(yas-x-prompt
202 yas-dropdown-prompt
203 yas-completing-prompt
204 yas-ido-prompt
205 yas-no-prompt)
206 "Functions to prompt for keys, templates, etc interactively.
207
208 These functions are called with the following arguments:
209
210 - PROMPT: A string to prompt the user
211
212 - CHOICES: a list of strings or objects.
213
214 - optional DISPLAY-FN : A function that, when applied to each of
215 the objects in CHOICES will return a string.
216
217 The return value of any function you put here should be one of
218 the objects in CHOICES, properly formatted with DISPLAY-FN (if
219 that is passed).
220
221 - To signal that your particular style of prompting is
222 unavailable at the moment, you can also have the function return
223 nil.
224
225 - To signal that the user quit the prompting process, you can
226 signal `quit' with
227
228 (signal 'quit \"user quit!\")."
229 :type '(repeat function)
230 :group 'yasnippet)
231
232 (defcustom yas-indent-line 'auto
233 "Controls indenting applied to a recent snippet expansion.
234
235 The following values are possible:
236
237 - `fixed' Indent the snippet to the current column;
238
239 - `auto' Indent each line of the snippet with `indent-according-to-mode'
240
241 Every other value means don't apply any snippet-side indentation
242 after expansion (the manual per-line \"$>\" indentation still
243 applies)."
244 :type '(choice (const :tag "Nothing" nothing)
245 (const :tag "Fixed" fixed)
246 (const :tag "Auto" auto))
247 :group 'yasnippet)
248
249 (defcustom yas-also-auto-indent-first-line nil
250 "Non-nil means also auto indent first line according to mode.
251
252 Naturally this is only valid when `yas-indent-line' is `auto'"
253 :type 'boolean
254 :group 'yasnippet)
255
256 (defcustom yas-snippet-revival t
257 "Non-nil means re-activate snippet fields after undo/redo."
258 :type 'boolean
259 :group 'yasnippet)
260
261 (defcustom yas-triggers-in-field nil
262 "If non-nil, allow stacked expansions (snippets inside snippets).
263
264 Otherwise `yas-next-field-or-maybe-expand' just moves on to the
265 next field"
266 :type 'boolean
267 :group 'yasnippet)
268
269 (defcustom yas-fallback-behavior 'call-other-command
270 "How to act when `yas-expand' does *not* expand a snippet.
271
272 - `call-other-command' means try to temporarily disable YASnippet
273 and call the next command bound to whatever key was used to
274 invoke `yas-expand'.
275
276 - nil or the symbol `return-nil' mean do nothing. (and
277 `yas-expand' returns nil)
278
279 - A Lisp form (apply COMMAND . ARGS) means interactively call
280 COMMAND, if ARGS is non-nil, call COMMAND non-interactively
281 with ARGS as arguments."
282 :type '(choice (const :tag "Call previous command" call-other-command)
283 (const :tag "Do nothing" return-nil))
284 :group 'yasnippet)
285
286 (defcustom yas-choose-keys-first nil
287 "If non-nil, prompt for snippet key first, then for template.
288
289 Otherwise prompts for all possible snippet names.
290
291 This affects `yas-insert-snippet' and `yas-visit-snippet-file'."
292 :type 'boolean
293 :group 'yasnippet)
294
295 (defcustom yas-choose-tables-first nil
296 "If non-nil, and multiple eligible snippet tables, prompts user for tables first.
297
298 Otherwise, user chooses between the merging together of all
299 eligible tables.
300
301 This affects `yas-insert-snippet', `yas-visit-snippet-file'"
302 :type 'boolean
303 :group 'yasnippet)
304
305 (defcustom yas-use-menu 'abbreviate
306 "Display a YASnippet menu in the menu bar.
307
308 When non-nil, submenus for each snippet table will be listed
309 under the menu \"Yasnippet\".
310
311 - If set to `abbreviate', only the current major-mode
312 menu and the modes set in `yas-extra-modes' are listed.
313
314 - If set to `full', every submenu is listed
315
316 - It set to nil, don't display a menu at all (this requires a
317 `yas-reload-all' call if the menu is already visible).
318
319 Any other non-nil value, every submenu is listed."
320 :type '(choice (const :tag "Full" full)
321 (const :tag "Abbreviate" abbreviate)
322 (const :tag "No menu" nil))
323 :group 'yasnippet)
324
325 (defcustom yas-trigger-symbol (or (and (eq window-system 'mac)
326 (ignore-errors
327 (char-to-string ?\x21E5))) ;; little ->| sign
328 " =>")
329 "The text that will be used in menu to represent the trigger."
330 :type 'string
331 :group 'yasnippet)
332
333 (defcustom yas-wrap-around-region nil
334 "If non-nil, snippet expansion wraps around selected region.
335
336 The wrapping occurs just before the snippet's exit marker. This
337 can be overridden on a per-snippet basis."
338 :type 'boolean
339 :group 'yasnippet)
340
341 (defcustom yas-good-grace t
342 "If non-nil, don't raise errors in inline elisp evaluation.
343
344 An error string \"[yas] error\" is returned instead."
345 :type 'boolean
346 :group 'yasnippet)
347
348 (defcustom yas-visit-from-menu nil
349 "If non-nil visit snippets's files from menu, instead of expanding them.
350
351 This can only work when snippets are loaded from files."
352 :type 'boolean
353 :group 'yasnippet)
354
355 (defcustom yas-expand-only-for-last-commands nil
356 "List of `last-command' values to restrict tab-triggering to, or nil.
357
358 Leave this set at nil (the default) to be able to trigger an
359 expansion simply by placing the cursor after a valid tab trigger,
360 using whichever commands.
361
362 Optionally, set this to something like '(self-insert-command) if
363 you to wish restrict expansion to only happen when the last
364 letter of the snippet tab trigger was typed immediately before
365 the trigger key itself."
366 :type '(repeat function)
367 :group 'yasnippet)
368
369 ;; Only two faces, and one of them shouldn't even be used...
370 ;;
371 (defface yas-field-highlight-face
372 '((t (:inherit 'region)))
373 "The face used to highlight the currently active field of a snippet"
374 :group 'yasnippet)
375
376 (defface yas--field-debug-face
377 '()
378 "The face used for debugging some overlays normally hidden"
379 :group 'yasnippet)
380
381 \f
382 ;;; User-visible variables
383
384 (defvar yas-keymap (let ((map (make-sparse-keymap)))
385 (define-key map [(tab)] 'yas-next-field-or-maybe-expand)
386 (define-key map (kbd "TAB") 'yas-next-field-or-maybe-expand)
387 (define-key map [(shift tab)] 'yas-prev-field)
388 (define-key map [backtab] 'yas-prev-field)
389 (define-key map (kbd "C-g") 'yas-abort-snippet)
390 (define-key map (kbd "C-d") 'yas-skip-and-clear-or-delete-char)
391 map)
392 "The active keymap while a snippet expansion is in progress.")
393
394 (defvar yas-key-syntaxes (list "w" "w_" "w_." "w_.()" "^ ")
395 "List of character syntaxes used to find a trigger key before point.
396 The list is tried in the order while scanning characters
397 backwards from point. For example, if the list is '(\"w\" \"w_\")
398 first look for trigger keys which are composed exclusively of
399 \"word\"-syntax characters, and then, if that fails, look for
400 keys which are either of \"word\" or \"symbol\"
401 syntax. Triggering after
402
403 foo-bar
404
405 will, according to the \"w\" element first try \"bar\". If that
406 isn't a trigger key, \"foo-bar\" is tried, respecting a second
407 \"w_\" element.")
408
409 (defvar yas-after-exit-snippet-hook
410 '()
411 "Hooks to run after a snippet exited.
412
413 The hooks will be run in an environment where some variables bound to
414 proper values:
415
416 `yas-snippet-beg' : The beginning of the region of the snippet.
417
418 `yas-snippet-end' : Similar to beg.
419
420 Attention: These hooks are not run when exiting nested/stacked snippet expansion!")
421
422 (defvar yas-before-expand-snippet-hook
423 '()
424 "Hooks to run just before expanding a snippet.")
425
426 (defvar yas-buffer-local-condition
427 '(if (and (or (fourth (syntax-ppss))
428 (fifth (syntax-ppss)))
429 this-command
430 (eq this-command 'yas-expand-from-trigger-key))
431 '(require-snippet-condition . force-in-comment)
432 t)
433 "Snippet expanding condition.
434
435 This variable is a Lisp form which is evaluated every time a
436 snippet expansion is attempted:
437
438 * If it evaluates to nil, no snippets can be expanded.
439
440 * If it evaluates to the a cons (require-snippet-condition
441 . REQUIREMENT)
442
443 * Snippets bearing no \"# condition:\" directive are not
444 considered
445
446 * Snippets bearing conditions that evaluate to nil (or
447 produce an error) won't be considered.
448
449 * If the snippet has a condition that evaluates to non-nil
450 RESULT:
451
452 * If REQUIREMENT is t, the snippet is considered
453
454 * If REQUIREMENT is `eq' RESULT, the snippet is
455 considered
456
457 * Otherwise, the snippet is not considered.
458
459 * If it evaluates to the symbol 'always, all snippets are
460 considered for expansion, regardless of any conditions.
461
462 * If it evaluates to t or some other non-nil value
463
464 * Snippet bearing no conditions, or conditions that
465 evaluate to non-nil, are considered for expansion.
466
467 * Otherwise, the snippet is not considered.
468
469 Here's an example preventing snippets from being expanded from
470 inside comments, in `python-mode' only, with the exception of
471 snippets returning the symbol 'force-in-comment in their
472 conditions.
473
474 (add-hook 'python-mode-hook
475 '(lambda ()
476 (setq yas-buffer-local-condition
477 '(if (python-in-string/comment)
478 '(require-snippet-condition . force-in-comment)
479 t))))
480
481 The default value is similar, it filters out potential snippet
482 expansions inside comments and string literals, unless the
483 snippet itself contains a condition that returns the symbol
484 `force-in-comment'.")
485
486 \f
487 ;;; Internal variables
488
489 (defvar yas--version "0.8.0beta")
490
491 (defvar yas--menu-table (make-hash-table)
492 "A hash table of MAJOR-MODE symbols to menu keymaps.")
493
494 (defvar yas--known-modes
495 '(ruby-mode rst-mode markdown-mode)
496 "A list of mode which is well known but not part of Emacs.")
497
498 (defvar yas--escaped-characters
499 '(?\\ ?` ?\" ?' ?$ ?} ?{ ?\( ?\))
500 "List of characters which *might* need to be escaped.")
501
502 (defconst yas--field-regexp
503 "${\\([0-9]+:\\)?\\([^}]*\\)}"
504 "A regexp to *almost* recognize a field.")
505
506 (defconst yas--multi-dollar-lisp-expression-regexp
507 "$+[ \t\n]*\\(([^)]*)\\)"
508 "A regexp to *almost* recognize a \"$(...)\" expression.")
509
510 (defconst yas--backquote-lisp-expression-regexp
511 "`\\([^`]*\\)`"
512 "A regexp to recognize a \"`lisp-expression`\" expression." )
513
514 (defconst yas--transform-mirror-regexp
515 "${\\(?:\\([0-9]+\\):\\)?$\\([ \t\n]*([^}]*\\)"
516 "A regexp to *almost* recognize a mirror with a transform.")
517
518 (defconst yas--simple-mirror-regexp
519 "$\\([0-9]+\\)"
520 "A regexp to recognize a simple mirror.")
521
522 (defvar yas--snippet-id-seed 0
523 "Contains the next id for a snippet.")
524
525 (defun yas--snippet-next-id ()
526 (let ((id yas--snippet-id-seed))
527 (incf yas--snippet-id-seed)
528 id))
529
530 \f
531 ;;; Minor mode stuff
532
533 ;; XXX: `last-buffer-undo-list' is somehow needed in Carbon Emacs for MacOSX
534 (defvar last-buffer-undo-list nil)
535
536 (defvar yas--minor-mode-menu nil
537 "Holds the YASnippet menu.")
538
539 (defun yas--init-minor-keymap ()
540 "Set up the `yas-minor-mode' keymap."
541 (let ((map (make-sparse-keymap)))
542 (when yas-use-menu
543 (easy-menu-define yas--minor-mode-menu
544 map
545 "Menu used when `yas-minor-mode' is active."
546 '("YASnippet"
547 "----"
548 ["Expand trigger" yas-expand
549 :help "Possibly expand tab trigger before point"]
550 ["Insert at point..." yas-insert-snippet
551 :help "Prompt for an expandable snippet and expand it at point"]
552 ["New snippet..." yas-new-snippet
553 :help "Create a new snippet in an appropriate directory"]
554 ["Visit snippet file..." yas-visit-snippet-file
555 :help "Prompt for an expandable snippet and find its file"]
556 "----"
557 ("Snippet menu behaviour"
558 ["Visit snippets" (setq yas-visit-from-menu t)
559 :help "Visit snippets from the menu"
560 :active t :style radio :selected yas-visit-from-menu]
561 ["Expand snippets" (setq yas-visit-from-menu nil)
562 :help "Expand snippets from the menu"
563 :active t :style radio :selected (not yas-visit-from-menu)]
564 "----"
565 ["Show all known modes" (setq yas-use-menu 'full)
566 :help "Show one snippet submenu for each loaded table"
567 :active t :style radio :selected (eq yas-use-menu 'full)]
568 ["Abbreviate according to current mode" (setq yas-use-menu 'abbreviate)
569 :help "Show only snippet submenus for the current active modes"
570 :active t :style radio :selected (eq yas-use-menu 'abbreviate)])
571 ("Indenting"
572 ["Auto" (setq yas-indent-line 'auto)
573 :help "Indent each line of the snippet with `indent-according-to-mode'"
574 :active t :style radio :selected (eq yas-indent-line 'auto)]
575 ["Fixed" (setq yas-indent-line 'fixed)
576 :help "Indent the snippet to the current column"
577 :active t :style radio :selected (eq yas-indent-line 'fixed)]
578 ["None" (setq yas-indent-line 'none)
579 :help "Don't apply any particular snippet indentation after expansion"
580 :active t :style radio :selected (not (member yas-indent-line '(fixed auto)))]
581 "----"
582 ["Also auto indent first line" (setq yas-also-auto-indent-first-line
583 (not yas-also-auto-indent-first-line))
584 :help "When auto-indenting also, auto indent the first line menu"
585 :active (eq yas-indent-line 'auto)
586 :style toggle :selected yas-also-auto-indent-first-line]
587 )
588 ("Prompting method"
589 ["System X-widget" (setq yas-prompt-functions
590 (cons 'yas-x-prompt
591 (remove 'yas-x-prompt
592 yas-prompt-functions)))
593 :help "Use your windowing system's (gtk, mac, windows, etc...) default menu"
594 :active t :style radio :selected (eq (car yas-prompt-functions)
595 'yas-x-prompt)]
596 ["Dropdown-list" (setq yas-prompt-functions
597 (cons 'yas-dropdown-prompt
598 (remove 'yas-dropdown-prompt
599 yas-prompt-functions)))
600 :help "Use a special dropdown list"
601 :active t :style radio :selected (eq (car yas-prompt-functions)
602 'yas-dropdown-prompt)]
603 ["Ido" (setq yas-prompt-functions
604 (cons 'yas-ido-prompt
605 (remove 'yas-ido-prompt
606 yas-prompt-functions)))
607 :help "Use an ido-style minibuffer prompt"
608 :active t :style radio :selected (eq (car yas-prompt-functions)
609 'yas-ido-prompt)]
610 ["Completing read" (setq yas-prompt-functions
611 (cons 'yas-completing-prompt
612 (remove 'yas-completing-prompt
613 yas-prompt-functions)))
614 :help "Use a normal minibuffer prompt"
615 :active t :style radio :selected (eq (car yas-prompt-functions)
616 'yas-completing-prompt)]
617 )
618 ("Misc"
619 ["Wrap region in exit marker"
620 (setq yas-wrap-around-region
621 (not yas-wrap-around-region))
622 :help "If non-nil automatically wrap the selected text in the $0 snippet exit"
623 :style toggle :selected yas-wrap-around-region]
624 ["Allow stacked expansions "
625 (setq yas-triggers-in-field
626 (not yas-triggers-in-field))
627 :help "If non-nil allow snippets to be triggered inside other snippet fields"
628 :style toggle :selected yas-triggers-in-field]
629 ["Revive snippets on undo "
630 (setq yas-snippet-revival
631 (not yas-snippet-revival))
632 :help "If non-nil allow snippets to become active again after undo"
633 :style toggle :selected yas-snippet-revival]
634 ["Good grace "
635 (setq yas-good-grace
636 (not yas-good-grace))
637 :help "If non-nil don't raise errors in bad embedded elisp in snippets"
638 :style toggle :selected yas-good-grace]
639 )
640 "----"
641 ["Load snippets..." yas-load-directory
642 :help "Load snippets from a specific directory"]
643 ["Reload everything" yas-reload-all
644 :help "Cleanup stuff, reload snippets, rebuild menus"]
645 ["About" yas-about
646 :help "Display some information about YASnippet"])))
647
648 ;; Now for the stuff that has direct keybindings
649 ;;
650 (define-key map [(tab)] 'yas-expand)
651 (define-key map (kbd "TAB") 'yas-expand)
652 (define-key map "\C-c&\C-s" 'yas-insert-snippet)
653 (define-key map "\C-c&\C-n" 'yas-new-snippet)
654 (define-key map "\C-c&\C-v" 'yas-visit-snippet-file)
655 map))
656
657 (defvar yas-minor-mode-map (yas--init-minor-keymap)
658 "The keymap used when `yas-minor-mode' is active.")
659
660 (defvar yas-extra-modes nil
661 "A list of modes for which to also lookup snippets.
662
663 This variable probably makes more sense as buffer-local, so
664 ensure your use `make-local-variable' when you set it.")
665
666 (defvar yas--tables (make-hash-table)
667 "A hash table of mode symbols to `yas--table' objects.")
668
669 (defvar yas--parents (make-hash-table)
670 "A hash table of mode symbols do lists of direct parent mode symbols.
671
672 This list is populated when reading the \".yas-parents\" files
673 found when traversing snippet directories with
674 `yas-load-directory'.
675
676 There might be additional parenting information stored in the
677 `derived-mode-parent' property of some mode symbols, but that is
678 not recorded here.")
679
680 (defvar yas--direct-keymaps (list)
681 "Keymap alist supporting direct snippet keybindings.
682
683 This variable is placed in `emulation-mode-map-alists'.
684
685 Its elements looks like (TABLE-NAME . KEYMAP). They're
686 instantiated on `yas-reload-all' but KEYMAP is added to only when
687 loading snippets. `yas--direct-TABLE-NAME' is then a variable set
688 buffer-locally when entering `yas-minor-mode'. KEYMAP binds all
689 defined direct keybindings to the command
690 `yas-expand-from-keymap' which then which snippet to expand.")
691
692 (defun yas-direct-keymaps-reload ()
693 "Force reload the direct keybinding for active snippet tables."
694 (interactive)
695 (setq yas--direct-keymaps nil)
696 (maphash #'(lambda (name table)
697 (push (cons (intern (format "yas--direct-%s" name))
698 (yas--table-direct-keymap table))
699 yas--direct-keymaps))
700 yas--tables))
701
702 (defun yas--modes-to-activate ()
703 "Compute list of mode symbols that are active for `yas-expand'
704 and friends."
705 (let (dfs)
706 (setq dfs (lambda (mode &optional explored)
707 (push mode explored)
708 (cons mode
709 (loop for neighbour
710 in (remove nil (cons (get mode
711 'derived-mode-parent)
712 (gethash mode yas--parents)))
713
714 unless (memq neighbour explored)
715 append (funcall dfs neighbour explored)))))
716 (remove-duplicates (append yas-extra-modes
717 (funcall dfs major-mode)))))
718
719 (defvar yas-minor-mode-hook nil
720 "Hook run when `yas-minor-mode' is turned on.")
721
722 ;;;###autoload
723 (define-minor-mode yas-minor-mode
724 "Toggle YASnippet mode.
725
726 When YASnippet mode is enabled, `yas-expand', normally bound to
727 the TAB key, expands snippets of code depending on the major
728 mode.
729
730 With no argument, this command toggles the mode.
731 positive prefix argument turns on the mode.
732 Negative prefix argument turns off the mode.
733
734 Key bindings:
735 \\{yas-minor-mode-map}"
736 nil
737 ;; The indicator for the mode line.
738 " yas"
739 :group 'yasnippet
740 (cond (yas-minor-mode
741 ;; Install the direct keymaps in `emulation-mode-map-alists'
742 ;; (we use `add-hook' even though it's not technically a hook,
743 ;; but it works). Then define variables named after modes to
744 ;; index `yas--direct-keymaps'.
745 ;;
746 ;; Also install the post-command-hook.
747 ;;
748 (add-hook 'emulation-mode-map-alists 'yas--direct-keymaps)
749 (add-hook 'post-command-hook 'yas--post-command-handler nil t)
750 ;; Set the `yas--direct-%s' vars for direct keymap expansion
751 ;;
752 (dolist (mode (yas--modes-to-activate))
753 (let ((name (intern (format "yas--direct-%s" mode))))
754 (set-default name nil)
755 (set (make-local-variable name) t)))
756 ;; Perform JIT loads
757 ;;
758 (yas--load-pending-jits))
759 (t
760 ;; Uninstall the direct keymaps and the post-command hook
761 ;;
762 (remove-hook 'post-command-hook 'yas--post-command-handler t)
763 (remove-hook 'emulation-mode-map-alists 'yas--direct-keymaps))))
764
765 (defvar yas-dont-activate '(minibufferp)
766 "If non-nil don't let `yas-global-mode' affect some buffers.
767
768 If a function of zero arguments, then its result is used.
769
770 If a list of functions, then all functions must return nil to
771 activate yas for this buffer.
772
773 In Emacsen <= 23, this variable is buffer-local. Because
774 `yas-minor-mode-on' is called by `yas-global-mode' after
775 executing the buffer's major mode hook, setting this variable
776 there is an effective way to define exceptions to the \"global\"
777 activation behaviour.
778
779 In Emacsen > 23, only the global value is used. To define
780 per-mode exceptions to the \"global\" activation behaviour, call
781 `yas-minor-mode' with a negative argument directily in the major
782 mode's hook.")
783 (unless (> emacs-major-version 23)
784 (with-no-warnings
785 (make-variable-buffer-local 'yas-dont-activate)))
786
787
788 (defun yas-minor-mode-on ()
789 "Turn on YASnippet minor mode.
790
791 Honour `yas-dont-activate', which see."
792 (interactive)
793 ;; Check `yas-dont-activate'
794 (unless (cond ((functionp yas-dont-activate)
795 (funcall yas-dont-activate))
796 ((consp yas-dont-activate)
797 (some #'funcall yas-dont-activate))
798 (yas-dont-activate))
799 (yas-minor-mode 1)))
800
801 ;;;###autoload
802 (define-globalized-minor-mode yas-global-mode yas-minor-mode yas-minor-mode-on
803 :group 'yasnippet
804 :require 'yasnippet)
805
806 (defun yas--global-mode-reload-with-jit-maybe ()
807 "Run `yas-reload-all' when `yas-global-mode' is on."
808 (when yas-global-mode (yas-reload-all)))
809
810 (add-hook 'yas-global-mode-hook 'yas--global-mode-reload-with-jit-maybe)
811
812 \f
813 ;;; Major mode stuff
814
815 (defvar yas--font-lock-keywords
816 (append '(("^#.*$" . font-lock-comment-face))
817 lisp-font-lock-keywords
818 lisp-font-lock-keywords-1
819 lisp-font-lock-keywords-2
820 '(("$\\([0-9]+\\)"
821 (0 font-lock-keyword-face)
822 (1 font-lock-string-face t))
823 ("${\\([0-9]+\\):?"
824 (0 font-lock-keyword-face)
825 (1 font-lock-warning-face t))
826 ("${" font-lock-keyword-face)
827 ("$[0-9]+?" font-lock-preprocessor-face)
828 ("\\(\\$(\\)" 1 font-lock-preprocessor-face)
829 ("}"
830 (0 font-lock-keyword-face)))))
831
832 (defvar snippet-mode-map
833 (let ((map (make-sparse-keymap)))
834 (easy-menu-define nil
835 map
836 "Menu used when snippet-mode is active."
837 (cons "Snippet"
838 (mapcar #'(lambda (ent)
839 (when (third ent)
840 (define-key map (third ent) (second ent)))
841 (vector (first ent) (second ent) t))
842 '(("Load this snippet" yas-load-snippet-buffer "\C-c\C-c")
843 ("Try out this snippet" yas-tryout-snippet "\C-c\C-t")))))
844 map)
845 "The keymap used when `snippet-mode' is active.")
846
847
848 (define-derived-mode snippet-mode text-mode "Snippet"
849 "A mode for editing yasnippets"
850 (setq font-lock-defaults '(yas--font-lock-keywords))
851 (set (make-local-variable 'require-final-newline) nil)
852 (set (make-local-variable 'comment-start) "#")
853 (set (make-local-variable 'comment-start-skip) "#+[\t ]*"))
854
855
856 \f
857 ;;; Internal structs for template management
858
859 (defstruct (yas--template (:constructor yas--make-blank-template))
860 "A template for a snippet."
861 key
862 content
863 name
864 condition
865 expand-env
866 file
867 keybinding
868 uuid
869 menu-binding-pair
870 group ;; as dictated by the #group: directive or .yas-make-groups
871 perm-group ;; as dictated by `yas-define-menu'
872 table
873 )
874
875 (defun yas--populate-template (template &rest args)
876 "Helper function to populate TEMPLATE with properties."
877 (while args
878 (aset template
879 (position (intern (substring (symbol-name (car args)) 1))
880 (mapcar #'car (get 'yas--template 'cl-struct-slots)))
881 (second args))
882 (setq args (cddr args)))
883 template)
884
885 (defstruct (yas--table (:constructor yas--make-snippet-table (name)))
886 "A table to store snippets for a particular mode.
887
888 Has the following fields:
889
890 `yas--table-name'
891
892 A symbol name normally corresponding to a major mode, but can
893 also be a pseudo major-mode to be referenced in
894 `yas-extra-modes', for example.
895
896 `yas--table-hash'
897
898 A hash table (KEY . NAMEHASH), known as the \"keyhash\". KEY is
899 a string or a vector, where the former is the snippet's trigger
900 and the latter means it's a direct keybinding. NAMEHASH is yet
901 another hash of (NAME . TEMPLATE) where NAME is the snippet's
902 name and TEMPLATE is a `yas--template' object.
903
904 `yas--table-direct-keymap'
905
906 A keymap for the snippets in this table that have direct
907 keybindings. This is kept in sync with the keyhash, i.e., all
908 the elements of the keyhash that are vectors appear here as
909 bindings to `yas-expand-from-keymap'.
910
911 `yas--table-uuidhash'
912
913 A hash table mapping snippets uuid's to the same `yas--template'
914 objects. A snippet uuid defaults to the snippet's name."
915 name
916 (hash (make-hash-table :test 'equal))
917 (uuidhash (make-hash-table :test 'equal))
918 (parents nil)
919 (direct-keymap (make-sparse-keymap)))
920
921 (defun yas--get-template-by-uuid (mode uuid)
922 "Find the snippet template in MODE by its UUID."
923 (let* ((table (gethash mode yas--tables mode)))
924 (when table
925 (gethash uuid (yas--table-uuidhash table)))))
926
927 ;; Apropos storing/updating in TABLE, this works in two steps:
928 ;;
929 ;; 1. `yas--remove-template-by-uuid' removes any
930 ;; keyhash-namehash-template mappings from TABLE, grabbing the
931 ;; snippet by its uuid. Also removes mappings from TABLE's
932 ;; `yas--table-direct-keymap' (FIXME: and should probably take care
933 ;; of potentially stale menu bindings right?.)
934 ;;
935 ;; 2. `yas--add-template' adds this all over again.
936 ;;
937 ;; Create a new or add to an existing keyhash-namehash mapping.
938 ;;
939 ;; For reference on understanding this, consider three snippet
940 ;; definitions:
941 ;;
942 ;; A: # name: The Foo
943 ;; # key: foo
944 ;; # binding: C-c M-l
945 ;;
946 ;; B: # name: Mrs Foo
947 ;; # key: foo
948 ;;
949 ;; C: # name: The Bar
950 ;; # binding: C-c M-l
951 ;;
952 ;; D: # name: Baz
953 ;; # key: baz
954 ;;
955 ;; keyhash namehashes(3) yas--template structs(4)
956 ;; -----------------------------------------------------
957 ;; __________
958 ;; / \
959 ;; "foo" ---> "The Foo" ---> [yas--template A] |
960 ;; "Mrs Foo" ---> [yas--template B] |
961 ;; |
962 ;; [C-c M-l] ---> "The Foo" -------------------------/
963 ;; "The Bar" ---> [yas--template C]
964 ;;
965 ;; "baz" ---> "Baz" ---> [yas--template D]
966 ;;
967 ;; Additionally, since uuid defaults to the name, we have a
968 ;; `yas--table-uuidhash' for TABLE
969 ;;
970 ;; uuidhash yas--template structs
971 ;; -------------------------------
972 ;; "The Foo" ---> [yas--template A]
973 ;; "Mrs Foo" ---> [yas--template B]
974 ;; "The Bar" ---> [yas--template C]
975 ;; "Baz" ---> [yas--template D]
976 ;;
977 ;; FIXME: the more I look at this data-structure the more I think I'm
978 ;; stupid. There has to be an easier way (but beware lots of code
979 ;; depends on this).
980 ;;
981 (defun yas--remove-template-by-uuid (table uuid)
982 "Remove from TABLE a template identified by UUID."
983 (let ((template (gethash uuid (yas--table-uuidhash table))))
984 (when template
985 (let* ((name (yas--template-name template))
986 (empty-keys nil))
987 ;; Remove the name from each of the targeted namehashes
988 ;;
989 (maphash #'(lambda (k v)
990 (let ((template (gethash name v)))
991 (when (and template
992 (eq uuid (yas--template-uuid template)))
993 (remhash name v)
994 (when (zerop (hash-table-count v))
995 (push k empty-keys)))))
996 (yas--table-hash table))
997 ;; Remove the namehash themselves if they've become empty
998 ;;
999 (dolist (key empty-keys)
1000 (when (vectorp key)
1001 (define-key (yas--table-direct-keymap table) key nil))
1002 (remhash key (yas--table-hash table)))
1003
1004 ;; Finally, remove the uuid from the uuidhash
1005 ;;
1006 (remhash uuid (yas--table-uuidhash table))))))
1007
1008 (defun yas--add-template (table template)
1009 "Store in TABLE the snippet template TEMPLATE.
1010
1011 KEY can be a string (trigger key) of a vector (direct
1012 keybinding)."
1013 (let ((name (yas--template-name template))
1014 (key (yas--template-key template))
1015 (keybinding (yas--template-keybinding template))
1016 (_menu-binding-pair (yas--template-menu-binding-pair-get-create template)))
1017 (dolist (k (remove nil (list key keybinding)))
1018 (puthash name
1019 template
1020 (or (gethash k
1021 (yas--table-hash table))
1022 (puthash k
1023 (make-hash-table :test 'equal)
1024 (yas--table-hash table))))
1025 (when (vectorp k)
1026 (define-key (yas--table-direct-keymap table) k 'yas-expand-from-keymap)))
1027
1028 ;; Update TABLE's `yas--table-uuidhash'
1029 (puthash (yas--template-uuid template)
1030 template
1031 (yas--table-uuidhash table))))
1032
1033 (defun yas--update-template (table template)
1034 "Add or update TEMPLATE in TABLE.
1035
1036 Also takes care of adding and updating to the associated menu."
1037 ;; Remove from table by uuid
1038 ;;
1039 (yas--remove-template-by-uuid table (yas--template-uuid template))
1040 ;; Add to table again
1041 ;;
1042 (yas--add-template table template)
1043 ;; Take care of the menu
1044 ;;
1045 (when yas-use-menu
1046 (yas--update-template-menu table template)))
1047
1048 (defun yas--update-template-menu (table template)
1049 "Update every menu-related for TEMPLATE."
1050 (let ((menu-binding-pair (yas--template-menu-binding-pair-get-create template))
1051 (key (yas--template-key template))
1052 (keybinding (yas--template-keybinding template)))
1053 ;; The snippet might have changed name or keys, so update
1054 ;; user-visible strings
1055 ;;
1056 (unless (eq (cdr menu-binding-pair) :none)
1057 ;; the menu item name
1058 ;;
1059 (setf (cadar menu-binding-pair) (yas--template-name template))
1060 ;; the :keys information (also visible to the user)
1061 (setf (getf (cdr (car menu-binding-pair)) :keys)
1062 (or (and keybinding (key-description keybinding))
1063 (and key (concat key yas-trigger-symbol))))))
1064 (unless (yas--template-menu-managed-by-yas-define-menu template)
1065 (let ((menu-keymap
1066 (yas--menu-keymap-get-create (yas--table-mode table)
1067 (mapcar #'yas--table-mode
1068 (yas--table-parents table))))
1069 (group (yas--template-group template)))
1070 ;; Remove from menu keymap
1071 ;;
1072 (assert menu-keymap)
1073 (yas--delete-from-keymap menu-keymap (yas--template-uuid template))
1074
1075 ;; Add necessary subgroups as necessary.
1076 ;;
1077 (dolist (subgroup group)
1078 (let ((subgroup-keymap (lookup-key menu-keymap (vector (make-symbol subgroup)))))
1079 (unless (and subgroup-keymap
1080 (keymapp subgroup-keymap))
1081 (setq subgroup-keymap (make-sparse-keymap))
1082 (define-key menu-keymap (vector (make-symbol subgroup))
1083 `(menu-item ,subgroup ,subgroup-keymap)))
1084 (setq menu-keymap subgroup-keymap)))
1085
1086 ;; Add this entry to the keymap
1087 ;;
1088 (define-key menu-keymap
1089 (vector (make-symbol (yas--template-uuid template)))
1090 (car (yas--template-menu-binding-pair template))))))
1091
1092 (defun yas--namehash-templates-alist (namehash)
1093 "Return NAMEHASH as an alist."
1094 (let (alist)
1095 (maphash #'(lambda (k v)
1096 (push (cons k v) alist))
1097 namehash)
1098 alist))
1099
1100 (defun yas--fetch (table key)
1101 "Fetch templates in TABLE by KEY.
1102
1103 Return a list of cons (NAME . TEMPLATE) where NAME is a
1104 string and TEMPLATE is a `yas--template' structure."
1105 (let* ((keyhash (yas--table-hash table))
1106 (namehash (and keyhash (gethash key keyhash))))
1107 (when namehash
1108 (yas--filter-templates-by-condition (yas--namehash-templates-alist namehash)))))
1109
1110 \f
1111 ;;; Filtering/condition logic
1112
1113 (defun yas--eval-condition (condition)
1114 (condition-case err
1115 (save-excursion
1116 (save-restriction
1117 (save-match-data
1118 (eval condition))))
1119 (error (progn
1120 (yas--message 1 "Error in condition evaluation: %s" (error-message-string err))
1121 nil))))
1122
1123
1124 (defun yas--filter-templates-by-condition (templates)
1125 "Filter the templates using the applicable condition.
1126
1127 TEMPLATES is a list of cons (NAME . TEMPLATE) where NAME is a
1128 string and TEMPLATE is a `yas--template' structure.
1129
1130 This function implements the rules described in
1131 `yas-buffer-local-condition'. See that variables documentation."
1132 (let ((requirement (yas--require-template-specific-condition-p)))
1133 (if (eq requirement 'always)
1134 templates
1135 (remove-if-not #'(lambda (pair)
1136 (yas--template-can-expand-p
1137 (yas--template-condition (cdr pair)) requirement))
1138 templates))))
1139
1140 (defun yas--require-template-specific-condition-p ()
1141 "Decide if this buffer requests/requires snippet-specific
1142 conditions to filter out potential expansions."
1143 (if (eq 'always yas-buffer-local-condition)
1144 'always
1145 (let ((local-condition (or (and (consp yas-buffer-local-condition)
1146 (yas--eval-condition yas-buffer-local-condition))
1147 yas-buffer-local-condition)))
1148 (when local-condition
1149 (if (eq local-condition t)
1150 t
1151 (and (consp local-condition)
1152 (eq 'require-snippet-condition (car local-condition))
1153 (symbolp (cdr local-condition))
1154 (cdr local-condition)))))))
1155
1156 (defun yas--template-can-expand-p (condition requirement)
1157 "Evaluate CONDITION and REQUIREMENT and return a boolean."
1158 (let* ((result (or (null condition)
1159 (yas--eval-condition condition))))
1160 (cond ((eq requirement t)
1161 result)
1162 (t
1163 (eq requirement result)))))
1164
1165 (defun yas--table-templates (table)
1166 (when table
1167 (let ((acc (list)))
1168 (maphash #'(lambda (_key namehash)
1169 (maphash #'(lambda (name template)
1170 (push (cons name template) acc))
1171 namehash))
1172 (yas--table-hash table))
1173 (yas--filter-templates-by-condition acc))))
1174
1175 (defun yas--current-key ()
1176 "Get the key under current position.
1177 A key is used to find the template of a snippet in the current snippet-table."
1178 (let ((start (point))
1179 (end (point))
1180 (syntaxes yas-key-syntaxes)
1181 syntax
1182 done
1183 templates)
1184 (while (and (not done) syntaxes)
1185 (setq syntax (car syntaxes))
1186 (setq syntaxes (cdr syntaxes))
1187 (save-excursion
1188 (skip-syntax-backward syntax)
1189 (setq start (point)))
1190 (setq templates
1191 (mapcan #'(lambda (table)
1192 (yas--fetch table (buffer-substring-no-properties start end)))
1193 (yas--get-snippet-tables)))
1194 (if templates
1195 (setq done t)
1196 (setq start end)))
1197 (list templates
1198 start
1199 end)))
1200
1201
1202 (defun yas--table-all-keys (table)
1203 "Get trigger keys of all active snippets in TABLE."
1204 (let ((acc))
1205 (maphash #'(lambda (key namehash)
1206 (when (yas--filter-templates-by-condition (yas--namehash-templates-alist namehash))
1207 (push key acc)))
1208 (yas--table-hash table))
1209 acc))
1210
1211 (defun yas--table-mode (table)
1212 (intern (yas--table-name table)))
1213
1214 \f
1215 ;;; Internal functions and macros:
1216
1217 (defun yas--real-mode? (mode)
1218 "Try to find out if MODE is a real mode.
1219
1220 The MODE bound to a function (like `c-mode') is considered real
1221 mode. Other well known mode like `ruby-mode' which is not part of
1222 Emacs might not bound to a function until it is loaded. So
1223 yasnippet keeps a list of modes like this to help the judgment."
1224 (or (fboundp mode)
1225 (find mode yas--known-modes)))
1226
1227 (defun yas--eval-lisp (form)
1228 "Evaluate FORM and convert the result to string."
1229 (let ((retval (catch 'yas--exception
1230 (condition-case err
1231 (save-excursion
1232 (save-restriction
1233 (save-match-data
1234 (widen)
1235 (let ((result (eval form)))
1236 (when result
1237 (format "%s" result))))))
1238 (error (if yas-good-grace
1239 (yas--format "elisp error! %s" (error-message-string err))
1240 (error (yas--format "elisp error: %s"
1241 (error-message-string err)))))))))
1242 (when (and (consp retval)
1243 (eq 'yas--exception (car retval)))
1244 (error (cdr retval)))
1245 retval))
1246
1247 (defun yas--eval-lisp-no-saves (form)
1248 (condition-case err
1249 (eval form)
1250 (error (if yas-good-grace
1251 (yas--format "elisp error! %s" (error-message-string err))
1252 (error (yas--format "elisp error: %s"
1253 (error-message-string err)))))))
1254
1255 (defun yas--read-lisp (string &optional nil-on-error)
1256 "Read STRING as a elisp expression and return it.
1257
1258 In case STRING in an invalid expression and NIL-ON-ERROR is nil,
1259 return an expression that when evaluated will issue an error."
1260 (condition-case err
1261 (read string)
1262 (error (and (not nil-on-error)
1263 `(error (error-message-string ,err))))))
1264
1265 (defun yas--read-keybinding (keybinding)
1266 "Read KEYBINDING as a snippet keybinding, return a vector."
1267 (when (and keybinding
1268 (not (string-match "keybinding" keybinding)))
1269 (condition-case err
1270 (let ((res (or (and (string-match "^\\[.*\\]$" keybinding)
1271 (read keybinding))
1272 (read-kbd-macro keybinding 'need-vector))))
1273 res)
1274 (error
1275 (yas--message 3 "warning: keybinding \"%s\" invalid since %s."
1276 keybinding (error-message-string err))
1277 nil))))
1278
1279 (defun yas--table-get-create (mode)
1280 "Get or create the snippet table corresponding to MODE."
1281 (let ((table (gethash mode
1282 yas--tables)))
1283 (unless table
1284 (setq table (yas--make-snippet-table (symbol-name mode)))
1285 (puthash mode table yas--tables)
1286 (push (cons (intern (format "yas--direct-%s" mode))
1287 (yas--table-direct-keymap table))
1288 yas--direct-keymaps))
1289 table))
1290
1291 (defun yas--get-snippet-tables ()
1292 "Get snippet tables for current buffer.
1293
1294 Return a list of `yas--table' objects. The list of modes to
1295 consider is returned by `yas--modes-to-activate'"
1296 (remove nil
1297 (mapcar #'(lambda (name)
1298 (gethash name yas--tables))
1299 (yas--modes-to-activate))))
1300
1301 (defun yas--menu-keymap-get-create (mode &optional parents)
1302 "Get or create the menu keymap for MODE and its PARENTS.
1303
1304 This may very well create a plethora of menu keymaps and arrange
1305 them all in `yas--menu-table'"
1306 (let* ((menu-keymap (or (gethash mode yas--menu-table)
1307 (puthash mode (make-sparse-keymap) yas--menu-table))))
1308 (mapc #'yas--menu-keymap-get-create parents)
1309 (define-key yas--minor-mode-menu (vector mode)
1310 `(menu-item ,(symbol-name mode) ,menu-keymap
1311 :visible (yas--show-menu-p ',mode)))
1312 menu-keymap))
1313
1314
1315 (defmacro yas--called-interactively-p (&optional kind)
1316 "A backward-compatible version of `called-interactively-p'.
1317
1318 Optional KIND is as documented at `called-interactively-p'
1319 in GNU Emacs 24.1 or higher."
1320 (if (string< emacs-version "24.1")
1321 '(called-interactively-p)
1322 `(called-interactively-p ,kind)))
1323
1324 \f
1325 ;;; Template-related and snippet loading functions
1326
1327 (defun yas--parse-template (&optional file)
1328 "Parse the template in the current buffer.
1329
1330 Optional FILE is the absolute file name of the file being
1331 parsed.
1332
1333 Optional GROUP is the group where the template is to go,
1334 otherwise we attempt to calculate it from FILE.
1335
1336 Return a snippet-definition, i.e. a list
1337
1338 (KEY TEMPLATE NAME CONDITION GROUP VARS FILE KEYBINDING UUID)
1339
1340 If the buffer contains a line of \"# --\" then the contents above
1341 this line are ignored. Directives can set most of these with the syntax:
1342
1343 # directive-name : directive-value
1344
1345 Here's a list of currently recognized directives:
1346
1347 * type
1348 * name
1349 * contributor
1350 * condition
1351 * group
1352 * key
1353 * expand-env
1354 * binding
1355 * uuid"
1356 (goto-char (point-min))
1357 (let* ((type 'snippet)
1358 (name (and file
1359 (file-name-nondirectory file)))
1360 (key nil)
1361 template
1362 bound
1363 condition
1364 (group (and file
1365 (yas--calculate-group file)))
1366 expand-env
1367 binding
1368 uuid)
1369 (if (re-search-forward "^# --\n" nil t)
1370 (progn (setq template
1371 (buffer-substring-no-properties (point)
1372 (point-max)))
1373 (setq bound (point))
1374 (goto-char (point-min))
1375 (while (re-search-forward "^# *\\([^ ]+?\\) *: *\\(.*\\)$" bound t)
1376 (when (string= "uuid" (match-string-no-properties 1))
1377 (setq uuid (match-string-no-properties 2)))
1378 (when (string= "type" (match-string-no-properties 1))
1379 (setq type (if (string= "command" (match-string-no-properties 2))
1380 'command
1381 'snippet)))
1382 (when (string= "key" (match-string-no-properties 1))
1383 (setq key (match-string-no-properties 2)))
1384 (when (string= "name" (match-string-no-properties 1))
1385 (setq name (match-string-no-properties 2)))
1386 (when (string= "condition" (match-string-no-properties 1))
1387 (setq condition (yas--read-lisp (match-string-no-properties 2))))
1388 (when (string= "group" (match-string-no-properties 1))
1389 (setq group (match-string-no-properties 2)))
1390 (when (string= "expand-env" (match-string-no-properties 1))
1391 (setq expand-env (yas--read-lisp (match-string-no-properties 2)
1392 'nil-on-error)))
1393 (when (string= "binding" (match-string-no-properties 1))
1394 (setq binding (match-string-no-properties 2)))))
1395 (setq template
1396 (buffer-substring-no-properties (point-min) (point-max))))
1397 (unless (or key binding)
1398 (setq key (and file (file-name-nondirectory file))))
1399 (when (eq type 'command)
1400 (setq template (yas--read-lisp (concat "(progn" template ")"))))
1401 (when group
1402 (setq group (split-string group "\\.")))
1403 (list key template name condition group expand-env file binding uuid)))
1404
1405 (defun yas--calculate-group (file)
1406 "Calculate the group for snippet file path FILE."
1407 (let* ((dominating-dir (locate-dominating-file file
1408 ".yas-make-groups"))
1409 (extra-path (and dominating-dir
1410 (replace-regexp-in-string (concat "^"
1411 (expand-file-name dominating-dir))
1412 ""
1413 (expand-file-name file))))
1414 (extra-dir (and extra-path
1415 (file-name-directory extra-path)))
1416 (group (and extra-dir
1417 (replace-regexp-in-string "/"
1418 "."
1419 (directory-file-name extra-dir)))))
1420 group))
1421
1422 (defun yas--subdirs (directory &optional filep)
1423 "Return subdirs or files of DIRECTORY according to FILEP."
1424 (remove-if (lambda (file)
1425 (or (string-match "^\\."
1426 (file-name-nondirectory file))
1427 (string-match "^#.*#$"
1428 (file-name-nondirectory file))
1429 (string-match "~$"
1430 (file-name-nondirectory file))
1431 (if filep
1432 (file-directory-p file)
1433 (not (file-directory-p file)))))
1434 (directory-files directory t)))
1435
1436 (defun yas--make-menu-binding (template)
1437 (let ((mode (yas--table-mode (yas--template-table template))))
1438 `(lambda () (interactive) (yas--expand-or-visit-from-menu ',mode ,(yas--template-uuid template)))))
1439
1440 (defun yas--expand-or-visit-from-menu (mode uuid)
1441 (let* ((table (yas--table-get-create mode))
1442 (yas--current-template (and table
1443 (gethash uuid (yas--table-uuidhash table)))))
1444 (when yas--current-template
1445 (if yas-visit-from-menu
1446 (yas--visit-snippet-file-1 yas--current-template)
1447 (let ((where (if (region-active-p)
1448 (cons (region-beginning) (region-end))
1449 (cons (point) (point)))))
1450 (yas-expand-snippet (yas--template-content yas--current-template)
1451 (car where)
1452 (cdr where)
1453 (yas--template-expand-env yas--current-template)))))))
1454
1455 (defun yas--key-from-desc (text)
1456 "Return a yasnippet key from a description string TEXT."
1457 (replace-regexp-in-string "\\(\\w+\\).*" "\\1" text))
1458
1459 \f
1460 ;;; Popping up for keys and templates
1461
1462 (defvar yas--x-pretty-prompt-templates nil
1463 "If non-nil, attempt to prompt for templates like TextMate.")
1464
1465
1466 (defun yas--prompt-for-template (templates &optional prompt)
1467 "Interactively choose a template from the list TEMPLATES.
1468
1469 TEMPLATES is a list of `yas--template'.
1470
1471 Optional PROMPT sets the prompt to use."
1472 (when templates
1473 (setq templates
1474 (sort templates #'(lambda (t1 t2)
1475 (< (length (yas--template-name t1))
1476 (length (yas--template-name t2))))))
1477 (if yas--x-pretty-prompt-templates
1478 (yas--x-pretty-prompt-templates "Choose a snippet" templates)
1479 (some #'(lambda (fn)
1480 (funcall fn (or prompt "Choose a snippet: ")
1481 templates
1482 #'yas--template-name))
1483 yas-prompt-functions))))
1484
1485 (defun yas--prompt-for-keys (keys &optional prompt)
1486 "Interactively choose a template key from the list KEYS.
1487
1488 Optional PROMPT sets the prompt to use."
1489 (when keys
1490 (some #'(lambda (fn)
1491 (funcall fn (or prompt "Choose a snippet key: ") keys))
1492 yas-prompt-functions)))
1493
1494 (defun yas--prompt-for-table (tables &optional prompt)
1495 "Interactively choose a table from the list TABLES.
1496
1497 Optional PROMPT sets the prompt to use."
1498 (when tables
1499 (some #'(lambda (fn)
1500 (funcall fn (or prompt "Choose a snippet table: ")
1501 tables
1502 #'yas--table-name))
1503 yas-prompt-functions)))
1504
1505 (defun yas-x-prompt (prompt choices &optional display-fn)
1506 "Display choices in a x-window prompt."
1507 ;; FIXME: HACK: if we notice that one of the objects in choices is
1508 ;; actually a `yas--template', defer to `yas--x-prompt-pretty-templates'
1509 ;;
1510 ;; This would be better implemented by passing CHOICES as a
1511 ;; structured tree rather than a list. Modifications would go as far
1512 ;; up as `yas--all-templates' I think.
1513 ;;
1514 (when (and window-system choices)
1515 (let ((chosen
1516 (let (menu d) ;; d for display
1517 (dolist (c choices)
1518 (setq d (or (and display-fn (funcall display-fn c))
1519 c))
1520 (cond ((stringp d)
1521 (push (cons (concat " " d) c) menu))
1522 ((listp d)
1523 (push (car d) menu))))
1524 (setq menu (list prompt (push "title" menu)))
1525 (x-popup-menu (if (fboundp 'posn-at-point)
1526 (let ((x-y (posn-x-y (posn-at-point (point)))))
1527 (list (list (+ (car x-y) 10)
1528 (+ (cdr x-y) 20))
1529 (selected-window)))
1530 t)
1531 menu))))
1532 (or chosen
1533 (keyboard-quit)))))
1534
1535 (defun yas--x-pretty-prompt-templates (prompt templates)
1536 "Display TEMPLATES, grouping neatly by table name."
1537 (let ((organized (make-hash-table :test #'equal))
1538 menu
1539 more-than-one-table
1540 prefix)
1541 (dolist (tl templates)
1542 (puthash (yas--template-table tl)
1543 (cons tl
1544 (gethash (yas--template-table tl) organized))
1545 organized))
1546 (setq more-than-one-table (> (hash-table-count organized) 1))
1547 (setq prefix (if more-than-one-table
1548 " " ""))
1549 (if more-than-one-table
1550 (maphash #'(lambda (table templates)
1551 (push (yas--table-name table) menu)
1552 (dolist (tl templates)
1553 (push (cons (concat prefix (yas--template-name tl)) tl) menu))) organized)
1554 (setq menu (mapcar #'(lambda (tl) (cons (concat prefix (yas--template-name tl)) tl)) templates)))
1555
1556 (setq menu (nreverse menu))
1557 (or (x-popup-menu (if (fboundp 'posn-at-point)
1558 (let ((x-y (posn-x-y (posn-at-point (point)))))
1559 (list (list (+ (car x-y) 10)
1560 (+ (cdr x-y) 20))
1561 (selected-window)))
1562 t)
1563 (list prompt (push "title" menu)))
1564 (keyboard-quit))))
1565
1566 (defun yas-ido-prompt (prompt choices &optional display-fn)
1567 (when (and (fboundp 'ido-completing-read)
1568 (or (>= emacs-major-version 24)
1569 ido-mode))
1570 (yas-completing-prompt prompt choices display-fn #'ido-completing-read)))
1571
1572 (defun yas-dropdown-prompt (_prompt choices &optional display-fn)
1573 (when (fboundp 'dropdown-list)
1574 (let (formatted-choices
1575 filtered-choices
1576 d
1577 n)
1578 (dolist (choice choices)
1579 (setq d (or (and display-fn (funcall display-fn choice))
1580 choice))
1581 (when (stringp d)
1582 (push d formatted-choices)
1583 (push choice filtered-choices)))
1584
1585 (setq n (and formatted-choices (dropdown-list formatted-choices)))
1586 (if n
1587 (nth n filtered-choices)
1588 (keyboard-quit)))))
1589
1590 (defun yas-completing-prompt (prompt choices &optional display-fn completion-fn)
1591 (let (formatted-choices
1592 filtered-choices
1593 chosen
1594 d
1595 (completion-fn (or completion-fn
1596 #'completing-read)))
1597 (dolist (choice choices)
1598 (setq d (or (and display-fn (funcall display-fn choice))
1599 choice))
1600 (when (stringp d)
1601 (push d formatted-choices)
1602 (push choice filtered-choices)))
1603 (setq chosen (and formatted-choices
1604 (funcall completion-fn prompt
1605 formatted-choices
1606 nil
1607 'require-match
1608 nil
1609 nil)))
1610 (let ((position (or (and chosen
1611 (position chosen formatted-choices :test #'string=))
1612 0)))
1613 (nth position filtered-choices))))
1614
1615 (defun yas-no-prompt (_prompt choices &optional _display-fn)
1616 (first choices))
1617
1618 \f
1619 ;;; Defining snippets
1620 ;; This consists of creating and registering `yas--template' objects in the
1621 ;; correct tables.
1622 ;;
1623
1624 (defvar yas--creating-compiled-snippets nil)
1625
1626 (defun yas--define-snippets-1 (snippet snippet-table)
1627 "Helper for `yas-define-snippets'."
1628 ;; X) Calculate some more defaults on the values returned by
1629 ;; `yas--parse-template'.
1630 ;;
1631 (let* ((file (seventh snippet))
1632 (key (car snippet))
1633 (name (or (third snippet)
1634 (and file
1635 (file-name-directory file))))
1636 (condition (fourth snippet))
1637 (group (fifth snippet))
1638 (keybinding (yas--read-keybinding (eighth snippet)))
1639 (uuid (or (ninth snippet)
1640 name))
1641 (template (or (gethash uuid (yas--table-uuidhash snippet-table))
1642 (yas--make-blank-template))))
1643 ;; X) populate the template object
1644 ;;
1645 (yas--populate-template template
1646 :table snippet-table
1647 :key key
1648 :content (second snippet)
1649 :name (or name key)
1650 :group group
1651 :condition condition
1652 :expand-env (sixth snippet)
1653 :file (seventh snippet)
1654 :keybinding keybinding
1655 :uuid uuid)
1656 ;; X) Update this template in the appropriate table. This step
1657 ;; also will take care of adding the key indicators in the
1658 ;; templates menu entry, if any
1659 ;;
1660 (yas--update-template snippet-table template)
1661 ;; X) Return the template
1662 ;;
1663 ;;
1664 template))
1665
1666 (defun yas-define-snippets (mode snippets)
1667 "Define SNIPPETS for MODE.
1668
1669 SNIPPETS is a list of snippet definitions, each taking the
1670 following form
1671
1672 (KEY TEMPLATE NAME CONDITION GROUP EXPAND-ENV FILE KEYBINDING UUID)
1673
1674 Within these, only KEY and TEMPLATE are actually mandatory.
1675
1676 TEMPLATE might be a Lisp form or a string, depending on whether
1677 this is a snippet or a snippet-command.
1678
1679 CONDITION, EXPAND-ENV and KEYBINDING are Lisp forms, they have
1680 been `yas--read-lisp'-ed and will eventually be
1681 `yas--eval-lisp'-ed.
1682
1683 The remaining elements are strings.
1684
1685 FILE is probably of very little use if you're programatically
1686 defining snippets.
1687
1688 UUID is the snippets \"unique-id\". Loading a second snippet file
1689 with the same uuid replaced the previous snippet.
1690
1691 You can use `yas--parse-template' to return such lists based on
1692 the current buffers contents."
1693 (if yas--creating-compiled-snippets
1694 (progn
1695 (insert ";;; Snippet definitions:\n;;;\n")
1696 (let ((literal-snippets (list))
1697 (print-length nil))
1698 (dolist (snippet snippets)
1699 (let ((key (nth 0 snippet))
1700 (template-content (nth 1 snippet))
1701 (name (nth 2 snippet))
1702 (condition (nth 3 snippet))
1703 (group (nth 4 snippet))
1704 (expand-env (nth 5 snippet))
1705 (file nil) ;; omit on purpose
1706 (binding (nth 7 snippet))
1707 (uuid (nth 8 snippet)))
1708 (push `(,key
1709 ,template-content
1710 ,name
1711 ,condition
1712 ,group
1713 ,expand-env
1714 ,file
1715 ,binding
1716 ,uuid)
1717 literal-snippets)))
1718 (insert (pp-to-string
1719 `(yas-define-snippets ',mode ',literal-snippets)))
1720 (insert "\n\n")))
1721 ;; Normal case.
1722 (let ((snippet-table (yas--table-get-create mode))
1723 (template nil))
1724 (dolist (snippet snippets)
1725 (setq template (yas--define-snippets-1 snippet
1726 snippet-table)))
1727 template)))
1728
1729 \f
1730 ;;; Loading snippets from files
1731
1732 (defun yas--load-yas-setup-file (file)
1733 (if (not yas--creating-compiled-snippets)
1734 ;; Normal case.
1735 (load file 'noerror)
1736 (let ((elfile (concat file ".el")))
1737 (when (file-exists-p elfile)
1738 (insert ";;; .yas-setup.el support file if any:\n;;;\n")
1739 (insert-file-contents elfile)
1740 (goto-char (point-max))))))
1741
1742 (defun yas--define-parents (mode parents)
1743 "Add PARENTS to the list of MODE's parents."
1744 (puthash mode (remove-duplicates
1745 (append parents
1746 (gethash mode yas--parents)))
1747 yas--parents))
1748
1749 (defun yas-load-directory (top-level-dir &optional use-jit interactive)
1750 "Load snippets in directory hierarchy TOP-LEVEL-DIR.
1751
1752 Below TOP-LEVEL-DIR each directory should be a mode name.
1753
1754 Optional USE-JIT use jit-loading of snippets."
1755 (interactive "DSelect the root directory: ni\np")
1756 (unless yas-snippet-dirs
1757 (setq yas-snippet-dirs top-level-dir))
1758 (dolist (dir (yas--subdirs top-level-dir))
1759 (let* ((major-mode-and-parents (yas--compute-major-mode-and-parents
1760 (concat dir "/dummy")))
1761 (mode-sym (car major-mode-and-parents))
1762 (parents (cdr major-mode-and-parents)))
1763 ;; Attention: The parents and the menus are already defined
1764 ;; here, even if the snippets are later jit-loaded.
1765 ;;
1766 ;; * We need to know the parents at this point since entering a
1767 ;; given mode should jit load for its parents
1768 ;; immediately. This could be reviewed, the parents could be
1769 ;; discovered just-in-time-as well
1770 ;;
1771 ;; * We need to create the menus here to support the `full'
1772 ;; option to `yas-use-menu' (all known snippet menus are shown to the user)
1773 ;;
1774 (yas--define-parents mode-sym parents)
1775 (yas--menu-keymap-get-create mode-sym)
1776 (let ((fun `(lambda () ;; FIXME: Simulating lexical-binding.
1777 (yas--load-directory-1 ',dir ',mode-sym))))
1778 (if (and use-jit
1779 (not (some #'(lambda (buffer)
1780 (with-current-buffer buffer
1781 ;; FIXME: Shouldn't this use derived-mode-p?
1782 (when (eq major-mode mode-sym)
1783 (yas--message 3 "Discovered there was already %s in %s" buffer mode-sym)
1784 t)))
1785 (buffer-list))))
1786 (yas--schedule-jit mode-sym fun)
1787 (funcall fun)))))
1788 (when interactive
1789 (yas--message 3 "Loaded snippets from %s." top-level-dir)))
1790
1791 (defun yas--load-directory-1 (directory mode-sym)
1792 "Recursively load snippet templates from DIRECTORY."
1793 (if yas--creating-compiled-snippets
1794 (let ((output-file (expand-file-name ".yas-compiled-snippets.el"
1795 directory)))
1796 (with-temp-file output-file
1797 (insert (format ";;; Compiled snippets and support files for `%s'\n"
1798 mode-sym))
1799 (yas--load-directory-2 directory mode-sym)
1800 (insert (format ";;; Do not edit! File generated at %s\n"
1801 (current-time-string)))))
1802 ;; Normal case.
1803 (unless (file-exists-p (concat directory "/" ".yas-skip"))
1804 (if (and (progn (yas--message 2 "Loading compiled snippets from %s" directory) t)
1805 (load (expand-file-name ".yas-compiled-snippets" directory) 'noerror (<= yas-verbosity 3)))
1806 (yas--message 2 "Loading snippet files from %s" directory)
1807 (yas--load-directory-2 directory mode-sym)))))
1808
1809 (defun yas--load-directory-2 (directory mode-sym)
1810 ;; Load .yas-setup.el files wherever we find them
1811 ;;
1812 (yas--load-yas-setup-file (expand-file-name ".yas-setup" directory))
1813 (let* ((default-directory directory)
1814 (snippet-defs nil))
1815 ;; load the snippet files
1816 ;;
1817 (with-temp-buffer
1818 (dolist (file (yas--subdirs directory 'no-subdirs-just-files))
1819 (when (file-readable-p file)
1820 (insert-file-contents file nil nil nil t)
1821 (push (yas--parse-template file)
1822 snippet-defs))))
1823 (when snippet-defs
1824 (yas-define-snippets mode-sym
1825 snippet-defs))
1826 ;; now recurse to a lower level
1827 ;;
1828 (dolist (subdir (yas--subdirs directory))
1829 (yas--load-directory-2 subdir
1830 mode-sym))))
1831
1832 (defun yas--load-snippet-dirs (&optional nojit)
1833 "Reload the directories listed in `yas-snippet-dirs' or
1834 prompt the user to select one."
1835 (let (errors)
1836 (if yas-snippet-dirs
1837 (dolist (directory (reverse (yas-snippet-dirs)))
1838 (cond ((file-directory-p directory)
1839 (yas-load-directory directory (not nojit))
1840 (if nojit
1841 (yas--message 3 "Loaded %s" directory)
1842 (yas--message 3 "Prepared just-in-time loading for %s" directory)))
1843 (t
1844 (push (yas--message 0 "Check your `yas-snippet-dirs': %s is not a directory" directory) errors))))
1845 (call-interactively 'yas-load-directory))
1846 errors))
1847
1848 (defun yas-reload-all (&optional interactive)
1849 "Reload all snippets and rebuild the YASnippet menu.
1850
1851 When called interactively force immediate reload of all known
1852 snippets under `yas-snippet-dirs', otherwise use just-in-time
1853 loading."
1854 (interactive "p")
1855 (catch 'abort
1856 (let ((errors)
1857 (snippet-editing-buffers
1858 (remove-if-not #'(lambda (buffer)
1859 (with-current-buffer buffer yas--editing-template))
1860 (buffer-list))))
1861 ;; Warn if there are buffers visiting snippets, since reloading will break
1862 ;; any on-line editing of those buffers.
1863 ;;
1864 (when snippet-editing-buffers
1865 (if interactive
1866 (if (y-or-n-p "Some buffers editing live snippets, close them and proceed with reload? ")
1867 (mapc #'kill-buffer snippet-editing-buffers)
1868 (yas--message 1 "Aborted reload...")
1869 (throw 'abort nil))
1870 ;; in a non-interactive use, at least set
1871 ;; `yas--editing-template' to nil, make it guess it next time around
1872 (mapc #'(lambda (buffer)
1873 (with-current-buffer buffer
1874 (kill-local-variable 'yas--editing-template)))
1875 (buffer-list))))
1876
1877 ;; Empty all snippet tables and parenting info
1878 ;;
1879 (setq yas--tables (make-hash-table))
1880 (setq yas--parents (make-hash-table))
1881
1882 ;; Before killing `yas--menu-table' use its keys to cleanup the
1883 ;; mode menu parts of `yas--minor-mode-menu' (thus also cleaning
1884 ;; up `yas-minor-mode-map', which points to it)
1885 ;;
1886 (maphash #'(lambda (menu-symbol _keymap)
1887 (define-key yas--minor-mode-menu (vector menu-symbol) nil))
1888 yas--menu-table)
1889 ;; Now empty `yas--menu-table' as well
1890 (setq yas--menu-table (make-hash-table))
1891
1892 ;; Cancel all pending 'yas--scheduled-jit-loads'
1893 ;;
1894 (setq yas--scheduled-jit-loads (make-hash-table))
1895
1896 ;; Reload the directories listed in `yas-snippet-dirs' or prompt
1897 ;; the user to select one.
1898 ;;
1899 (setq errors (yas--load-snippet-dirs interactive))
1900 ;; Reload the direct keybindings
1901 ;;
1902 (yas-direct-keymaps-reload)
1903
1904 (yas--message 3 "Reloaded everything%s...%s."
1905 (if interactive "" " (snippets will load just-in-time)")
1906 (if errors " (some errors, check *Messages*)" "")))))
1907
1908 (defun yas--load-pending-jits ()
1909 (dolist (mode (yas--modes-to-activate))
1910 (let ((funs (reverse (gethash mode yas--scheduled-jit-loads))))
1911 ;; must reverse to maintain coherence with `yas-snippet-dirs'
1912 (dolist (fun funs)
1913 (yas--message 3 "Loading for `%s', just-in-time: %s!" mode fun)
1914 (funcall fun))
1915 (remhash mode yas--scheduled-jit-loads))))
1916
1917 ;; (when (<= emacs-major-version 22)
1918 ;; (add-hook 'after-change-major-mode-hook 'yas--load-pending-jits))
1919
1920 (defun yas--quote-string (string)
1921 "Escape and quote STRING.
1922 foo\"bar\\! -> \"foo\\\"bar\\\\!\""
1923 (concat "\""
1924 (replace-regexp-in-string "[\\\"]"
1925 "\\\\\\&"
1926 string
1927 t)
1928 "\""))
1929 \f
1930 ;;; Snippet compilation function
1931
1932 (defun yas--initialize ()
1933 "For backward compatibility, enable `yas-minor-mode' globally."
1934 (yas-global-mode 1))
1935
1936 (defun yas-compile-directory (top-level-dir)
1937 "Create .yas-compiled-snippets.el files under subdirs of TOP-LEVEL-DIR.
1938
1939 This works by stubbing a few functions, then calling
1940 `yas-load-directory'."
1941 (interactive "DTop level snippet directory?")
1942 (let ((yas--creating-compiled-snippets t))
1943 (yas-load-directory top-level-dir nil)))
1944
1945 (defun yas-recompile-all ()
1946 "Compile every dir in `yas-snippet-dirs'."
1947 (interactive)
1948 (mapc #'yas-compile-directory (yas-snippet-dirs)))
1949
1950
1951 ;;; JIT loading
1952 ;;;
1953
1954 (defvar yas--scheduled-jit-loads (make-hash-table)
1955 "Alist of mode-symbols to forms to be evaled when `yas-minor-mode' kicks in.")
1956
1957 (defun yas--schedule-jit (mode fun)
1958 (push fun (gethash mode yas--scheduled-jit-loads)))
1959
1960
1961 \f
1962 ;;; Some user level functions
1963
1964 (defun yas-about ()
1965 (interactive)
1966 (message (concat "yasnippet (version "
1967 yas--version
1968 ") -- pluskid <pluskid@gmail.com>/joaotavora <joaotavora@gmail.com>")))
1969
1970 \f
1971 ;;; Apropos snippet menu:
1972 ;;
1973 ;; The snippet menu keymaps are store by mode in hash table called
1974 ;; `yas--menu-table'. They are linked to the main menu in
1975 ;; `yas--menu-keymap-get-create' and are initially created empty,
1976 ;; reflecting the table hierarchy.
1977 ;;
1978 ;; They can be populated in two mutually exclusive ways: (1) by
1979 ;; reading `yas--template-group', which in turn is populated by the "#
1980 ;; group:" directives of the snippets or the ".yas-make-groups" file
1981 ;; or (2) by using a separate `yas-define-menu' call, which declares a
1982 ;; menu structure based on snippets uuids.
1983 ;;
1984 ;; Both situations are handled in `yas--update-template-menu', which
1985 ;; uses the predicate `yas--template-menu-managed-by-yas-define-menu'
1986 ;; that can tell between the two situations.
1987 ;;
1988 ;; Note:
1989 ;;
1990 ;; * if `yas-define-menu' is used it must run before
1991 ;; `yas-define-snippets' and the UUIDS must match, otherwise we get
1992 ;; duplicate entries. The `yas--template' objects are created in
1993 ;; `yas-define-menu', holding nothing but the menu entry,
1994 ;; represented by a pair of ((menu-item NAME :keys KEYS) TYPE) and
1995 ;; stored in `yas--template-menu-binding-pair'. The (menu-item ...)
1996 ;; part is then stored in the menu keymap itself which make the item
1997 ;; appear to the user. These limitations could probably be revised.
1998 ;;
1999 ;; * The `yas--template-perm-group' slot is only used in
2000 ;; `yas-describe-tables'.
2001 ;;
2002 (defun yas--template-menu-binding-pair-get-create (template &optional type)
2003 "Get TEMPLATE's menu binding or assign it a new one.
2004
2005 TYPE may be `:stay', signaling this menu binding should be
2006 static in the menu."
2007 (or (yas--template-menu-binding-pair template)
2008 (let (;; (key (yas--template-key template))
2009 ;; (keybinding (yas--template-keybinding template))
2010 )
2011 (setf (yas--template-menu-binding-pair template)
2012 (cons `(menu-item ,(or (yas--template-name template)
2013 (yas--template-uuid template))
2014 ,(yas--make-menu-binding template)
2015 :keys ,nil)
2016 type)))))
2017 (defun yas--template-menu-managed-by-yas-define-menu (template)
2018 "Non-nil if TEMPLATE's menu entry was included in a `yas-define-menu' call."
2019 (cdr (yas--template-menu-binding-pair template)))
2020
2021
2022 (defun yas--show-menu-p (mode)
2023 (cond ((eq yas-use-menu 'abbreviate)
2024 (find mode
2025 (mapcar #'(lambda (table)
2026 (yas--table-mode table))
2027 (yas--get-snippet-tables))))
2028 ((eq yas-use-menu 'full)
2029 t)
2030 ((eq yas-use-menu t)
2031 t)))
2032
2033 (defun yas--delete-from-keymap (keymap uuid)
2034 "Recursively delete items with UUID from KEYMAP and its submenus."
2035
2036 ;; XXX: This used to skip any submenus named \"parent mode\"
2037 ;;
2038 ;; First of all, recursively enter submenus, i.e. the tree is
2039 ;; searched depth first so that stale submenus can be found in the
2040 ;; higher passes.
2041 ;;
2042 (mapc #'(lambda (item)
2043 (when (and (listp (cdr item))
2044 (keymapp (third (cdr item))))
2045 (yas--delete-from-keymap (third (cdr item)) uuid)))
2046 (rest keymap))
2047 ;; Set the uuid entry to nil
2048 ;;
2049 (define-key keymap (vector (make-symbol uuid)) nil)
2050 ;; Destructively modify keymap
2051 ;;
2052 (setcdr keymap (delete-if #'(lambda (item)
2053 (or (null (cdr item))
2054 (and (keymapp (third (cdr item)))
2055 (null (cdr (third (cdr item)))))))
2056 (rest keymap))))
2057
2058 (defun yas-define-menu (mode menu &optional omit-items)
2059 "Define a snippet menu for MODE according to MENU, omitting OMIT-ITEMS.
2060
2061 MENU is a list, its elements can be:
2062
2063 - (yas-item UUID) : Creates an entry the snippet identified with
2064 UUID. The menu entry for a snippet thus identified is
2065 permanent, i.e. it will never move (be reordered) in the menu.
2066
2067 - (yas-separator) : Creates a separator
2068
2069 - (yas-submenu NAME SUBMENU) : Creates a submenu with NAME,
2070 SUBMENU has the same form as MENU. NAME is also added to the
2071 list of groups of the snippets defined thereafter.
2072
2073 OMIT-ITEMS is a list of snippet uuid's that will always be
2074 omitted from MODE's menu, even if they're manually loaded.
2075
2076 This function does nothing if `yas-use-menu' is nil."
2077 (when yas-use-menu
2078 (let* ((table (yas--table-get-create mode))
2079 (hash (yas--table-uuidhash table)))
2080 (yas--define-menu-1 table
2081 (yas--menu-keymap-get-create mode)
2082 menu
2083 hash)
2084 (dolist (uuid omit-items)
2085 (let ((template (or (gethash uuid hash)
2086 (yas--populate-template (puthash uuid
2087 (yas--make-blank-template)
2088 hash)
2089 :table table
2090 :uuid uuid))))
2091 (setf (yas--template-menu-binding-pair template) (cons nil :none)))))))
2092
2093 (defun yas--define-menu-1 (table menu-keymap menu uuidhash &optional group-list)
2094 "Helper for `yas-define-menu'."
2095 (dolist (e (reverse menu))
2096 (cond ((eq (first e) 'yas-item)
2097 (let ((template (or (gethash (second e) uuidhash)
2098 (yas--populate-template (puthash (second e)
2099 (yas--make-blank-template)
2100 uuidhash)
2101 :table table
2102 :perm-group group-list
2103 :uuid (second e)))))
2104 (define-key menu-keymap (vector (gensym))
2105 (car (yas--template-menu-binding-pair-get-create template :stay)))))
2106 ((eq (first e) 'yas-submenu)
2107 (let ((subkeymap (make-sparse-keymap)))
2108 (define-key menu-keymap (vector (gensym))
2109 `(menu-item ,(second e) ,subkeymap))
2110 (yas--define-menu-1 table
2111 subkeymap
2112 (third e)
2113 uuidhash
2114 (append group-list (list (second e))))))
2115 ((eq (first e) 'yas-separator)
2116 (define-key menu-keymap (vector (gensym))
2117 '(menu-item "----")))
2118 (t
2119 (yas--message 3 "Don't know anything about menu entry %s" (first e))))))
2120 \f
2121 (defun yas--define (mode key template &optional name condition group)
2122 "Define a snippet. Expanding KEY into TEMPLATE.
2123
2124 NAME is a description to this template. Also update the menu if
2125 `yas-use-menu' is t. CONDITION is the condition attached to
2126 this snippet. If you attach a condition to a snippet, then it
2127 will only be expanded when the condition evaluated to non-nil."
2128 (yas-define-snippets mode
2129 (list (list key template name condition group))))
2130
2131 (defun yas-hippie-try-expand (first-time?)
2132 "Integrate with hippie expand.
2133
2134 Just put this function in `hippie-expand-try-functions-list'."
2135 (when yas-minor-mode
2136 (if (not first-time?)
2137 (let ((yas-fallback-behavior 'return-nil))
2138 (yas-expand))
2139 (undo 1)
2140 nil)))
2141
2142
2143 ;;; Apropos condition-cache:
2144 ;;;
2145 ;;;
2146 ;;;
2147 ;;;
2148 (defvar yas--condition-cache-timestamp nil)
2149 (defmacro yas-define-condition-cache (func doc &rest body)
2150 "Define a function FUNC with doc DOC and body BODY.
2151 BODY is executed at most once every snippet expansion attempt, to check
2152 expansion conditions.
2153
2154 It doesn't make any sense to call FUNC programatically."
2155 `(defun ,func () ,(if (and doc
2156 (stringp doc))
2157 (concat doc
2158 "\n\nFor use in snippets' conditions. Within each
2159 snippet-expansion routine like `yas-expand', computes actual
2160 value for the first time then always returns a cached value.")
2161 (setq body (cons doc body))
2162 nil)
2163 (let ((timestamp-and-value (get ',func 'yas--condition-cache)))
2164 (if (equal (car timestamp-and-value) yas--condition-cache-timestamp)
2165 (cdr timestamp-and-value)
2166 (let ((new-value (progn
2167 ,@body
2168 )))
2169 (put ',func 'yas--condition-cache (cons yas--condition-cache-timestamp new-value))
2170 new-value)))))
2171
2172 (defalias 'yas-expand 'yas-expand-from-trigger-key)
2173 (defun yas-expand-from-trigger-key (&optional field)
2174 "Expand a snippet before point.
2175
2176 If no snippet expansion is possible, fall back to the behaviour
2177 defined in `yas-fallback-behavior'.
2178
2179 Optional argument FIELD is for non-interactive use and is an
2180 object satisfying `yas--field-p' to restrict the expansion to."
2181 (interactive)
2182 (setq yas--condition-cache-timestamp (current-time))
2183 (let (templates-and-pos)
2184 (unless (and yas-expand-only-for-last-commands
2185 (not (member last-command yas-expand-only-for-last-commands)))
2186 (setq templates-and-pos (if field
2187 (save-restriction
2188 (narrow-to-region (yas--field-start field)
2189 (yas--field-end field))
2190 (yas--current-key))
2191 (yas--current-key))))
2192 (if (and templates-and-pos
2193 (first templates-and-pos))
2194 (yas--expand-or-prompt-for-template (first templates-and-pos)
2195 (second templates-and-pos)
2196 (third templates-and-pos))
2197 (yas--fallback))))
2198
2199 (defun yas-expand-from-keymap ()
2200 "Directly expand some snippets, searching `yas--direct-keymaps'.
2201
2202 If expansion fails, execute the previous binding for this key"
2203 (interactive)
2204 (setq yas--condition-cache-timestamp (current-time))
2205 (let* ((vec (subseq (this-command-keys-vector) (if current-prefix-arg
2206 (length (this-command-keys))
2207 0)))
2208 (templates (mapcan #'(lambda (table)
2209 (yas--fetch table vec))
2210 (yas--get-snippet-tables))))
2211 (if templates
2212 (yas--expand-or-prompt-for-template templates)
2213 (let ((yas-fallback-behavior 'call-other-command))
2214 (yas--fallback)))))
2215
2216 (defun yas--expand-or-prompt-for-template (templates &optional start end)
2217 "Expand one of TEMPLATES from START to END.
2218
2219 Prompt the user if TEMPLATES has more than one element, else
2220 expand immediately. Common gateway for
2221 `yas-expand-from-trigger-key' and `yas-expand-from-keymap'."
2222 (let ((yas--current-template (or (and (rest templates) ;; more than one
2223 (yas--prompt-for-template (mapcar #'cdr templates)))
2224 (cdar templates))))
2225 (when yas--current-template
2226 (yas-expand-snippet (yas--template-content yas--current-template)
2227 start
2228 end
2229 (yas--template-expand-env yas--current-template)))))
2230
2231 ;; Apropos the trigger key and the fallback binding:
2232 ;;
2233 ;; When `yas-minor-mode-map' binds <tab>, that correctly overrides
2234 ;; org-mode's <tab>, for example and searching for fallbacks correctly
2235 ;; returns `org-cycle'. However, most other modes bind "TAB". TODO,
2236 ;; improve this explanation.
2237 ;;
2238 (defun yas--fallback ()
2239 "Fallback after expansion has failed.
2240
2241 Common gateway for `yas-expand-from-trigger-key' and
2242 `yas-expand-from-keymap'."
2243 (cond ((eq yas-fallback-behavior 'return-nil)
2244 ;; return nil
2245 nil)
2246 ((eq yas-fallback-behavior 'call-other-command)
2247 (let* ((beyond-yasnippet (yas--keybinding-beyond-yasnippet)))
2248 (yas--message 4 "Falling back to %s" beyond-yasnippet)
2249 (assert (or (null beyond-yasnippet) (commandp beyond-yasnippet)))
2250 (setq this-original-command beyond-yasnippet)
2251 (call-interactively beyond-yasnippet)))
2252 ((and (listp yas-fallback-behavior)
2253 (cdr yas-fallback-behavior)
2254 (eq 'apply (car yas-fallback-behavior)))
2255 (if (cddr yas-fallback-behavior)
2256 (apply (cadr yas-fallback-behavior)
2257 (cddr yas-fallback-behavior))
2258 (when (commandp (cadr yas-fallback-behavior))
2259 (setq this-command (cadr yas-fallback-behavior))
2260 (call-interactively (cadr yas-fallback-behavior)))))
2261 (t
2262 ;; also return nil if all the other fallbacks have failed
2263 nil)))
2264
2265 (defun yas--keybinding-beyond-yasnippet ()
2266 "Return the ??"
2267 (let* ((yas-minor-mode nil)
2268 (yas--direct-keymaps nil)
2269 (keys (this-single-command-keys)))
2270 (or (key-binding keys t)
2271 (key-binding (yas--fallback-translate-input keys) t))))
2272
2273 (defun yas--fallback-translate-input (keys)
2274 "Emulate `read-key-sequence', at least what I think it does.
2275
2276 Keys should be an untranslated key vector. Returns a translated
2277 vector of keys. FIXME not thoroughly tested."
2278 (let ((retval [])
2279 (i 0))
2280 (while (< i (length keys))
2281 (let ((j i)
2282 (translated local-function-key-map))
2283 (while (and (< j (length keys))
2284 translated
2285 (keymapp translated))
2286 (setq translated (cdr (assoc (aref keys j) (remove 'keymap translated)))
2287 j (1+ j)))
2288 (setq retval (vconcat retval (cond ((symbolp translated)
2289 `[,translated])
2290 ((vectorp translated)
2291 translated)
2292 (t
2293 (substring keys i j)))))
2294 (setq i j)))
2295 retval))
2296
2297 \f
2298 ;;; Utils for snippet development:
2299
2300 (defun yas--all-templates (tables)
2301 "Get `yas--template' objects in TABLES, applicable for buffer and point.
2302
2303 Honours `yas-choose-tables-first', `yas-choose-keys-first' and
2304 `yas-buffer-local-condition'"
2305 (when yas-choose-tables-first
2306 (setq tables (list (yas--prompt-for-table tables))))
2307 (mapcar #'cdr
2308 (if yas-choose-keys-first
2309 (let ((key (yas--prompt-for-keys
2310 (mapcan #'yas--table-all-keys tables))))
2311 (when key
2312 (mapcan #'(lambda (table)
2313 (yas--fetch table key))
2314 tables)))
2315 (remove-duplicates (mapcan #'yas--table-templates tables)
2316 :test #'equal))))
2317
2318 (defun yas-insert-snippet (&optional no-condition)
2319 "Choose a snippet to expand, pop-up a list of choices according
2320 to `yas--prompt-function'.
2321
2322 With prefix argument NO-CONDITION, bypass filtering of snippets
2323 by condition."
2324 (interactive "P")
2325 (setq yas--condition-cache-timestamp (current-time))
2326 (let* ((yas-buffer-local-condition (or (and no-condition
2327 'always)
2328 yas-buffer-local-condition))
2329 (templates (yas--all-templates (yas--get-snippet-tables)))
2330 (yas--current-template (and templates
2331 (or (and (rest templates) ;; more than one template for same key
2332 (yas--prompt-for-template templates))
2333 (car templates))))
2334 (where (if (region-active-p)
2335 (cons (region-beginning) (region-end))
2336 (cons (point) (point)))))
2337 (if yas--current-template
2338 (yas-expand-snippet (yas--template-content yas--current-template)
2339 (car where)
2340 (cdr where)
2341 (yas--template-expand-env yas--current-template))
2342 (yas--message 3 "No snippets can be inserted here!"))))
2343
2344 (defun yas-visit-snippet-file ()
2345 "Choose a snippet to edit, selection like `yas-insert-snippet'.
2346
2347 Only success if selected snippet was loaded from a file. Put the
2348 visited file in `snippet-mode'."
2349 (interactive)
2350 (let* ((yas-buffer-local-condition 'always)
2351 (templates (yas--all-templates (yas--get-snippet-tables)))
2352 (yas-prompt-functions '(yas-ido-prompt yas-completing-prompt))
2353 (template (and templates
2354 (or (yas--prompt-for-template templates
2355 "Choose a snippet template to edit: ")
2356 (car templates)))))
2357
2358 (if template
2359 (yas--visit-snippet-file-1 template)
2360 (message "No snippets tables active!"))))
2361
2362 (defun yas--visit-snippet-file-1 (template)
2363 "Helper for `yas-visit-snippet-file'."
2364 (let ((file (yas--template-file template)))
2365 (cond ((and file (file-readable-p file))
2366 (find-file-other-window file)
2367 (snippet-mode)
2368 (set (make-local-variable 'yas--editing-template) template))
2369 (file
2370 (message "Original file %s no longer exists!" file))
2371 (t
2372 (switch-to-buffer (format "*%s*"(yas--template-name template)))
2373 (let ((type 'snippet))
2374 (when (listp (yas--template-content template))
2375 (insert (format "# type: command\n"))
2376 (setq type 'command))
2377 (insert (format "# key: %s\n" (yas--template-key template)))
2378 (insert (format "# name: %s\n" (yas--template-name template)))
2379 (when (yas--template-keybinding template)
2380 (insert (format "# binding: %s\n" (yas--template-keybinding template))))
2381 (when (yas--template-expand-env template)
2382 (insert (format "# expand-env: %s\n" (yas--template-expand-env template))))
2383 (when (yas--template-condition template)
2384 (insert (format "# condition: %s\n" (yas--template-condition template))))
2385 (insert "# --\n")
2386 (insert (if (eq type 'command)
2387 (pp-to-string (yas--template-content template))
2388 (yas--template-content template))))
2389 (snippet-mode)
2390 (set (make-local-variable 'yas--editing-template) template)))))
2391
2392 (defun yas--guess-snippet-directories-1 (table)
2393 "Guess possible snippet subdirectories for TABLE."
2394 (cons (yas--table-name table)
2395 (mapcan #'(lambda (parent)
2396 (yas--guess-snippet-directories-1
2397 parent))
2398 (yas--table-parents table))))
2399
2400 (defun yas--guess-snippet-directories (&optional table)
2401 "Try to guess suitable directories based on the current active
2402 tables (or optional TABLE).
2403
2404 Returns a list of elements (TABLE . DIRS) where TABLE is a
2405 `yas--table' object and DIRS is a list of all possible directories
2406 where snippets of table might exist."
2407 (let ((main-dir (replace-regexp-in-string
2408 "/+$" ""
2409 (or (first (or (yas-snippet-dirs)
2410 (setq yas-snippet-dirs '("~/.emacs.d/snippets")))))))
2411 (tables (or (and table
2412 (list table))
2413 (yas--get-snippet-tables))))
2414 ;; HACK! the snippet table created here is actually registered!
2415 ;;
2416 (unless (or table (gethash major-mode yas--tables))
2417 (push (yas--table-get-create major-mode)
2418 tables))
2419
2420 (mapcar #'(lambda (table)
2421 (cons table
2422 (mapcar #'(lambda (subdir)
2423 (concat main-dir "/" subdir))
2424 (yas--guess-snippet-directories-1 table))))
2425 tables)))
2426
2427 (defun yas--make-directory-maybe (table-and-dirs &optional main-table-string)
2428 "Return a dir inside TABLE-AND-DIRS, prompts for creation if none exists."
2429 (or (some #'(lambda (dir) (when (file-directory-p dir) dir)) (cdr table-and-dirs))
2430 (let ((candidate (first (cdr table-and-dirs))))
2431 (unless (file-writable-p (file-name-directory candidate))
2432 (error (yas--format "%s is not writable." candidate)))
2433 (if (y-or-n-p (format "Guessed directory (%s) for%s%s table \"%s\" does not exist! Create? "
2434 candidate
2435 (if (gethash (yas--table-mode (car table-and-dirs))
2436 yas--tables)
2437 ""
2438 " brand new")
2439 (or main-table-string
2440 "")
2441 (yas--table-name (car table-and-dirs))))
2442 (progn
2443 (make-directory candidate 'also-make-parents)
2444 ;; create the .yas-parents file here...
2445 candidate)))))
2446
2447 (defun yas-new-snippet (&optional no-template)
2448 "Pops a new buffer for writing a snippet.
2449
2450 Expands a snippet-writing snippet, unless the optional prefix arg
2451 NO-TEMPLATE is non-nil."
2452 (interactive "P")
2453 (let ((guessed-directories (yas--guess-snippet-directories)))
2454
2455 (switch-to-buffer "*new snippet*")
2456 (erase-buffer)
2457 (kill-all-local-variables)
2458 (snippet-mode)
2459 (yas-minor-mode 1)
2460 (set (make-local-variable 'yas--guessed-modes) (mapcar #'(lambda (d)
2461 (yas--table-mode (car d)))
2462 guessed-directories))
2463 (if (and (not no-template) yas-new-snippet-default)
2464 (yas-expand-snippet yas-new-snippet-default))))
2465
2466 (defun yas--compute-major-mode-and-parents (file)
2467 "Given FILE, find the nearest snippet directory for a given mode.
2468
2469 Returns a list (MODE-SYM PARENTS), the mode's symbol and a list
2470 representing one or more of the mode's parents.
2471
2472 Note that MODE-SYM need not be the symbol of a real major mode,
2473 neither do the elements of PARENTS."
2474 (let* ((file-dir (and file
2475 (directory-file-name (or (some #'(lambda (special)
2476 (locate-dominating-file file special))
2477 '(".yas-setup.el"
2478 ".yas-make-groups"
2479 ".yas-parents"))
2480 (directory-file-name (file-name-directory file))))))
2481 (parents-file-name (concat file-dir "/.yas-parents"))
2482 (major-mode-name (and file-dir
2483 (file-name-nondirectory file-dir)))
2484 (major-mode-sym (or (and major-mode-name
2485 (intern major-mode-name))))
2486 (parents (when (file-readable-p parents-file-name)
2487 (mapcar #'intern
2488 (split-string
2489 (with-temp-buffer
2490 (insert-file-contents parents-file-name)
2491 (buffer-substring-no-properties (point-min)
2492 (point-max))))))))
2493 (when major-mode-sym
2494 (cons major-mode-sym (remove major-mode-sym parents)))))
2495
2496 (defvar yas--editing-template nil
2497 "Supporting variable for `yas-load-snippet-buffer' and `yas--visit-snippet'.")
2498
2499 (defvar yas--current-template nil
2500 "Holds the current template being expanded into a snippet.")
2501
2502 (defvar yas--guessed-modes nil
2503 "List of guessed modes supporting `yas-load-snippet-buffer'.")
2504
2505 (defun yas--read-table ()
2506 "Ask user for a snippet table, help with some guessing."
2507 (let ((prompt (if (and (featurep 'ido)
2508 ido-mode)
2509 'ido-completing-read 'completing-read)))
2510 (unless yas--guessed-modes
2511 (set (make-local-variable 'yas--guessed-modes)
2512 (or (yas--compute-major-mode-and-parents buffer-file-name))))
2513 (intern
2514 (funcall prompt (format "Choose or enter a table (yas guesses %s): "
2515 (if yas--guessed-modes
2516 (first yas--guessed-modes)
2517 "nothing"))
2518 (mapcar #'symbol-name yas--guessed-modes)
2519 nil
2520 nil
2521 nil
2522 nil
2523 (if (first yas--guessed-modes)
2524 (symbol-name (first yas--guessed-modes)))))))
2525
2526 (defun yas-load-snippet-buffer (table &optional interactive)
2527 "Parse and load current buffer's snippet definition into TABLE.
2528
2529 TABLE is a symbol naming a passed to `yas--table-get-create'.
2530
2531 When called interactively, prompt for the table name and
2532 whether (and where) to save the snippet, then quit the window."
2533 (interactive (list (yas--read-table) t))
2534 (cond
2535 ;; We have `yas--editing-template', this buffer's content comes from a
2536 ;; template which is already loaded and neatly positioned,...
2537 ;;
2538 (yas--editing-template
2539 (yas--define-snippets-1 (yas--parse-template (yas--template-file yas--editing-template))
2540 (yas--template-table yas--editing-template)))
2541 ;; Try to use `yas--guessed-modes'. If we don't have that use the
2542 ;; value from `yas--compute-major-mode-and-parents'
2543 ;;
2544 (t
2545 (unless yas--guessed-modes
2546 (set (make-local-variable 'yas--guessed-modes) (or (yas--compute-major-mode-and-parents buffer-file-name))))
2547 (let* ((table (yas--table-get-create table)))
2548 (set (make-local-variable 'yas--editing-template)
2549 (yas--define-snippets-1 (yas--parse-template buffer-file-name)
2550 table)))))
2551
2552 (when (and interactive
2553 (or
2554 ;; Only offer to save this if it looks like a library or new
2555 ;; snippet (loaded from elisp, from a dir in `yas-snippet-dirs'
2556 ;; which is not the first, or from an unwritable file)
2557 ;;
2558 (not (yas--template-file yas--editing-template))
2559 (not (file-writable-p (yas--template-file yas--editing-template)))
2560 (and (listp yas-snippet-dirs)
2561 (second yas-snippet-dirs)
2562 (not (string-match (expand-file-name (first yas-snippet-dirs))
2563 (yas--template-file yas--editing-template)))))
2564 (y-or-n-p (yas--format "Looks like a library or new snippet. Save to new file? ")))
2565 (let* ((option (first (yas--guess-snippet-directories (yas--template-table yas--editing-template))))
2566 (chosen (and option
2567 (yas--make-directory-maybe option))))
2568 (when chosen
2569 (let ((default-file-name (or (and (yas--template-file yas--editing-template)
2570 (file-name-nondirectory (yas--template-file yas--editing-template)))
2571 (yas--template-name yas--editing-template))))
2572 (write-file (concat chosen "/"
2573 (read-from-minibuffer (format "File name to create in %s? " chosen)
2574 default-file-name)))
2575 (setf (yas--template-file yas--editing-template) buffer-file-name)))))
2576 (when interactive
2577 (yas--message 3 "Snippet \"%s\" loaded for %s."
2578 (yas--template-name yas--editing-template)
2579 (yas--table-name (yas--template-table yas--editing-template)))
2580 (quit-window interactive)))
2581
2582 (defun yas-tryout-snippet (&optional debug)
2583 "Test current buffer's snippet template in other buffer."
2584 (interactive "P")
2585 (let* ((major-mode-and-parent (yas--compute-major-mode-and-parents buffer-file-name))
2586 (parsed (yas--parse-template))
2587 (test-mode (or (and (car major-mode-and-parent)
2588 (fboundp (car major-mode-and-parent))
2589 (car major-mode-and-parent))
2590 (first yas--guessed-modes)
2591 (intern (read-from-minibuffer (yas--format "Please input a mode: ")))))
2592 (yas--current-template
2593 (and parsed
2594 (fboundp test-mode)
2595 (yas--populate-template (yas--make-blank-template)
2596 :table nil ;; no tables for ephemeral snippets
2597 :key (first parsed)
2598 :content (second parsed)
2599 :name (third parsed)
2600 :expand-env (sixth parsed)))))
2601 (cond (yas--current-template
2602 (let ((buffer-name (format "*testing snippet: %s*" (yas--template-name yas--current-template))))
2603 (kill-buffer (get-buffer-create buffer-name))
2604 (switch-to-buffer (get-buffer-create buffer-name))
2605 (setq buffer-undo-list nil)
2606 (condition-case nil (funcall test-mode) (error nil))
2607 (yas-minor-mode 1)
2608 (setq buffer-read-only nil)
2609 (yas-expand-snippet (yas--template-content yas--current-template)
2610 (point-min)
2611 (point-max)
2612 (yas--template-expand-env yas--current-template))
2613 (when (and debug
2614 (require 'yasnippet-debug nil t))
2615 (add-hook 'post-command-hook 'yas-debug-snippet-vars nil t))))
2616 (t
2617 (yas--message 3 "Cannot test snippet for unknown major mode")))))
2618
2619 (defun yas-active-keys ()
2620 "Return all active trigger keys for current buffer and point."
2621 (remove-duplicates
2622 (remove-if-not #'stringp (mapcan #'yas--table-all-keys (yas--get-snippet-tables)))
2623 :test #'string=))
2624
2625 (defun yas--template-fine-group (template)
2626 (car (last (or (yas--template-group template)
2627 (yas--template-perm-group template)))))
2628
2629 (defun yas-describe-tables (&optional choose)
2630 "Display snippets for each table."
2631 (interactive "P")
2632 (let* ((by-name-hash (and choose
2633 (y-or-n-p "Show by namehash? ")))
2634 (buffer (get-buffer-create "*YASnippet tables*"))
2635 (active-tables (yas--get-snippet-tables))
2636 (remain-tables (let ((all))
2637 (maphash #'(lambda (_k v)
2638 (unless (find v active-tables)
2639 (push v all)))
2640 yas--tables)
2641 all))
2642 (table-lists (list active-tables remain-tables))
2643 (original-buffer (current-buffer))
2644 (continue t)
2645 (yas--condition-cache-timestamp (current-time)))
2646 (with-current-buffer buffer
2647 (setq buffer-read-only nil)
2648 (erase-buffer)
2649 (cond ((not by-name-hash)
2650 (insert "YASnippet tables: \n")
2651 (while (and table-lists
2652 continue)
2653 (dolist (table (car table-lists))
2654 (yas--describe-pretty-table table original-buffer))
2655 (setq table-lists (cdr table-lists))
2656 (when table-lists
2657 (yas--create-snippet-xrefs)
2658 (display-buffer buffer)
2659 (setq continue (and choose (y-or-n-p "Show also non-active tables? ")))))
2660 (yas--create-snippet-xrefs)
2661 (help-mode)
2662 (goto-char 1))
2663 (t
2664 (insert "\n\nYASnippet tables by NAMEHASH: \n")
2665 (dolist (table (append active-tables remain-tables))
2666 (insert (format "\nSnippet table `%s':\n\n" (yas--table-name table)))
2667 (let ((keys))
2668 (maphash #'(lambda (k _v)
2669 (push k keys))
2670 (yas--table-hash table))
2671 (dolist (key keys)
2672 (insert (format " key %s maps snippets: %s\n" key
2673 (let ((names))
2674 (maphash #'(lambda (k _v)
2675 (push k names))
2676 (gethash key (yas--table-hash table)))
2677 names))))))))
2678 (goto-char 1)
2679 (setq buffer-read-only t))
2680 (display-buffer buffer)))
2681
2682 (defun yas--describe-pretty-table (table &optional original-buffer)
2683 (insert (format "\nSnippet table `%s'"
2684 (yas--table-name table)))
2685 (if (yas--table-parents table)
2686 (insert (format " parents: %s\n"
2687 (mapcar #'yas--table-name
2688 (yas--table-parents table))))
2689 (insert "\n"))
2690 (insert (make-string 100 ?-) "\n")
2691 (insert "group state name key binding\n")
2692 (let ((groups-hash (make-hash-table :test #'equal)))
2693 (maphash #'(lambda (_k v)
2694 (let ((group (or (yas--template-fine-group v)
2695 "(top level)")))
2696 (when (yas--template-name v)
2697 (puthash group
2698 (cons v (gethash group groups-hash))
2699 groups-hash))))
2700 (yas--table-uuidhash table))
2701 (maphash
2702 #'(lambda (group templates)
2703 (setq group (truncate-string-to-width group 25 0 ? "..."))
2704 (insert (make-string 100 ?-) "\n")
2705 (dolist (p templates)
2706 (let ((name (truncate-string-to-width (propertize (format "\\\\snippet `%s'" (yas--template-name p))
2707 'yasnippet p)
2708 50 0 ? "..."))
2709 (group (prog1 group
2710 (setq group (make-string (length group) ? ))))
2711 (condition-string (let ((condition (yas--template-condition p)))
2712 (if (and condition
2713 original-buffer)
2714 (with-current-buffer original-buffer
2715 (if (yas--eval-condition condition)
2716 "(y)"
2717 "(s)"))
2718 "(a)"))))
2719 (insert group " ")
2720 (insert condition-string " ")
2721 (insert name
2722 (if (string-match "\\.\\.\\.$" name)
2723 "'"
2724 " ")
2725 " ")
2726 (insert (truncate-string-to-width (or (yas--template-key p) "")
2727 15 0 ? "...") " ")
2728 (insert (truncate-string-to-width (key-description (yas--template-keybinding p))
2729 15 0 ? "...") " ")
2730 (insert "\n"))))
2731 groups-hash)))
2732
2733
2734 \f
2735 ;;; User convenience functions, for using in snippet definitions
2736
2737 (defvar yas-modified-p nil
2738 "Non-nil if field has been modified by user or transformation.")
2739
2740 (defvar yas-moving-away-p nil
2741 "Non-nil if user is about to exit field.")
2742
2743 (defvar yas-text nil
2744 "Contains current field text.")
2745
2746 (defun yas-substr (str pattern &optional subexp)
2747 "Search PATTERN in STR and return SUBEXPth match.
2748
2749 If found, the content of subexp group SUBEXP (default 0) is
2750 returned, or else the original STR will be returned."
2751 (let ((grp (or subexp 0)))
2752 (save-match-data
2753 (if (string-match pattern str)
2754 (match-string-no-properties grp str)
2755 str))))
2756
2757 (defun yas-choose-value (&rest possibilities)
2758 "Prompt for a string in POSSIBILITIES and return it.
2759
2760 The last element of POSSIBILITIES may be a list of strings."
2761 (unless (or yas-moving-away-p
2762 yas-modified-p)
2763 (setq possibilities (nreverse possibilities))
2764 (setq possibilities (if (listp (car possibilities))
2765 (append (reverse (car possibilities)) (rest possibilities))
2766 possibilities))
2767 (some #'(lambda (fn)
2768 (funcall fn "Choose: " possibilities))
2769 yas-prompt-functions)))
2770
2771 (defun yas-key-to-value (alist)
2772 (unless (or yas-moving-away-p
2773 yas-modified-p)
2774 (let ((key (read-key-sequence "")))
2775 (when (stringp key)
2776 (or (cdr (find key alist :key #'car :test #'string=))
2777 key)))))
2778
2779 (defun yas-throw (text)
2780 "Throw a yas--exception with TEXT as the reason."
2781 (throw 'yas--exception (cons 'yas--exception text)))
2782
2783 (defun yas-verify-value (possibilities)
2784 "Verify that the current field value is in POSSIBILITIES.
2785
2786 Otherwise throw exception."
2787 (when (and yas-moving-away-p (notany #'(lambda (pos) (string= pos yas-text)) possibilities))
2788 (yas-throw (yas--format "Field only allows %s" possibilities))))
2789
2790 (defun yas-field-value (number)
2791 "Get the string for field with NUMBER.
2792
2793 Use this in primary and mirror transformations to tget."
2794 (let* ((snippet (car (yas--snippets-at-point)))
2795 (field (and snippet
2796 (yas--snippet-find-field snippet number))))
2797 (when field
2798 (yas--field-text-for-display field))))
2799
2800 (defun yas-text ()
2801 "Return `yas-text' if that exists and is non-empty, else nil."
2802 (if (and yas-text
2803 (not (string= "" yas-text)))
2804 yas-text))
2805
2806 (defun yas-selected-text ()
2807 "Return `yas-selected-text' if that exists and is non-empty, else nil."
2808 (if (and yas-selected-text
2809 (not (string= "" yas-selected-text)))
2810 yas-selected-text))
2811
2812 (defun yas--get-field-once (number &optional transform-fn)
2813 (unless yas-modified-p
2814 (if transform-fn
2815 (funcall transform-fn (yas-field-value number))
2816 (yas-field-value number))))
2817
2818 (defun yas-default-from-field (number)
2819 (unless yas-modified-p
2820 (yas-field-value number)))
2821
2822 (defun yas-inside-string ()
2823 "Return non-nil if the point is inside a string according to font-lock."
2824 (equal 'font-lock-string-face (get-char-property (1- (point)) 'face)))
2825
2826 (defun yas-unimplemented (&optional missing-feature)
2827 (if yas--current-template
2828 (if (y-or-n-p (format "This snippet is unimplemented (missing %s) Visit the snippet definition? "
2829 (or missing-feature
2830 "something")))
2831 (yas--visit-snippet-file-1 yas--current-template))
2832 (message "No implementation. Missing %s" (or missing-feature "something"))))
2833
2834 \f
2835 ;;; Snippet expansion and field management
2836
2837 (defvar yas--active-field-overlay nil
2838 "Overlays the currently active field.")
2839
2840 (defvar yas--field-protection-overlays nil
2841 "Two overlays protect the current active field.")
2842
2843 (defvar yas-selected-text nil
2844 "The selected region deleted on the last snippet expansion.")
2845
2846 (defvar yas--start-column nil
2847 "The column where the snippet expansion started.")
2848
2849 (make-variable-buffer-local 'yas--active-field-overlay)
2850 (make-variable-buffer-local 'yas--field-protection-overlays)
2851 (put 'yas--active-field-overlay 'permanent-local t)
2852 (put 'yas--field-protection-overlays 'permanent-local t)
2853
2854 (defstruct (yas--snippet (:constructor yas--make-snippet ()))
2855 "A snippet.
2856
2857 ..."
2858 (fields '())
2859 (exit nil)
2860 (id (yas--snippet-next-id) :read-only t)
2861 (control-overlay nil)
2862 active-field
2863 ;; stacked expansion: the `previous-active-field' slot saves the
2864 ;; active field where the child expansion took place
2865 previous-active-field
2866 force-exit)
2867
2868 (defstruct (yas--field (:constructor yas--make-field (number start end parent-field)))
2869 "A field.
2870
2871 NUMBER is the field number.
2872 START and END are mostly buffer markers, but see \"apropos markers-to-points\".
2873 PARENT-FIELD is a `yas--field' this field is nested under, or nil.
2874 MIRRORS is a list of `yas--mirror's
2875 TRANSFORM is a lisp form.
2876 MODIFIED-P is a boolean set to true once user inputs text.
2877 NEXT is another `yas--field' or `yas--mirror' or `yas--exit'.
2878 "
2879 number
2880 start end
2881 parent-field
2882 (mirrors '())
2883 (transform nil)
2884 (modified-p nil)
2885 next)
2886
2887
2888 (defstruct (yas--mirror (:constructor yas--make-mirror (start end transform)))
2889 "A mirror.
2890
2891 START and END are mostly buffer markers, but see \"apropos markers-to-points\".
2892 TRANSFORM is a lisp form.
2893 PARENT-FIELD is a `yas--field' this mirror is nested under, or nil.
2894 NEXT is another `yas--field' or `yas--mirror' or `yas--exit'
2895 DEPTH is a count of how many nested mirrors can affect this mirror"
2896 start end
2897 (transform nil)
2898 parent-field
2899 next
2900 depth)
2901
2902 (defstruct (yas--exit (:constructor yas--make-exit (marker)))
2903 marker
2904 next)
2905
2906 (defun yas--apply-transform (field-or-mirror field &optional empty-on-nil-p)
2907 "Calculate transformed string for FIELD-OR-MIRROR from FIELD.
2908
2909 If there is no transform for ht field, return nil.
2910
2911 If there is a transform but it returns nil, return the empty
2912 string iff EMPTY-ON-NIL-P is true."
2913 (let* ((yas-text (yas--field-text-for-display field))
2914 (yas-modified-p (yas--field-modified-p field))
2915 (yas-moving-away-p nil)
2916 (transform (if (yas--mirror-p field-or-mirror)
2917 (yas--mirror-transform field-or-mirror)
2918 (yas--field-transform field-or-mirror)))
2919 (start-point (if (yas--mirror-p field-or-mirror)
2920 (yas--mirror-start field-or-mirror)
2921 (yas--field-start field-or-mirror)))
2922 (transformed (and transform
2923 (save-excursion
2924 (goto-char start-point)
2925 (let ((ret (yas--eval-lisp transform)))
2926 (or ret (and empty-on-nil-p "")))))))
2927 transformed))
2928
2929 (defsubst yas--replace-all (from to &optional text)
2930 "Replace all occurrences from FROM to TO.
2931
2932 With optional string TEXT do it in that string."
2933 (if text
2934 (replace-regexp-in-string (regexp-quote from) to text t t)
2935 (goto-char (point-min))
2936 (while (search-forward from nil t)
2937 (replace-match to t t text))))
2938
2939 (defun yas--snippet-find-field (snippet number)
2940 (find-if #'(lambda (field)
2941 (eq number (yas--field-number field)))
2942 (yas--snippet-fields snippet)))
2943
2944 (defun yas--snippet-sort-fields (snippet)
2945 "Sort the fields of SNIPPET in navigation order."
2946 (setf (yas--snippet-fields snippet)
2947 (sort (yas--snippet-fields snippet)
2948 #'yas--snippet-field-compare)))
2949
2950 (defun yas--snippet-field-compare (field1 field2)
2951 "Compare FIELD1 and FIELD2.
2952
2953 The field with a number is sorted first. If they both have a
2954 number, compare through the number. If neither have, compare
2955 through the field's start point"
2956 (let ((n1 (yas--field-number field1))
2957 (n2 (yas--field-number field2)))
2958 (if n1
2959 (if n2
2960 (or (zerop n2) (and (not (zerop n1))
2961 (< n1 n2)))
2962 (not (zerop n1)))
2963 (if n2
2964 (zerop n2)
2965 (< (yas--field-start field1)
2966 (yas--field-start field2))))))
2967
2968 (defun yas--field-probably-deleted-p (snippet field)
2969 "Guess if SNIPPET's FIELD should be skipped."
2970 (and
2971 ;; field must be zero length
2972 ;;
2973 (zerop (- (yas--field-start field) (yas--field-end field)))
2974 ;; skip if:
2975 (or
2976 ;; 1) is a nested field and it's been modified
2977 ;;
2978 (and (yas--field-parent-field field)
2979 (yas--field-modified-p field))
2980 ;; 2) ends just before the snippet end
2981 ;;
2982 (and (eq field (car (last (yas--snippet-fields snippet))))
2983 (= (yas--field-start field) (overlay-end (yas--snippet-control-overlay snippet)))))
2984 ;; the field numbered 0, just before the exit marker, should
2985 ;; never be skipped
2986 ;;
2987 (not (zerop (yas--field-number field)))))
2988
2989 (defun yas--snippets-at-point (&optional all-snippets)
2990 "Return a sorted list of snippets at point.
2991
2992 The most recently-inserted snippets are returned first."
2993 (sort
2994 (remove nil (remove-duplicates (mapcar #'(lambda (ov)
2995 (overlay-get ov 'yas--snippet))
2996 (if all-snippets
2997 (overlays-in (point-min) (point-max))
2998 (nconc (overlays-at (point)) (overlays-at (1- (point))))))))
2999 #'(lambda (s1 s2)
3000 (<= (yas--snippet-id s2) (yas--snippet-id s1)))))
3001
3002 (defun yas-next-field-or-maybe-expand ()
3003 "Try to expand a snippet at a key before point.
3004
3005 Otherwise delegate to `yas-next-field'."
3006 (interactive)
3007 (if yas-triggers-in-field
3008 (let ((yas-fallback-behavior 'return-nil)
3009 (active-field (overlay-get yas--active-field-overlay 'yas--field)))
3010 (when active-field
3011 (unless (yas-expand-from-trigger-key active-field)
3012 (yas-next-field))))
3013 (yas-next-field)))
3014
3015 (defun yas-next-field (&optional arg)
3016 "Navigate to the ARGth next field.
3017
3018 If there's none, exit the snippet."
3019 (interactive)
3020 (let* ((arg (or arg
3021 1))
3022 (snippet (first (yas--snippets-at-point)))
3023 (active-field (overlay-get yas--active-field-overlay 'yas--field))
3024 (live-fields (remove-if #'(lambda (field)
3025 (and (not (eq field active-field))
3026 (yas--field-probably-deleted-p snippet field)))
3027 (yas--snippet-fields snippet)))
3028 (active-field-pos (position active-field live-fields))
3029 (target-pos (and active-field-pos (+ arg active-field-pos)))
3030 (target-field (and target-pos (nth target-pos live-fields))))
3031 ;; First check if we're moving out of a field with a transform
3032 ;;
3033 (when (and active-field
3034 (yas--field-transform active-field))
3035 (let* ((yas-moving-away-p t)
3036 (yas-text (yas--field-text-for-display active-field))
3037 (yas-modified-p (yas--field-modified-p active-field)))
3038 ;; primary field transform: exit call to field-transform
3039 (yas--eval-lisp (yas--field-transform active-field))))
3040 ;; Now actually move...
3041 (cond ((and target-pos (>= target-pos (length live-fields)))
3042 (yas-exit-snippet snippet))
3043 (target-field
3044 (yas--move-to-field snippet target-field))
3045 (t
3046 nil))))
3047
3048 (defun yas--place-overlays (snippet field)
3049 "Correctly place overlays for SNIPPET's FIELD."
3050 (yas--make-move-field-protection-overlays snippet field)
3051 (yas--make-move-active-field-overlay snippet field))
3052
3053 (defun yas--move-to-field (snippet field)
3054 "Update SNIPPET to move to field FIELD.
3055
3056 Also create some protection overlays"
3057 (goto-char (yas--field-start field))
3058 (yas--place-overlays snippet field)
3059 (overlay-put yas--active-field-overlay 'yas--field field)
3060 (let ((number (yas--field-number field)))
3061 ;; check for the special ${0: ...} field
3062 (if (and number (zerop number))
3063 (progn
3064 (set-mark (yas--field-end field))
3065 (setf (yas--snippet-force-exit snippet)
3066 (or (yas--field-transform field)
3067 t)))
3068 ;; make this field active
3069 (setf (yas--snippet-active-field snippet) field)
3070 ;; primary field transform: first call to snippet transform
3071 (unless (yas--field-modified-p field)
3072 (if (yas--field-update-display field)
3073 (yas--update-mirrors snippet)
3074 (setf (yas--field-modified-p field) nil))))))
3075
3076 (defun yas-prev-field ()
3077 "Navigate to prev field. If there's none, exit the snippet."
3078 (interactive)
3079 (yas-next-field -1))
3080
3081 (defun yas-abort-snippet (&optional snippet)
3082 (interactive)
3083 (let ((snippet (or snippet
3084 (car (yas--snippets-at-point)))))
3085 (when snippet
3086 (setf (yas--snippet-force-exit snippet) t))))
3087
3088 (defun yas-exit-snippet (snippet)
3089 "Goto exit-marker of SNIPPET."
3090 (interactive (list (first (yas--snippets-at-point))))
3091 (when snippet
3092 (setf (yas--snippet-force-exit snippet) t)
3093 (goto-char (if (yas--snippet-exit snippet)
3094 (yas--exit-marker (yas--snippet-exit snippet))
3095 (overlay-end (yas--snippet-control-overlay snippet))))))
3096
3097 (defun yas-exit-all-snippets ()
3098 "Exit all snippets."
3099 (interactive)
3100 (mapc #'(lambda (snippet)
3101 (yas-exit-snippet snippet)
3102 (yas--check-commit-snippet))
3103 (yas--snippets-at-point 'all-snippets)))
3104
3105 \f
3106 ;;; Some low level snippet-routines:
3107
3108 (defvar yas--inhibit-overlay-hooks nil
3109 "Bind this temporarily to non-nil to prevent running `yas--on-*-modification'.")
3110
3111 (defmacro yas--inhibit-overlay-hooks (&rest body)
3112 "Run BODY with `yas--inhibit-overlay-hooks' set to t."
3113 (declare (indent 0))
3114 `(let ((yas--inhibit-overlay-hooks t))
3115 ,@body))
3116
3117 (defvar yas-snippet-beg nil "Beginning position of the last snippet committed.")
3118 (defvar yas-snippet-end nil "End position of the last snippet committed.")
3119
3120 (defun yas--commit-snippet (snippet)
3121 "Commit SNIPPET, but leave point as it is.
3122
3123 This renders the snippet as ordinary text."
3124
3125 (let ((control-overlay (yas--snippet-control-overlay snippet)))
3126 ;;
3127 ;; Save the end of the moribund snippet in case we need to revive it
3128 ;; its original expansion.
3129 ;;
3130 (when (and control-overlay
3131 (overlay-buffer control-overlay))
3132 (setq yas-snippet-beg (overlay-start control-overlay))
3133 (setq yas-snippet-end (overlay-end control-overlay))
3134 (delete-overlay control-overlay))
3135
3136 (yas--inhibit-overlay-hooks
3137 (when yas--active-field-overlay
3138 (delete-overlay yas--active-field-overlay))
3139 (when yas--field-protection-overlays
3140 (mapc #'delete-overlay yas--field-protection-overlays)))
3141
3142 ;; stacked expansion: if the original expansion took place from a
3143 ;; field, make sure we advance it here at least to
3144 ;; `yas-snippet-end'...
3145 ;;
3146 (let ((previous-field (yas--snippet-previous-active-field snippet)))
3147 (when (and yas-snippet-end previous-field)
3148 (yas--advance-end-maybe previous-field yas-snippet-end)))
3149
3150 ;; Convert all markers to points,
3151 ;;
3152 (yas--markers-to-points snippet)
3153
3154 ;; Take care of snippet revival
3155 ;;
3156 (if yas-snippet-revival
3157 (push `(apply yas--snippet-revive ,yas-snippet-beg ,yas-snippet-end ,snippet)
3158 buffer-undo-list)
3159 ;; Dismember the snippet... this is useful if we get called
3160 ;; again from `yas--take-care-of-redo'....
3161 (setf (yas--snippet-fields snippet) nil)))
3162
3163 (yas--message 3 "Snippet %s exited." (yas--snippet-id snippet)))
3164
3165 (defun yas--safely-run-hooks (hook-var)
3166 (condition-case error
3167 (run-hooks hook-var)
3168 (error
3169 (yas--message 3 "%s error: %s" hook-var (error-message-string error)))))
3170
3171
3172 (defun yas--check-commit-snippet ()
3173 "Check if point exited the currently active field of the snippet.
3174
3175 If so cleans up the whole snippet up."
3176 (let* ((snippets (yas--snippets-at-point 'all-snippets))
3177 (snippets-left snippets)
3178 (snippet-exit-transform))
3179 (dolist (snippet snippets)
3180 (let ((active-field (yas--snippet-active-field snippet)))
3181 (setq snippet-exit-transform (yas--snippet-force-exit snippet))
3182 (cond ((or snippet-exit-transform
3183 (not (and active-field (yas--field-contains-point-p active-field))))
3184 (setq snippets-left (delete snippet snippets-left))
3185 (setf (yas--snippet-force-exit snippet) nil)
3186 (yas--commit-snippet snippet))
3187 ((and active-field
3188 (or (not yas--active-field-overlay)
3189 (not (overlay-buffer yas--active-field-overlay))))
3190 ;;
3191 ;; stacked expansion: this case is mainly for recent
3192 ;; snippet exits that place us back int the field of
3193 ;; another snippet
3194 ;;
3195 (save-excursion
3196 (yas--move-to-field snippet active-field)
3197 (yas--update-mirrors snippet)))
3198 (t
3199 nil))))
3200 (unless (or (null snippets) snippets-left)
3201 (if snippet-exit-transform
3202 (yas--eval-lisp-no-saves snippet-exit-transform))
3203 (yas--safely-run-hooks 'yas-after-exit-snippet-hook))))
3204
3205 ;; Apropos markers-to-points:
3206 ;;
3207 ;; This was found useful for performance reasons, so that an
3208 ;; excessive number of live markers aren't kept around in the
3209 ;; `buffer-undo-list'. However, in `markers-to-points', the
3210 ;; set-to-nil markers can't simply be discarded and replaced with
3211 ;; fresh ones in `points-to-markers'. The original marker that was
3212 ;; just set to nil has to be reused.
3213 ;;
3214 ;; This shouldn't bring horrible problems with undo/redo, but it
3215 ;; you never know
3216 ;;
3217 (defun yas--markers-to-points (snippet)
3218 "Convert all markers in SNIPPET to a cons (POINT . MARKER)
3219 where POINT is the original position of the marker and MARKER is
3220 the original marker object with the position set to nil."
3221 (dolist (field (yas--snippet-fields snippet))
3222 (let ((start (marker-position (yas--field-start field)))
3223 (end (marker-position (yas--field-end field))))
3224 (set-marker (yas--field-start field) nil)
3225 (set-marker (yas--field-end field) nil)
3226 (setf (yas--field-start field) (cons start (yas--field-start field)))
3227 (setf (yas--field-end field) (cons end (yas--field-end field))))
3228 (dolist (mirror (yas--field-mirrors field))
3229 (let ((start (marker-position (yas--mirror-start mirror)))
3230 (end (marker-position (yas--mirror-end mirror))))
3231 (set-marker (yas--mirror-start mirror) nil)
3232 (set-marker (yas--mirror-end mirror) nil)
3233 (setf (yas--mirror-start mirror) (cons start (yas--mirror-start mirror)))
3234 (setf (yas--mirror-end mirror) (cons end (yas--mirror-end mirror))))))
3235 (let ((snippet-exit (yas--snippet-exit snippet)))
3236 (when snippet-exit
3237 (let ((exit (marker-position (yas--exit-marker snippet-exit))))
3238 (set-marker (yas--exit-marker snippet-exit) nil)
3239 (setf (yas--exit-marker snippet-exit) (cons exit (yas--exit-marker snippet-exit)))))))
3240
3241 (defun yas--points-to-markers (snippet)
3242 "Convert all cons (POINT . MARKER) in SNIPPET to markers.
3243
3244 This is done by setting MARKER to POINT with `set-marker'."
3245 (dolist (field (yas--snippet-fields snippet))
3246 (setf (yas--field-start field) (set-marker (cdr (yas--field-start field))
3247 (car (yas--field-start field))))
3248 (setf (yas--field-end field) (set-marker (cdr (yas--field-end field))
3249 (car (yas--field-end field))))
3250 (dolist (mirror (yas--field-mirrors field))
3251 (setf (yas--mirror-start mirror) (set-marker (cdr (yas--mirror-start mirror))
3252 (car (yas--mirror-start mirror))))
3253 (setf (yas--mirror-end mirror) (set-marker (cdr (yas--mirror-end mirror))
3254 (car (yas--mirror-end mirror))))))
3255 (let ((snippet-exit (yas--snippet-exit snippet)))
3256 (when snippet-exit
3257 (setf (yas--exit-marker snippet-exit) (set-marker (cdr (yas--exit-marker snippet-exit))
3258 (car (yas--exit-marker snippet-exit)))))))
3259
3260 (defun yas--field-contains-point-p (field &optional point)
3261 (let ((point (or point
3262 (point))))
3263 (and (>= point (yas--field-start field))
3264 (<= point (yas--field-end field)))))
3265
3266 (defun yas--field-text-for-display (field)
3267 "Return the propertized display text for field FIELD."
3268 (buffer-substring (yas--field-start field) (yas--field-end field)))
3269
3270 (defun yas--undo-in-progress ()
3271 "True if some kind of undo is in progress."
3272 (or undo-in-progress
3273 (eq this-command 'undo)
3274 (eq this-command 'redo)))
3275
3276 (defun yas--make-control-overlay (snippet start end)
3277 "Create the control overlay that surrounds the snippet and
3278 holds the keymap."
3279 (let ((overlay (make-overlay start
3280 end
3281 nil
3282 nil
3283 t)))
3284 (overlay-put overlay 'keymap yas-keymap)
3285 (overlay-put overlay 'priority 100)
3286 (overlay-put overlay 'yas--snippet snippet)
3287 overlay))
3288
3289 (defun yas-skip-and-clear-or-delete-char (&optional field)
3290 "Clears unmodified field if at field start, skips to next tab.
3291
3292 Otherwise deletes a character normally by calling `delete-char'."
3293 (interactive)
3294 (let ((field (or field
3295 (and yas--active-field-overlay
3296 (overlay-buffer yas--active-field-overlay)
3297 (overlay-get yas--active-field-overlay 'yas--field)))))
3298 (cond ((and field
3299 (not (yas--field-modified-p field))
3300 (eq (point) (marker-position (yas--field-start field))))
3301 (yas--skip-and-clear field)
3302 (yas-next-field 1))
3303 (t
3304 (call-interactively 'delete-char)))))
3305
3306 (defun yas--skip-and-clear (field)
3307 "Deletes the region of FIELD and sets it's modified state to t."
3308 ;; Just before skipping-and-clearing the field, mark its children
3309 ;; fields as modified, too. If the children have mirrors-in-fields
3310 ;; this prevents them from updating erroneously (we're skipping and
3311 ;; deleting!).
3312 ;;
3313 (yas--mark-this-and-children-modified field)
3314 (delete-region (yas--field-start field) (yas--field-end field)))
3315
3316 (defun yas--mark-this-and-children-modified (field)
3317 (setf (yas--field-modified-p field) t)
3318 (let ((fom (yas--field-next field)))
3319 (while (and fom
3320 (yas--fom-parent-field fom))
3321 (when (and (eq (yas--fom-parent-field fom) field)
3322 (yas--field-p fom))
3323 (yas--mark-this-and-children-modified fom))
3324 (setq fom (yas--fom-next fom)))))
3325
3326 (defun yas--make-move-active-field-overlay (snippet field)
3327 "Place the active field overlay in SNIPPET's FIELD.
3328
3329 Move the overlay, or create it if it does not exit."
3330 (if (and yas--active-field-overlay
3331 (overlay-buffer yas--active-field-overlay))
3332 (move-overlay yas--active-field-overlay
3333 (yas--field-start field)
3334 (yas--field-end field))
3335 (setq yas--active-field-overlay
3336 (make-overlay (yas--field-start field)
3337 (yas--field-end field)
3338 nil nil t))
3339 (overlay-put yas--active-field-overlay 'priority 100)
3340 (overlay-put yas--active-field-overlay 'face 'yas-field-highlight-face)
3341 (overlay-put yas--active-field-overlay 'yas--snippet snippet)
3342 (overlay-put yas--active-field-overlay 'modification-hooks '(yas--on-field-overlay-modification))
3343 (overlay-put yas--active-field-overlay 'insert-in-front-hooks
3344 '(yas--on-field-overlay-modification))
3345 (overlay-put yas--active-field-overlay 'insert-behind-hooks
3346 '(yas--on-field-overlay-modification))))
3347
3348 (defun yas--on-field-overlay-modification (overlay after? _beg _end &optional _length)
3349 "Clears the field and updates mirrors, conditionally.
3350
3351 Only clears the field if it hasn't been modified and it point it
3352 at field start. This hook doesn't do anything if an undo is in
3353 progress."
3354 (unless (or yas--inhibit-overlay-hooks
3355 (yas--undo-in-progress))
3356 (let* ((field (overlay-get overlay 'yas--field))
3357 (snippet (overlay-get yas--active-field-overlay 'yas--snippet)))
3358 (cond (after?
3359 (yas--advance-end-maybe field (overlay-end overlay))
3360 (save-excursion
3361 (yas--field-update-display field))
3362 (yas--update-mirrors snippet))
3363 (field
3364 (when (and (not after?)
3365 (not (yas--field-modified-p field))
3366 (eq (point) (if (markerp (yas--field-start field))
3367 (marker-position (yas--field-start field))
3368 (yas--field-start field))))
3369 (yas--skip-and-clear field))
3370 (setf (yas--field-modified-p field) t))))))
3371 \f
3372 ;;; Apropos protection overlays:
3373 ;;
3374 ;; These exist for nasty users who will try to delete parts of the
3375 ;; snippet outside the active field. Actual protection happens in
3376 ;; `yas--on-protection-overlay-modification'.
3377 ;;
3378 ;; Currently this signals an error which inhibits the command. For
3379 ;; commands that move point (like `kill-line'), point is restored in
3380 ;; the `yas--post-command-handler' using a global
3381 ;; `yas--protection-violation' variable.
3382 ;;
3383 ;; Alternatively, I've experimented with an implementation that
3384 ;; commits the snippet before actually calling `this-command'
3385 ;; interactively, and then signals an error, which is ignored. but
3386 ;; blocks all other million modification hooks. This presented some
3387 ;; problems with stacked expansion.
3388 ;;
3389 (defun yas--make-move-field-protection-overlays (snippet field)
3390 "Place protection overlays surrounding SNIPPET's FIELD.
3391
3392 Move the overlays, or create them if they do not exit."
3393 (let ((start (yas--field-start field))
3394 (end (yas--field-end field)))
3395 ;; First check if the (1+ end) is contained in the buffer,
3396 ;; otherwise we'll have to do a bit of cheating and silently
3397 ;; insert a newline. the `(1+ (buffer-size))' should prevent this
3398 ;; when using stacked expansion
3399 ;;
3400 (when (< (buffer-size) end)
3401 (save-excursion
3402 (yas--inhibit-overlay-hooks
3403 (goto-char (point-max))
3404 (newline))))
3405 ;; go on to normal overlay creation/moving
3406 ;;
3407 (cond ((and yas--field-protection-overlays
3408 (every #'overlay-buffer yas--field-protection-overlays))
3409 (move-overlay (first yas--field-protection-overlays) (1- start) start)
3410 (move-overlay (second yas--field-protection-overlays) end (1+ end)))
3411 (t
3412 (setq yas--field-protection-overlays
3413 (list (make-overlay (1- start) start nil t nil)
3414 (make-overlay end (1+ end) nil t nil)))
3415 (dolist (ov yas--field-protection-overlays)
3416 (overlay-put ov 'face 'yas--field-debug-face)
3417 (overlay-put ov 'yas--snippet snippet)
3418 ;; (overlay-put ov 'evaporate t)
3419 (overlay-put ov 'modification-hooks '(yas--on-protection-overlay-modification)))))))
3420
3421 (defvar yas--protection-violation nil
3422 "When non-nil, signals attempts to erroneously exit or modify the snippet.
3423
3424 Functions in the `post-command-hook', for example
3425 `yas--post-command-handler' can check it and reset its value to
3426 nil. The variables value is the point where the violation
3427 originated")
3428
3429 (defun yas--on-protection-overlay-modification (_overlay after? _beg _end &optional _length)
3430 "Signals a snippet violation, then issues error.
3431
3432 The error should be ignored in `debug-ignored-errors'"
3433 (unless yas--inhibit-overlay-hooks
3434 (cond ((not (or after?
3435 (yas--undo-in-progress)))
3436 (setq yas--protection-violation (point))
3437 (error "Exit the snippet first!")))))
3438
3439 (add-to-list 'debug-ignored-errors "^Exit the snippet first!$")
3440
3441 \f
3442 ;;; Snippet expansion and "stacked" expansion:
3443 ;;
3444 ;; Stacked expansion is when you try to expand a snippet when already
3445 ;; inside a snippet expansion.
3446 ;;
3447 ;; The parent snippet does not run its fields modification hooks
3448 ;; (`yas--on-field-overlay-modification' and
3449 ;; `yas--on-protection-overlay-modification') while the child snippet
3450 ;; is active. This means, among other things, that the mirrors of the
3451 ;; parent snippet are not updated, this only happening when one exits
3452 ;; the child snippet.
3453 ;;
3454 ;; Unfortunately, this also puts some ugly (and not fully-tested)
3455 ;; bits of code in `yas-expand-snippet' and
3456 ;; `yas--commit-snippet'. I've tried to mark them with "stacked
3457 ;; expansion:".
3458 ;;
3459 ;; This was thought to be safer in an undo/redo perspective, but
3460 ;; maybe the correct implementation is to make the globals
3461 ;; `yas--active-field-overlay' and `yas--field-protection-overlays' be
3462 ;; snippet-local and be active even while the child snippet is
3463 ;; running. This would mean a lot of overlay modification hooks
3464 ;; running, but if managed correctly (including overlay priorities)
3465 ;; they should account for all situations...
3466 ;;
3467 (defun yas-expand-snippet (content &optional start end expand-env)
3468 "Expand snippet CONTENT at current point.
3469
3470 Text between START and END will be deleted before inserting
3471 template. EXPAND-ENV is are let-style variable to value bindings
3472 considered when expanding the snippet."
3473 (run-hooks 'yas-before-expand-snippet-hook)
3474
3475 ;;
3476 (let* ((yas-selected-text (or yas-selected-text
3477 (and (region-active-p)
3478 (buffer-substring-no-properties (region-beginning)
3479 (region-end)))))
3480 (start (or start
3481 (and (region-active-p)
3482 (region-beginning))
3483 (point)))
3484 (end (or end
3485 (and (region-active-p)
3486 (region-end))
3487 (point)))
3488 (to-delete (and start
3489 end
3490 (buffer-substring-no-properties start end)))
3491 snippet)
3492 (goto-char start)
3493 (setq yas--indent-original-column (current-column))
3494 ;; Delete the region to delete, this *does* get undo-recorded.
3495 ;;
3496 (when (and to-delete
3497 (> end start))
3498 (delete-region start end))
3499
3500 (cond ((listp content)
3501 ;; x) This is a snippet-command
3502 ;;
3503 (yas--eval-lisp-no-saves content))
3504 (t
3505 ;; x) This is a snippet-snippet :-)
3506 ;;
3507 ;; Narrow the region down to the content, shoosh the
3508 ;; `buffer-undo-list', and create the snippet, the new
3509 ;; snippet updates its mirrors once, so we are left with
3510 ;; some plain text. The undo action for deleting this
3511 ;; plain text will get recorded at the end.
3512 ;;
3513 ;; stacked expansion: also shoosh the overlay modification hooks
3514 (save-restriction
3515 (narrow-to-region start start)
3516 (let ((buffer-undo-list t))
3517 ;; snippet creation might evaluate users elisp, which
3518 ;; might generate errors, so we have to be ready to catch
3519 ;; them mostly to make the undo information
3520 ;;
3521 (setq yas--start-column (save-restriction (widen) (current-column)))
3522 (yas--inhibit-overlay-hooks
3523 (setq snippet
3524 (if expand-env
3525 (eval `(let* ,expand-env
3526 (insert content)
3527 (yas--snippet-create (point-min))))
3528 (insert content)
3529 (yas--snippet-create (point-min)))))))
3530
3531 ;; stacked-expansion: This checks for stacked expansion, save the
3532 ;; `yas--previous-active-field' and advance its boundary.
3533 ;;
3534 (let ((existing-field (and yas--active-field-overlay
3535 (overlay-buffer yas--active-field-overlay)
3536 (overlay-get yas--active-field-overlay 'yas--field))))
3537 (when existing-field
3538 (setf (yas--snippet-previous-active-field snippet) existing-field)
3539 (yas--advance-end-maybe existing-field (overlay-end yas--active-field-overlay))))
3540
3541 ;; Exit the snippet immediately if no fields
3542 ;;
3543 (unless (yas--snippet-fields snippet)
3544 (yas-exit-snippet snippet))
3545
3546 ;; Push two undo actions: the deletion of the inserted contents of
3547 ;; the new snippet (without the "key") followed by an apply of
3548 ;; `yas--take-care-of-redo' on the newly inserted snippet boundaries
3549 ;;
3550 ;; A small exception, if `yas-also-auto-indent-first-line'
3551 ;; is t and `yas--indent' decides to indent the line to a
3552 ;; point before the actual expansion point, undo would be
3553 ;; messed up. We call the early point "newstart"". case,
3554 ;; and attempt to fix undo.
3555 ;;
3556 (let ((newstart (overlay-start (yas--snippet-control-overlay snippet)))
3557 (end (overlay-end (yas--snippet-control-overlay snippet))))
3558 (when (< newstart start)
3559 (push (cons (make-string (- start newstart) ? ) newstart) buffer-undo-list))
3560 (push (cons newstart end) buffer-undo-list)
3561 (push `(apply yas--take-care-of-redo ,start ,end ,snippet)
3562 buffer-undo-list))
3563 ;; Now, schedule a move to the first field
3564 ;;
3565 (let ((first-field (car (yas--snippet-fields snippet))))
3566 (when first-field
3567 (sit-for 0) ;; fix issue 125
3568 (yas--move-to-field snippet first-field)))
3569 (yas--message 3 "snippet expanded.")
3570 t))))
3571
3572 (defun yas--take-care-of-redo (_beg _end snippet)
3573 "Commits SNIPPET, which in turn pushes an undo action for reviving it.
3574
3575 Meant to exit in the `buffer-undo-list'."
3576 ;; slightly optimize: this action is only needed for snippets with
3577 ;; at least one field
3578 (when (yas--snippet-fields snippet)
3579 (yas--commit-snippet snippet)))
3580
3581 (defun yas--snippet-revive (beg end snippet)
3582 "Revives SNIPPET and creates a control overlay from BEG to END.
3583
3584 BEG and END are, we hope, the original snippets boundaries.
3585 All the markers/points exiting existing inside SNIPPET should point
3586 to their correct locations *at the time the snippet is revived*.
3587
3588 After revival, push the `yas--take-care-of-redo' in the
3589 `buffer-undo-list'"
3590 ;; Reconvert all the points to markers
3591 ;;
3592 (yas--points-to-markers snippet)
3593 ;; When at least one editable field existed in the zombie snippet,
3594 ;; try to revive the whole thing...
3595 ;;
3596 (let ((target-field (or (yas--snippet-active-field snippet)
3597 (car (yas--snippet-fields snippet)))))
3598 (when target-field
3599 (setf (yas--snippet-control-overlay snippet) (yas--make-control-overlay snippet beg end))
3600 (overlay-put (yas--snippet-control-overlay snippet) 'yas--snippet snippet)
3601
3602 (yas--move-to-field snippet target-field)
3603
3604 (push `(apply yas--take-care-of-redo ,beg ,end ,snippet)
3605 buffer-undo-list))))
3606
3607 (defun yas--snippet-create (begin)
3608 "Create a snippet from a template inserted at BEGIN.
3609
3610 Returns the newly created snippet."
3611 (let ((snippet (yas--make-snippet)))
3612 (goto-char begin)
3613 (yas--snippet-parse-create snippet)
3614
3615 ;; Sort and link each field
3616 (yas--snippet-sort-fields snippet)
3617
3618 ;; Create keymap overlay for snippet
3619 (setf (yas--snippet-control-overlay snippet)
3620 (yas--make-control-overlay snippet (point-min) (point-max)))
3621
3622 ;; Move to end
3623 (goto-char (point-max))
3624
3625 snippet))
3626
3627 \f
3628 ;;; Apropos adjacencies and "fom's":
3629 ;;
3630 ;; Once the $-constructs bits like "$n" and "${:n" are deleted in the
3631 ;; recently expanded snippet, we might actually have many fields,
3632 ;; mirrors (and the snippet exit) in the very same position in the
3633 ;; buffer. Therefore we need to single-link the
3634 ;; fields-or-mirrors-or-exit (which I have abbreviated to "fom")
3635 ;; according to their original positions in the buffer.
3636 ;;
3637 ;; Then we have operation `yas--advance-end-maybe' and
3638 ;; `yas--advance-start-maybe', which conditionally push the starts and
3639 ;; ends of these foms down the chain.
3640 ;;
3641 ;; This allows for like the printf with the magic ",":
3642 ;;
3643 ;; printf ("${1:%s}\\n"${1:$(if (string-match "%" text) "," "\);")} \
3644 ;; $2${1:$(if (string-match "%" text) "\);" "")}$0
3645 ;;
3646 (defun yas--fom-start (fom)
3647 (cond ((yas--field-p fom)
3648 (yas--field-start fom))
3649 ((yas--mirror-p fom)
3650 (yas--mirror-start fom))
3651 (t
3652 (yas--exit-marker fom))))
3653
3654 (defun yas--fom-end (fom)
3655 (cond ((yas--field-p fom)
3656 (yas--field-end fom))
3657 ((yas--mirror-p fom)
3658 (yas--mirror-end fom))
3659 (t
3660 (yas--exit-marker fom))))
3661
3662 (defun yas--fom-next (fom)
3663 (cond ((yas--field-p fom)
3664 (yas--field-next fom))
3665 ((yas--mirror-p fom)
3666 (yas--mirror-next fom))
3667 (t
3668 (yas--exit-next fom))))
3669
3670 (defun yas--fom-parent-field (fom)
3671 (cond ((yas--field-p fom)
3672 (yas--field-parent-field fom))
3673 ((yas--mirror-p fom)
3674 (yas--mirror-parent-field fom))
3675 (t
3676 nil)))
3677
3678 (defun yas--calculate-adjacencies (snippet)
3679 "Calculate adjacencies for fields or mirrors of SNIPPET.
3680
3681 This is according to their relative positions in the buffer, and
3682 has to be called before the $-constructs are deleted."
3683 (let* ((fom-set-next-fom
3684 (lambda (fom nextfom)
3685 (cond ((yas--field-p fom)
3686 (setf (yas--field-next fom) nextfom))
3687 ((yas--mirror-p fom)
3688 (setf (yas--mirror-next fom) nextfom))
3689 (t
3690 (setf (yas--exit-next fom) nextfom)))))
3691 (compare-fom-begs
3692 (lambda (fom1 fom2)
3693 (if (= (yas--fom-start fom2) (yas--fom-start fom1))
3694 (yas--mirror-p fom2)
3695 (>= (yas--fom-start fom2) (yas--fom-start fom1)))))
3696 (link-foms fom-set-next-fom))
3697 ;; make some yas--field, yas--mirror and yas--exit soup
3698 (let ((soup))
3699 (when (yas--snippet-exit snippet)
3700 (push (yas--snippet-exit snippet) soup))
3701 (dolist (field (yas--snippet-fields snippet))
3702 (push field soup)
3703 (dolist (mirror (yas--field-mirrors field))
3704 (push mirror soup)))
3705 (setq soup
3706 (sort soup compare-fom-begs))
3707 (when soup
3708 (reduce link-foms soup)))))
3709
3710 (defun yas--calculate-mirrors-in-fields (snippet mirror)
3711 "Attempt to assign a parent field of SNIPPET to the mirror MIRROR.
3712
3713 Use the tightest containing field if more than one field contains
3714 the mirror. Intended to be called *before* the dollar-regions are
3715 deleted."
3716 (let ((min (point-min))
3717 (max (point-max)))
3718 (dolist (field (yas--snippet-fields snippet))
3719 (when (and (<= (yas--field-start field) (yas--mirror-start mirror))
3720 (<= (yas--mirror-end mirror) (yas--field-end field))
3721 (< min (yas--field-start field))
3722 (< (yas--field-end field) max))
3723 (setq min (yas--field-start field)
3724 max (yas--field-end field))
3725 (setf (yas--mirror-parent-field mirror) field)))))
3726
3727 (defun yas--advance-end-maybe (fom newend)
3728 "Maybe advance FOM's end to NEWEND if it needs it.
3729
3730 If it does, also:
3731
3732 * call `yas--advance-start-maybe' on FOM's next fom.
3733
3734 * in case FOM is field call `yas--advance-end-maybe' on its parent
3735 field
3736
3737 Also, if FOM is an exit-marker, always call
3738 `yas--advance-start-maybe' on its next fom. This is because
3739 exit-marker have identical start and end markers."
3740 (cond ((and fom (< (yas--fom-end fom) newend))
3741 (set-marker (yas--fom-end fom) newend)
3742 (yas--advance-start-maybe (yas--fom-next fom) newend)
3743 (yas--advance-end-of-parents-maybe (yas--fom-parent-field fom) newend))
3744 ((yas--exit-p fom)
3745 (yas--advance-start-maybe (yas--fom-next fom) newend))))
3746
3747 (defun yas--advance-start-maybe (fom newstart)
3748 "Maybe advance FOM's start to NEWSTART if it needs it.
3749
3750 If it does, also call `yas--advance-end-maybe' on FOM."
3751 (when (and fom (< (yas--fom-start fom) newstart))
3752 (set-marker (yas--fom-start fom) newstart)
3753 (yas--advance-end-maybe fom newstart)))
3754
3755 (defun yas--advance-end-of-parents-maybe (field newend)
3756 "Like `yas--advance-end-maybe' but for parent fields.
3757
3758 Only works for fields and doesn't care about the start of the
3759 next FOM. Works its way up recursively for parents of parents."
3760 (when (and field
3761 (< (yas--field-end field) newend))
3762 (set-marker (yas--field-end field) newend)
3763 (yas--advance-end-of-parents-maybe (yas--field-parent-field field) newend)))
3764
3765 (defvar yas--dollar-regions nil
3766 "When expanding the snippet the \"parse-create\" functions add
3767 cons cells to this var.")
3768
3769 (defvar yas--backquote-markers-and-strings nil
3770 "List of (MARKER . STRING) marking where the values from
3771 backquoted Lisp expressions should be inserted at the end of
3772 expansion.")
3773
3774 (defun yas--snippet-parse-create (snippet)
3775 "Parse a recently inserted snippet template, creating all
3776 necessary fields, mirrors and exit points.
3777
3778 Meant to be called in a narrowed buffer, does various passes"
3779 (let ((parse-start (point)))
3780 ;; Reset the yas--dollar-regions
3781 ;;
3782 (setq yas--dollar-regions nil)
3783 ;; protect just the backquotes
3784 ;;
3785 (yas--protect-escapes nil '(?`))
3786 ;; replace all backquoted expressions
3787 ;;
3788 (goto-char parse-start)
3789 (yas--save-backquotes)
3790 ;; protect escaped characters
3791 ;;
3792 (yas--protect-escapes)
3793 ;; parse fields with {}
3794 ;;
3795 (goto-char parse-start)
3796 (yas--field-parse-create snippet)
3797 ;; parse simple mirrors and fields
3798 ;;
3799 (goto-char parse-start)
3800 (yas--simple-mirror-parse-create snippet)
3801 ;; parse mirror transforms
3802 ;;
3803 (goto-char parse-start)
3804 (yas--transform-mirror-parse-create snippet)
3805 ;; calculate adjacencies of fields and mirrors
3806 ;;
3807 (yas--calculate-adjacencies snippet)
3808 ;; Delete $-constructs
3809 ;;
3810 (yas--delete-regions yas--dollar-regions)
3811 ;; restore backquoted expression values
3812 ;;
3813 (yas--restore-backquotes)
3814 ;; restore escapes
3815 ;;
3816 (goto-char parse-start)
3817 (yas--restore-escapes)
3818 ;; update mirrors for the first time
3819 ;;
3820 (yas--update-mirrors snippet)
3821 ;; indent the best we can
3822 ;;
3823 (goto-char parse-start)
3824 (yas--indent snippet)))
3825
3826 (defun yas--indent-according-to-mode (snippet-markers)
3827 "Indent current line according to mode, preserving SNIPPET-MARKERS."
3828 ;;; Apropos indenting problems....
3829 ;;
3830 ;; `indent-according-to-mode' uses whatever `indent-line-function'
3831 ;; is available. Some implementations of these functions delete text
3832 ;; before they insert. If there happens to be a marker just after
3833 ;; the text being deleted, the insertion actually happens after the
3834 ;; marker, which misplaces it.
3835 ;;
3836 ;; This would also happen if we had used overlays with the
3837 ;; `front-advance' property set to nil.
3838 ;;
3839 ;; This is why I have these `trouble-markers', they are the ones at
3840 ;; they are the ones at the first non-whitespace char at the line
3841 ;; (i.e. at `yas--real-line-beginning'. After indentation takes place
3842 ;; we should be at the correct to restore them to. All other
3843 ;; non-trouble-markers have been *pushed* and don't need special
3844 ;; attention.
3845 ;;
3846 (goto-char (yas--real-line-beginning))
3847 (let ((trouble-markers (remove-if-not #'(lambda (marker)
3848 (= marker (point)))
3849 snippet-markers)))
3850 (save-restriction
3851 (widen)
3852 (condition-case _
3853 (indent-according-to-mode)
3854 (error (yas--message 3 "Warning: `yas--indent-according-to-mode' having problems running %s" indent-line-function)
3855 nil)))
3856 (mapc #'(lambda (marker)
3857 (set-marker marker (point)))
3858 trouble-markers)))
3859
3860 (defvar yas--indent-original-column nil)
3861 (defun yas--indent (snippet)
3862 (let ((snippet-markers (yas--collect-snippet-markers snippet)))
3863 ;; Look for those $>
3864 (save-excursion
3865 (while (re-search-forward "$>" nil t)
3866 (delete-region (match-beginning 0) (match-end 0))
3867 (when (not (eq yas-indent-line 'auto))
3868 (yas--indent-according-to-mode snippet-markers))))
3869 ;; Now do stuff for 'fixed and 'auto
3870 (save-excursion
3871 (cond ((eq yas-indent-line 'fixed)
3872 (while (and (zerop (forward-line))
3873 (zerop (current-column)))
3874 (indent-to-column yas--indent-original-column)))
3875 ((eq yas-indent-line 'auto)
3876 (let ((end (set-marker (make-marker) (point-max)))
3877 (indent-first-line-p yas-also-auto-indent-first-line))
3878 (while (and (zerop (if indent-first-line-p
3879 (prog1
3880 (forward-line 0)
3881 (setq indent-first-line-p nil))
3882 (forward-line 1)))
3883 (not (eobp))
3884 (<= (point) end))
3885 (yas--indent-according-to-mode snippet-markers))))
3886 (t
3887 nil)))))
3888
3889 (defun yas--collect-snippet-markers (snippet)
3890 "Make a list of all the markers used by SNIPPET."
3891 (let (markers)
3892 (dolist (field (yas--snippet-fields snippet))
3893 (push (yas--field-start field) markers)
3894 (push (yas--field-end field) markers)
3895 (dolist (mirror (yas--field-mirrors field))
3896 (push (yas--mirror-start mirror) markers)
3897 (push (yas--mirror-end mirror) markers)))
3898 (let ((snippet-exit (yas--snippet-exit snippet)))
3899 (when (and snippet-exit
3900 (marker-buffer (yas--exit-marker snippet-exit)))
3901 (push (yas--exit-marker snippet-exit) markers)))
3902 markers))
3903
3904 (defun yas--real-line-beginning ()
3905 (let ((c (char-after (line-beginning-position)))
3906 (n (line-beginning-position)))
3907 (while (or (eql c ?\ )
3908 (eql c ?\t))
3909 (incf n)
3910 (setq c (char-after n)))
3911 n))
3912
3913 (defun yas--escape-string (escaped)
3914 (concat "YASESCAPE" (format "%d" escaped) "PROTECTGUARD"))
3915
3916 (defun yas--protect-escapes (&optional text escaped)
3917 "Protect all escaped characters with their numeric ASCII value.
3918
3919 With optional string TEXT do it in string instead of buffer."
3920 (let ((changed-text text)
3921 (text-provided-p text))
3922 (mapc #'(lambda (escaped)
3923 (setq changed-text
3924 (yas--replace-all (concat "\\" (char-to-string escaped))
3925 (yas--escape-string escaped)
3926 (when text-provided-p changed-text))))
3927 (or escaped yas--escaped-characters))
3928 changed-text))
3929
3930 (defun yas--restore-escapes (&optional text escaped)
3931 "Restore all escaped characters from their numeric ASCII value.
3932
3933 With optional string TEXT do it in string instead of the buffer."
3934 (let ((changed-text text)
3935 (text-provided-p text))
3936 (mapc #'(lambda (escaped)
3937 (setq changed-text
3938 (yas--replace-all (yas--escape-string escaped)
3939 (char-to-string escaped)
3940 (when text-provided-p changed-text))))
3941 (or escaped yas--escaped-characters))
3942 changed-text))
3943
3944 (defun yas--save-backquotes ()
3945 "Save all the \"`(lisp-expression)`\"-style expressions
3946 with their evaluated value into `yas--backquote-markers-and-strings'."
3947 (while (re-search-forward yas--backquote-lisp-expression-regexp nil t)
3948 (let ((current-string (match-string-no-properties 1)) transformed)
3949 (delete-region (match-beginning 0) (match-end 0))
3950 (setq transformed (yas--eval-lisp (yas--read-lisp (yas--restore-escapes current-string '(?`)))))
3951 (goto-char (match-beginning 0))
3952 (when transformed
3953 (let ((marker (make-marker)))
3954 (insert "Y") ;; quite horrendous, I love it :)
3955 (set-marker marker (point))
3956 (insert "Y")
3957 (push (cons marker transformed) yas--backquote-markers-and-strings))))))
3958
3959 (defun yas--restore-backquotes ()
3960 "Replace markers in `yas--backquote-markers-and-strings' with their values."
3961 (while yas--backquote-markers-and-strings
3962 (let* ((marker-and-string (pop yas--backquote-markers-and-strings))
3963 (marker (car marker-and-string))
3964 (string (cdr marker-and-string)))
3965 (save-excursion
3966 (goto-char marker)
3967 (delete-char -1)
3968 (insert string)
3969 (delete-char 1)
3970 (set-marker marker nil)))))
3971
3972 (defun yas--scan-sexps (from count)
3973 (condition-case _
3974 (with-syntax-table (standard-syntax-table)
3975 (scan-sexps from count))
3976 (error
3977 nil)))
3978
3979 (defun yas--make-marker (pos)
3980 "Create a marker at POS with nil `marker-insertion-type'."
3981 (let ((marker (set-marker (make-marker) pos)))
3982 (set-marker-insertion-type marker nil)
3983 marker))
3984
3985 (defun yas--field-parse-create (snippet &optional parent-field)
3986 "Parse most field expressions in SNIPPET, except for the simple one \"$n\".
3987
3988 The following count as a field:
3989
3990 * \"${n: text}\", for a numbered field with default text, as long as N is not 0;
3991
3992 * \"${n: text$(expression)}, the same with a Lisp expression;
3993 this is caught with the curiously named `yas--multi-dollar-lisp-expression-regexp'
3994
3995 * the same as above but unnumbered, (no N:) and number is calculated automatically.
3996
3997 When multiple expressions are found, only the last one counts."
3998 ;;
3999 (save-excursion
4000 (while (re-search-forward yas--field-regexp nil t)
4001 (let* ((real-match-end-0 (yas--scan-sexps (1+ (match-beginning 0)) 1))
4002 (number (and (match-string-no-properties 1)
4003 (string-to-number (match-string-no-properties 1))))
4004 (brand-new-field (and real-match-end-0
4005 ;; break if on "$(" immediately
4006 ;; after the ":", this will be
4007 ;; caught as a mirror with
4008 ;; transform later.
4009 (not (save-match-data
4010 (eq (string-match "$[ \t\n]*("
4011 (match-string-no-properties 2)) 0)))
4012 ;; allow ${0: some exit text}
4013 ;; (not (and number (zerop number)))
4014 (yas--make-field number
4015 (yas--make-marker (match-beginning 2))
4016 (yas--make-marker (1- real-match-end-0))
4017 parent-field))))
4018 (when brand-new-field
4019 (goto-char real-match-end-0)
4020 (push (cons (1- real-match-end-0) real-match-end-0)
4021 yas--dollar-regions)
4022 (push (cons (match-beginning 0) (match-beginning 2))
4023 yas--dollar-regions)
4024 (push brand-new-field (yas--snippet-fields snippet))
4025 (save-excursion
4026 (save-restriction
4027 (narrow-to-region (yas--field-start brand-new-field) (yas--field-end brand-new-field))
4028 (goto-char (point-min))
4029 (yas--field-parse-create snippet brand-new-field)))))))
4030 ;; if we entered from a parent field, now search for the
4031 ;; `yas--multi-dollar-lisp-expression-regexp'. This is used for
4032 ;; primary field transformations
4033 ;;
4034 (when parent-field
4035 (save-excursion
4036 (while (re-search-forward yas--multi-dollar-lisp-expression-regexp nil t)
4037 (let* ((real-match-end-1 (yas--scan-sexps (match-beginning 1) 1)))
4038 ;; commit the primary field transformation if:
4039 ;;
4040 ;; 1. we don't find it in yas--dollar-regions (a subnested
4041 ;; field) might have already caught it.
4042 ;;
4043 ;; 2. we really make sure we have either two '$' or some
4044 ;; text and a '$' after the colon ':'. This is a FIXME: work
4045 ;; my regular expressions and end these ugly hacks.
4046 ;;
4047 (when (and real-match-end-1
4048 (not (member (cons (match-beginning 0)
4049 real-match-end-1)
4050 yas--dollar-regions))
4051 (not (eq ?:
4052 (char-before (1- (match-beginning 1))))))
4053 (let ((lisp-expression-string (buffer-substring-no-properties (match-beginning 1)
4054 real-match-end-1)))
4055 (setf (yas--field-transform parent-field)
4056 (yas--read-lisp (yas--restore-escapes lisp-expression-string))))
4057 (push (cons (match-beginning 0) real-match-end-1)
4058 yas--dollar-regions)))))))
4059
4060 (defun yas--transform-mirror-parse-create (snippet)
4061 "Parse the \"${n:$(lisp-expression)}\" mirror transformations in SNIPPET."
4062 (while (re-search-forward yas--transform-mirror-regexp nil t)
4063 (let* ((real-match-end-0 (yas--scan-sexps (1+ (match-beginning 0)) 1))
4064 (number (string-to-number (match-string-no-properties 1)))
4065 (field (and number
4066 (not (zerop number))
4067 (yas--snippet-find-field snippet number)))
4068 (brand-new-mirror
4069 (and real-match-end-0
4070 field
4071 (yas--make-mirror (yas--make-marker (match-beginning 0))
4072 (yas--make-marker (match-beginning 0))
4073 (yas--read-lisp
4074 (yas--restore-escapes
4075 (buffer-substring-no-properties (match-beginning 2)
4076 (1- real-match-end-0))))))))
4077 (when brand-new-mirror
4078 (push brand-new-mirror
4079 (yas--field-mirrors field))
4080 (yas--calculate-mirrors-in-fields snippet brand-new-mirror)
4081 (push (cons (match-beginning 0) real-match-end-0) yas--dollar-regions)))))
4082
4083 (defun yas--simple-mirror-parse-create (snippet)
4084 "Parse the simple \"$n\" fields/mirrors/exitmarkers in SNIPPET."
4085 (while (re-search-forward yas--simple-mirror-regexp nil t)
4086 (let ((number (string-to-number (match-string-no-properties 1))))
4087 (cond ((zerop number)
4088
4089 (setf (yas--snippet-exit snippet)
4090 (yas--make-exit (yas--make-marker (match-end 0))))
4091 (save-excursion
4092 (goto-char (match-beginning 0))
4093 (when yas-wrap-around-region
4094 (cond (yas-selected-text
4095 (insert yas-selected-text))
4096 ((and (eq yas-wrap-around-region 'cua)
4097 cua-mode
4098 (get-register ?0))
4099 (insert (prog1 (get-register ?0)
4100 (set-register ?0 nil))))))
4101 (push (cons (point) (yas--exit-marker (yas--snippet-exit snippet)))
4102 yas--dollar-regions)))
4103 (t
4104 (let ((field (yas--snippet-find-field snippet number)))
4105 (if field
4106 (let ((brand-new-mirror (yas--make-mirror
4107 (yas--make-marker (match-beginning 0))
4108 (yas--make-marker (match-beginning 0))
4109 nil)))
4110 (push brand-new-mirror
4111 (yas--field-mirrors field))
4112 (yas--calculate-mirrors-in-fields snippet brand-new-mirror))
4113 (push (yas--make-field number
4114 (yas--make-marker (match-beginning 0))
4115 (yas--make-marker (match-beginning 0))
4116 nil)
4117 (yas--snippet-fields snippet))))
4118 (push (cons (match-beginning 0) (match-end 0))
4119 yas--dollar-regions))))))
4120
4121 (defun yas--delete-regions (regions)
4122 "Sort disjuct REGIONS by start point, then delete from the back."
4123 (mapc #'(lambda (reg)
4124 (delete-region (car reg) (cdr reg)))
4125 (sort regions
4126 #'(lambda (r1 r2)
4127 (>= (car r1) (car r2))))))
4128
4129 (defun yas--calculate-mirror-depth (mirror &optional traversed)
4130 (let* ((parent (yas--mirror-parent-field mirror))
4131 (parents-mirrors (and parent
4132 (yas--field-mirrors parent))))
4133 (or (yas--mirror-depth mirror)
4134 (setf (yas--mirror-depth mirror)
4135 (cond ((memq mirror traversed)
4136 0)
4137 ((and parent parents-mirrors)
4138 (1+ (reduce #'max
4139 (mapcar #'(lambda (m)
4140 (yas--calculate-mirror-depth m
4141 (cons mirror
4142 traversed)))
4143 parents-mirrors))))
4144 (parent
4145 1)
4146 (t
4147 0))))))
4148
4149 (defun yas--update-mirrors (snippet)
4150 "Update all the mirrors of SNIPPET."
4151 (save-excursion
4152 (dolist (field-and-mirror (sort
4153 ;; make a list of ((F1 . M1) (F1 . M2) (F2 . M3) (F2 . M4) ...)
4154 ;; where F is the field that M is mirroring
4155 ;;
4156 (mapcan #'(lambda (field)
4157 (mapcar #'(lambda (mirror)
4158 (cons field mirror))
4159 (yas--field-mirrors field)))
4160 (yas--snippet-fields snippet))
4161 ;; then sort this list so that entries with mirrors with parent
4162 ;; fields appear before. This was important for fixing #290, and
4163 ;; luckily also handles the case where a mirror in a field causes
4164 ;; another mirror to need reupdating
4165 ;;
4166 #'(lambda (field-and-mirror1 field-and-mirror2)
4167 (> (yas--calculate-mirror-depth (cdr field-and-mirror1))
4168 (yas--calculate-mirror-depth (cdr field-and-mirror2))))))
4169 (let* ((field (car field-and-mirror))
4170 (mirror (cdr field-and-mirror))
4171 (parent-field (yas--mirror-parent-field mirror)))
4172 ;; before updating a mirror with a parent-field, maybe advance
4173 ;; its start (#290)
4174 ;;
4175 (when parent-field
4176 (yas--advance-start-maybe mirror (yas--fom-start parent-field)))
4177 ;; update this mirror
4178 ;;
4179 (yas--mirror-update-display mirror field)
4180 ;; `yas--place-overlays' is needed if the active field and
4181 ;; protected overlays have been changed because of insertions
4182 ;; in `yas--mirror-update-display'
4183 ;;
4184 (when (eq field (yas--snippet-active-field snippet))
4185 (yas--place-overlays snippet field))))))
4186
4187 (defun yas--mirror-update-display (mirror field)
4188 "Update MIRROR according to FIELD (and mirror transform)."
4189
4190 (let* ((mirror-parent-field (yas--mirror-parent-field mirror))
4191 (reflection (and (not (and mirror-parent-field
4192 (yas--field-modified-p mirror-parent-field)))
4193 (or (yas--apply-transform mirror field 'empty-on-nil)
4194 (yas--field-text-for-display field)))))
4195 (when (and reflection
4196 (not (string= reflection (buffer-substring-no-properties (yas--mirror-start mirror)
4197 (yas--mirror-end mirror)))))
4198 (goto-char (yas--mirror-start mirror))
4199 (yas--inhibit-overlay-hooks
4200 (insert reflection))
4201 (if (> (yas--mirror-end mirror) (point))
4202 (delete-region (point) (yas--mirror-end mirror))
4203 (set-marker (yas--mirror-end mirror) (point))
4204 (yas--advance-start-maybe (yas--mirror-next mirror) (point))
4205 ;; super-special advance
4206 (yas--advance-end-of-parents-maybe mirror-parent-field (point))))))
4207
4208 (defun yas--field-update-display (field)
4209 "Much like `yas--mirror-update-display', but for fields."
4210 (when (yas--field-transform field)
4211 (let ((transformed (and (not (eq (yas--field-number field) 0))
4212 (yas--apply-transform field field))))
4213 (when (and transformed
4214 (not (string= transformed (buffer-substring-no-properties (yas--field-start field)
4215 (yas--field-end field)))))
4216 (setf (yas--field-modified-p field) t)
4217 (goto-char (yas--field-start field))
4218 (yas--inhibit-overlay-hooks
4219 (insert transformed)
4220 (if (> (yas--field-end field) (point))
4221 (delete-region (point) (yas--field-end field))
4222 (set-marker (yas--field-end field) (point))
4223 (yas--advance-start-maybe (yas--field-next field) (point)))
4224 t)))))
4225
4226 \f
4227 ;;; Post-command hook:
4228 ;;
4229 (defun yas--post-command-handler ()
4230 "Handles various yasnippet conditions after each command."
4231 (cond (yas--protection-violation
4232 (goto-char yas--protection-violation)
4233 (setq yas--protection-violation nil))
4234 ((eq 'undo this-command)
4235 ;;
4236 ;; After undo revival the correct field is sometimes not
4237 ;; restored correctly, this condition handles that
4238 ;;
4239 (let* ((snippet (car (yas--snippets-at-point)))
4240 (target-field (and snippet
4241 (find-if-not #'(lambda (field)
4242 (yas--field-probably-deleted-p snippet field))
4243 (remove nil
4244 (cons (yas--snippet-active-field snippet)
4245 (yas--snippet-fields snippet)))))))
4246 (when target-field
4247 (yas--move-to-field snippet target-field))))
4248 ((not (yas--undo-in-progress))
4249 ;; When not in an undo, check if we must commit the snippet
4250 ;; (user exited it).
4251 (yas--check-commit-snippet))))
4252 \f
4253 ;;; Fancy docs:
4254 ;;
4255 ;; The docstrings for some functions are generated dynamically
4256 ;; depending on the context.
4257 ;;
4258 (put 'yas-expand 'function-documentation
4259 '(yas--expand-from-trigger-key-doc))
4260 (defun yas--expand-from-trigger-key-doc ()
4261 "A doc synthesizer for `yas--expand-from-trigger-key-doc'."
4262 (let ((fallback-description
4263 (cond ((eq yas-fallback-behavior 'call-other-command)
4264 (let* ((fallback (yas--keybinding-beyond-yasnippet)))
4265 (or (and fallback
4266 (format " call command `%s'." (pp-to-string fallback)))
4267 " do nothing (`yas-expand' doesn't shadow\nanything)")))
4268 ((eq yas-fallback-behavior 'return-nil)
4269 ", do nothing.")
4270 (t
4271 ", defer to `yas-fallback-behaviour' (which see)"))))
4272 (concat "Expand a snippet before point. If no snippet
4273 expansion is possible,"
4274 fallback-description
4275 "\n\nOptional argument FIELD is for non-interactive use and is an
4276 object satisfying `yas--field-p' to restrict the expansion to.")))
4277
4278 (put 'yas-expand-from-keymap 'function-documentation '(yas--expand-from-keymap-doc))
4279 (defun yas--expand-from-keymap-doc ()
4280 "A doc synthesizer for `yas--expand-from-keymap-doc'."
4281 (add-hook 'temp-buffer-show-hook 'yas--snippet-description-finish-runonce)
4282 (concat "Expand/run snippets from keymaps, possibly falling back to original binding.\n"
4283 (when (eq this-command 'describe-key)
4284 (let* ((vec (this-single-command-keys))
4285 (templates (mapcan #'(lambda (table)
4286 (yas--fetch table vec))
4287 (yas--get-snippet-tables)))
4288 (yas--direct-keymaps nil)
4289 (fallback (key-binding vec)))
4290 (concat "In this case, "
4291 (when templates
4292 (concat "these snippets are bound to this key:\n"
4293 (yas--template-pretty-list templates)
4294 "\n\nIf none of these expands, "))
4295 (or (and fallback
4296 (format "fallback `%s' will be called." (pp-to-string fallback)))
4297 "no fallback keybinding is called."))))))
4298
4299 (defun yas--template-pretty-list (templates)
4300 (let ((acc)
4301 (yas-buffer-local-condition 'always))
4302 (dolist (plate templates)
4303 (setq acc (concat acc "\n*) "
4304 (propertize (concat "\\\\snippet `" (car plate) "'")
4305 'yasnippet (cdr plate)))))
4306 acc))
4307
4308 (define-button-type 'help-snippet-def
4309 :supertype 'help-xref
4310 'help-function (lambda (template) (yas--visit-snippet-file-1 template))
4311 'help-echo (purecopy "mouse-2, RET: find snippets's definition"))
4312
4313 (defun yas--snippet-description-finish-runonce ()
4314 "Final adjustments for the help buffer when snippets are concerned."
4315 (yas--create-snippet-xrefs)
4316 (remove-hook 'temp-buffer-show-hook 'yas--snippet-description-finish-runonce))
4317
4318 (defun yas--create-snippet-xrefs ()
4319 (save-excursion
4320 (goto-char (point-min))
4321 (while (search-forward-regexp "\\\\\\\\snippet[ \s\t]+`\\([^']+\\)'" nil t)
4322 (let ((template (get-text-property (match-beginning 1)
4323 'yasnippet)))
4324 (when template
4325 (help-xref-button 1 'help-snippet-def template)
4326 (kill-region (match-end 1) (match-end 0))
4327 (kill-region (match-beginning 0) (match-beginning 1)))))))
4328 \f
4329 ;;; Utils
4330
4331 (defvar yas-verbosity 4
4332 "Log level for `yas--message' 4 means trace most anything, 0 means nothing.")
4333
4334 (defun yas--message (level message &rest args)
4335 "When LEVEL is above `yas-verbosity-level', log MESSAGE and ARGS."
4336 (when (> yas-verbosity level)
4337 (message "%s" (apply #'yas--format message args))))
4338
4339 (defun yas--format (format-control &rest format-args)
4340 (apply #'format (concat "[yas] " format-control) format-args))
4341
4342 \f
4343 ;;; Some hacks:
4344 ;;
4345 ;; The functions
4346 ;;
4347 ;; `locate-dominating-file'
4348 ;; `region-active-p'
4349 ;;
4350 ;; added for compatibility in emacsen < 23
4351 (unless (>= emacs-major-version 23)
4352 (unless (fboundp 'region-active-p)
4353 (defun region-active-p () (and transient-mark-mode mark-active)))
4354
4355 (unless (fboundp 'locate-dominating-file)
4356 (defvar locate-dominating-stop-dir-regexp
4357 "\\`\\(?:[\\/][\\/][^\\/]+[\\/]\\|/\\(?:net\\|afs\\|\\.\\.\\.\\)/\\)\\'"
4358 "Regexp of directory names which stop the search in `locate-dominating-file'.
4359 Any directory whose name matches this regexp will be treated like
4360 a kind of root directory by `locate-dominating-file' which will stop its search
4361 when it bumps into it.
4362 The default regexp prevents fruitless and time-consuming attempts to find
4363 special files in directories in which filenames are interpreted as hostnames,
4364 or mount points potentially requiring authentication as a different user.")
4365
4366 (defun locate-dominating-file (file name)
4367 "Look up the directory hierarchy from FILE for a file named NAME.
4368 Stop at the first parent directory containing a file NAME,
4369 and return the directory. Return nil if not found."
4370 ;; We used to use the above locate-dominating-files code, but the
4371 ;; directory-files call is very costly, so we're much better off doing
4372 ;; multiple calls using the code in here.
4373 ;;
4374 ;; Represent /home/luser/foo as ~/foo so that we don't try to look for
4375 ;; `name' in /home or in /.
4376 (setq file (abbreviate-file-name file))
4377 (let ((root nil)
4378 try)
4379 (while (not (or root
4380 (null file)
4381 ;; FIXME: Disabled this heuristic because it is sometimes
4382 ;; inappropriate.
4383 ;; As a heuristic, we stop looking up the hierarchy of
4384 ;; directories as soon as we find a directory belonging
4385 ;; to another user. This should save us from looking in
4386 ;; things like /net and /afs. This assumes that all the
4387 ;; files inside a project belong to the same user.
4388 ;; (let ((prev-user user))
4389 ;; (setq user (nth 2 (file-attributes file)))
4390 ;; (and prev-user (not (equal user prev-user))))
4391 (string-match locate-dominating-stop-dir-regexp file)))
4392 (setq try (file-exists-p (expand-file-name name file)))
4393 (cond (try (setq root file))
4394 ((equal file (setq file (file-name-directory
4395 (directory-file-name file))))
4396 (setq file nil))))
4397 root))))
4398
4399 ;; `c-neutralize-syntax-in-CPP` sometimes fires "End of Buffer" error
4400 ;; (when it execute forward-char) and interrupt the after change
4401 ;; hook. Thus prevent the insert-behind hook of yasnippet to be
4402 ;; invoked. Here's a way to reproduce it:
4403
4404 ;; # open a *new* Emacs.
4405 ;; # load yasnippet.
4406 ;; # open a *new* .cpp file.
4407 ;; # input "inc" and press TAB to expand the snippet.
4408 ;; # select the `#include <...>` snippet.
4409 ;; # type inside `<>`
4410
4411 (defadvice c-neutralize-syntax-in-CPP
4412 (around yas--mp/c-neutralize-syntax-in-CPP activate)
4413 "Adviced `c-neutralize-syntax-in-CPP' to properly
4414 handle the `end-of-buffer' error fired in it by calling
4415 `forward-char' at the end of buffer."
4416 (condition-case err
4417 ad-do-it
4418 (error (message (error-message-string err)))))
4419
4420 ;; disable c-electric-* serial command in YAS fields
4421 (add-hook 'c-mode-common-hook
4422 '(lambda ()
4423 (dolist (k '(":" ">" ";" "<" "{" "}"))
4424 (define-key (symbol-value (make-local-variable 'yas-keymap))
4425 k 'self-insert-command))))
4426 \f
4427 ;;; Backward compatibility to yasnippet <= 0.7
4428
4429 (defvar yas--exported-syms '(;; `defcustom's
4430 ;;
4431 yas-snippet-dirs
4432 yas-prompt-functions
4433 yas-indent-line
4434 yas-also-auto-indent-first-line
4435 yas-snippet-revival
4436 yas-triggers-in-field
4437 yas-fallback-behavior
4438 yas-choose-keys-first
4439 yas-choose-tables-first
4440 yas-use-menu
4441 yas-trigger-symbol
4442 yas-wrap-around-region
4443 yas-good-grace
4444 yas-visit-from-menu
4445 yas-expand-only-for-last-commands
4446 yas-field-highlight-face
4447
4448 ;; these vars can be customized as well
4449 ;;
4450 yas-keymap
4451 yas-verbosity
4452 yas-extra-modes
4453 yas-key-syntaxes
4454 yas-after-exit-snippet-hook
4455 yas-before-expand-snippet-hook
4456 yas-buffer-local-condition
4457 yas-dont-activate
4458
4459 ;; prompting functions
4460 ;;
4461 yas-x-prompt
4462 yas-ido-prompt
4463 yas-no-prompt
4464 yas-completing-prompt
4465 yas-dropdown-prompt
4466
4467 ;; interactive functions
4468 ;;
4469 yas-expand
4470 yas-minor-mode
4471 yas-global-mode
4472 yas-direct-keymaps-reload
4473 yas-minor-mode-on
4474 yas-load-directory
4475 yas-reload-all
4476 yas-compile-directory
4477 yas-recompile-all
4478 yas-about
4479 yas-expand-from-trigger-key
4480 yas-expand-from-keymap
4481 yas-insert-snippet
4482 yas-visit-snippet-file
4483 yas-new-snippet
4484 yas-load-snippet-buffer
4485 yas-tryout-snippet
4486 yas-describe-tables
4487 yas-next-field-or-maybe-expand
4488 yas-next-field
4489 yas-prev-field
4490 yas-abort-snippet
4491 yas-exit-snippet
4492 yas-exit-all-snippets
4493 yas-skip-and-clear-or-delete-char
4494
4495 ;; symbols that I "exported" for use
4496 ;; in snippets and hookage
4497 ;;
4498 yas-expand-snippet
4499 yas-define-snippets
4500 yas-define-menu
4501 yas-snippet-beg
4502 yas-snippet-end
4503 yas-modified-p
4504 yas-moving-away-p
4505 yas-text
4506 yas-substr
4507 yas-choose-value
4508 yas-key-to-value
4509 yas-throw
4510 yas-verify-value
4511 yas-field-value
4512 yas-text
4513 yas-selected-text
4514 yas-default-from-field
4515 yas-inside-string
4516 yas-unimplemented
4517 yas-define-condition-cache
4518 yas-hippie-try-expand
4519 yas-active-keys
4520
4521 ;; debug definitions
4522 ;; yas-debug-snippet-vars
4523 ;; yas-exterminate-package
4524 ;; yas-debug-test
4525
4526 ;; testing definitions
4527 ;; yas-should-expand
4528 ;; yas-should-not-expand
4529 ;; yas-mock-insert
4530 ;; yas-make-file-or-dirs
4531 ;; yas-variables
4532 ;; yas-saving-variables
4533 ;; yas-call-with-snippet-dirs
4534 ;; yas-with-snippet-dirs
4535 )
4536 "Exported yasnippet symbols.
4537
4538 i.e. ones that I will try to keep in future yasnippet versions
4539 and ones that other elisp libraries can more or less safely rely
4540 upon.")
4541
4542 (defvar yas--dont-backport '(yas-active-keys)
4543 "Exported symbols that don't map back to \"yas/*\" variants.")
4544
4545 (dolist (sym (set-difference yas--exported-syms yas--dont-backport))
4546 (let ((backported (intern (replace-regexp-in-string "^yas-" "yas/" (symbol-name sym)))))
4547 (when (boundp sym)
4548 (make-obsolete-variable backported sym "yasnippet 0.8")
4549 (defvaralias backported sym))
4550 (when (fboundp sym)
4551 (make-obsolete backported sym "yasnippet 0.8")
4552 (defalias backported sym))))
4553
4554 \f
4555 (provide 'yasnippet)
4556
4557 ;;; yasnippet.el ends here
4558 ;; Local Variables:
4559 ;; coding: utf-8
4560 ;; byte-compile-warnings: (not cl-functions)
4561 ;; End: