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