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