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