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