Personal emacs config
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.

5291 lines
214 KiB

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