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