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