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