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