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