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