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