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