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