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