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