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