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