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