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