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