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