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