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