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