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