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