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