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