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