]> code.delx.au - gnu-emacs-elpa/blob - yasnippet.el
* Fix issue 72 with snippet conditions
[gnu-emacs-elpa] / yasnippet.el
1 ;;; Yasnippet.el --- Yet another snippet extension for Emacs.
2
3 ;; Copyright 2008 pluskid
4
5 ;; Authors: pluskid <pluskid@gmail.com>, joaotavora <joaotavora@gmail.com>
6 ;; Version: 0.6.1
7 ;; Package-version: 0.6.1b
8 ;; X-URL: http://code.google.com/p/yasnippet/
9 ;; Keywords: snippet, textmate
10 ;; URL: http://code.google.com/p/yasnippet/
11 ;; EmacsWiki: YaSnippetMode
12
13 ;; This file is free software; you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation; either version 2, or (at your option)
16 ;; any later version.
17
18 ;; This file is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs; see the file COPYING. If not, write to
25 ;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
26 ;; Boston, MA 02111-1307, USA.
27
28 ;;; Commentary:
29
30 ;; Basic steps to setup:
31 ;;
32 ;; 1. In your .emacs file:
33 ;; (add-to-list 'load-path "/dir/to/yasnippet.el")
34 ;; (require 'yasnippet)
35 ;; 2. Place the `snippets' directory somewhere. E.g: ~/.emacs.d/snippets
36 ;; 3. In your .emacs file
37 ;; (setq yas/root-directory "~/.emacs/snippets")
38 ;; (yas/load-directory yas/root-directory)
39 ;; 4. To enable the YASnippet menu and tab-trigger expansion
40 ;; M-x yas/minor-mode
41 ;; 5. To globally enable the minor mode in *all* buffers
42 ;; M-x yas/global-mode
43 ;;
44 ;; Steps 4. and 5. are optional, you don't have to use the minor
45 ;; mode to use YASnippet.
46 ;;
47 ;; Interesting variables are:
48 ;;
49 ;; `yas/root-directory'
50 ;;
51 ;; The directory where user-created snippets are to be
52 ;; stored. Can also be a list of directories that
53 ;; `yas/reload-all' will use for bulk-reloading snippets. In
54 ;; that case the first directory the default for storing new
55 ;; snippets.
56 ;;
57 ;; `yas/mode-symbol'
58 ;;
59 ;; A local variable that you can set in a hook to override
60 ;; snippet-lookup based on major mode. It is a a symbol (or
61 ;; list of symbols) that correspond to subdirectories of
62 ;; `yas/root-directory' and is used for deciding which
63 ;; snippets to consider for the active buffer.
64 ;;
65 ;; Major commands are:
66 ;;
67 ;; M-x yas/expand
68 ;;
69 ;; Try to expand snippets before point. In `yas/minor-mode',
70 ;; this is bound to `yas/trigger-key' which you can customize.
71 ;;
72 ;; M-x yas/load-directory
73 ;;
74 ;; Prompts you for a directory hierarchy of snippets to load.
75 ;;
76 ;; M-x yas/insert-snippet
77 ;;
78 ;; Prompts you for possible snippet expansion if that is
79 ;; possible according to buffer-local and snippet-local
80 ;; expansion conditions. With prefix argument, ignore these
81 ;; conditions.
82 ;;
83 ;; M-x yas/find-snippets
84 ;;
85 ;; Lets you find the snippet files in the correct
86 ;; subdirectory of `yas/root-directory', according to the
87 ;; active major mode (if it exists) like
88 ;; `find-file-other-window'.
89 ;;
90 ;; M-x yas/visit-snippet-file
91 ;;
92 ;; Prompts you for possible snippet expansions like
93 ;; `yas/insert-snippet', but instead of expanding it, takes
94 ;; you directly to the snippet definition's file, if it
95 ;; exists.
96 ;;
97 ;; M-x yas/new-snippet
98 ;;
99 ;; Lets you create a new snippet file in the correct
100 ;; subdirectory of `yas/root-directory', according to the
101 ;; active major mode.
102 ;;
103 ;; M-x yas/load-snippet-buffer
104 ;;
105 ;; When editing a snippet, this loads the snippet. This is
106 ;; bound to "C-c C-c" while in the `snippet-mode' editing
107 ;; mode.
108 ;;
109 ;; M-x yas/tryout-snippet
110 ;;
111 ;; When editing a snippet, this opens a new empty buffer,
112 ;; sets it to the appropriate major mode and inserts the
113 ;; snippet there, so you can see what it looks like. This is
114 ;; bound to "C-c C-t" while in `snippet-mode'.
115 ;;
116 ;; The `dropdown-list.el' extension is bundled with YASnippet, you
117 ;; can optionally use it the preferred "prompting method", puting in
118 ;; your .emacs file, for example:
119 ;;
120 ;; (require 'dropdown-list)
121 ;; (setq 'yas/prompt-functions '(yas/dropdown-prompt
122 ;; yas/ido-prompt
123 ;; yas/completing-prompt))
124 ;;
125 ;; Also check out the customization group
126 ;;
127 ;; M-x customize-group RET yasnippet RET
128 ;;
129 ;; For more information and detailed usage, refer to the project page:
130 ;; http://code.google.com/p/yasnippet/
131
132 ;;; Code:
133
134 (require 'cl)
135 (require 'easymenu)
136
137 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
138 ;; User customizable variables
139 ;;
140
141 (defgroup yasnippet nil
142 "Yet Another Snippet extension"
143 :group 'editing)
144
145 (defcustom yas/root-directory nil
146 "Root directory that stores the snippets for each major mode.
147
148 Can also be a list of strings, for multiple root directories. If
149 you make this a list, the first element is always the
150 user-created snippets directory. Other directories are used for
151 bulk reloading of all snippets using `yas/reload-all'"
152
153 :type '(string)
154 :group 'yasnippet)
155
156 (defcustom yas/prompt-functions '(yas/x-prompt
157 yas/dropdown-prompt
158 yas/completing-prompt
159 yas/ido-prompt
160 yas/no-prompt)
161 "Functions to prompt for keys, templates, etc interactively."
162 :type 'list
163 :group 'yasnippet)
164
165 (defcustom yas/indent-line 'auto
166 "Controls indenting applied to a recent snippet expansion.
167
168 The following values are possible:
169
170 `fixed' Indent the snippet to the current column;
171
172 `auto' Indent each line of the snippet with `indent-according-to-mode'
173
174 Every other value means don't apply any snippet-side indendation
175 after expansion (the manual per-line \"$>\" indentation still
176 applies)."
177 :type '(choice (const :tag "Nothing" nothing)
178 (const :tag "Fixed" fixed)
179 (const :tag "Auto" auto))
180 :group 'yasnippet)
181
182 (defcustom yas/also-auto-indent-first-line nil
183 "Non-nil means also auto indent first line according to mode.
184
185 Naturally this is only valid when `yas/indent-line' is `auto'"
186 :type 'boolean
187 :group 'yasnippet)
188
189 (defcustom yas/snippet-revival t
190 "Non-nil means re-activate snippet fields after undo/redo."
191 :type 'boolean
192 :group 'yasnippet)
193
194 (defcustom yas/trigger-key "TAB"
195 "The key bound to `yas/expand' when function `yas/minor-mode' is active.
196
197 Value is a string that is converted to the internal Emacs key
198 representation using `read-kbd-macro'."
199 :type 'string
200 :group 'yasnippet)
201
202 (defcustom yas/next-field-key "TAB"
203 "The key to navigate to next field when a snippet is active.
204
205 Value is a string that is converted to the internal Emacs key
206 representation using `read-kbd-macro'."
207 :type 'string
208 :group 'yasnippet)
209
210 (defcustom yas/prev-field-key '("<backtab>" "<S-tab>")
211 "The key to navigate to previous field when a snippet is active.
212
213 Can also be a list of keys.
214
215 Value is a string that is converted to the internal Emacs key
216 representation using `read-kbd-macro'."
217 :type 'string
218 :group 'yasnippet)
219
220 (defcustom yas/skip-and-clear-key "C-d"
221 "The key to clear the currently active field.
222
223 Value is a string that is converted to the internal Emacs key
224 representation using `read-kbd-macro'."
225 :type 'string
226 :group 'yasnippet)
227
228 (defcustom yas/triggers-in-field nil
229 "If non-nil, `yas/next-field-key' can trigger stacked expansions.
230
231 Otherwise, `yas/next-field-key' just tries to move on to the next
232 field"
233 :type 'boolean
234 :group 'yasnippet)
235
236 (defcustom yas/fallback-behavior 'call-other-command
237 "How to act when `yas/trigger-key' does *not* expand a snippet.
238
239 The fall back behavior of YASnippet when it can't find a snippet
240 to expand.
241
242 `call-other-command' means try to temporarily disable YASnippet
243 and call the next command bound to `yas/trigger-key'.
244
245 `return-nil' means return do nothing.
246
247 An entry (apply COMMAND . ARGS) means interactively call COMMAND,
248 if ARGS is non-nil, call COMMAND non-interactively with ARGS as
249 arguments."
250 :type '(choice (const :tag "Call previous command" 'call-other-command)
251 (const :tag "Do nothing" 'return-nil))
252 :group 'yasnippet)
253
254 (defcustom yas/choose-keys-first t
255 "If non-nil, prompts for key first, then for template if more than one.
256
257 Otherwise prompts for all possible templates
258
259 This affects `yas/insert-snippet' and `yas/visit-snippet-file'."
260 :type 'boolean
261 :group 'yasnippet)
262
263 (defcustom yas/choose-tables-first nil
264 "If non-nil, and multiple eligible snippet tables, prompts user for tables first.
265
266 Otherwise, user chooses between the merging together of all
267 eligible tables.
268
269 This affects `yas/insert-snippet', `yas/visit-snippet-file'"
270 :type 'boolean
271 :group 'yasnippet)
272
273 (defcustom yas/use-menu t
274 "Display a YASnippet menu in the menu bar.
275
276 When non-nil, snippet templates will be listed under the menu
277 \"Yasnippet\". If set to `abbreviate', only the current major-mode
278 menu and the modes set in `yas/mode-symbol' are listed."
279 :type '(choice (const :tag "Full" t)
280 (const :tag "Abbreviate" abbreviate))
281 :group 'yasnippet)
282
283 (defcustom yas/trigger-symbol " =>"
284 "The text that will be used in menu to represent the trigger."
285 :type 'string
286 :group 'yasnippet)
287
288 (defcustom yas/wrap-around-region nil
289 "If non-nil, snippet expansion wraps around selected region.
290
291 The wrapping occurs just before the snippet's exit marker. This
292 can be overriden on a per-snippet basis."
293 :type 'boolean
294 :group 'yasnippet)
295
296 (defcustom yas/good-grace t
297 "If non-nil, don't raise errors in inline elisp evaluation.
298
299 An error string \"[yas] error\" is returned instead."
300 :type 'boolean
301 :group 'yasnippet)
302
303 (defface yas/field-highlight-face
304 '((((class color) (background light)) (:background "DarkSeaGreen1"))
305 (t (:background "DimGrey")))
306 "The face used to highlight the currently active field of a snippet"
307 :group 'yasnippet)
308
309 (defface yas/field-debug-face
310 '()
311 "The face used for debugging some overlays normally hidden"
312 :group 'yasnippet)
313
314 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
315 ;; User semi-customizable variables
316 ;;
317
318 (defvar yas/keymap (make-sparse-keymap)
319 "The keymap active while a snippet expansion is in progress.")
320
321 (defun yas/define-some-keys (keys keymap definition)
322 "Bind KEYS to DEFINITION in KEYMAP, read with `read-kbd-macro'."
323 (let ((keys (or (and (listp keys) keys)
324 (list keys))))
325 (dolist (key keys)
326 (define-key keymap (read-kbd-macro key) definition))))
327
328 (yas/define-some-keys yas/next-field-key yas/keymap 'yas/next-field-or-maybe-expand)
329 (yas/define-some-keys yas/prev-field-key yas/keymap 'yas/prev-field)
330 (yas/define-some-keys yas/skip-and-clear-key yas/keymap 'yas/skip-and-clear-or-delete-char)
331
332 (defvar yas/key-syntaxes (list "w" "w_" "w_." "^ ")
333 "A list of syntax of a key. This list is tried in the order
334 to try to find a key. For example, if the list is '(\"w\" \"w_\").
335 And in emacs-lisp-mode, where \"-\" has the syntax of \"_\":
336
337 foo-bar
338
339 will first try \"bar\", if not found, then \"foo-bar\" is tried.")
340
341 (defvar yas/after-exit-snippet-hook
342 '()
343 "Hooks to run after a snippet exited.
344
345 The hooks will be run in an environment where some variables bound to
346 proper values:
347
348 `yas/snippet-beg' : The beginning of the region of the snippet.
349
350 `yas/snippet-end' : Similar to beg.
351
352 Attention: These hooks are not run when exiting nested/stackd snippet expansion!")
353
354 (defvar yas/before-expand-snippet-hook
355 '()
356 "Hooks to run just before expanding a snippet.")
357
358 (defvar yas/buffer-local-condition
359 '(if (and (not (bobp))
360 (or (equal 'font-lock-comment-face
361 (get-char-property (1- (point))
362 'face))
363 (equal 'font-lock-string-face
364 (get-char-property (1- (point))
365 'face))))
366 '(require-snippet-condition . force-in-comment)
367 t)
368 "Condition to yasnippet local to each buffer.
369
370 The default value helps filtering out potential snippet
371 expansions inside comments and string literals, unless the
372 snippet itself contains a condition that returns the symbol
373 `force-in-comment'.
374
375 * If yas/buffer-local-condition evaluate to nil, snippet
376 won't be expanded.
377
378 * If it evaluate to the a cons cell where the car is the
379 symbol `require-snippet-condition' and the cdr is a
380 symbol (let's call it \"requirement\"):
381 * If the snippet has no condition, then it won't be
382 expanded.
383 * If the snippet has a condition but it evaluates to nil or
384 error occured during evaluation, it won't be expanded.
385 * If the snippet has a condition that evaluate to
386 non-nil (let's call it \"result\"):
387 * If \"requirement\" is t, the snippet is ready to be
388 expanded.
389 * If \"requirement\" is eq to \"result\", the snippet is ready
390 to be expanded.
391 * Otherwise the snippet won't be expanded.
392
393 * If it evaluates to `always', snippet is unconditionally
394 expanded.
395
396 * If it evaluates to other non-nil value:
397 * If the snippet has no condition, or has a condition that
398 evaluate to non-nil, it is ready to be expanded.
399 * Otherwise, it won't be expanded.
400
401 Here's an example:
402
403 (add-hook 'python-mode-hook
404 '(lambda ()
405 (setq yas/buffer-local-condition
406 '(if (python-in-string/comment)
407 '(require-snippet-condition . force-in-comment)
408 t))))")
409 (make-variable-buffer-local 'yas/buffer-local-condition)
410
411 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
412 ;; Internal variables
413 ;;
414
415 (defvar yas/version "0.6.0b")
416
417 (defvar yas/snippet-tables (make-hash-table)
418 "A hash table of snippet tables corresponding to each major mode.")
419
420 (defvar yas/menu-table (make-hash-table)
421 "A hash table of menus of corresponding major mode.")
422
423 (defvar yas/known-modes
424 '(ruby-mode rst-mode markdown-mode)
425 "A list of mode which is well known but not part of emacs.")
426
427 (defvar yas/escaped-characters
428 '(?\\ ?` ?' ?$ ?} )
429 "List of characters which *might* need to be escaped.")
430
431 (defconst yas/field-regexp
432 "${\\([0-9]+:\\)?\\([^}]*\\)}"
433 "A regexp to *almost* recognize a field.")
434
435 (defconst yas/multi-dollar-lisp-expression-regexp
436 "$+[ \t\n]*\\(([^)]*)\\)"
437 "A regexp to *almost* recognize a \"$(...)\" expression.")
438
439 (defconst yas/backquote-lisp-expression-regexp
440 "`\\([^`]*\\)`"
441 "A regexp to recognize a \"`lisp-expression`\" expression." )
442
443 (defconst yas/transform-mirror-regexp
444 "${\\(?:\\([0-9]+\\):\\)?$\\([^}]*\\)"
445 "A regexp to *almost* recognize a mirror with a transform.")
446
447 (defconst yas/simple-mirror-regexp
448 "$\\([0-9]+\\)"
449 "A regexp to recognize a simple mirror.")
450
451 (defvar yas/snippet-id-seed 0
452 "Contains the next id for a snippet.")
453
454 (defun yas/snippet-next-id ()
455 (let ((id yas/snippet-id-seed))
456 (incf yas/snippet-id-seed)
457 id))
458
459 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
460 ;; Minor mode stuff
461 ;;
462 ;; TODO: XXX: This is somehow needed in Carbon Emacs for MacOSX
463 (defvar last-buffer-undo-list nil)
464
465 (defvar yas/minor-mode-map (make-sparse-keymap)
466 "The keymap used when function `yas/minor-mode' is active.")
467
468 (defvar yas/minor-mode-menu (make-sparse-keymap)
469 "Holds the YASnippet menu. For use with `easy-menu-define'.")
470
471 (defun yas/init-keymap-and-menu ()
472 (easy-menu-define yas/minor-mode-menu
473 yas/minor-mode-map
474 "Menu used when YAS/minor-mode is active."
475 (cons "YASnippet"
476 (mapcar #'(lambda (ent)
477 (when (third ent)
478 (define-key yas/minor-mode-map (third ent) (second ent)))
479 (vector (first ent) (second ent) t))
480 (list (list "--")
481 (list "Expand trigger" 'yas/expand (when yas/trigger-key (read-kbd-macro yas/trigger-key)))
482 (list "Insert at point..." 'yas/insert-snippet "\C-c&\C-s")
483 (list "Visit snippet file..." 'yas/visit-snippet-file "\C-c&\C-v")
484 (list "Find snippets..." 'yas/find-snippets "\C-c&\C-f")
485 (list "About" 'yas/about)
486 (list "Reload-all-snippets" 'yas/reload-all)
487 (list "Load snippets..." 'yas/load-directory))))))
488
489 (define-minor-mode yas/minor-mode
490 "Toggle YASnippet mode.
491
492 When YASnippet mode is enabled, the `tas/trigger-key' key expands
493 snippets of code depending on the mode.
494
495 With no argument, this command toggles the mode.
496 positive prefix argument turns on the mode.
497 Negative prefix argument turns off the mode.
498
499 You can customize the key through `yas/trigger-key'.
500
501 Key bindings:
502 \\{yas/minor-mode-map}"
503 nil
504 ;; The indicator for the mode line.
505 " yas"
506 :group 'yasnippet
507 (when yas/minor-mode
508 ;; when turning on theminor mode, re-read the `yas/trigger-key'
509 ;; if a `yas/minor-mode-map' is already built. Else, call
510 ;; `yas/init-keymap-and-menu' to build it
511 (if (and (cdr yas/minor-mode-map)
512 yas/trigger-key)
513 (define-key yas/minor-mode-map (read-kbd-macro yas/trigger-key) 'yas/expand)
514 (yas/init-keymap-and-menu))))
515
516 (defun yas/minor-mode-on ()
517 "Turn on YASnippet minor mode."
518 (interactive)
519 (yas/minor-mode 1))
520
521 (defun yas/minor-mode-off ()
522 "Turn off YASnippet minor mode."
523 (interactive)
524 (yas/minor-mode -1))
525
526 (define-globalized-minor-mode yas/global-mode yas/minor-mode yas/minor-mode-on
527 :group 'yasnippet)
528
529 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
530 ;; Major mode stuff
531 ;;
532 (defvar yas/font-lock-keywords
533 (append '(("^#.*$" . font-lock-comment-face))
534 lisp-font-lock-keywords
535 lisp-font-lock-keywords-1
536 lisp-font-lock-keywords-2
537 '(("$\\([0-9]+\\)"
538 (0 font-lock-keyword-face)
539 (1 font-lock-string-face t))
540 ("${\\([0-9]+\\):?"
541 (0 font-lock-keyword-face)
542 (1 font-lock-warning-face t))
543 ("${" font-lock-keyword-face)
544 ("$[0-9]+?" font-lock-preprocessor-face)
545 ("\\(\\$(\\)" 1 font-lock-preprocessor-face)
546 ("}"
547 (0 font-lock-keyword-face)))))
548
549 (defvar snippet-mode-map (make-sparse-keymap))
550 (define-key snippet-mode-map "\C-c\C-c" 'yas/load-snippet-buffer)
551 (define-key snippet-mode-map "\C-c\C-t" 'yas/tryout-snippet)
552
553
554 (define-derived-mode snippet-mode text-mode "YASnippet"
555 "A mode for editing yasnippets"
556 (set-syntax-table (standard-syntax-table))
557 (setq font-lock-defaults '(yas/font-lock-keywords))
558 (set (make-local-variable 'require-final-newline) nil)
559 (use-local-map snippet-mode-map))
560
561
562
563 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
564 ;; Internal structs for template management
565 ;;
566
567 (defstruct (yas/template (:constructor yas/make-template
568 (content name condition env file)))
569 "A template for a snippet."
570 content
571 name
572 condition
573 env
574 file)
575
576 (defstruct (yas/snippet-table (:constructor yas/make-snippet-table (name)))
577 "A table to store snippets for a perticular mode."
578 name
579 (hash (make-hash-table :test 'equal))
580 (parents nil))
581
582 (defun yas/template-condition-predicate (condition)
583 (condition-case err
584 (save-excursion
585 (save-restriction
586 (save-match-data
587 (eval condition))))
588 (error (progn
589 (message (format "[yas]error in condition evaluation: %s"
590 (error-message-string err)))
591 nil))))
592
593
594 (defun yas/filter-templates-by-condition (templates)
595 "Filter the templates using the applicable condition.
596
597 TEMPLATES is a list of cons (KEY . TEMPLATE) where KEY is a
598 string and TEMPLATE is a `yas/template' structure.
599
600 This function implements the rules described in
601 `yas/buffer-local-condition'. See that variables documentation."
602 (let ((requirement (yas/require-template-specific-condition-p)))
603 (if (eq requirement 'always)
604 templates
605 (remove-if-not #'(lambda (pair)
606 (let* ((condition (yas/template-condition (cdr pair)))
607 (result (and condition
608 (yas/template-condition-predicate condition))))
609 (cond ((eq requirement t)
610 result)
611 (t
612 (eq requirement result)))))
613 templates))))
614
615 (defun yas/snippet-table-fetch (table key)
616 "Fetch a snippet binding to KEY from TABLE."
617 (when table
618 (yas/filter-templates-by-condition (gethash key (yas/snippet-table-hash table)))))
619
620 (defun yas/snippet-table-get-all-parents (table)
621 (let ((parents (yas/snippet-table-parents table)))
622 (when parents
623 (append parents
624 (mapcan #'yas/snippet-table-get-all-parents parents)))))
625
626 (defun yas/snippet-table-templates (table)
627 (when table
628 (let ((acc))
629 (maphash #'(lambda (key templates)
630 (setq acc (append acc templates)))
631 (yas/snippet-table-hash table))
632 (yas/filter-templates-by-condition acc))))
633
634 (defun yas/snippet-table-all-keys (table)
635 (when table
636 (let ((acc))
637 (maphash #'(lambda (key templates)
638 (when (yas/filter-templates-by-condition templates)
639 (push key acc)))
640 (yas/snippet-table-hash table))
641 acc)))
642
643 (defun yas/snippet-table-store (table full-key key template)
644 "Store a snippet template in the TABLE."
645 (puthash key
646 (yas/modify-alist (gethash key
647 (yas/snippet-table-hash table))
648 full-key
649 template)
650 (yas/snippet-table-hash table)))
651
652 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
653 ;; Internal functions
654 ;;
655
656 (defun yas/real-mode? (mode)
657 "Try to find out if MODE is a real mode. The MODE bound to
658 a function (like `c-mode') is considered real mode. Other well
659 known mode like `ruby-mode' which is not part of Emacs might
660 not bound to a function until it is loaded. So yasnippet keeps
661 a list of modes like this to help the judgement."
662 (or (fboundp mode)
663 (find mode yas/known-modes)))
664
665 (defun yas/eval-string (string)
666 ;; TODO: This is a possible optimization point, the expression could
667 ;; be stored in cons format instead of string,
668 "Evaluate STRING and convert the result to string."
669 (let ((retval (catch 'yas/exception
670 (condition-case err
671 (save-excursion
672 (save-restriction
673 (save-match-data
674 (widen)
675 (let ((result (eval (read string))))
676 (when result
677 (format "%s" result))))))
678 (error (if yas/good-grace
679 "[yas] elisp error!"
680 (error (format "[yas] elisp error: %s"
681 (error-message-string err)))))))))
682 (when (and (consp retval)
683 (eq 'yas/exception (car retval)))
684 (error (cdr retval)))
685 retval))
686
687 (defvar yas/mode-symbol nil
688 "If non-nil, lookup snippets using this instead of `major-mode'.")
689 (make-variable-buffer-local 'yas/mode-symbol)
690
691 (defun yas/snippet-table-get-create (mode)
692 "Get the snippet table corresponding to MODE.
693
694 Optional DIRECTORY gets recorded as the default directory to
695 search for snippet files if the retrieved/created table didn't
696 already have such a property."
697 (let ((table (gethash mode
698 yas/snippet-tables)))
699 (unless table
700 (setq table (yas/make-snippet-table (symbol-name mode)))
701 (puthash mode table yas/snippet-tables))
702 table))
703
704 (defun yas/get-snippet-tables (&optional mode-symbol dont-search-parents)
705 "Get snippet tables for current buffer.
706
707 Return tables in this order: optional MODE-SYMBOL, then
708 `yas/mode-symbol', then `major-mode' then, unless
709 DONT-SEARCH-PARENTS is non-nil, the guessed parent mode of either
710 MODE-SYMBOL or `major-mode'."
711 (let ((mode-tables
712 (mapcar #'(lambda (mode)
713 (gethash mode yas/snippet-tables))
714 (append (list mode-symbol)
715 (if (listp yas/mode-symbol)
716 yas/mode-symbol
717 (list yas/mode-symbol))
718 (list major-mode
719 (and (not dont-search-parents)
720 (get (or mode-symbol major-mode)
721 'derived-mode-parent))))))
722 (all-tables))
723 (dolist (table (remove nil mode-tables))
724 (push table all-tables)
725 (nconc all-tables (yas/snippet-table-get-all-parents table)))
726 (remove-duplicates all-tables)))
727
728 (defun yas/menu-keymap-get-create (mode)
729 "Get the menu keymap correspondong to MODE."
730 (or (gethash mode yas/menu-table)
731 (puthash mode (make-sparse-keymap) yas/menu-table)))
732
733 (defun yas/current-key ()
734 "Get the key under current position. A key is used to find
735 the template of a snippet in the current snippet-table."
736 (let ((start (point))
737 (end (point))
738 (syntaxes yas/key-syntaxes)
739 syntax done templates)
740 (while (and (not done) syntaxes)
741 (setq syntax (car syntaxes))
742 (setq syntaxes (cdr syntaxes))
743 (save-excursion
744 (skip-syntax-backward syntax)
745 (setq start (point)))
746 (setq templates
747 (mapcan #'(lambda (table)
748 (yas/snippet-table-fetch table (buffer-substring-no-properties start end)))
749 (yas/get-snippet-tables)))
750 (if templates
751 (setq done t)
752 (setq start end)))
753 (list templates
754 start
755 end)))
756
757 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
758 ;;; Template-related and snippet loading functions
759
760 (defun yas/parse-template (&optional file)
761 "Parse the template in the current buffer.
762
763 Optional FILE is the absolute file name of the file being
764 parsed.
765
766 Return a snippet-definition, i.e. a list
767
768 (KEY TEMPLATE NAME CONDITION GROUP ENV)
769
770 If the buffer contains a line of \"# --\" then the contents
771 above this line are ignored. Variables can be set above this
772 line through the syntax:
773
774 #name : value
775
776 Here's a list of currently recognized variables:
777
778 * name
779 * contributor
780 * condition
781 * key
782 * group
783 * env
784
785 #name: #include \"...\"
786 # --
787 #include \"$1\""
788 (goto-char (point-min))
789 (let* ((name (and file (file-name-nondirectory file)))
790 (key name)
791 template
792 bound
793 condition
794 group
795 env)
796 (if (re-search-forward "^# --\n" nil t)
797 (progn (setq template
798 (buffer-substring-no-properties (point)
799 (point-max)))
800 (setq bound (point))
801 (goto-char (point-min))
802 (while (re-search-forward "^# *\\([^ ]+?\\) *: *\\(.*\\)$" bound t)
803 (when (string= "name" (match-string-no-properties 1))
804 (setq name (match-string-no-properties 2)))
805 (when (string= "condition" (match-string-no-properties 1))
806 (setq condition (read (match-string-no-properties 2))))
807 (when (string= "group" (match-string-no-properties 1))
808 (setq group (match-string-no-properties 2)))
809 (when (string= "env" (match-string-no-properties 1))
810 (setq env (match-string-no-properties 2)))
811 (when (string= "key" (match-string-no-properties 1))
812 (setq key (match-string-no-properties 2)))))
813 (setq template
814 (buffer-substring-no-properties (point-min) (point-max))))
815 (list key template name condition group env file)))
816
817 (defun yas/subdirs (directory &optional file?)
818 "Return subdirs or files of DIRECTORY according to FILE?."
819 (remove-if (lambda (file)
820 (or (string-match "^\\."
821 (file-name-nondirectory file))
822 (string-match "~$"
823 (file-name-nondirectory file))
824 (if file?
825 (file-directory-p file)
826 (not (file-directory-p file)))))
827 (directory-files directory t)))
828
829 (defun yas/make-menu-binding (template)
830 `(lambda () (interactive) (yas/expand-from-menu ,template)))
831
832 (defun yas/expand-from-menu (template)
833 (let ((where (if mark-active
834 (cons (region-beginning) (region-end))
835 (cons (point) (point)))))
836 (yas/expand-snippet (car where)
837 (cdr where)
838 (yas/template-content template))))
839
840 (defun yas/modify-alist (alist key value)
841 "Modify ALIST to map KEY to VALUE. return the new alist."
842 (let ((pair (assoc key alist)))
843 (if (null pair)
844 (cons (cons key value)
845 alist)
846 (setcdr pair value)
847 alist)))
848
849 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
850 ;; Popping up for keys and templates
851 ;;
852 (defun yas/prompt-for-template (templates &optional prompt)
853 "Interactively choose a template from the list TEMPLATES.
854
855 TEMPLATES is a list of `yas/template'."
856 (when templates
857 (some #'(lambda (fn)
858 (funcall fn (or prompt "Choose a snippet: ")
859 templates
860 #'yas/template-name))
861 yas/prompt-functions)))
862
863 (defun yas/prompt-for-keys (keys &optional prompt)
864 "Interactively choose a template key from the list KEYS."
865 (when keys
866 (some #'(lambda (fn)
867 (funcall fn (or prompt "Choose a snippet key: ") keys))
868 yas/prompt-functions)))
869
870 (defun yas/prompt-for-table (tables &optional prompt)
871 (when tables
872 (some #'(lambda (fn)
873 (funcall fn (or prompt "Choose a snippet table: ")
874 tables
875 #'yas/snippet-table-name))
876 yas/prompt-functions)))
877
878 (defun yas/x-prompt (prompt choices &optional display-fn)
879 (when (and window-system choices)
880 (let ((keymap (cons 'keymap
881 (cons
882 prompt
883 (mapcar (lambda (choice)
884 (list choice
885 'menu-item
886 (if display-fn
887 (funcall display-fn choice)
888 choice)
889 t))
890 choices)))))
891 (when (cdr keymap)
892 (car (x-popup-menu (if (fboundp 'posn-at-point)
893 (let ((x-y (posn-x-y (posn-at-point (point)))))
894 (list (list (+ (car x-y) 10)
895 (+ (cdr x-y) 20))
896 (selected-window)))
897 t)
898 keymap))))))
899
900 (defun yas/ido-prompt (prompt choices &optional display-fn)
901 (when (and (featurep 'ido)
902 ido-mode)
903 (let* ((formatted-choices (or (and display-fn
904 (mapcar display-fn choices))
905 choices))
906 (chosen (and formatted-choices
907 (ido-completing-read prompt
908 formatted-choices
909 nil
910 'require-match
911 nil
912 nil))))
913 (when chosen
914 (nth (position chosen formatted-choices :test #'string=) choices)))))
915
916 (eval-when-compile (require 'dropdown-list nil t))
917 (defun yas/dropdown-prompt (prompt choices &optional display-fn)
918 (when (featurep 'dropdown-list)
919 (let* ((formatted-choices (or (and display-fn
920 (mapcar display-fn choices))
921 choices))
922 (chosen (and formatted-choices
923 (nth (dropdown-list formatted-choices)
924 choices))))
925 chosen)))
926
927 (defun yas/completing-prompt (prompt choices &optional display-fn)
928 (let* ((formatted-choices (or (and display-fn
929 (mapcar display-fn choices))
930 choices))
931 (chosen (and formatted-choices
932 (completing-read prompt
933 formatted-choices
934 nil
935 'require-match
936 nil
937 nil))))
938 (when chosen
939 (nth (position chosen formatted-choices :test #'string=) choices))))
940
941 (defun yas/no-prompt (prompt choices &optional display-fn)
942 (first choices))
943
944 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
945 ;; Loading snippets from files
946 ;;
947 (defun yas/load-directory-1 (directory &optional parents no-hierarchy-parents)
948 "Recursively load snippet templates from DIRECTORY."
949
950 (let* ((major-mode-and-parents (yas/compute-major-mode-and-parents (concat directory "/dummy")
951 nil
952 no-hierarchy-parents))
953 (mode-sym (car major-mode-and-parents))
954 (parents (rest major-mode-and-parents))
955 (snippet-defs nil))
956 (with-temp-buffer
957 (dolist (file (yas/subdirs directory 'no-subdirs-just-files))
958 (when (file-readable-p file)
959 (insert-file-contents file nil nil nil t)
960 (push (yas/parse-template file)
961 snippet-defs))))
962 (yas/define-snippets mode-sym
963 snippet-defs
964 parents)
965 (dolist (subdir (yas/subdirs directory))
966 (yas/load-directory-1 subdir (list mode-sym)))))
967
968 (defun yas/load-directory (directory)
969 "Load snippet definition from a directory hierarchy.
970
971 Below the top-level directory, each directory is a mode
972 name. And under each subdirectory, each file is a definition
973 of a snippet. The file name is the trigger key and the
974 content of the file is the template."
975 (interactive "DSelect the root directory: ")
976 (unless (file-directory-p directory)
977 (error "Error %s not a directory" directory))
978 (add-to-list 'yas/root-directory directory)
979 (dolist (dir (yas/subdirs directory))
980 (yas/load-directory-1 dir nil 'no-hierarchy-parents))
981 (when (interactive-p)
982 (message "done.")))
983
984 (defun yas/reload-all ()
985 "Reload all snippets and rebuild the YASnippet menu. "
986
987 (interactive)
988 (let ((restore-global-mode nil)
989 (restore-minor-mode nil))
990 (setq yas/snippet-tables (make-hash-table))
991 (setq yas/menu-table (make-hash-table))
992 (setf (cdr yas/minor-mode-menu) nil)
993 (setf (cdr yas/minor-mode-map) nil)
994 (when yas/global-mode
995 (yas/global-mode -1)
996 (setq restore-global-mode t))
997
998 (when yas/minor-mode
999 (yas/minor-mode -1)
1000 (setq restore-minor-mode t))
1001
1002 (yas/init-keymap-and-menu)
1003
1004 (if yas/root-directory
1005 (if (listp yas/root-directory)
1006 (dolist (directory yas/root-directory)
1007 (yas/load-directory directory))
1008 (yas/load-directory yas/root-directory))
1009 (call-interactively 'yas/load-directory))
1010
1011
1012 (when restore-minor-mode
1013 (yas/minor-mode 1))
1014
1015 (when restore-global-mode
1016 (yas/global-mode 1))
1017
1018 (message "done.")))
1019
1020 (defun yas/quote-string (string)
1021 "Escape and quote STRING.
1022 foo\"bar\\! -> \"foo\\\"bar\\\\!\""
1023 (concat "\""
1024 (replace-regexp-in-string "[\\\"]"
1025 "\\\\\\&"
1026 string
1027 t)
1028 "\""))
1029 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1030 ;;; Yasnippet Bundle
1031
1032 (defun yas/initialize ()
1033 "For backward compatibility, enable `yas/minor-mode' globally"
1034 (yas/global-mode 1))
1035
1036 (defun yas/compile-bundle
1037 (&optional yasnippet yasnippet-bundle snippet-roots code dropdown)
1038 "Compile snippets in SNIPPET-ROOTS to a single bundle file.
1039 SNIPPET-ROOTS is a list of root directories that contains the
1040 snippets definition. YASNIPPET is the yasnippet.el file
1041 path. YASNIPPET-BUNDLE is the output file of the compile
1042 result. CODE is the code you would like to used to initialize
1043 yasnippet. Last optional argument DROPDOWN is the filename of the
1044 dropdown-list.el library.
1045
1046 Here's the default value for all the parameters:
1047
1048 (yas/compile-bundle \"yasnippet.el\"
1049 \"./yasnippet-bundle.el\"
1050 '(\"snippets\")
1051 \"(yas/initialize)\")
1052
1053 ..
1054
1055 "
1056 (when (null yasnippet)
1057 (setq yasnippet "yasnippet.el"))
1058 (when (null yasnippet-bundle)
1059 (setq yasnippet-bundle "./yasnippet-bundle.el"))
1060 (when (null snippet-roots)
1061 (setq snippet-roots '("snippets")))
1062 (when (null dropdown)
1063 (setq dropdown "dropdown-list.el"))
1064 (when (null code)
1065 (setq code (concat "(yas/initialize-bundle)"
1066 "\n;;;###autoload" ; break through so that won't
1067 "(require 'yasnippet-bundle)"))) ; be treated as magic comment
1068
1069 (let ((dirs (or (and (listp snippet-roots) snippet-roots)
1070 (list snippet-roots)))
1071 (bundle-buffer nil))
1072 (with-temp-buffer
1073 (setq bundle-buffer (current-buffer))
1074 (insert ";;; yasnippet-bundle.el --- "
1075 "Yet another snippet extension (Auto compiled bundle)\n")
1076 (insert-file-contents yasnippet)
1077 (goto-char (point-max))
1078 (insert "\n")
1079 (when dropdown
1080 (insert-file-contents dropdown))
1081 (goto-char (point-max))
1082 (insert ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n")
1083 (insert ";;;; Auto-generated code ;;;;\n")
1084 (insert ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n")
1085 (insert "(defun yas/initialize-bundle ()\n"
1086 " \"Initialize YASnippet and load snippets in the bundle.\""
1087 " (yas/global-mode 1)\n")
1088 (flet ((yas/define-snippets
1089 (mode snippets &optional parent directory)
1090 (with-current-buffer bundle-buffer
1091 (insert ";;; snippets for " (symbol-name mode) "\n")
1092 (insert "(yas/define-snippets '" (symbol-name mode) "\n")
1093 (insert "'(\n")
1094 (dolist (snippet snippets)
1095 (insert " ("
1096 (yas/quote-string (car snippet))
1097 " "
1098 (yas/quote-string (nth 1 snippet))
1099 " "
1100 (if (nth 2 snippet)
1101 (yas/quote-string (nth 2 snippet))
1102 "nil")
1103 " "
1104 (if (nth 3 snippet)
1105 (format "'%s" (nth 3 snippet))
1106 "nil")
1107 " "
1108 (if (nth 4 snippet)
1109 (yas/quote-string (nth 4 snippet))
1110 "nil")
1111 ")\n"))
1112 (insert " )\n")
1113 (insert (if parent
1114 (concat "'" (symbol-name parent))
1115 "nil")
1116 ;; (if directory
1117 ;; (concat "\"" directory "\"")
1118 ;; "nil")
1119 ")\n\n"))))
1120 (dolist (dir dirs)
1121 (dolist (subdir (yas/subdirs dir))
1122 (yas/load-directory-1 subdir nil))))
1123
1124 (insert ")\n\n" code "\n")
1125 (insert "(provide '"
1126 (file-name-nondirectory
1127 (file-name-sans-extension
1128 yasnippet-bundle))
1129 ")\n")
1130 (insert ";;; "
1131 (file-name-nondirectory yasnippet-bundle)
1132 " ends here\n")
1133 (setq buffer-file-name yasnippet-bundle)
1134 (save-buffer))))
1135
1136 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1137 ;;; Some user level functions
1138 ;;;
1139
1140 (defun yas/about ()
1141 (interactive)
1142 (message (concat "yasnippet (version "
1143 yas/version
1144 ") -- pluskid <pluskid@gmail.com>/joaotavora <joaotavora@gmail.com>")))
1145
1146 (defun yas/define-snippets (mode snippets &optional parent-mode)
1147 "Define snippets for MODE. SNIPPETS is a list of
1148 snippet definitions, each taking the following form:
1149
1150 (KEY TEMPLATE NAME CONDITION GROUP)
1151
1152 NAME, CONDITION or GROUP may be omitted.
1153
1154 Optional PARENT-MODE can be used to specify the parent modes of
1155 MODE. It can be a mode symbol of a list of mode symbols. It does
1156 not need to be a real mode.
1157
1158 That is, when looking a snippet in MODE failed, it can refer to
1159 its parent modes."
1160 (let ((snippet-table (yas/snippet-table-get-create mode))
1161 (parent-tables (mapcar #'yas/snippet-table-get-create
1162 (if (listp parent-mode)
1163 parent-mode
1164 (list parent-mode))))
1165 (keymap (if yas/use-menu
1166 (yas/menu-keymap-get-create mode)
1167 nil)))
1168 (when parent-tables
1169 (setf (yas/snippet-table-parents snippet-table)
1170 parent-tables)
1171 (when yas/use-menu
1172 (let ((parent-menu-syms-and-names
1173 (if (listp parent-mode)
1174 (mapcar #'(lambda (sym)
1175 (cons sym (concat "parent mode - " (symbol-name sym))))
1176 parent-mode)
1177 '((parent-mode . "parent mode")))))
1178 (mapc #'(lambda (sym-and-name)
1179 (define-key keymap (vector (intern (replace-regexp-in-string " " "_" (cdr sym-and-name))))
1180 (list 'menu-item (cdr sym-and-name)
1181 (yas/menu-keymap-get-create (car sym-and-name)))))
1182 (reverse parent-menu-syms-and-names)))))
1183 (when (and yas/use-menu
1184 (yas/real-mode? mode))
1185 (define-key yas/minor-mode-menu (vector mode)
1186 `(menu-item ,(symbol-name mode) ,keymap
1187 :visible (yas/show-menu-p ',mode))))
1188 (dolist (snippet snippets)
1189 (let* ((full-key (car snippet))
1190 (key (file-name-sans-extension full-key))
1191 (name (or (nth 2 snippet) (file-name-extension full-key)))
1192 (condition (nth 3 snippet))
1193 (group (nth 4 snippet))
1194 (template (yas/make-template (nth 1 snippet)
1195 (or name key)
1196 condition
1197 (nth 5 snippet)
1198 (nth 6 snippet))))
1199 (yas/snippet-table-store snippet-table
1200 full-key
1201 key
1202 template)
1203 (when yas/use-menu
1204 (let ((group-keymap keymap))
1205 ;; delete this entry from another group if already exists
1206 ;; in some other group. An entry is considered as existing
1207 ;; in another group if its name string-matches.
1208 (yas/delete-from-keymap group-keymap name)
1209
1210 ;; ... then add this entry to the correct group
1211 (when (and (not (null group))
1212 (not (string= "" group)))
1213 (dolist (subgroup (mapcar #'make-symbol
1214 (split-string group "\\.")))
1215 (let ((subgroup-keymap (lookup-key group-keymap
1216 (vector subgroup))))
1217 (when (null subgroup-keymap)
1218 (setq subgroup-keymap (make-sparse-keymap))
1219 (define-key group-keymap (vector subgroup)
1220 `(menu-item ,(symbol-name subgroup)
1221 ,subgroup-keymap)))
1222 (setq group-keymap subgroup-keymap))))
1223 (define-key group-keymap (vector (make-symbol full-key))
1224 `(menu-item ,(yas/template-name template)
1225 ,(yas/make-menu-binding template)
1226 :keys ,(concat key yas/trigger-symbol)))))))))
1227
1228 (defun yas/show-menu-p (mode)
1229 (message "what")
1230 (or (not (eq yas/use-menu 'abbreviate))
1231 (find mode (cons major-mode
1232 (if (listp yas/mode-symbol)
1233 yas/mode-symbol
1234 (list yas/mode-symbol))))))
1235
1236 (defun yas/delete-from-keymap (keymap name)
1237 "Recursively delete items name NAME from KEYMAP and its submenus.
1238
1239 Skip any submenus named \"parent mode\""
1240 ;; First of all, recursively enter submenus, i.e. the tree is
1241 ;; searched depth first so that stale submenus can be found in the
1242 ;; higher passes.
1243 ;;
1244 (mapc #'(lambda (item)
1245 (when (and (keymapp (fourth item))
1246 (stringp (third item))
1247 (not (string-match "parent mode" (third item))))
1248 (yas/delete-from-keymap (fourth item) name)))
1249 (rest keymap))
1250 ;;
1251 (when (keymapp keymap)
1252 (let ((pos-in-keymap))
1253 (while (setq pos-in-keymap (position-if #'(lambda (item)
1254 (and (listp item)
1255 (or
1256 ;; the menu item we want to delete
1257 (and (eq 'menu-item (second item))
1258 (third item)
1259 (and (string= (third item) name)))
1260 ;; a stale subgroup
1261 (and (keymapp (fourth item))
1262 (not (and (stringp (third item))
1263 (string-match "parent mode" (third item))))
1264 (null (rest (fourth item)))))))
1265 keymap))
1266 (setf (nthcdr pos-in-keymap keymap)
1267 (nthcdr (+ 1 pos-in-keymap) keymap))))))
1268
1269 (defun yas/define (mode key template &optional name condition group)
1270 "Define a snippet. Expanding KEY into TEMPLATE.
1271
1272 NAME is a description to this template. Also update the menu if
1273 `yas/use-menu' is `t'. CONDITION is the condition attached to
1274 this snippet. If you attach a condition to a snippet, then it
1275 will only be expanded when the condition evaluated to non-nil."
1276 (yas/define-snippets mode
1277 (list (list key template name condition group))))
1278
1279 (defun yas/hippie-try-expand (first-time?)
1280 "Integrate with hippie expand. Just put this function in
1281 `hippie-expand-try-functions-list'."
1282 (if (not first-time?)
1283 (let ((yas/fallback-behavior 'return-nil))
1284 (yas/expand))
1285 (undo 1)
1286 nil))
1287
1288 (defun yas/require-template-specific-condition-p ()
1289 "Decides if this buffer requests/requires snippet-specific
1290 conditions to filter out potential expansions."
1291 (if (eq 'always yas/buffer-local-condition)
1292 'always
1293 (let ((local-condition (yas/template-condition-predicate
1294 yas/buffer-local-condition)))
1295 (when local-condition
1296 (if (eq local-condition t)
1297 t
1298 (and (consp local-condition)
1299 (eq 'require-snippet-condition (car local-condition))
1300 (symbolp (cdr local-condition))
1301 (cdr local-condition)))))))
1302
1303 (defun yas/expand ()
1304 "Expand a snippet before point.
1305
1306 If no snippet expansion is possible, fall back to the behaviour
1307 defined in `yas/fallback-behavior'"
1308 (interactive)
1309 (yas/expand-1))
1310
1311 (defun yas/expand-1 (&optional field)
1312 "Actually fo the work for `yas/expand'"
1313 (multiple-value-bind (templates start end) (if field
1314 (save-restriction
1315 (narrow-to-region (yas/field-start field) (yas/field-end field))
1316 (yas/current-key))
1317 (yas/current-key))
1318 (if templates
1319 (let ((template (or (and (rest templates) ;; more than one
1320 (yas/prompt-for-template (mapcar #'cdr templates)))
1321 (cdar templates))))
1322 (when template
1323 (yas/expand-snippet start
1324 end
1325 (yas/template-content template)
1326 (yas/template-env template))))
1327 (cond ((eq yas/fallback-behavior 'return-nil)
1328 ;; return nil
1329 nil)
1330 ((eq yas/fallback-behavior 'call-other-command)
1331 (let* ((yas/minor-mode nil)
1332 (command (key-binding (read-kbd-macro yas/trigger-key))))
1333 (when (commandp command)
1334 (setq this-command command)
1335 (call-interactively command))))
1336 ((and (listp yas/fallback-behavior)
1337 (cdr yas/fallback-behavior)
1338 (eq 'apply (car yas/fallback-behavior)))
1339 (if (cddr yas/fallback-behavior)
1340 (apply (cadr yas/fallback-behavior)
1341 (cddr yas/fallback-behavior))
1342 (when (commandp (cadr yas/fallback-behavior))
1343 (setq this-command (cadr yas/fallback-behavior))
1344 (call-interactively (cadr yas/fallback-behavior)))))
1345 (t
1346 ;; also return nil if all the other fallbacks have failed
1347 nil)))))
1348
1349 (defun yas/all-templates (tables)
1350 "Return all snippet tables applicable for the current buffer.
1351
1352 Honours `yas/choose-tables-first', `yas/choose-keys-first' and
1353 `yas/buffer-local-condition'"
1354 (when yas/choose-tables-first
1355 (setq tables (list (yas/prompt-for-table tables))))
1356 (mapcar #'cdr
1357 (if yas/choose-keys-first
1358 (let ((key (yas/prompt-for-keys
1359 (mapcan #'yas/snippet-table-all-keys tables))))
1360 (when key
1361 (mapcan #'(lambda (table)
1362 (yas/snippet-table-fetch table key))
1363 tables)))
1364 (mapcan #'yas/snippet-table-templates tables))))
1365
1366 (defun yas/insert-snippet (&optional no-condition)
1367 "Choose a snippet to expand, pop-up a list of choices according
1368 to `yas/prompt-function'.
1369
1370 With prefix argument NO-CONDITION, bypass filtering of snippets
1371 by condition."
1372 (interactive "P")
1373 (let* ((yas/buffer-local-condition (or (and no-condition
1374 'always)
1375 yas/buffer-local-condition))
1376 (templates (yas/all-templates (yas/get-snippet-tables)))
1377 (template (and templates
1378 (or (and (rest templates) ;; more than one template for same key
1379 (yas/prompt-for-template templates))
1380 (car templates))))
1381 (where (if mark-active
1382 (cons (region-beginning) (region-end))
1383 (cons (point) (point)))))
1384 (if template
1385 (yas/expand-snippet (car where)
1386 (cdr where)
1387 (yas/template-content template)
1388 (yas/template-env template))
1389 (message "[yas] No snippets can be inserted here!"))))
1390
1391 (defun yas/visit-snippet-file ()
1392 "Choose a snippet to edit, selection like `yas/insert-snippet'.
1393
1394 Only success if selected snippet was loaded from a file. Put the
1395 visited file in `snippet-mode'."
1396 (interactive)
1397 (let* ((yas/buffer-local-condition 'always)
1398 (templates (yas/all-templates (yas/get-snippet-tables)))
1399 (template (and templates
1400 (or (and (rest templates) ;; more than one template for same key
1401 (yas/prompt-for-template templates
1402 "Choose a snippet template to edit: "))
1403 (car templates)))))
1404
1405 (when template
1406 (let ((file (yas/template-file template)))
1407 (cond ((and file (file-exists-p file))
1408 (find-file-other-window file)
1409 (snippet-mode))
1410 (file
1411 (message "Original file %s no longer exists!" file))
1412 (t
1413 (message "This snippet was not loaded from a file!")))))))
1414
1415 (defun yas/guess-snippet-directory ()
1416 "Try to guess suitable directories based on `major-mode' and
1417 also the current active tables."
1418 (let ((main-dir (or (and (listp yas/root-directory)
1419 (first yas/root-directory))
1420 yas/root-directory
1421 "~/.emacs.d/snippets"))
1422 (mode major-mode)
1423 (options))
1424 ;; Lookup main mode and add that to the options
1425 ;;
1426 (push (format "%s/%s" main-dir mode) options)
1427 ;; Next lookup the main active table
1428 ;;
1429 (let ((active-tables (first (yas/get-snippet-tables)))
1430 (other-path-alternative main-dir))
1431 (when active-tables
1432 (setq active-tables (cons active-tables
1433 (yas/snippet-table-get-all-parents active-tables))))
1434 (dolist (table (reverse active-tables))
1435 (setq other-path-alternative
1436 (concat other-path-alternative "/" (yas/snippet-table-name table))))
1437 (push other-path-alternative options))
1438 ;; Finally add to the options the guessed parent of major-mode
1439 ;; (this is almost never works out)
1440 (when (get mode 'derived-mode-parent)
1441 (push (format "%s/%s" main-dir (get mode 'derived-mode-parent)) options))
1442 (reverse options)))
1443
1444 (defun yas/new-snippet (&optional same-window)
1445 "Create a new snippet in guessed current mode's directory."
1446 (interactive)
1447 (yas/find-snippets same-window
1448 (read-from-minibuffer "Enter snippet name: ")))
1449
1450
1451 (defun yas/find-snippets (&optional same-window file-name)
1452 "Look for user snippets in guessed current mode's directory.
1453
1454 Calls `find-file' interactively in the guessed directory.
1455
1456 With prefix arg SAME-WINDOW opens the buffer in the same window.
1457
1458 With optional FILE-NAME, finds the file directly, i.e. `find-file' is
1459 called non-interactively.
1460
1461 Because snippets can be loaded from many different locations,
1462 this has to guess the correct directory using
1463 `yas/guess-directory', which returns a list of options. If any
1464 one of these exists, it is taken and `find-file' is called there,
1465 otherwise, proposes to create the first option returned by
1466 `yas/guess-directory'."
1467 (interactive "P")
1468 (let* ((guessed-directories (yas/guess-snippet-directory))
1469 (target-directory (first (remove-if-not #'file-exists-p guessed-directories)))
1470 (buffer))
1471
1472 (unless target-directory
1473 (when (y-or-n-p (format "Guessed directory (%s) does not exist! Create? " (first guessed-directories)))
1474 (setq target-directory (first guessed-directories))
1475 (make-directory target-directory 'also-make-parents)))
1476
1477 (when target-directory
1478 (let ((default-directory target-directory))
1479 (setq buffer (if file-name
1480 (if same-window
1481 (find-file file-name)
1482 (find-file-other-window file-name))
1483 (call-interactively (if same-window
1484 'find-file
1485 'find-file-other-window))))
1486 (when buffer
1487 (save-excursion
1488 (set-buffer buffer)
1489 (when (eq major-mode 'fundamental-mode)
1490 (snippet-mode))))))))
1491
1492 (defun yas/compute-major-mode-and-parents (file &optional prompt-if-failed no-hierarchy-parents)
1493 (let* ((file-dir (and file
1494 (directory-file-name (file-name-directory file))))
1495 (major-mode-name (and file-dir
1496 (file-name-nondirectory file-dir)))
1497 (parent-file-dir (and file-dir
1498 (directory-file-name (file-name-directory file-dir))))
1499 (parent-mode-name (and parent-file-dir
1500 (not no-hierarchy-parents)
1501 (file-name-nondirectory parent-file-dir)))
1502 (major-mode-sym (or (and major-mode-name
1503 (intern major-mode-name))
1504 (when prompt-if-failed
1505 (read-from-minibuffer "[yas] Cannot auto-detect major mode! Enter a major mode: "))))
1506 (parent-mode-sym (and parent-mode-name
1507 (intern parent-mode-name)))
1508 (extra-parents-file-name (concat file-dir "/.yas-parents"))
1509 (more-parents (when (file-readable-p extra-parents-file-name)
1510 (mapcar #'intern
1511 (split-string
1512 (with-temp-buffer
1513 (insert-file extra-parents-file-name)
1514 (buffer-substring-no-properties (point-min)
1515 (point-max))))))))
1516 (when major-mode-sym
1517 (remove nil (append (list major-mode-sym parent-mode-sym)
1518 more-parents)))))
1519
1520 (defun yas/load-snippet-buffer (&optional kill)
1521 "Parse and load current buffer's snippet definition.
1522
1523 With optional prefix argument KILL quit the window and buffer."
1524 (interactive "P")
1525 (if buffer-file-name
1526 (let ((major-mode-and-parent (yas/compute-major-mode-and-parents buffer-file-name)))
1527 (if major-mode-and-parent
1528 (let* ((parsed (yas/parse-template buffer-file-name))
1529 (name (and parsed
1530 (third parsed))))
1531 (when name
1532 (yas/define-snippets (car major-mode-and-parent)
1533 (list parsed)
1534 (cdr major-mode-and-parent))
1535 (when (and (buffer-modified-p)
1536 (y-or-n-p "Save snippet? "))
1537 (save-buffer))
1538 (if kill
1539 (quit-window kill)
1540 (message "[yas] Snippet \"%s\" loaded for %s." name (car major-mode-and-parent)))))
1541 (message "[yas] Cannot load snippet for unknown major mode")))
1542 (message "Save the buffer as a file first!")))
1543
1544 (defun yas/tryout-snippet (&optional debug)
1545 "Test current buffers's snippet template in other buffer."
1546 (interactive "P")
1547 (let* ((major-mode-and-parent (yas/compute-major-mode-and-parents buffer-file-name))
1548 (parsed (and major-mode-and-parent
1549 (fboundp (car major-mode-and-parent))
1550 (yas/parse-template (symbol-name (car major-mode-and-parent)))))
1551 (template (and parsed
1552 (yas/make-template (second parsed) (third parsed) nil (sixth parsed) nil))))
1553 (cond (template
1554 (let ((buffer-name (format "*YAS TEST: %s*" (yas/template-name template))))
1555 (set-buffer (switch-to-buffer buffer-name))
1556 (erase-buffer)
1557 (setq buffer-undo-list nil)
1558 (funcall (car major-mode-and-parent))
1559 (yas/expand-snippet (point-min) (point-max) (yas/template-content template) (yas/template-env template))
1560 (when debug
1561 (add-hook 'post-command-hook 'yas/debug-some-vars 't 'local))))
1562 (t
1563 (message "[yas] Cannot test snippet for unknown major mode")))))
1564
1565 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1566 ;;; User convenience functions, for using in snippet definitions
1567 ;;;
1568
1569 (defvar yas/modified-p nil
1570 "Non-nil if field has been modified by user or transformation.")
1571
1572 (defvar yas/moving-away-p nil
1573 "Non-nil if user is about to exit field.")
1574
1575 (defvar yas/text nil
1576 "Contains current field text.")
1577
1578 (defun yas/substr (str pattern &optional subexp)
1579 "Search PATTERN in STR and return SUBEXPth match.
1580
1581 If found, the content of subexp group SUBEXP (default 0) is
1582 returned, or else the original STR will be returned."
1583 (let ((grp (or subexp 0)))
1584 (save-match-data
1585 (if (string-match pattern str)
1586 (match-string-no-properties grp str)
1587 str))))
1588
1589 (defun yas/choose-value (possibilities)
1590 "Prompt for a string in the list POSSIBILITIES and return it."
1591 (unless (or yas/moving-away-p
1592 yas/modified-p)
1593 (some #'(lambda (fn)
1594 (funcall fn "Choose: " possibilities))
1595 yas/prompt-functions)))
1596
1597 (defun yas/key-to-value (alist)
1598 "Prompt for a string in the list POSSIBILITIES and return it."
1599 (unless (or yas/moving-away-p
1600 yas/modified-p)
1601 (let ((key (read-key-sequence "")))
1602 (when (stringp key)
1603 (or (cdr (find key alist :key #'car :test #'string=))
1604 key)))))
1605
1606 (defun yas/throw (text)
1607 "Throw a yas/exception with TEXT as the reason."
1608 (throw 'yas/exception (cons 'yas/exception text)))
1609
1610 (defun yas/verify-value (possibilities)
1611 "Verify that the current field value is in POSSIBILITIES
1612
1613 Otherwise throw exception."
1614 (when (and yas/moving-away-p (notany #'(lambda (pos) (string= pos yas/text)) possibilities))
1615 (yas/throw (format "[yas] field only allows %s" possibilities))))
1616
1617 (defun yas/field-value (number)
1618 (let* ((snippet (car (yas/snippets-at-point)))
1619 (field (and snippet
1620 (yas/snippet-find-field snippet number))))
1621 (when field
1622 (yas/field-text-for-display field))))
1623
1624 (defun yas/oni (text oni-regexp)
1625 "Runs ruby to parse TEXT with Oniguruma regexp ONI-REGEXP."
1626 (shell-command-to-string (format "ruby -e 'print \"%s\".gsub(\"a\",\"b\")'" "aha")))
1627
1628
1629 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1630 ;;; Snippet expansion and field management
1631
1632 (defvar yas/active-field-overlay nil
1633 "Overlays the currently active field.")
1634
1635 (defvar yas/field-protection-overlays nil
1636 "Two overlays protect the current active field ")
1637
1638 (defvar yas/deleted-text nil
1639 "The text deleted in the last snippet expansion.")
1640
1641 (defvar yas/selected-text nil
1642 "The selected region deleted on the last snippet expansion.")
1643
1644 (defvar yas/start-column nil
1645 "The column where the snippet expansion started.")
1646
1647 (make-variable-buffer-local 'yas/active-field-overlay)
1648 (make-variable-buffer-local 'yas/field-protection-overlays)
1649 (make-variable-buffer-local 'yas/deleted-text)
1650
1651 (defstruct (yas/snippet (:constructor yas/make-snippet ()))
1652 "A snippet.
1653
1654 ..."
1655 (fields '())
1656 (exit nil)
1657 (id (yas/snippet-next-id) :read-only t)
1658 (control-overlay nil)
1659 active-field
1660 ;; stacked expansion: the `previous-active-field' slot saves the
1661 ;; active field where the child expansion took place
1662 previous-active-field
1663 force-exit)
1664
1665 (defstruct (yas/field (:constructor yas/make-field (number start end parent-field)))
1666 "A field."
1667 number
1668 start end
1669 parent-field
1670 (mirrors '())
1671 (transform nil)
1672 (modified-p nil)
1673 next)
1674
1675 (defstruct (yas/mirror (:constructor yas/make-mirror (start end transform)))
1676 "A mirror."
1677 start end
1678 (transform nil)
1679 next)
1680
1681 (defstruct (yas/exit (:constructor yas/make-exit (marker)))
1682 marker
1683 next)
1684
1685 (defun yas/apply-transform (field-or-mirror field)
1686 "Calculate the value of the field/mirror. If there's a transform
1687 for this field, apply it. Otherwise, returned nil."
1688 (let* ((yas/text (yas/field-text-for-display field))
1689 (text yas/text)
1690 (yas/modified-p (yas/field-modified-p field))
1691 (yas/moving-away-p nil)
1692 (transform (if (yas/mirror-p field-or-mirror)
1693 (yas/mirror-transform field-or-mirror)
1694 (yas/field-transform field-or-mirror)))
1695 (start-point (if (yas/mirror-p field-or-mirror)
1696 (yas/mirror-start field-or-mirror)
1697 (yas/field-start field-or-mirror)))
1698 (transformed (and transform
1699 (save-excursion
1700 (goto-char start-point)
1701 (yas/eval-string transform)))))
1702 transformed))
1703
1704 (defsubst yas/replace-all (from to &optional text)
1705 "Replace all occurance from FROM to TO.
1706
1707 With optional string TEXT do it in that string."
1708 (if text
1709 (replace-regexp-in-string (regexp-quote from) to text t t)
1710 (goto-char (point-min))
1711 (while (search-forward from nil t)
1712 (replace-match to t t text))))
1713
1714 (defun yas/snippet-find-field (snippet number)
1715 (find-if #'(lambda (field)
1716 (eq number (yas/field-number field)))
1717 (yas/snippet-fields snippet)))
1718
1719 (defun yas/snippet-sort-fields (snippet)
1720 "Sort the fields of SNIPPET in navigation order."
1721 (setf (yas/snippet-fields snippet)
1722 (sort (yas/snippet-fields snippet)
1723 '(lambda (field1 field2)
1724 (yas/snippet-field-compare field1 field2)))))
1725
1726 (defun yas/snippet-field-compare (field1 field2)
1727 "Compare two fields. The field with a number is sorted first.
1728 If they both have a number, compare through the number. If neither
1729 have, compare through the field's start point"
1730 (let ((n1 (yas/field-number field1))
1731 (n2 (yas/field-number field2)))
1732 (if n1
1733 (if n2
1734 (< n1 n2)
1735 t)
1736 (if n2
1737 nil
1738 (< (yas/field-start field1)
1739 (yas/field-start field2))))))
1740
1741 (defun yas/field-probably-deleted-p (snippet field)
1742 "Guess if SNIPPET's FIELD should be skipped."
1743 (and (zerop (- (yas/field-start field) (yas/field-end field)))
1744 (or (yas/field-parent-field field)
1745 (and (eq field (car (last (yas/snippet-fields snippet))))
1746 (= (yas/field-start field) (overlay-end (yas/snippet-control-overlay snippet)))))))
1747
1748 (defun yas/snippets-at-point (&optional all-snippets)
1749 "Return a sorted list of snippets at point, most recently
1750 inserted first."
1751 (sort
1752 (remove nil (remove-duplicates (mapcar #'(lambda (ov)
1753 (overlay-get ov 'yas/snippet))
1754 (if all-snippets
1755 (overlays-in (point-min) (point-max))
1756 (overlays-at (point))))))
1757 #'(lambda (s1 s2)
1758 (<= (yas/snippet-id s2) (yas/snippet-id s1)))))
1759
1760 (defun yas/next-field-or-maybe-expand ()
1761 "Try to expand a snippet at a key before point, otherwise
1762 delegate to `yas/next-field'."
1763 (interactive)
1764 (if yas/triggers-in-field
1765 (let ((yas/fallback-behavior 'return-nil)
1766 (active-field (overlay-get yas/active-field-overlay 'yas/field)))
1767 (when active-field
1768 (unless (yas/expand-1 active-field)
1769 (yas/next-field))))
1770 (yas/next-field)))
1771
1772 (defun yas/next-field (&optional arg)
1773 "Navigate to next field. If there's none, exit the snippet."
1774 (interactive)
1775 (let* ((arg (or arg
1776 1))
1777 (snippet (first (yas/snippets-at-point)))
1778 (active-field (overlay-get yas/active-field-overlay 'yas/field))
1779 (live-fields (remove-if #'(lambda (field)
1780 (and (not (eq field active-field))
1781 (yas/field-probably-deleted-p snippet field)))
1782 (yas/snippet-fields snippet)))
1783 (active-field-pos (position active-field live-fields))
1784 (target-pos (and active-field-pos (+ arg active-field-pos)))
1785 (target-field (nth target-pos live-fields)))
1786 ;; First check if we're moving out of a field with a transform
1787 ;;
1788 (when (and active-field
1789 (yas/field-transform active-field))
1790 (let* ((yas/moving-away-p t)
1791 (yas/text (yas/field-text-for-display active-field))
1792 (text yas/text)
1793 (yas/modified-p (yas/field-modified-p active-field)))
1794 ;;; primary field transform: exit call to field-transform
1795 (yas/eval-string (yas/field-transform active-field))))
1796 ;; Now actually move...
1797 (cond ((>= target-pos (length live-fields))
1798 (yas/exit-snippet snippet))
1799 (target-field
1800 (yas/move-to-field snippet target-field))
1801 (t
1802 nil))))
1803
1804 (defun yas/place-overlays (snippet field)
1805 "Correctly place overlays for SNIPPET's FIELD"
1806 (yas/make-move-field-protection-overlays snippet field)
1807 (yas/make-move-active-field-overlay snippet field))
1808
1809 (defun yas/move-to-field (snippet field)
1810 "Update SNIPPET to move to field FIELD.
1811
1812 Also create some protection overlays"
1813 (goto-char (yas/field-start field))
1814 (setf (yas/snippet-active-field snippet) field)
1815 (yas/place-overlays snippet field)
1816 (overlay-put yas/active-field-overlay 'yas/field field)
1817 ;;; primary field transform: first call to snippet transform
1818 (unless (yas/field-modified-p field)
1819 (if (yas/field-update-display field snippet)
1820 (let ((inhibit-modification-hooks t))
1821 (yas/update-mirrors snippet))
1822 (setf (yas/field-modified-p field) nil))))
1823
1824 (defun yas/prev-field ()
1825 "Navigate to prev field. If there's none, exit the snippet."
1826 (interactive)
1827 (yas/next-field -1))
1828
1829 (defun yas/exit-snippet (snippet)
1830 "Goto exit-marker of SNIPPET."
1831 (interactive)
1832 (setf (yas/snippet-force-exit snippet) t)
1833 (goto-char (if (yas/snippet-exit snippet)
1834 (yas/exit-marker (yas/snippet-exit snippet))
1835 (overlay-end (yas/snippet-control-overlay snippet)))))
1836
1837 ;;; Apropos markers-to-points:
1838 ;;;
1839 ;;; This was found useful for performance reasons, so that an
1840 ;;; excessive number of live markers aren't kept around in the
1841 ;;; `buffer-undo-list'. However, in `markers-to-points', the
1842 ;;; set-to-nil markers can't simply be discarded and replaced with
1843 ;;; fresh ones in `points-to-markers'. The original marker that was
1844 ;;; just set to nil has to be reused.
1845 ;;;
1846 ;;; This shouldn't bring horrible problems with undo/redo, but it
1847 ;;; you never know
1848 ;;;
1849
1850 (defun yas/markers-to-points (snippet)
1851 "Convert all markers in SNIPPET to a cons (POINT . MARKER)
1852 where POINT is the original position of the marker and MARKER is
1853 the original marker object with the position set to nil."
1854 (dolist (field (yas/snippet-fields snippet))
1855 (let ((start (marker-position (yas/field-start field)))
1856 (end (marker-position (yas/field-end field))))
1857 (set-marker (yas/field-start field) nil)
1858 (set-marker (yas/field-end field) nil)
1859 (setf (yas/field-start field) (cons start (yas/field-start field)))
1860 (setf (yas/field-end field) (cons end (yas/field-end field))))
1861 (dolist (mirror (yas/field-mirrors field))
1862 (let ((start (marker-position (yas/mirror-start mirror)))
1863 (end (marker-position (yas/mirror-end mirror))))
1864 (set-marker (yas/mirror-start mirror) nil)
1865 (set-marker (yas/mirror-end mirror) nil)
1866 (setf (yas/mirror-start mirror) (cons start (yas/mirror-start mirror)))
1867 (setf (yas/mirror-end mirror) (cons end (yas/mirror-end mirror))))))
1868 (let ((snippet-exit (yas/snippet-exit snippet)))
1869 (when snippet-exit
1870 (let ((exit (marker-position (yas/exit-marker snippet-exit))))
1871 (set-marker (yas/exit-marker snippet-exit) nil)
1872 (setf (yas/exit-marker snippet-exit) (cons exit (yas/exit-marker snippet-exit)))))))
1873
1874 (defun yas/points-to-markers (snippet)
1875 "Convert all cons (POINT . MARKER) in SNIPPET to markers. This
1876 is done by setting MARKER to POINT with `set-marker'."
1877 (dolist (field (yas/snippet-fields snippet))
1878 (setf (yas/field-start field) (set-marker (cdr (yas/field-start field)) (car (yas/field-start field))))
1879 (setf (yas/field-end field) (set-marker (cdr (yas/field-end field)) (car (yas/field-end field))))
1880 (dolist (mirror (yas/field-mirrors field))
1881 (setf (yas/mirror-start mirror) (set-marker (cdr (yas/mirror-start mirror)) (car (yas/mirror-start mirror))))
1882 (setf (yas/mirror-end mirror) (set-marker (cdr (yas/mirror-end mirror)) (car (yas/mirror-end mirror))))))
1883 (let ((snippet-exit (yas/snippet-exit snippet)))
1884 (when snippet-exit
1885 (setf (yas/exit-marker snippet-exit) (set-marker (cdr (yas/exit-marker snippet-exit)) (car (yas/exit-marker snippet-exit)))))))
1886
1887 (defun yas/commit-snippet (snippet &optional no-hooks)
1888 "Commit SNIPPET, but leave point as it is. This renders the
1889 snippet as ordinary text.
1890
1891 Return a buffer position where the point should be placed if
1892 exiting the snippet.
1893
1894 NO-HOOKS means don't run the `yas/after-exit-snippet-hook' hooks."
1895
1896 (let ((control-overlay (yas/snippet-control-overlay snippet))
1897 yas/snippet-beg
1898 yas/snippet-end)
1899 ;;
1900 ;; Save the end of the moribund snippet in case we need to revive it
1901 ;; its original expansion.
1902 ;;
1903 (when (and control-overlay
1904 (overlay-buffer control-overlay))
1905 (setq yas/snippet-beg (overlay-start control-overlay))
1906 (setq yas/snippet-end (overlay-end control-overlay))
1907 (delete-overlay control-overlay))
1908
1909 (let ((inhibit-modification-hooks t))
1910 (when yas/active-field-overlay
1911 (delete-overlay yas/active-field-overlay))
1912 (when yas/field-protection-overlays
1913 (mapc #'delete-overlay yas/field-protection-overlays)))
1914
1915 ;; stacked expansion: if the original expansion took place from a
1916 ;; field, make sure we advance it here at least to
1917 ;; `yas/snippet-end'...
1918 ;;
1919 (let ((previous-field (yas/snippet-previous-active-field snippet)))
1920 (when (and yas/snippet-end previous-field)
1921 (yas/advance-end-maybe previous-field yas/snippet-end)))
1922
1923 ;; Convert all markers to points,
1924 ;;
1925 (yas/markers-to-points snippet)
1926
1927 ;; Take care of snippet revival
1928 ;;
1929 (if yas/snippet-revival
1930 (push `(apply yas/snippet-revive ,yas/snippet-beg ,yas/snippet-end ,snippet)
1931 buffer-undo-list)
1932 ;; Dismember the snippet... this is useful if we get called
1933 ;; again from `yas/take-care-of-redo'....
1934 (setf (yas/snippet-fields snippet) nil))
1935
1936 ;; XXX: `yas/after-exit-snippet-hook' should be run with
1937 ;; `yas/snippet-beg' and `yas/snippet-end' bound. That might not
1938 ;; be the case if the main overlay had somehow already
1939 ;; disappeared, which sometimes happens when the snippet's messed
1940 ;; up...
1941 ;;
1942 (unless no-hooks (run-hooks 'yas/after-exit-snippet-hook)))
1943
1944 (message "[yas] snippet exited."))
1945
1946 (defun yas/check-commit-snippet ()
1947 "Checks if point exited the currently active field of the
1948 snippet, if so cleans up the whole snippet up."
1949 (let* ((snippets (yas/snippets-at-point 'all-snippets))
1950 (snippets-left snippets))
1951 (dolist (snippet snippets)
1952 (let ((active-field (yas/snippet-active-field snippet)))
1953 (cond ((or (prog1 (yas/snippet-force-exit snippet)
1954 (setf (yas/snippet-force-exit snippet) nil))
1955 (not (and active-field (yas/field-contains-point-p active-field))))
1956 (setq snippets-left (delete snippet snippets-left))
1957 (yas/commit-snippet snippet snippets-left))
1958 ((and active-field
1959 (or (not yas/active-field-overlay)
1960 (not (overlay-buffer yas/active-field-overlay))))
1961 ;;
1962 ;; stacked expansion: this case is mainly for recent
1963 ;; snippet exits that place us back int the field of
1964 ;; another snippet
1965 ;;
1966 (save-excursion
1967 (yas/move-to-field snippet active-field)
1968 (yas/update-mirrors snippet)))
1969 (t
1970 nil))))
1971 (unless snippets-left
1972 (remove-hook 'post-command-hook 'yas/post-command-handler 'local)
1973 (remove-hook 'pre-command-hook 'yas/pre-command-handler 'local))))
1974
1975 (defun yas/field-contains-point-p (field &optional point)
1976 (let ((point (or point
1977 (point))))
1978 (and (>= point (yas/field-start field))
1979 (<= point (yas/field-end field)))))
1980
1981 (defun yas/field-text-for-display (field)
1982 "Return the propertized display text for field FIELD. "
1983 (buffer-substring (yas/field-start field) (yas/field-end field)))
1984
1985 (defun yas/undo-in-progress ()
1986 "True if some kind of undo is in progress"
1987 (or undo-in-progress
1988 (eq this-command 'undo)
1989 (eq this-command 'redo)))
1990
1991 (defun yas/make-control-overlay (snippet start end)
1992 "Creates the control overlay that surrounds the snippet and
1993 holds the keymap."
1994 (let ((overlay (make-overlay start
1995 end
1996 nil
1997 nil
1998 t)))
1999 (overlay-put overlay 'keymap yas/keymap)
2000 (overlay-put overlay 'yas/snippet snippet)
2001 overlay))
2002
2003 (defun yas/skip-and-clear-or-delete-char (&optional field)
2004 "Clears unmodified field if at field start, skips to next tab.
2005
2006 Otherwise deletes a character normally by calling `delete-char'."
2007 (interactive)
2008 (let ((field (or field
2009 (and yas/active-field-overlay
2010 (overlay-buffer yas/active-field-overlay)
2011 (overlay-get yas/active-field-overlay 'yas/field)))))
2012 (cond ((and field
2013 (not (yas/field-modified-p field))
2014 (eq (point) (marker-position (yas/field-start field))))
2015 (yas/skip-and-clear field)
2016 (yas/next-field 1))
2017 (t
2018 (call-interactively 'delete-char)))))
2019
2020 (defun yas/skip-and-clear (field)
2021 "Deletes the region of FIELD and sets it modified state to t"
2022 (setf (yas/field-modified-p field) t)
2023 (delete-region (yas/field-start field) (yas/field-end field)))
2024
2025 (defun yas/make-move-active-field-overlay (snippet field)
2026 "Place the active field overlay in SNIPPET's FIELD.
2027
2028 Move the overlay, or create it if it does not exit."
2029 (if (and yas/active-field-overlay
2030 (overlay-buffer yas/active-field-overlay))
2031 (move-overlay yas/active-field-overlay
2032 (yas/field-start field)
2033 (yas/field-end field))
2034 (setq yas/active-field-overlay
2035 (make-overlay (yas/field-start field)
2036 (yas/field-end field)
2037 nil nil t))
2038 (overlay-put yas/active-field-overlay 'face 'yas/field-highlight-face)
2039 (overlay-put yas/active-field-overlay 'yas/snippet snippet)
2040 (overlay-put yas/active-field-overlay 'modification-hooks '(yas/on-field-overlay-modification))
2041 (overlay-put yas/active-field-overlay 'insert-in-front-hooks '(yas/on-field-overlay-modification))
2042 (overlay-put yas/active-field-overlay 'insert-behind-hooks '(yas/on-field-overlay-modification))))
2043
2044 (defun yas/on-field-overlay-modification (overlay after? beg end &optional length)
2045 "Clears the field and updates mirrors, conditionally.
2046
2047 Only clears the field if it hasn't been modified and it point it
2048 at field start. This hook doesn't do anything if an undo is in
2049 progress."
2050 (unless (yas/undo-in-progress)
2051 (let ((field (overlay-get yas/active-field-overlay 'yas/field)))
2052 (cond (after?
2053 (yas/advance-end-maybe field (overlay-end overlay))
2054 ;;; primary field transform: normal calls to expression
2055 (let ((saved-point (point)))
2056 (yas/field-update-display field (car (yas/snippets-at-point)))
2057 (goto-char saved-point))
2058 (yas/update-mirrors (car (yas/snippets-at-point))))
2059 (field
2060 (when (and (not after?)
2061 (not (yas/field-modified-p field))
2062 (eq (point) (if (markerp (yas/field-start field))
2063 (marker-position (yas/field-start field))
2064 (yas/field-start field))))
2065 (yas/skip-and-clear field))
2066 (setf (yas/field-modified-p field) t))))))
2067
2068 ;;; Apropos protection overlays:
2069 ;;;
2070 ;;; These exist for nasty users who will try to delete parts of the
2071 ;;; snippet outside the active field. Actual protection happens in
2072 ;;; `yas/on-protection-overlay-modification'.
2073 ;;;
2074 ;;; Currently this signals an error which inhibits the command. For
2075 ;;; commands that move point (like `kill-line'), point is restored in
2076 ;;; the `yas/post-command-handler' using a global
2077 ;;; `yas/protection-violation' variable.
2078 ;;;
2079 ;;; Alternatively, I've experimented with an implementation that
2080 ;;; commits the snippet before actually calling `this-command'
2081 ;;; interactively, and then signals an eror, which is ignored. but
2082 ;;; blocks all other million modification hooks. This presented some
2083 ;;; problems with stacked expansion.
2084 ;;;
2085
2086 (defun yas/make-move-field-protection-overlays (snippet field)
2087 "Place protection overlays surrounding SNIPPET's FIELD.
2088
2089 Move the overlays, or create them if they do not exit."
2090 (let ((start (yas/field-start field))
2091 (end (yas/field-end field)))
2092 ;; First check if the (1+ end) is contained in the buffer,
2093 ;; otherwise we'll have to do a bit of cheating and silently
2094 ;; insert a newline. the `(1+ (buffer-size))' should prevent this
2095 ;; when using stacked expansion
2096 ;;
2097 (when (< (buffer-size) end)
2098 (save-excursion
2099 (let ((inhibit-modification-hooks t))
2100 (goto-char (point-max))
2101 (newline))))
2102 ;; go on to normal overlay creation/moving
2103 ;;
2104 (cond ((and yas/field-protection-overlays
2105 (every #'overlay-buffer yas/field-protection-overlays))
2106 (move-overlay (first yas/field-protection-overlays) (1- start) start)
2107 (move-overlay (second yas/field-protection-overlays) end (1+ end)))
2108 (t
2109 (setq yas/field-protection-overlays
2110 (list (make-overlay (1- start) start nil t nil)
2111 (make-overlay end (1+ end) nil t nil)))
2112 (dolist (ov yas/field-protection-overlays)
2113 (overlay-put ov 'face 'yas/field-debug-face)
2114 (overlay-put ov 'yas/snippet snippet)
2115 ;; (overlay-put ov 'evaporate t)
2116 (overlay-put ov 'modification-hooks '(yas/on-protection-overlay-modification)))))))
2117
2118 (defvar yas/protection-violation nil
2119 "When non-nil, signals attempts to erronesly exit or modify the snippet.
2120
2121 Functions in the `post-command-hook', for example
2122 `yas/post-command-handler' can check it and reset its value to nil. The variables value is the point where the violation originated")
2123
2124 (defun yas/on-protection-overlay-modification (overlay after? beg end &optional length)
2125 "Signals a snippet violation, then issues error.
2126
2127 The error should be ignored in `debug-ignored-errors'"
2128 (cond ((not (or after?
2129 (yas/undo-in-progress)))
2130 (setq yas/protection-violation (point))
2131 (error "Exit the snippet first!"))))
2132
2133 (add-to-list 'debug-ignored-errors "^Exit the snippet first!$")
2134
2135 ;;; Apropos stacked expansion:
2136 ;;;
2137 ;;; the parent snippet does not run its fields modification hooks
2138 ;;; (`yas/on-field-overlay-modification' and
2139 ;;; `yas/on-protection-overlay-modification') while the child snippet
2140 ;;; is active. This means, among other things, that the mirrors of the
2141 ;;; parent snippet are not updated, this only happening when one exits
2142 ;;; the child snippet.
2143 ;;;
2144 ;;; Unfortunately, this also puts some ugly (and not fully-tested)
2145 ;;; bits of code in `yas/expand-snippet' and
2146 ;;; `yas/commit-snippet'. I've tried to mark them with "stacked
2147 ;;; expansion:".
2148 ;;;
2149 ;;; This was thought to be safer in in an undo/redo perpective, but
2150 ;;; maybe the correct implementation is to make the globals
2151 ;;; `yas/active-field-overlay' and `yas/field-protection-overlays' be
2152 ;;; snippet-local and be active even while the child snippet is
2153 ;;; running. This would mean a lot of overlay modification hooks
2154 ;;; running, but if managed correctly (including overlay priorities)
2155 ;;; they should account for all situations...
2156 ;;;
2157
2158 (defun yas/expand-snippet (start end template &optional snippet-vars)
2159 "Expand snippet at current point. Text between START and END
2160 will be deleted before inserting template."
2161 (run-hooks 'yas/before-expand-snippet-hook)
2162 (goto-char start)
2163
2164 ;; stacked expansion: shoosh the overlay modification hooks
2165 ;;
2166 (let ((key (buffer-substring-no-properties start end))
2167 (inhibit-modification-hooks t)
2168 (column (current-column))
2169 snippet)
2170
2171 ;; Delete the trigger key, this *does* get undo-recorded.
2172 ;;
2173 (delete-region start end)
2174
2175 ;; Narrow the region down to the template, shoosh the
2176 ;; `buffer-undo-list', and create the snippet, the new snippet
2177 ;; updates its mirrors once, so we are left with some plain text.
2178 ;; The undo action for deleting this plain text will get recorded
2179 ;; at the end of this function.
2180 (save-restriction
2181 (narrow-to-region start start)
2182 (let ((buffer-undo-list t))
2183 ;; snippet creation might evaluate users elisp, which
2184 ;; might generate errors, so we have to be ready to catch
2185 ;; them mostly to make the undo information
2186 ;;
2187 (setq yas/start-column (save-restriction (widen) (current-column)))
2188 (insert template)
2189 (setq yas/deleted-text key)
2190 (setq yas/selected-text (when mark-active key))
2191 (setq snippet
2192 (if snippet-vars
2193 (eval `(let ,(read snippet-vars)
2194 (yas/snippet-create (point-min) (point-max))))
2195 (yas/snippet-create (point-min) (point-max))))))
2196
2197 ;; stacked-expansion: This checks for stacked expansion, save the
2198 ;; `yas/previous-active-field' and advance its boudary.
2199 ;;
2200 (let ((existing-field (and yas/active-field-overlay
2201 (overlay-buffer yas/active-field-overlay)
2202 (overlay-get yas/active-field-overlay 'yas/field))))
2203 (when existing-field
2204 (setf (yas/snippet-previous-active-field snippet) existing-field)
2205 (yas/advance-end-maybe existing-field (overlay-end yas/active-field-overlay))))
2206
2207 ;; Exit the snippet immediately if no fields
2208 ;;
2209 (unless (yas/snippet-fields snippet)
2210 (yas/exit-snippet snippet))
2211
2212 ;; Push two undo actions: the deletion of the inserted contents of
2213 ;; the new snippet (whitout the "key") followed by an apply of
2214 ;; `yas/take-care-of-redo' on the newly inserted snippet boundaries
2215 ;;
2216 (let ((start (overlay-start (yas/snippet-control-overlay snippet)))
2217 (end (overlay-end (yas/snippet-control-overlay snippet))))
2218 (push (cons start end) buffer-undo-list)
2219 (push `(apply yas/take-care-of-redo ,start ,end ,snippet)
2220 buffer-undo-list))
2221 ;; Now, move to the first field
2222 ;;
2223 (let ((first-field (car (yas/snippet-fields snippet))))
2224 (when first-field
2225 (yas/move-to-field snippet first-field))))
2226 (message "[yas] snippet expanded."))
2227
2228 (defun yas/take-care-of-redo (beg end snippet)
2229 "Commits SNIPPET, which in turn pushes an undo action for
2230 reviving it.
2231
2232 Meant to exit in the `buffer-undo-list'."
2233 ;; slightly optimize: this action is only needed for snippets with
2234 ;; at least one field
2235 (when (yas/snippet-fields snippet)
2236 (yas/commit-snippet snippet 'no-hooks)))
2237
2238 (defun yas/snippet-revive (beg end snippet)
2239 "Revives the SNIPPET and creates a control overlay from BEG to
2240 END.
2241
2242 BEG and END are, we hope, the original snippets boudaries. All
2243 the markers/points exiting existing inside SNIPPET should point
2244 to their correct locations *at the time the snippet is revived*.
2245
2246 After revival, push the `yas/take-care-of-redo' in the
2247 `buffer-undo-list'"
2248 ;; Reconvert all the points to markers
2249 ;;
2250 (yas/points-to-markers snippet)
2251 ;; When at least one editable field existed in the zombie snippet,
2252 ;; try to revive the whole thing...
2253 ;;
2254 (let ((target-field (or (yas/snippet-active-field snippet)
2255 (car (yas/snippet-fields snippet)))))
2256 (when target-field
2257 (setf (yas/snippet-control-overlay snippet) (yas/make-control-overlay snippet beg end))
2258 (overlay-put (yas/snippet-control-overlay snippet) 'yas/snippet snippet)
2259
2260 (yas/move-to-field snippet target-field)
2261
2262 (add-hook 'post-command-hook 'yas/post-command-handler nil t)
2263 (add-hook 'pre-command-hook 'yas/pre-command-handler t t)
2264
2265 (push `(apply yas/take-care-of-redo ,beg ,end ,snippet)
2266 buffer-undo-list))))
2267
2268 (defun yas/snippet-create (begin end)
2269 "Creates a snippet from an template inserted between BEGIN and END.
2270
2271 Returns the newly created snippet."
2272 (let ((snippet (yas/make-snippet)))
2273 (goto-char begin)
2274 (yas/snippet-parse-create snippet)
2275
2276 ;; Sort and link each field
2277 (yas/snippet-sort-fields snippet)
2278
2279 ;; Update the mirrors for the first time
2280 (yas/update-mirrors snippet)
2281
2282 ;; Create keymap overlay for snippet
2283 (setf (yas/snippet-control-overlay snippet) (yas/make-control-overlay snippet (point-min) (point-max)))
2284
2285 ;; Move to end
2286 (goto-char (point-max))
2287
2288 ;; Setup hooks
2289 (add-hook 'post-command-hook 'yas/post-command-handler nil t)
2290 (add-hook 'pre-command-hook 'yas/pre-command-handler t t)
2291
2292 snippet))
2293
2294 ;;; apropos adjacencies: Once the $-constructs bits like "$n" and
2295 ;;; "${:n" are deleted in the recently expanded snippet, we might
2296 ;;; actually have many fields, mirrors (and the snippet exit) in the
2297 ;;; very same position in the buffer. Therefore we need to single-link
2298 ;;; the fields-or-mirrors-or-exit, which I have called "fom",
2299 ;;; according to their original positions in the buffer.
2300 ;;;
2301 ;;; Then we have operation `yas/advance-end-maybe' and
2302 ;;; `yas/advance-start-maybe', which conditionally push the starts and
2303 ;;; ends of these foms down the chain.
2304 ;;;
2305 ;;; This allows for like the printf with the magic ",":
2306 ;;;
2307 ;;; printf ("${1:%s}\\n"${1:$(if (string-match "%" text) "," "\);")} \
2308 ;;; $2${1:$(if (string-match "%" text) "\);" "")}$0
2309 ;;;
2310
2311 (defun yas/fom-start (fom)
2312 (cond ((yas/field-p fom)
2313 (yas/field-start fom))
2314 ((yas/mirror-p fom)
2315 (yas/mirror-start fom))
2316 (t
2317 (yas/exit-marker fom))))
2318
2319 (defun yas/fom-end (fom)
2320 (cond ((yas/field-p fom)
2321 (yas/field-end fom))
2322 ((yas/mirror-p fom)
2323 (yas/mirror-end fom))
2324 (t
2325 (yas/exit-marker fom))))
2326
2327 (defun yas/fom-next (fom)
2328 (cond ((yas/field-p fom)
2329 (yas/field-next fom))
2330 ((yas/mirror-p fom)
2331 (yas/mirror-next fom))
2332 (t
2333 (yas/exit-next fom))))
2334
2335 (defun yas/calculate-adjacencies (snippet)
2336 "Calculate adjacencies for fields or mirrors of SNIPPET.
2337
2338 This is according to their relative positions in the buffer, and
2339 has to be called before the $-constructs are deleted."
2340 (flet ((yas/fom-set-next-fom (fom nextfom)
2341 (cond ((yas/field-p fom)
2342 (setf (yas/field-next fom) nextfom))
2343 ((yas/mirror-p fom)
2344 (setf (yas/mirror-next fom) nextfom))
2345 (t
2346 (setf (yas/exit-next fom) nextfom))))
2347 (yas/compare-fom-begs (fom1 fom2)
2348 (> (yas/fom-start fom2) (yas/fom-start fom1)))
2349 (yas/link-foms (fom1 fom2)
2350 (yas/fom-set-next-fom fom1 fom2)))
2351 ;; make some yas/field, yas/mirror and yas/exit soup
2352 (let ((soup))
2353 (when (yas/snippet-exit snippet)
2354 (push (yas/snippet-exit snippet) soup))
2355 (dolist (field (yas/snippet-fields snippet))
2356 (push field soup)
2357 (dolist (mirror (yas/field-mirrors field))
2358 (push mirror soup)))
2359 (setq soup
2360 (sort soup
2361 #'yas/compare-fom-begs))
2362 (when soup
2363 (reduce #'yas/link-foms soup)))))
2364
2365 (defun yas/advance-end-maybe (fom newend)
2366 "Maybe advance FOM's end to NEWEND if it needs it.
2367
2368 If it does, also:
2369
2370 * call `yas/advance-start-maybe' on FOM's next fom.
2371
2372 * in case FOM is field call `yas/advance-end-maybe' on its parent
2373 field"
2374 (when (and fom (< (yas/fom-end fom) newend))
2375 (set-marker (yas/fom-end fom) newend)
2376 (yas/advance-start-maybe (yas/fom-next fom) newend)
2377 (if (and (yas/field-p fom)
2378 (yas/field-parent-field fom))
2379 (yas/advance-end-maybe (yas/field-parent-field fom) newend))))
2380
2381 (defun yas/advance-start-maybe (fom newstart)
2382 "Maybe advance FOM's start to NEWSTART if it needs it.
2383
2384 If it does, also call `yas/advance-end-maybe' on FOM."
2385 (when (and fom (< (yas/fom-start fom) newstart))
2386 (set-marker (yas/fom-start fom) newstart)
2387 (yas/advance-end-maybe fom newstart)))
2388
2389 (defun yas/snippet-parse-create (snippet)
2390 "Parse a recently inserted snippet template, creating all
2391 necessary fields, mirrors and exit points.
2392
2393 Meant to be called in a narrowed buffer, does various passes"
2394 (let ((parse-start (point))
2395 (dollar-regions (list 'reg)))
2396 ;; protect quote and backquote escapes
2397 ;;
2398 (yas/protect-escapes nil '(?` ?'))
2399 ;; replace all backquoted expressions
2400 ;;
2401 (goto-char parse-start)
2402 (yas/replace-backquotes)
2403 ;; protect escapes again since previous stepds might have
2404 ;; generated more characters needing escapinge
2405 ;;
2406 (goto-char parse-start)
2407 (yas/protect-escapes)
2408 ;; parse fields with {}
2409 ;;
2410 (goto-char parse-start)
2411 (yas/field-parse-create snippet dollar-regions)
2412 ;; parse simple mirrors and fields
2413 ;;
2414 (goto-char parse-start)
2415 (yas/simple-mirror-parse-create snippet dollar-regions)
2416 ;; parse mirror transforms
2417 ;;
2418 (goto-char parse-start)
2419 (yas/transform-mirror-parse-create snippet dollar-regions)
2420 ;; calculate adjacencies of fields and mirrors
2421 ;;
2422 (yas/calculate-adjacencies snippet)
2423 ;; Delete $-constructs
2424 ;;
2425 (yas/delete-regions (copy-list (rest dollar-regions)))
2426 ;; restore escapes
2427 ;;
2428 (goto-char parse-start)
2429 (yas/restore-escapes)
2430 ;; update mirrors for the first time
2431 ;;
2432 (yas/update-mirrors snippet)
2433 ;; indent the best we can
2434 ;;
2435 (goto-char parse-start)
2436 (yas/indent snippet)))
2437
2438 (defun yas/indent (snippet)
2439 (save-excursion
2440 (while (re-search-forward "$>" nil t)
2441 (delete-region (match-beginning 0) (match-end 0))
2442 (when (not (eq yas/indent-line 'auto))
2443 (indent-according-to-mode))))
2444 (save-excursion
2445 (cond ((eq yas/indent-line 'fixed)
2446 (let* ((indent (if indent-tabs-mode
2447 (concat (make-string (/ column tab-width) ?\t)
2448 (make-string (% column tab-width) ?\ ))
2449 (make-string (current-column) ?\ ))))
2450 (goto-char (point-min))
2451 (while (and (zerop (forward-line))
2452 (= (current-column) 0))
2453 (insert indent))))
2454 ((eq yas/indent-line 'auto)
2455 (let ((end (set-marker (make-marker) (point-max)))
2456 (indent-first-line-p yas/also-auto-indent-first-line)
2457 (snippet-markers (yas/collect-snippet-markers snippet)))
2458 (save-restriction
2459 (widen)
2460 ;; XXX: Here seems to be the indent problem:
2461 ;;
2462 ;; `indent-according-to-mode' uses whatever
2463 ;; `indent-line-function' is available. Some
2464 ;; implementations of these functions delete text
2465 ;; before they insert. If there happens to be a marker
2466 ;; just after the text being deleted, the insertion
2467 ;; actually happens after the marker, which misplaces
2468 ;; it.
2469 ;;
2470 ;; This would also happen if we had used overlays with
2471 ;; the `front-advance' property set to nil.
2472 ;;
2473 (while (and (zerop (if indent-first-line-p
2474 (prog1
2475 (forward-line 0)
2476 (setq indent-first-line-p nil))
2477 (forward-line 1)))
2478 (not (eobp))
2479 (<= (point) end))
2480 (goto-char (yas/real-line-beginning))
2481 (let ((trouble-markers (remove-if-not #'(lambda (marker)
2482 (= marker (point)))
2483 snippet-markers)))
2484 (indent-according-to-mode)
2485 (mapc #'(lambda (marker)
2486 (set-marker marker (point)))
2487 trouble-markers)
2488 (indent-according-to-mode)))
2489 (set-marker end nil))))
2490 (t
2491 nil))))
2492
2493 (defun yas/collect-snippet-markers (snippet)
2494 "Make a list of all the markers used by SNIPPET."
2495 (let (markers)
2496 (dolist (field (yas/snippet-fields snippet))
2497 (push (yas/field-start field) markers)
2498 (push (yas/field-end field) markers)
2499 (dolist (mirror (yas/field-mirrors field))
2500 (push (yas/mirror-start mirror) markers)
2501 (push (yas/mirror-end mirror) markers)))
2502 (let ((snippet-exit (yas/snippet-exit snippet)))
2503 (when (and snippet-exit
2504 (marker-buffer (yas/exit-marker snippet-exit)))
2505 (push (yas/exit-marker snippet-exit) markers)))
2506 markers))
2507
2508 (defun yas/real-line-beginning ()
2509 (let ((c (char-after (line-beginning-position)))
2510 (n (line-beginning-position)))
2511 (while (or (eql c ?\ )
2512 (eql c ?\t))
2513 (incf n)
2514 (setq c (char-after n)))
2515 n))
2516
2517 (defun yas/escape-string (escaped)
2518 (concat "YASESCAPE" (format "%d" escaped) "PROTECTGUARD"))
2519
2520 (defun yas/protect-escapes (&optional text escaped)
2521 "Protect all escaped characters with their numeric ASCII value.
2522
2523 With optional string TEXT do it in string instead of buffer."
2524 (let ((changed-text text)
2525 (text-provided-p text))
2526 (mapc #'(lambda (escaped)
2527 (setq changed-text
2528 (yas/replace-all (concat "\\" (char-to-string escaped))
2529 (yas/escape-string escaped)
2530 (when text-provided-p changed-text))))
2531 (or escaped yas/escaped-characters))
2532 changed-text))
2533
2534 (defun yas/restore-escapes (&optional text escaped)
2535 "Restore all escaped characters from their numeric ASCII value.
2536
2537 With optional string TEXT do it in string instead of the buffer."
2538 (let ((changed-text text)
2539 (text-provided-p text))
2540 (mapc #'(lambda (escaped)
2541 (setq changed-text
2542 (yas/replace-all (yas/escape-string escaped)
2543 (char-to-string escaped)
2544 (when text-provided-p changed-text))))
2545 (or escaped yas/escaped-characters))
2546 changed-text))
2547
2548 (defun yas/replace-backquotes ()
2549 "Replace all the \"`(lisp-expression)`\"-style expression
2550 with their evaluated value"
2551 (while (re-search-forward yas/backquote-lisp-expression-regexp nil t)
2552 (let ((transformed (yas/eval-string (yas/restore-escapes (match-string 1)))))
2553 (goto-char (match-end 0))
2554 (when transformed (insert transformed))
2555 (delete-region (match-beginning 0) (match-end 0)))))
2556
2557 (defun yas/scan-sexps (from count)
2558 (condition-case err
2559 (with-syntax-table (standard-syntax-table)
2560 (scan-sexps from count))
2561 (error
2562 nil)))
2563
2564 (defun yas/make-marker (pos)
2565 "Create a marker at POS with `nil' `marker-insertion-type'"
2566 (let ((marker (set-marker (make-marker) pos)))
2567 (set-marker-insertion-type marker nil)
2568 marker))
2569
2570 (defun yas/add-to-list (l e)
2571 (setf (cdr l)
2572 (cons e (cdr l))))
2573
2574 (defun yas/field-parse-create (snippet dollar-regions &optional parent-field)
2575 "Parse most field expression, except for the simple one \"$n\".
2576
2577 The following count as a field:
2578
2579 * \"${n: text}\", for a numbered field with default text, as long as N is not 0;
2580 * \"${n: text$(expression)}, the same with a lisp expression;
2581 * the same as above but unnumbered, (no N:) and number is calculated automatically.
2582
2583 When multiple expressions are found, only the last one counts."
2584 (save-excursion
2585 (while (re-search-forward yas/field-regexp nil t)
2586 (let* ((real-match-end-0 (yas/scan-sexps (1+ (match-beginning 0)) 1))
2587 (number (and (match-string-no-properties 1)
2588 (string-to-number (match-string-no-properties 1))))
2589 (brand-new-field (and real-match-end-0
2590 (not (save-match-data
2591 (eq (string-match "$[ \t\n]*(" (match-string-no-properties 2)) 0)))
2592 (not (and number (zerop number)))
2593 (yas/make-field number
2594 (yas/make-marker (match-beginning 2))
2595 (yas/make-marker (1- real-match-end-0))
2596 parent-field))))
2597 (when brand-new-field
2598 (yas/add-to-list dollar-regions
2599 (cons (1- real-match-end-0) real-match-end-0))
2600 (yas/add-to-list dollar-regions
2601 (cons (match-beginning 0) (match-beginning 2)))
2602 (push brand-new-field (yas/snippet-fields snippet))
2603 (save-excursion
2604 (save-restriction
2605 (narrow-to-region (yas/field-start brand-new-field) (yas/field-end brand-new-field))
2606 (goto-char (point-min))
2607 (yas/field-parse-create snippet dollar-regions brand-new-field)))))))
2608 (when parent-field
2609 (save-excursion
2610 (while (re-search-forward yas/multi-dollar-lisp-expression-regexp nil t)
2611 (let* ((real-match-end-1 (yas/scan-sexps (match-beginning 1) 1)))
2612 (when real-match-end-1
2613 (let ((lisp-expression-string (buffer-substring-no-properties (match-beginning 1) real-match-end-1)))
2614 (setf (yas/field-transform parent-field) (yas/restore-escapes lisp-expression-string)))
2615 (yas/add-to-list dollar-regions
2616 (cons (match-beginning 0) real-match-end-1))))))))
2617
2618 (defun yas/transform-mirror-parse-create (snippet dollar-regions)
2619 "Parse the \"${n:$(lisp-expression)}\" mirror transformations."
2620 (while (re-search-forward yas/transform-mirror-regexp nil t)
2621 (let* ((real-match-end-0 (yas/scan-sexps (1+ (match-beginning 0)) 1))
2622 (number (string-to-number (match-string-no-properties 1)))
2623 (field (and number
2624 (not (zerop number))
2625 (yas/snippet-find-field snippet number))))
2626 (when (and real-match-end-0
2627 field)
2628 (push (yas/make-mirror (yas/make-marker (match-beginning 0))
2629 (yas/make-marker (match-beginning 0))
2630 (yas/restore-escapes (buffer-substring-no-properties (match-beginning 2)
2631 (1- real-match-end-0))))
2632 (yas/field-mirrors field))
2633 (yas/add-to-list dollar-regions
2634 (cons (match-beginning 0) real-match-end-0))))))
2635
2636 (defun yas/simple-mirror-parse-create (snippet dollar-regions)
2637 "Parse the simple \"$n\" mirrors and the exit-marker."
2638 (while (re-search-forward yas/simple-mirror-regexp nil t)
2639 (let ((number (string-to-number (match-string-no-properties 1))))
2640 (cond ((zerop number)
2641
2642 (setf (yas/snippet-exit snippet)
2643 (yas/make-exit (yas/make-marker (match-end 0))))
2644 (save-excursion
2645 (goto-char (match-beginning 0))
2646 (when (and yas/wrap-around-region yas/selected-text)
2647 (insert yas/selected-text))
2648 (yas/add-to-list dollar-regions
2649 (cons (point) (yas/exit-marker (yas/snippet-exit snippet))))))
2650 (t
2651 (let ((field (yas/snippet-find-field snippet number)))
2652 (if field
2653 (push (yas/make-mirror (yas/make-marker (match-beginning 0))
2654 (yas/make-marker (match-beginning 0))
2655 nil)
2656 (yas/field-mirrors field))
2657 (push (yas/make-field number
2658 (yas/make-marker (match-beginning 0))
2659 (yas/make-marker (match-beginning 0))
2660 nil)
2661 (yas/snippet-fields snippet))))
2662 (yas/add-to-list dollar-regions
2663 (cons (match-beginning 0) (match-end 0))))))))
2664
2665 (defun yas/delete-regions (regions)
2666 "Sort disjuct REGIONS by start point, then delete from the back."
2667 (mapc #'(lambda (reg)
2668 (delete-region (car reg) (cdr reg)))
2669 (sort regions
2670 #'(lambda (r1 r2)
2671 (>= (car r1) (car r2))))))
2672
2673 (defun yas/update-mirrors (snippet)
2674 "Updates all the mirrors of SNIPPET."
2675 (save-excursion
2676 (dolist (field (yas/snippet-fields snippet))
2677 (dolist (mirror (yas/field-mirrors field))
2678 ;; stacked expansion: I added an `inhibit-modification-hooks'
2679 ;; here, for safety, may need to remove if we the mechanism is
2680 ;; altered.
2681 ;;
2682 (let ((inhibit-modification-hooks t))
2683 (yas/mirror-update-display mirror field)
2684 ;; `yas/place-overlays' is needed if the active field and
2685 ;; protected overlays have been changed because of insertions
2686 ;; in `yas/mirror-update-display'
2687 ;;
2688 (when (eq field (yas/snippet-active-field snippet))
2689 (yas/place-overlays snippet field)))))))
2690
2691 (defun yas/mirror-update-display (mirror field)
2692 "Update MIRROR according to FIELD (and mirror transform)."
2693 (let ((reflection (or (yas/apply-transform mirror field)
2694 (yas/field-text-for-display field))))
2695 (when (and reflection
2696 (not (string= reflection (buffer-substring-no-properties (yas/mirror-start mirror) (yas/mirror-end mirror)))))
2697 (goto-char (yas/mirror-start mirror))
2698 (insert reflection)
2699 (if (> (yas/mirror-end mirror) (point))
2700 (delete-region (point) (yas/mirror-end mirror))
2701 (set-marker (yas/mirror-end mirror) (point))
2702 (yas/advance-start-maybe (yas/mirror-next mirror) (point))))))
2703
2704 (defun yas/field-update-display (field snippet)
2705 "Much like `yas/mirror-update-display', but for fields"
2706 (when (yas/field-transform field)
2707 (let ((inhibit-modification-hooks t)
2708 (transformed (yas/apply-transform field field))
2709 (point (point)))
2710 (when (and transformed
2711 (not (string= transformed (buffer-substring-no-properties (yas/field-start field) (yas/field-end field)))))
2712 (setf (yas/field-modified-p field) t)
2713 (goto-char (yas/field-start field))
2714 (insert transformed)
2715 (if (> (yas/field-end field) (point))
2716 (delete-region (point) (yas/field-end field))
2717 (set-marker (yas/field-end field) (point))
2718 (yas/advance-start-maybe (yas/field-next field) (point)))
2719 t))))
2720
2721 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2722 ;; Pre- and post-command hooks
2723 ;;
2724 (defun yas/pre-command-handler () )
2725
2726 (defun yas/post-command-handler ()
2727 "Handles various yasnippet conditions after each command."
2728 (cond (yas/protection-violation
2729 (goto-char yas/protection-violation)
2730 (setq yas/protection-violation nil))
2731 ((eq 'undo this-command)
2732 ;;
2733 ;; After undo revival the correct field is sometimes not
2734 ;; restored correctly, this condition handles that
2735 ;;
2736 (let* ((snippet (car (yas/snippets-at-point)))
2737 (target-field (and snippet
2738 (find-if-not #'(lambda (field)
2739 (yas/field-probably-deleted-p snippet field))
2740 (remove nil
2741 (cons (yas/snippet-active-field snippet)
2742 (yas/snippet-fields snippet)))))))
2743 (when target-field
2744 (yas/move-to-field snippet target-field))))
2745 ((not (yas/undo-in-progress))
2746 ;; When not in an undo, check if we must commit the snippet (use exited it).
2747 (yas/check-commit-snippet))))
2748
2749 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2750 ;; Debug functions. Use (or change) at will whenever needed.
2751 ;;
2752
2753 (defun yas/debug-some-vars ()
2754 "Debug snippets, fields, mirrors and the `buffer-undo-list'."
2755 (interactive)
2756 (with-output-to-temp-buffer "*YASnippet trace*"
2757 (princ "Interesting YASnippet vars: \n\n")
2758
2759 (princ (format "\nPost command hook: %s\n" post-command-hook))
2760 (princ (format "\nPre command hook: %s\n" pre-command-hook))
2761
2762 (princ (format "%s live snippets in total\n" (length (yas/snippets-at-point (quote all-snippets)))))
2763 (princ (format "%s overlays in buffer:\n\n" (length (overlays-in (point-min) (point-max)))))
2764 (princ (format "%s live snippets at point:\n\n" (length (yas/snippets-at-point))))
2765
2766
2767 (dolist (snippet (yas/snippets-at-point))
2768 (princ (format "\tsid: %d control overlay from %d to %d\n"
2769 (yas/snippet-id snippet)
2770 (overlay-start (yas/snippet-control-overlay snippet))
2771 (overlay-end (yas/snippet-control-overlay snippet))))
2772 (princ (format "\tactive field: %d from %s to %s covering \"%s\"\n"
2773 (yas/field-number (yas/snippet-active-field snippet))
2774 (marker-position (yas/field-start (yas/snippet-active-field snippet)))
2775 (marker-position (yas/field-end (yas/snippet-active-field snippet)))
2776 (buffer-substring-no-properties (yas/field-start (yas/snippet-active-field snippet)) (yas/field-end (yas/snippet-active-field snippet)))))
2777 (when (yas/snippet-exit snippet)
2778 (princ (format "\tsnippet-exit: at %s next: %s\n"
2779 (yas/exit-marker (yas/snippet-exit snippet))
2780 (yas/exit-next (yas/snippet-exit snippet)))))
2781 (dolist (field (yas/snippet-fields snippet))
2782 (princ (format "\tfield: %d from %s to %s covering \"%s\" next: %s\n"
2783 (yas/field-number field)
2784 (marker-position (yas/field-start field))
2785 (marker-position (yas/field-end field))
2786 (buffer-substring-no-properties (yas/field-start field) (yas/field-end field))
2787 (yas/debug-format-fom-concise (yas/field-next field))))
2788 (dolist (mirror (yas/field-mirrors field))
2789 (princ (format "\t\tmirror: from %s to %s covering \"%s\" next: %s\n"
2790 (marker-position (yas/mirror-start mirror))
2791 (marker-position (yas/mirror-end mirror))
2792 (buffer-substring-no-properties (yas/mirror-start mirror) (yas/mirror-end mirror))
2793 (yas/debug-format-fom-concise (yas/mirror-next mirror)))))))
2794
2795 (princ (format "\nUndo is %s and point-max is %s.\n"
2796 (if (eq buffer-undo-list t)
2797 "DISABLED"
2798 "ENABLED")
2799 (point-max)))
2800 (unless (eq buffer-undo-list t)
2801 (princ (format "Undpolist has %s elements. First 10 elements follow:\n" (length buffer-undo-list)))
2802 (let ((first-ten (subseq buffer-undo-list 0 19)))
2803 (dolist (undo-elem first-ten)
2804 (princ (format "%2s: %s\n" (position undo-elem first-ten) (truncate-string-to-width (format "%s" undo-elem) 70))))))))
2805
2806 (defun yas/debug-format-fom-concise (fom)
2807 (when fom
2808 (cond ((yas/field-p fom)
2809 (format "field %d from %d to %d"
2810 (yas/field-number fom)
2811 (marker-position (yas/field-start fom))
2812 (marker-position (yas/field-end fom))))
2813 ((yas/mirror-p fom)
2814 (format "mirror from %d to %d"
2815 (marker-position (yas/mirror-start fom))
2816 (marker-position (yas/mirror-end fom))))
2817 (t
2818 (format "snippet exit at %d"
2819 (marker-position (yas/fom-start fom)))))))
2820
2821
2822 (defun yas/exterminate-package ()
2823 (interactive)
2824 (yas/global-mode -1)
2825 (yas/minor-mode -1)
2826 (mapatoms #'(lambda (atom)
2827 (when (string-match "yas/" (symbol-name atom))
2828 (unintern atom)))))
2829
2830 (defun yas/debug-test (&optional quiet)
2831 (interactive "P")
2832 (yas/load-directory (or (and (listp yas/root-directory)
2833 (first yas/root-directory))
2834 yas/root-directory
2835 "~/Source/yasnippet/snippets/"))
2836 (set-buffer (switch-to-buffer "*YAS TEST*"))
2837 (mapc #'yas/commit-snippet (yas/snippets-at-point 'all-snippets))
2838 (erase-buffer)
2839 (setq buffer-undo-list nil)
2840 (setq undo-in-progress nil)
2841 (snippet-mode)
2842 (yas/minor-mode 1)
2843 (let ((abbrev))
2844 (setq abbrev "$f")
2845 (insert abbrev))
2846 (unless quiet
2847 (add-hook 'post-command-hook 'yas/debug-some-vars 't 'local)))
2848
2849 (provide 'yasnippet)
2850
2851 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2852 ;; Monkey patching for other functions that's causing
2853 ;; problems to yasnippet. For details on why I patch
2854 ;; those functions, refer to
2855 ;; http://code.google.com/p/yasnippet/wiki/MonkeyPatching
2856 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2857 (defadvice c-neutralize-syntax-in-CPP
2858 (around yas-mp/c-neutralize-syntax-in-CPP activate)
2859 "Adviced `c-neutralize-syntax-in-CPP' to properly
2860 handle the end-of-buffer error fired in it by calling
2861 `forward-char' at the end of buffer."
2862 (condition-case err
2863 ad-do-it
2864 (error (message (error-message-string err)))))
2865
2866 ;; disable c-electric-* serial command in YAS fields
2867 (add-hook 'c-mode-common-hook
2868 '(lambda ()
2869 (make-variable-buffer-local 'yas/keymap)
2870 (dolist (k '(":" ">" ";" "<" "{" "}"))
2871 (define-key yas/keymap
2872 k 'self-insert-command))))
2873
2874
2875 ;;; yasnippet.el ends here