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