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