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