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