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