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