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