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