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