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