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