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