Emacs config utilizing prelude as a base
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4297 lines
171 KiB

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