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