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