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