abbrev.el 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028
  1. ;;; abbrev.el --- abbrev mode commands for Emacs -*- lexical-binding: t -*-
  2. ;; Copyright (C) 1985-1987, 1992, 2001-2015 Free Software Foundation,
  3. ;; Inc.
  4. ;; Maintainer: emacs-devel@gnu.org
  5. ;; Keywords: abbrev convenience
  6. ;; Package: emacs
  7. ;; This file is part of GNU Emacs.
  8. ;; GNU Emacs is free software: you can redistribute it and/or modify
  9. ;; it under the terms of the GNU General Public License as published by
  10. ;; the Free Software Foundation, either version 3 of the License, or
  11. ;; (at your option) any later version.
  12. ;; GNU Emacs is distributed in the hope that it will be useful,
  13. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. ;; GNU General Public License for more details.
  16. ;; You should have received a copy of the GNU General Public License
  17. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  18. ;;; Commentary:
  19. ;; This facility is documented in the Emacs Manual.
  20. ;; Todo:
  21. ;; - Cleanup name space.
  22. ;;; Code:
  23. (eval-when-compile (require 'cl-lib))
  24. (defgroup abbrev-mode nil
  25. "Word abbreviations mode."
  26. :link '(custom-manual "(emacs)Abbrevs")
  27. :group 'abbrev)
  28. (defcustom abbrev-file-name
  29. (locate-user-emacs-file "abbrev_defs" ".abbrev_defs")
  30. "Default name of file from which to read abbrevs."
  31. :initialize 'custom-initialize-delay
  32. :type 'file)
  33. (defcustom only-global-abbrevs nil
  34. "Non-nil means user plans to use global abbrevs only.
  35. This makes the commands that normally define mode-specific abbrevs
  36. define global abbrevs instead."
  37. :type 'boolean
  38. :group 'abbrev-mode
  39. :group 'convenience)
  40. (define-minor-mode abbrev-mode
  41. "Toggle Abbrev mode in the current buffer.
  42. With a prefix argument ARG, enable Abbrev mode if ARG is
  43. positive, and disable it otherwise. If called from Lisp, enable
  44. Abbrev mode if ARG is omitted or nil.
  45. In Abbrev mode, inserting an abbreviation causes it to expand and
  46. be replaced by its expansion."
  47. ;; It's defined in C, this stops the d-m-m macro defining it again.
  48. :variable abbrev-mode)
  49. (put 'abbrev-mode 'safe-local-variable 'booleanp)
  50. (defvar edit-abbrevs-mode-map
  51. (let ((map (make-sparse-keymap)))
  52. (define-key map "\C-x\C-s" 'abbrev-edit-save-buffer)
  53. (define-key map "\C-x\C-w" 'abbrev-edit-save-to-file)
  54. (define-key map "\C-c\C-c" 'edit-abbrevs-redefine)
  55. map)
  56. "Keymap used in `edit-abbrevs'.")
  57. (define-obsolete-variable-alias 'edit-abbrevs-map
  58. 'edit-abbrevs-mode-map "24.4")
  59. (defun kill-all-abbrevs ()
  60. "Undefine all defined abbrevs."
  61. (interactive)
  62. (dolist (tablesym abbrev-table-name-list)
  63. (clear-abbrev-table (symbol-value tablesym))))
  64. (defun copy-abbrev-table (table)
  65. "Make a new abbrev-table with the same abbrevs as TABLE.
  66. Does not copy property lists."
  67. (let ((new-table (make-abbrev-table)))
  68. (mapatoms
  69. (lambda (symbol)
  70. (define-abbrev new-table
  71. (symbol-name symbol)
  72. (symbol-value symbol)
  73. (symbol-function symbol)))
  74. table)
  75. new-table))
  76. (defun insert-abbrevs ()
  77. "Insert after point a description of all defined abbrevs.
  78. Mark is set after the inserted text."
  79. (interactive)
  80. (push-mark
  81. (save-excursion
  82. (dolist (tablesym abbrev-table-name-list)
  83. (insert-abbrev-table-description tablesym t))
  84. (point))))
  85. (defun list-abbrevs (&optional local)
  86. "Display a list of defined abbrevs.
  87. If LOCAL is non-nil, interactively when invoked with a
  88. prefix arg, display only local, i.e. mode-specific, abbrevs.
  89. Otherwise display all abbrevs."
  90. (interactive "P")
  91. (display-buffer (prepare-abbrev-list-buffer local)))
  92. (defun abbrev-table-name (table)
  93. "Value is the name of abbrev table TABLE."
  94. (let ((tables abbrev-table-name-list)
  95. found)
  96. (while (and (not found) tables)
  97. (when (eq (symbol-value (car tables)) table)
  98. (setq found (car tables)))
  99. (setq tables (cdr tables)))
  100. found))
  101. (defun prepare-abbrev-list-buffer (&optional local)
  102. (let ((local-table local-abbrev-table))
  103. (with-current-buffer (get-buffer-create "*Abbrevs*")
  104. (erase-buffer)
  105. (if local
  106. (insert-abbrev-table-description
  107. (abbrev-table-name local-table) t)
  108. (let (empty-tables)
  109. (dolist (table abbrev-table-name-list)
  110. (if (abbrev-table-empty-p (symbol-value table))
  111. (push table empty-tables)
  112. (insert-abbrev-table-description table t)))
  113. (dolist (table (nreverse empty-tables))
  114. (insert-abbrev-table-description table t)))
  115. ;; Note: `list-abbrevs' can display only local abbrevs, in
  116. ;; which case editing could lose abbrevs of other tables. Thus
  117. ;; enter `edit-abbrevs-mode' only if LOCAL is nil.
  118. (edit-abbrevs-mode))
  119. (goto-char (point-min))
  120. (set-buffer-modified-p nil)
  121. (current-buffer))))
  122. (defun edit-abbrevs ()
  123. "Alter abbrev definitions by editing a list of them.
  124. Selects a buffer containing a list of abbrev definitions with
  125. point located in the abbrev table of current buffer.
  126. You can edit them and type \\<edit-abbrevs-map>\\[edit-abbrevs-redefine] to redefine abbrevs
  127. according to your editing.
  128. Buffer contains a header line for each abbrev table,
  129. which is the abbrev table name in parentheses.
  130. This is followed by one line per abbrev in that table:
  131. NAME USECOUNT EXPANSION HOOK
  132. where NAME and EXPANSION are strings with quotes,
  133. USECOUNT is an integer, and HOOK is any valid function
  134. or may be omitted (it is usually omitted)."
  135. (interactive)
  136. (let ((table-name (abbrev-table-name local-abbrev-table)))
  137. (switch-to-buffer (prepare-abbrev-list-buffer))
  138. (when (and table-name
  139. (search-forward
  140. (concat "(" (symbol-name table-name) ")\n\n") nil t))
  141. (goto-char (match-end 0)))))
  142. (defun edit-abbrevs-redefine ()
  143. "Redefine abbrevs according to current buffer contents."
  144. (interactive)
  145. (save-restriction
  146. (widen)
  147. (define-abbrevs t)
  148. (set-buffer-modified-p nil)))
  149. (defun define-abbrevs (&optional arg)
  150. "Define abbrevs according to current visible buffer contents.
  151. See documentation of `edit-abbrevs' for info on the format of the
  152. text you must have in the buffer.
  153. With argument, eliminate all abbrev definitions except
  154. the ones defined from the buffer now."
  155. (interactive "P")
  156. (if arg (kill-all-abbrevs))
  157. (save-excursion
  158. (goto-char (point-min))
  159. (while (and (not (eobp)) (re-search-forward "^(" nil t))
  160. (let* ((buf (current-buffer))
  161. (table (read buf))
  162. abbrevs name hook exp count sys)
  163. (forward-line 1)
  164. (while (progn (forward-line 1)
  165. (not (eolp)))
  166. (setq name (read buf) count (read buf))
  167. (if (equal count '(sys))
  168. (setq sys t count (read buf))
  169. (setq sys nil))
  170. (setq exp (read buf))
  171. (skip-chars-backward " \t\n\f")
  172. (setq hook (if (not (eolp)) (read buf)))
  173. (skip-chars-backward " \t\n\f")
  174. (setq abbrevs (cons (list name exp hook count sys) abbrevs)))
  175. (define-abbrev-table table abbrevs)))))
  176. (defun read-abbrev-file (&optional file quietly)
  177. "Read abbrev definitions from file written with `write-abbrev-file'.
  178. Optional argument FILE is the name of the file to read;
  179. it defaults to the value of `abbrev-file-name'.
  180. Optional second argument QUIETLY non-nil means don't display a message."
  181. (interactive
  182. (list
  183. (read-file-name (format "Read abbrev file (default %s): "
  184. abbrev-file-name)
  185. nil abbrev-file-name t)))
  186. (load (or file abbrev-file-name) nil quietly)
  187. (setq abbrevs-changed nil))
  188. (defun quietly-read-abbrev-file (&optional file)
  189. "Read abbrev definitions from file written with `write-abbrev-file'.
  190. Optional argument FILE is the name of the file to read;
  191. it defaults to the value of `abbrev-file-name'.
  192. Does not display any message."
  193. ;(interactive "fRead abbrev file: ")
  194. (read-abbrev-file file t))
  195. (defun write-abbrev-file (&optional file verbose)
  196. "Write all user-level abbrev definitions to a file of Lisp code.
  197. This does not include system abbrevs; it includes only the abbrev tables
  198. listed in listed in `abbrev-table-name-list'.
  199. The file written can be loaded in another session to define the same abbrevs.
  200. The argument FILE is the file name to write. If omitted or nil, the file
  201. specified in `abbrev-file-name' is used.
  202. If VERBOSE is non-nil, display a message indicating where abbrevs
  203. have been saved."
  204. (interactive
  205. (list
  206. (read-file-name "Write abbrev file: "
  207. (file-name-directory (expand-file-name abbrev-file-name))
  208. abbrev-file-name)))
  209. (or (and file (> (length file) 0))
  210. (setq file abbrev-file-name))
  211. (let ((coding-system-for-write 'utf-8))
  212. (with-temp-buffer
  213. (dolist (table
  214. ;; We sort the table in order to ease the automatic
  215. ;; merging of different versions of the user's abbrevs
  216. ;; file. This is useful, for example, for when the
  217. ;; user keeps their home directory in a revision
  218. ;; control system, and is therefore keeping multiple
  219. ;; slightly-differing copies loosely synchronized.
  220. (sort (copy-sequence abbrev-table-name-list)
  221. (lambda (s1 s2)
  222. (string< (symbol-name s1)
  223. (symbol-name s2)))))
  224. (insert-abbrev-table-description table nil))
  225. (when (unencodable-char-position (point-min) (point-max) 'utf-8)
  226. (setq coding-system-for-write
  227. (if (> emacs-major-version 24)
  228. 'utf-8-emacs
  229. ;; For compatibility with Emacs 22 (See Bug#8308)
  230. 'emacs-mule)))
  231. (goto-char (point-min))
  232. (insert (format ";;-*-coding: %s;-*-\n" coding-system-for-write))
  233. (write-region nil nil file nil (and (not verbose) 0)))))
  234. (defun abbrev-edit-save-to-file (file)
  235. "Save all user-level abbrev definitions in current buffer to FILE."
  236. (interactive
  237. (list (read-file-name "Save abbrevs to file: "
  238. (file-name-directory
  239. (expand-file-name abbrev-file-name))
  240. abbrev-file-name)))
  241. (edit-abbrevs-redefine)
  242. (write-abbrev-file file t))
  243. (defun abbrev-edit-save-buffer ()
  244. "Save all user-level abbrev definitions in current buffer.
  245. The saved abbrevs are written to the file specified by
  246. `abbrev-file-name'."
  247. (interactive)
  248. (abbrev-edit-save-to-file abbrev-file-name))
  249. (defun add-mode-abbrev (arg)
  250. "Define mode-specific abbrev for last word(s) before point.
  251. Argument is how many words before point form the expansion;
  252. or zero means the region is the expansion.
  253. A negative argument means to undefine the specified abbrev.
  254. Reads the abbreviation in the minibuffer.
  255. Don't use this function in a Lisp program; use `define-abbrev' instead."
  256. (interactive "p")
  257. (add-abbrev
  258. (if only-global-abbrevs
  259. global-abbrev-table
  260. (or local-abbrev-table
  261. (error "No per-mode abbrev table")))
  262. "Mode" arg))
  263. (defun add-global-abbrev (arg)
  264. "Define global (all modes) abbrev for last word(s) before point.
  265. The prefix argument specifies the number of words before point that form the
  266. expansion; or zero means the region is the expansion.
  267. A negative argument means to undefine the specified abbrev.
  268. This command uses the minibuffer to read the abbreviation.
  269. Don't use this function in a Lisp program; use `define-abbrev' instead."
  270. (interactive "p")
  271. (add-abbrev global-abbrev-table "Global" arg))
  272. (defun add-abbrev (table type arg)
  273. (let ((exp (and (>= arg 0)
  274. (buffer-substring-no-properties
  275. (point)
  276. (if (= arg 0) (mark)
  277. (save-excursion (forward-word (- arg)) (point))))))
  278. name)
  279. (setq name
  280. (read-string (format (if exp "%s abbrev for \"%s\": "
  281. "Undefine %s abbrev: ")
  282. type exp)))
  283. (set-text-properties 0 (length name) nil name)
  284. (if (or (null exp)
  285. (not (abbrev-expansion name table))
  286. (y-or-n-p (format "%s expands to \"%s\"; redefine? "
  287. name (abbrev-expansion name table))))
  288. (define-abbrev table (downcase name) exp))))
  289. (defun inverse-add-mode-abbrev (n)
  290. "Define last word before point as a mode-specific abbrev.
  291. With prefix argument N, defines the Nth word before point.
  292. This command uses the minibuffer to read the expansion.
  293. Expands the abbreviation after defining it."
  294. (interactive "p")
  295. (inverse-add-abbrev
  296. (if only-global-abbrevs
  297. global-abbrev-table
  298. (or local-abbrev-table
  299. (error "No per-mode abbrev table")))
  300. "Mode" n))
  301. (defun inverse-add-global-abbrev (n)
  302. "Define last word before point as a global (mode-independent) abbrev.
  303. With prefix argument N, defines the Nth word before point.
  304. This command uses the minibuffer to read the expansion.
  305. Expands the abbreviation after defining it."
  306. (interactive "p")
  307. (inverse-add-abbrev global-abbrev-table "Global" n))
  308. (defun inverse-add-abbrev (table type arg)
  309. (let (name exp start end)
  310. (save-excursion
  311. (forward-word (1+ (- arg)))
  312. (setq end (point))
  313. (backward-word 1)
  314. (setq start (point)
  315. name (buffer-substring-no-properties start end)))
  316. (setq exp (read-string (format "%s expansion for \"%s\": " type name)
  317. nil nil nil t))
  318. (when (or (not (abbrev-expansion name table))
  319. (y-or-n-p (format "%s expands to \"%s\"; redefine? "
  320. name (abbrev-expansion name table))))
  321. (define-abbrev table (downcase name) exp)
  322. (save-excursion
  323. (goto-char end)
  324. (expand-abbrev)))))
  325. (defun abbrev-prefix-mark (&optional arg)
  326. "Mark current point as the beginning of an abbrev.
  327. Abbrev to be expanded starts here rather than at beginning of word.
  328. This way, you can expand an abbrev with a prefix: insert the prefix,
  329. use this command, then insert the abbrev. This command inserts a
  330. temporary hyphen after the prefix (until the intended abbrev
  331. expansion occurs).
  332. If the prefix is itself an abbrev, this command expands it, unless
  333. ARG is non-nil. Interactively, ARG is the prefix argument."
  334. (interactive "P")
  335. (or arg (expand-abbrev))
  336. (setq abbrev-start-location (point-marker)
  337. abbrev-start-location-buffer (current-buffer))
  338. (insert "-"))
  339. (defun expand-region-abbrevs (start end &optional noquery)
  340. "For abbrev occurrence in the region, offer to expand it.
  341. The user is asked to type `y' or `n' for each occurrence.
  342. A prefix argument means don't query; expand all abbrevs."
  343. (interactive "r\nP")
  344. (save-excursion
  345. (goto-char start)
  346. (let ((lim (- (point-max) end))
  347. pnt string)
  348. (while (and (not (eobp))
  349. (progn (forward-word 1)
  350. (<= (setq pnt (point)) (- (point-max) lim))))
  351. (if (abbrev-expansion
  352. (setq string
  353. (buffer-substring-no-properties
  354. (save-excursion (forward-word -1) (point))
  355. pnt)))
  356. (if (or noquery (y-or-n-p (format-message "Expand `%s'? " string)))
  357. (expand-abbrev)))))))
  358. ;;; Abbrev properties.
  359. (defun abbrev-table-get (table prop)
  360. "Get the PROP property of abbrev table TABLE."
  361. (let ((sym (intern-soft "" table)))
  362. (if sym (get sym prop))))
  363. (defun abbrev-table-put (table prop val)
  364. "Set the PROP property of abbrev table TABLE to VAL."
  365. (let ((sym (intern "" table)))
  366. (set sym nil) ; Make sure it won't be confused for an abbrev.
  367. (put sym prop val)))
  368. (defalias 'abbrev-get 'get
  369. "Get the property PROP of abbrev ABBREV
  370. \(fn ABBREV PROP)")
  371. (defalias 'abbrev-put 'put
  372. "Set the property PROP of abbrev ABBREV to value VAL.
  373. See `define-abbrev' for the effect of some special properties.
  374. \(fn ABBREV PROP VAL)")
  375. ;;; Code that used to be implemented in src/abbrev.c
  376. (defvar abbrev-table-name-list '(fundamental-mode-abbrev-table
  377. global-abbrev-table)
  378. "List of symbols whose values are abbrev tables.")
  379. (defun make-abbrev-table (&optional props)
  380. "Create a new, empty abbrev table object.
  381. PROPS is a list of properties."
  382. ;; The value 59 is an arbitrary prime number.
  383. (let ((table (make-vector 59 0)))
  384. ;; Each abbrev-table has a `modiff' counter which can be used to detect
  385. ;; when an abbreviation was added. An example of use would be to
  386. ;; construct :regexp dynamically as the union of all abbrev names, so
  387. ;; `modiff' can let us detect that an abbrev was added and hence :regexp
  388. ;; needs to be refreshed.
  389. ;; The presence of `modiff' entry is also used as a tag indicating this
  390. ;; vector is really an abbrev-table.
  391. (abbrev-table-put table :abbrev-table-modiff 0)
  392. (while (consp props)
  393. (abbrev-table-put table (pop props) (pop props)))
  394. table))
  395. (defun abbrev-table-p (object)
  396. "Return non-nil if OBJECT is an abbrev table."
  397. (and (vectorp object)
  398. (numberp (abbrev-table-get object :abbrev-table-modiff))))
  399. (defun abbrev-table-empty-p (object &optional ignore-system)
  400. "Return nil if there are no abbrev symbols in OBJECT.
  401. If IGNORE-SYSTEM is non-nil, system definitions are ignored."
  402. (unless (abbrev-table-p object)
  403. (error "Non abbrev table object"))
  404. (not (catch 'some
  405. (mapatoms (lambda (abbrev)
  406. (unless (or (zerop (length (symbol-name abbrev)))
  407. (and ignore-system
  408. (abbrev-get abbrev :system)))
  409. (throw 'some t)))
  410. object))))
  411. (defvar global-abbrev-table (make-abbrev-table)
  412. "The abbrev table whose abbrevs affect all buffers.
  413. Each buffer may also have a local abbrev table.
  414. If it does, the local table overrides the global one
  415. for any particular abbrev defined in both.")
  416. (defvar abbrev-minor-mode-table-alist nil
  417. "Alist of abbrev tables to use for minor modes.
  418. Each element looks like (VARIABLE . ABBREV-TABLE);
  419. ABBREV-TABLE is active whenever VARIABLE's value is non-nil.
  420. ABBREV-TABLE can also be a list of abbrev tables.")
  421. (defvar fundamental-mode-abbrev-table
  422. (let ((table (make-abbrev-table)))
  423. ;; Set local-abbrev-table's default to be fundamental-mode-abbrev-table.
  424. (setq-default local-abbrev-table table)
  425. table)
  426. "The abbrev table of mode-specific abbrevs for Fundamental Mode.")
  427. (defvar abbrevs-changed nil
  428. "Set non-nil by defining or altering any word abbrevs.
  429. This causes `save-some-buffers' to offer to save the abbrevs.")
  430. (defcustom abbrev-all-caps nil
  431. "Non-nil means expand multi-word abbrevs all caps if abbrev was so."
  432. :type 'boolean
  433. :group 'abbrev-mode)
  434. (defvar abbrev-start-location nil
  435. "Buffer position for `expand-abbrev' to use as the start of the abbrev.
  436. When nil, use the word before point as the abbrev.
  437. Calling `expand-abbrev' sets this to nil.")
  438. (defvar abbrev-start-location-buffer nil
  439. "Buffer that `abbrev-start-location' has been set for.
  440. Trying to expand an abbrev in any other buffer clears `abbrev-start-location'.")
  441. (defvar last-abbrev nil
  442. "The abbrev-symbol of the last abbrev expanded. See `abbrev-symbol'.")
  443. (defvar last-abbrev-text nil
  444. "The exact text of the last abbrev expanded.
  445. It is nil if the abbrev has already been unexpanded.")
  446. (defvar last-abbrev-location 0
  447. "The location of the start of the last abbrev expanded.")
  448. ;; (defvar local-abbrev-table fundamental-mode-abbrev-table
  449. ;; "Local (mode-specific) abbrev table of current buffer.")
  450. ;; (make-variable-buffer-local 'local-abbrev-table)
  451. (defcustom pre-abbrev-expand-hook nil
  452. "Function or functions to be called before abbrev expansion is done.
  453. This is the first thing that `expand-abbrev' does, and so this may change
  454. the current abbrev table before abbrev lookup happens."
  455. :type 'hook
  456. :group 'abbrev-mode)
  457. (make-obsolete-variable 'pre-abbrev-expand-hook 'abbrev-expand-function "23.1")
  458. (defun clear-abbrev-table (table)
  459. "Undefine all abbrevs in abbrev table TABLE, leaving it empty."
  460. (setq abbrevs-changed t)
  461. (let* ((sym (intern-soft "" table)))
  462. (dotimes (i (length table))
  463. (aset table i 0))
  464. ;; Preserve the table's properties.
  465. (cl-assert sym)
  466. (let ((newsym (intern "" table)))
  467. (set newsym nil) ; Make sure it won't be confused for an abbrev.
  468. (setplist newsym (symbol-plist sym)))
  469. (abbrev-table-put table :abbrev-table-modiff
  470. (1+ (abbrev-table-get table :abbrev-table-modiff))))
  471. ;; For backward compatibility, always return nil.
  472. nil)
  473. (defun define-abbrev (table name expansion &optional hook &rest props)
  474. "Define an abbrev in TABLE named NAME, to expand to EXPANSION and call HOOK.
  475. NAME must be a string, and should be lower-case.
  476. EXPANSION should usually be a string.
  477. To undefine an abbrev, define it with EXPANSION = nil.
  478. If HOOK is non-nil, it should be a function of no arguments;
  479. it is called after EXPANSION is inserted.
  480. If EXPANSION is not a string (and not nil), the abbrev is a
  481. special one, which does not expand in the usual way but only
  482. runs HOOK.
  483. If HOOK is a non-nil symbol with a non-nil `no-self-insert' property,
  484. it can control whether the character that triggered abbrev expansion
  485. is inserted. If such a HOOK returns non-nil, the character is not
  486. inserted. If such a HOOK returns nil, then so does `abbrev-insert'
  487. \(and `expand-abbrev'), as if no abbrev expansion had taken place.
  488. PROPS is a property list. The following properties are special:
  489. - `:count': the value for the abbrev's usage-count, which is incremented each
  490. time the abbrev is used (the default is zero).
  491. - `:system': if non-nil, says that this is a \"system\" abbreviation
  492. which should not be saved in the user's abbreviation file.
  493. Unless `:system' is `force', a system abbreviation will not
  494. overwrite a non-system abbreviation of the same name.
  495. - `:case-fixed': non-nil means that abbreviations are looked up without
  496. case-folding, and the expansion is not capitalized/upcased.
  497. - `:enable-function': a function of no argument which returns non-nil if the
  498. abbrev should be used for a particular call of `expand-abbrev'.
  499. An obsolete but still supported calling form is:
  500. \(define-abbrev TABLE NAME EXPANSION &optional HOOK COUNT SYSTEM)."
  501. (when (and (consp props) (or (null (car props)) (numberp (car props))))
  502. ;; Old-style calling convention.
  503. (setq props `(:count ,(car props)
  504. ,@(if (cadr props) (list :system (cadr props))))))
  505. (unless (plist-get props :count)
  506. (setq props (plist-put props :count 0)))
  507. (setq props (plist-put props :abbrev-table-modiff
  508. (abbrev-table-get table :abbrev-table-modiff)))
  509. (let ((system-flag (plist-get props :system))
  510. (sym (intern name table)))
  511. ;; Don't override a prior user-defined abbrev with a system abbrev,
  512. ;; unless system-flag is `force'.
  513. (unless (and (not (memq system-flag '(nil force)))
  514. (boundp sym) (symbol-value sym)
  515. (not (abbrev-get sym :system)))
  516. (unless (or system-flag
  517. (and (boundp sym)
  518. ;; load-file-name
  519. (equal (symbol-value sym) expansion)
  520. (equal (symbol-function sym) hook)))
  521. (setq abbrevs-changed t))
  522. (set sym expansion)
  523. (fset sym hook)
  524. (setplist sym
  525. ;; Don't store the `force' value of `system-flag' into
  526. ;; the :system property.
  527. (if (eq 'force system-flag) (plist-put props :system t) props))
  528. (abbrev-table-put table :abbrev-table-modiff
  529. (1+ (abbrev-table-get table :abbrev-table-modiff))))
  530. name))
  531. (defun abbrev--check-chars (abbrev global)
  532. "Check if the characters in ABBREV have word syntax in either the
  533. current (if global is nil) or standard syntax table."
  534. (with-syntax-table
  535. (cond ((null global) (syntax-table))
  536. ;; ((syntax-table-p global) global)
  537. (t (standard-syntax-table)))
  538. (when (string-match "\\W" abbrev)
  539. (let ((badchars ())
  540. (pos 0))
  541. (while (string-match "\\W" abbrev pos)
  542. (cl-pushnew (aref abbrev (match-beginning 0)) badchars)
  543. (setq pos (1+ pos)))
  544. (error "Some abbrev characters (%s) are not word constituents %s"
  545. (apply 'string (nreverse badchars))
  546. (if global "in the standard syntax" "in this mode"))))))
  547. (defun define-global-abbrev (abbrev expansion)
  548. "Define ABBREV as a global abbreviation for EXPANSION.
  549. The characters in ABBREV must all be word constituents in the standard
  550. syntax table."
  551. (interactive "sDefine global abbrev: \nsExpansion for %s: ")
  552. (abbrev--check-chars abbrev 'global)
  553. (define-abbrev global-abbrev-table (downcase abbrev) expansion))
  554. (defun define-mode-abbrev (abbrev expansion)
  555. "Define ABBREV as a mode-specific abbreviation for EXPANSION.
  556. The characters in ABBREV must all be word-constituents in the current mode."
  557. (interactive "sDefine mode abbrev: \nsExpansion for %s: ")
  558. (unless local-abbrev-table
  559. (error "Major mode has no abbrev table"))
  560. (abbrev--check-chars abbrev nil)
  561. (define-abbrev local-abbrev-table (downcase abbrev) expansion))
  562. (defun abbrev--active-tables (&optional tables)
  563. "Return the list of abbrev tables currently active.
  564. TABLES if non-nil overrides the usual rules. It can hold
  565. either a single abbrev table or a list of abbrev tables."
  566. ;; We could just remove the `tables' arg and let callers use
  567. ;; (or table (abbrev--active-tables)) but then they'd have to be careful
  568. ;; to treat the distinction between a single table and a list of tables.
  569. (cond
  570. ((consp tables) tables)
  571. ((vectorp tables) (list tables))
  572. (t
  573. (let ((tables (if (listp local-abbrev-table)
  574. (append local-abbrev-table
  575. (list global-abbrev-table))
  576. (list local-abbrev-table global-abbrev-table))))
  577. ;; Add the minor-mode abbrev tables.
  578. (dolist (x abbrev-minor-mode-table-alist)
  579. (when (and (symbolp (car x)) (boundp (car x)) (symbol-value (car x)))
  580. (setq tables
  581. (if (listp (cdr x))
  582. (append (cdr x) tables) (cons (cdr x) tables)))))
  583. tables))))
  584. (defun abbrev--symbol (abbrev table)
  585. "Return the symbol representing abbrev named ABBREV in TABLE.
  586. This symbol's name is ABBREV, but it is not the canonical symbol of that name;
  587. it is interned in the abbrev-table TABLE rather than the normal obarray.
  588. The value is nil if that abbrev is not defined."
  589. (let* ((case-fold (not (abbrev-table-get table :case-fixed)))
  590. ;; In case the table doesn't set :case-fixed but some of the
  591. ;; abbrevs do, we have to be careful.
  592. (sym
  593. ;; First try without case-folding.
  594. (or (intern-soft abbrev table)
  595. (when case-fold
  596. ;; We didn't find any abbrev, try case-folding.
  597. (let ((sym (intern-soft (downcase abbrev) table)))
  598. ;; Only use it if it doesn't require :case-fixed.
  599. (and sym (not (abbrev-get sym :case-fixed))
  600. sym))))))
  601. (if (symbol-value sym)
  602. sym)))
  603. (defun abbrev-symbol (abbrev &optional table)
  604. "Return the symbol representing abbrev named ABBREV.
  605. This symbol's name is ABBREV, but it is not the canonical symbol of that name;
  606. it is interned in an abbrev-table rather than the normal obarray.
  607. The value is nil if that abbrev is not defined.
  608. Optional second arg TABLE is abbrev table to look it up in.
  609. The default is to try buffer's mode-specific abbrev table, then global table."
  610. (let ((tables (abbrev--active-tables table))
  611. sym)
  612. (while (and tables (not sym))
  613. (let* ((table (pop tables)))
  614. (setq tables (append (abbrev-table-get table :parents) tables))
  615. (setq sym (abbrev--symbol abbrev table))))
  616. sym))
  617. (defun abbrev-expansion (abbrev &optional table)
  618. "Return the string that ABBREV expands into in the current buffer.
  619. Optionally specify an abbrev table as second arg;
  620. then ABBREV is looked up in that table only."
  621. (symbol-value (abbrev-symbol abbrev table)))
  622. (defun abbrev--before-point ()
  623. "Try and find an abbrev before point. Return it if found, nil otherwise."
  624. (unless (eq abbrev-start-location-buffer (current-buffer))
  625. (setq abbrev-start-location nil))
  626. (let ((tables (abbrev--active-tables))
  627. (pos (point))
  628. start end name res)
  629. (if abbrev-start-location
  630. (progn
  631. (setq start abbrev-start-location)
  632. (setq abbrev-start-location nil)
  633. ;; Remove the hyphen inserted by `abbrev-prefix-mark'.
  634. (if (and (< start (point-max))
  635. (eq (char-after start) ?-))
  636. (delete-region start (1+ start)))
  637. (skip-syntax-backward " ")
  638. (setq end (point))
  639. (when (> end start)
  640. (setq name (buffer-substring start end))
  641. (goto-char pos) ; Restore point.
  642. (list (abbrev-symbol name tables) name start end)))
  643. (while (and tables (not (car res)))
  644. (let* ((table (pop tables))
  645. (enable-fun (abbrev-table-get table :enable-function)))
  646. (setq tables (append (abbrev-table-get table :parents) tables))
  647. (setq res
  648. (and (or (not enable-fun) (funcall enable-fun))
  649. (let ((re (abbrev-table-get table :regexp)))
  650. (if (null re)
  651. ;; We used to default `re' to "\\<\\(\\w+\\)\\W*"
  652. ;; but when words-include-escapes is set, that
  653. ;; is not right and fixing it is boring.
  654. (let ((lim (point)))
  655. (backward-word 1)
  656. (setq start (point))
  657. (forward-word 1)
  658. (setq end (min (point) lim)))
  659. (when (looking-back re (line-beginning-position))
  660. (setq start (match-beginning 1))
  661. (setq end (match-end 1)))))
  662. (setq name (buffer-substring start end))
  663. (let ((abbrev (abbrev--symbol name table)))
  664. (when abbrev
  665. (setq enable-fun (abbrev-get abbrev :enable-function))
  666. (and (or (not enable-fun) (funcall enable-fun))
  667. ;; This will also look it up in parent tables.
  668. ;; This is not on purpose, but it seems harmless.
  669. (list abbrev name start end))))))
  670. ;; Restore point.
  671. (goto-char pos)))
  672. res)))
  673. (defun abbrev-insert (abbrev &optional name wordstart wordend)
  674. "Insert abbrev ABBREV at point.
  675. If non-nil, NAME is the name by which this abbrev was found.
  676. If non-nil, WORDSTART is the place where to insert the abbrev.
  677. If WORDEND is non-nil, the abbrev replaces the previous text between
  678. WORDSTART and WORDEND.
  679. Return ABBREV if the expansion should be considered as having taken place.
  680. The return value can be influenced by a `no-self-insert' property;
  681. see `define-abbrev' for details."
  682. (unless name (setq name (symbol-name abbrev)))
  683. (unless wordstart (setq wordstart (point)))
  684. (unless wordend (setq wordend wordstart))
  685. ;; Increment use count.
  686. (abbrev-put abbrev :count (1+ (abbrev-get abbrev :count)))
  687. (let ((value abbrev))
  688. ;; If this abbrev has an expansion, delete the abbrev
  689. ;; and insert the expansion.
  690. (when (stringp (symbol-value abbrev))
  691. (goto-char wordstart)
  692. ;; Insert at beginning so that markers at the end (e.g. point)
  693. ;; are preserved.
  694. (insert (symbol-value abbrev))
  695. (delete-char (- wordend wordstart))
  696. (let ((case-fold-search nil))
  697. ;; If the abbrev's name is different from the buffer text (the
  698. ;; only difference should be capitalization), then we may want
  699. ;; to adjust the capitalization of the expansion.
  700. (when (and (not (equal name (symbol-name abbrev)))
  701. (string-match "[[:upper:]]" name))
  702. (if (not (string-match "[[:lower:]]" name))
  703. ;; Abbrev was all caps. If expansion is multiple words,
  704. ;; normally capitalize each word.
  705. (if (and (not abbrev-all-caps)
  706. (save-excursion
  707. (> (progn (backward-word 1) (point))
  708. (progn (goto-char wordstart)
  709. (forward-word 1) (point)))))
  710. (upcase-initials-region wordstart (point))
  711. (upcase-region wordstart (point)))
  712. ;; Abbrev included some caps. Cap first initial of expansion.
  713. (let ((end (point)))
  714. ;; Find the initial.
  715. (goto-char wordstart)
  716. (skip-syntax-forward "^w" (1- end))
  717. ;; Change just that.
  718. (upcase-initials-region (point) (1+ (point)))
  719. (goto-char end))))))
  720. ;; Now point is at the end of the expansion and the beginning is
  721. ;; in last-abbrev-location.
  722. (when (symbol-function abbrev)
  723. (let* ((hook (symbol-function abbrev))
  724. (expanded
  725. ;; If the abbrev has a hook function, run it.
  726. (funcall hook)))
  727. ;; In addition, if the hook function is a symbol with
  728. ;; a non-nil `no-self-insert' property, let the value it
  729. ;; returned specify whether we consider that an expansion took
  730. ;; place. If it returns nil, no expansion has been done.
  731. (if (and (symbolp hook)
  732. (null expanded)
  733. (get hook 'no-self-insert))
  734. (setq value nil))))
  735. value))
  736. (defvar abbrev-expand-functions nil
  737. "Wrapper hook around `abbrev--default-expand'.")
  738. (make-obsolete-variable 'abbrev-expand-functions 'abbrev-expand-function "24.4")
  739. (defvar abbrev-expand-function #'abbrev--default-expand
  740. "Function that `expand-abbrev' uses to perform abbrev expansion.
  741. Takes no argument and should return the abbrev symbol if expansion took place.")
  742. (defun expand-abbrev ()
  743. "Expand the abbrev before point, if there is an abbrev there.
  744. Effective when explicitly called even when `abbrev-mode' is nil.
  745. Before doing anything else, runs `pre-abbrev-expand-hook'.
  746. Calls `abbrev-expand-function' with no argument to do the work,
  747. and returns whatever it does. (This should be the abbrev symbol
  748. if expansion occurred, else nil.)"
  749. (interactive)
  750. (run-hooks 'pre-abbrev-expand-hook)
  751. (funcall abbrev-expand-function))
  752. (defun abbrev--default-expand ()
  753. "Default function to use for `abbrev-expand-function'.
  754. This respects the wrapper hook `abbrev-expand-functions'.
  755. Calls `abbrev-insert' to insert any expansion, and returns what it does."
  756. (with-wrapper-hook abbrev-expand-functions ()
  757. (pcase-let ((`(,sym ,name ,wordstart ,wordend) (abbrev--before-point)))
  758. (when sym
  759. (let ((startpos (copy-marker (point) t))
  760. (endmark (copy-marker wordend t)))
  761. (unless (or ;; executing-kbd-macro
  762. noninteractive
  763. (window-minibuffer-p))
  764. ;; Add an undo boundary, in case we are doing this for
  765. ;; a self-inserting command which has avoided making one so far.
  766. (undo-boundary))
  767. ;; Now sym is the abbrev symbol.
  768. (setq last-abbrev-text name)
  769. (setq last-abbrev sym)
  770. (setq last-abbrev-location wordstart)
  771. ;; If this abbrev has an expansion, delete the abbrev
  772. ;; and insert the expansion.
  773. (prog1
  774. (abbrev-insert sym name wordstart wordend)
  775. ;; Yuck!! If expand-abbrev is called with point slightly
  776. ;; further than the end of the abbrev, move point back to
  777. ;; where it started.
  778. (if (and (> startpos endmark)
  779. (= (point) endmark)) ;Obey skeletons that move point.
  780. (goto-char startpos))))))))
  781. (defun unexpand-abbrev ()
  782. "Undo the expansion of the last abbrev that expanded.
  783. This differs from ordinary undo in that other editing done since then
  784. is not undone."
  785. (interactive)
  786. (save-excursion
  787. (unless (or (< last-abbrev-location (point-min))
  788. (> last-abbrev-location (point-max)))
  789. (goto-char last-abbrev-location)
  790. (when (stringp last-abbrev-text)
  791. ;; This isn't correct if last-abbrev's hook was used
  792. ;; to do the expansion.
  793. (let ((val (symbol-value last-abbrev)))
  794. (unless (stringp val)
  795. (error "Value of abbrev-symbol must be a string"))
  796. ;; Don't inherit properties here; just copy from old contents.
  797. (insert last-abbrev-text)
  798. ;; Delete after inserting, to better preserve markers.
  799. (delete-region (point) (+ (point) (length val)))
  800. (setq last-abbrev-text nil))))))
  801. (defun abbrev--write (sym)
  802. "Write the abbrev in a `read'able form.
  803. Only writes the non-system abbrevs.
  804. Presumes that `standard-output' points to `current-buffer'."
  805. (unless (or (null (symbol-value sym)) (abbrev-get sym :system))
  806. (insert " (")
  807. (prin1 (symbol-name sym))
  808. (insert " ")
  809. (prin1 (symbol-value sym))
  810. (insert " ")
  811. (prin1 (symbol-function sym))
  812. (insert " ")
  813. (prin1 (abbrev-get sym :count))
  814. (insert ")\n")))
  815. (defun abbrev--describe (sym)
  816. (when (symbol-value sym)
  817. (prin1 (symbol-name sym))
  818. (if (null (abbrev-get sym :system))
  819. (indent-to 15 1)
  820. (insert " (sys)")
  821. (indent-to 20 1))
  822. (prin1 (abbrev-get sym :count))
  823. (indent-to 20 1)
  824. (prin1 (symbol-value sym))
  825. (when (symbol-function sym)
  826. (indent-to 45 1)
  827. (prin1 (symbol-function sym)))
  828. (terpri)))
  829. (defun insert-abbrev-table-description (name &optional readable)
  830. "Insert before point a full description of abbrev table named NAME.
  831. NAME is a symbol whose value is an abbrev table.
  832. If optional 2nd arg READABLE is non-nil, a human-readable description
  833. is inserted. Otherwise the description is an expression,
  834. a call to `define-abbrev-table', which would
  835. define the abbrev table NAME exactly as it is currently defined.
  836. Abbrevs marked as \"system abbrevs\" are omitted."
  837. (let ((table (symbol-value name))
  838. (symbols ()))
  839. (mapatoms (lambda (sym) (if (symbol-value sym) (push sym symbols))) table)
  840. (setq symbols (sort symbols 'string-lessp))
  841. (let ((standard-output (current-buffer)))
  842. (if readable
  843. (progn
  844. (insert "(")
  845. (prin1 name)
  846. (insert ")\n\n")
  847. (mapc 'abbrev--describe symbols)
  848. (insert "\n\n"))
  849. (insert "(define-abbrev-table '")
  850. (prin1 name)
  851. (if (null symbols)
  852. (insert " '())\n\n")
  853. (insert "\n '(\n")
  854. (mapc 'abbrev--write symbols)
  855. (insert " ))\n\n")))
  856. nil)))
  857. (defun define-abbrev-table (tablename definitions
  858. &optional docstring &rest props)
  859. "Define TABLENAME (a symbol) as an abbrev table name.
  860. Define abbrevs in it according to DEFINITIONS, which is a list of elements
  861. of the form (ABBREVNAME EXPANSION ...) that are passed to `define-abbrev'.
  862. PROPS is a property list to apply to the table.
  863. Properties with special meaning:
  864. - `:parents' contains a list of abbrev tables from which this table inherits
  865. abbreviations.
  866. - `:case-fixed' non-nil means that abbreviations are looked up without
  867. case-folding, and the expansion is not capitalized/upcased.
  868. - `:regexp' is a regular expression that specifies how to extract the
  869. name of the abbrev before point. The submatch 1 is treated
  870. as the potential name of an abbrev. If :regexp is nil, the default
  871. behavior uses `backward-word' and `forward-word' to extract the name
  872. of the abbrev, which can therefore only be a single word.
  873. - `:enable-function' can be set to a function of no argument which returns
  874. non-nil if and only if the abbrevs in this table should be used for this
  875. instance of `expand-abbrev'."
  876. (declare (doc-string 3))
  877. ;; We used to manually add the docstring, but we also want to record this
  878. ;; location as the definition of the variable (in load-history), so we may
  879. ;; as well just use `defvar'.
  880. (if (and docstring props (symbolp docstring))
  881. ;; There is really no docstring, instead the docstring arg
  882. ;; is a property name.
  883. (push docstring props) (setq docstring nil))
  884. (eval `(defvar ,tablename nil ,@(if docstring (list docstring))))
  885. (let ((table (if (boundp tablename) (symbol-value tablename))))
  886. (unless table
  887. (setq table (make-abbrev-table))
  888. (set tablename table)
  889. (unless (memq tablename abbrev-table-name-list)
  890. (push tablename abbrev-table-name-list)))
  891. ;; We used to just pass them to `make-abbrev-table', but that fails
  892. ;; if the table was pre-existing as is the case if it was created by
  893. ;; loading the user's abbrev file.
  894. (while (consp props)
  895. (unless (cdr props) (error "Missing value for property %S" (car props)))
  896. (abbrev-table-put table (pop props) (pop props)))
  897. (dolist (elt definitions)
  898. (apply 'define-abbrev table elt))))
  899. (defun abbrev-table-menu (table &optional prompt sortfun)
  900. "Return a menu that shows all abbrevs in TABLE.
  901. Selecting an entry runs `abbrev-insert'.
  902. PROMPT is the prompt to use for the keymap.
  903. SORTFUN is passed to `sort' to change the default ordering."
  904. (unless sortfun (setq sortfun 'string-lessp))
  905. (let ((entries ()))
  906. (mapatoms (lambda (abbrev)
  907. (when (symbol-value abbrev)
  908. (let ((name (symbol-name abbrev)))
  909. (push `(,(intern name) menu-item ,name
  910. (lambda () (interactive)
  911. (abbrev-insert ',abbrev)))
  912. entries))))
  913. table)
  914. (nconc (make-sparse-keymap prompt)
  915. (sort entries (lambda (x y)
  916. (funcall sortfun (nth 2 x) (nth 2 y)))))))
  917. ;; Keep it after define-abbrev-table, since define-derived-mode uses
  918. ;; define-abbrev-table.
  919. (define-derived-mode edit-abbrevs-mode fundamental-mode "Edit-Abbrevs"
  920. "Major mode for editing the list of abbrev definitions.")
  921. (provide 'abbrev)
  922. ;;; abbrev.el ends here