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