PageRenderTime 85ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/vendor/yasnippet/yasnippet.el

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