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