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