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