* etags.c (get_language_from_filename): Add one argument.
[bpt/emacs.git] / lisp / subr.el
CommitLineData
c88ab9ce 1;;; subr.el --- basic lisp subroutines for Emacs
630cc463 2
2c642c03 3;; Copyright (C) 1985, 86, 92, 94, 95, 99, 2000, 2001, 2002
fe10cef0 4;; Free Software Foundation, Inc.
be9b65ac
DL
5
6;; This file is part of GNU Emacs.
7
8;; GNU Emacs is free software; you can redistribute it and/or modify
9;; it under the terms of the GNU General Public License as published by
492878e4 10;; the Free Software Foundation; either version 2, or (at your option)
be9b65ac
DL
11;; any later version.
12
13;; GNU Emacs is distributed in the hope that it will be useful,
14;; but WITHOUT ANY WARRANTY; without even the implied warranty of
15;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16;; GNU General Public License for more details.
17
18;; You should have received a copy of the GNU General Public License
b578f267
EN
19;; along with GNU Emacs; see the file COPYING. If not, write to the
20;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21;; Boston, MA 02111-1307, USA.
be9b65ac 22
60370d40
PJ
23;;; Commentary:
24
630cc463 25;;; Code:
77a5664f
RS
26(defvar custom-declare-variable-list nil
27 "Record `defcustom' calls made before `custom.el' is loaded to handle them.
28Each element of this list holds the arguments to one call to `defcustom'.")
29
68e3e5f5 30;; Use this, rather than defcustom, in subr.el and other files loaded
77a5664f
RS
31;; before custom.el.
32(defun custom-declare-variable-early (&rest arguments)
33 (setq custom-declare-variable-list
34 (cons arguments custom-declare-variable-list)))
2c642c03
GM
35
36\f
37(defun macro-declaration-function (macro decl)
38 "Process a declaration found in a macro definition.
39This is set as the value of the variable `macro-declaration-function'.
40MACRO is the name of the macro being defined.
41DECL is a list `(declare ...)' containing the declarations.
42The return value of this function is not used."
43 (dolist (d (cdr decl))
44 (cond ((and (consp d) (eq (car d) 'indent))
45 (put macro 'lisp-indent-function (cadr d)))
46 ((and (consp d) (eq (car d) 'debug))
47 (put macro 'edebug-form-spec (cadr d)))
48 (t
49 (message "Unknown declaration %s" d)))))
50
51(setq macro-declaration-function 'macro-declaration-function)
52
9a5336ae
JB
53\f
54;;;; Lisp language features.
55
0764e16f
SM
56(defalias 'not 'null)
57
9a5336ae
JB
58(defmacro lambda (&rest cdr)
59 "Return a lambda expression.
60A call of the form (lambda ARGS DOCSTRING INTERACTIVE BODY) is
61self-quoting; the result of evaluating the lambda expression is the
62expression itself. The lambda expression may then be treated as a
bec0d7f9
RS
63function, i.e., stored as the function value of a symbol, passed to
64funcall or mapcar, etc.
65
9a5336ae 66ARGS should take the same form as an argument list for a `defun'.
8fd68088
RS
67DOCSTRING is an optional documentation string.
68 If present, it should describe how to call the function.
69 But documentation strings are usually not useful in nameless functions.
9a5336ae
JB
70INTERACTIVE should be a call to the function `interactive', which see.
71It may also be omitted.
72BODY should be a list of lisp expressions."
73 ;; Note that this definition should not use backquotes; subr.el should not
74 ;; depend on backquote.el.
75 (list 'function (cons 'lambda cdr)))
76
1be152fc 77(defmacro push (newelt listname)
fa65505b 78 "Add NEWELT to the list stored in the symbol LISTNAME.
1be152fc 79This is equivalent to (setq LISTNAME (cons NEWELT LISTNAME)).
d270117a 80LISTNAME must be a symbol."
22d85d00
DL
81 (list 'setq listname
82 (list 'cons newelt listname)))
d270117a
RS
83
84(defmacro pop (listname)
85 "Return the first element of LISTNAME's value, and remove it from the list.
86LISTNAME must be a symbol whose value is a list.
87If the value is nil, `pop' returns nil but does not actually
88change the list."
89 (list 'prog1 (list 'car listname)
90 (list 'setq listname (list 'cdr listname))))
91
debff3c3 92(defmacro when (cond &rest body)
b021ef18 93 "If COND yields non-nil, do BODY, else return nil."
debff3c3 94 (list 'if cond (cons 'progn body)))
9a5336ae 95
debff3c3 96(defmacro unless (cond &rest body)
b021ef18 97 "If COND yields nil, do BODY, else return nil."
debff3c3 98 (cons 'if (cons cond (cons nil body))))
d370591d 99
a0b0756a
RS
100(defmacro dolist (spec &rest body)
101 "(dolist (VAR LIST [RESULT]) BODY...): loop over a list.
102Evaluate BODY with VAR bound to each car from LIST, in turn.
103Then evaluate RESULT to get return value, default nil."
e4295aa1
RS
104 (let ((temp (make-symbol "--dolist-temp--")))
105 (list 'let (list (list temp (nth 1 spec)) (car spec))
106 (list 'while temp
107 (list 'setq (car spec) (list 'car temp))
108 (cons 'progn
109 (append body
110 (list (list 'setq temp (list 'cdr temp))))))
111 (if (cdr (cdr spec))
112 (cons 'progn
113 (cons (list 'setq (car spec) nil) (cdr (cdr spec))))))))
a0b0756a
RS
114
115(defmacro dotimes (spec &rest body)
116 "(dotimes (VAR COUNT [RESULT]) BODY...): loop a certain number of times.
117Evaluate BODY with VAR bound to successive integers running from 0,
118inclusive, to COUNT, exclusive. Then evaluate RESULT to get
119the return value (nil if RESULT is omitted)."
e4295aa1
RS
120 (let ((temp (make-symbol "--dotimes-temp--")))
121 (list 'let (list (list temp (nth 1 spec)) (list (car spec) 0))
122 (list 'while (list '< (car spec) temp)
123 (cons 'progn
124 (append body (list (list 'setq (car spec)
125 (list '1+ (car spec)))))))
126 (if (cdr (cdr spec))
127 (car (cdr (cdr spec)))
128 nil))))
a0b0756a 129
d370591d
RS
130(defsubst caar (x)
131 "Return the car of the car of X."
132 (car (car x)))
133
134(defsubst cadr (x)
135 "Return the car of the cdr of X."
136 (car (cdr x)))
137
138(defsubst cdar (x)
139 "Return the cdr of the car of X."
140 (cdr (car x)))
141
142(defsubst cddr (x)
143 "Return the cdr of the cdr of X."
144 (cdr (cdr x)))
e8c32c99 145
369fba5f
RS
146(defun last (x &optional n)
147 "Return the last link of the list X. Its car is the last element.
148If X is nil, return nil.
149If N is non-nil, return the Nth-to-last link of X.
150If N is bigger than the length of X, return X."
151 (if n
152 (let ((m 0) (p x))
153 (while (consp p)
154 (setq m (1+ m) p (cdr p)))
155 (if (<= n 0) p
156 (if (< n m) (nthcdr (- m n) x) x)))
6bfdc2e2 157 (while (consp (cdr x))
369fba5f
RS
158 (setq x (cdr x)))
159 x))
526d204e 160
1c1c65de
KH
161(defun butlast (x &optional n)
162 "Returns a copy of LIST with the last N elements removed."
163 (if (and n (<= n 0)) x
164 (nbutlast (copy-sequence x) n)))
165
166(defun nbutlast (x &optional n)
167 "Modifies LIST to remove the last N elements."
168 (let ((m (length x)))
169 (or n (setq n 1))
170 (and (< n m)
171 (progn
172 (if (> n 0) (setcdr (nthcdr (- (1- m) n) x) nil))
173 x))))
174
13157efc 175(defun remove (elt seq)
963f49a2 176 "Return a copy of SEQ with all occurrences of ELT removed.
13157efc
GM
177SEQ must be a list, vector, or string. The comparison is done with `equal'."
178 (if (nlistp seq)
179 ;; If SEQ isn't a list, there's no need to copy SEQ because
180 ;; `delete' will return a new object.
181 (delete elt seq)
182 (delete elt (copy-sequence seq))))
183
184(defun remq (elt list)
185 "Return a copy of LIST with all occurences of ELT removed.
186The comparison is done with `eq'."
187 (if (memq elt list)
188 (delq elt (copy-sequence list))
189 list))
190
8a288450
RS
191(defun assoc-default (key alist &optional test default)
192 "Find object KEY in a pseudo-alist ALIST.
193ALIST is a list of conses or objects. Each element (or the element's car,
194if it is a cons) is compared with KEY by evaluating (TEST (car elt) KEY).
195If that is non-nil, the element matches;
196then `assoc-default' returns the element's cdr, if it is a cons,
526d204e 197or DEFAULT if the element is not a cons.
8a288450
RS
198
199If no element matches, the value is nil.
200If TEST is omitted or nil, `equal' is used."
201 (let (found (tail alist) value)
202 (while (and tail (not found))
203 (let ((elt (car tail)))
204 (when (funcall (or test 'equal) (if (consp elt) (car elt) elt) key)
205 (setq found t value (if (consp elt) (cdr elt) default))))
206 (setq tail (cdr tail)))
207 value))
98aae5f6
KH
208
209(defun assoc-ignore-case (key alist)
210 "Like `assoc', but ignores differences in case and text representation.
211KEY must be a string. Upper-case and lower-case letters are treated as equal.
212Unibyte strings are converted to multibyte for comparison."
213 (let (element)
214 (while (and alist (not element))
215 (if (eq t (compare-strings key 0 nil (car (car alist)) 0 nil t))
216 (setq element (car alist)))
217 (setq alist (cdr alist)))
218 element))
219
220(defun assoc-ignore-representation (key alist)
221 "Like `assoc', but ignores differences in text representation.
222KEY must be a string.
223Unibyte strings are converted to multibyte for comparison."
224 (let (element)
225 (while (and alist (not element))
226 (if (eq t (compare-strings key 0 nil (car (car alist)) 0 nil))
227 (setq element (car alist)))
228 (setq alist (cdr alist)))
229 element))
cbbc3205
GM
230
231(defun member-ignore-case (elt list)
232 "Like `member', but ignores differences in case and text representation.
233ELT must be a string. Upper-case and lower-case letters are treated as equal.
234Unibyte strings are converted to multibyte for comparison."
242c13e8
MB
235 (while (and list (not (eq t (compare-strings elt 0 nil (car list) 0 nil t))))
236 (setq list (cdr list)))
237 list)
cbbc3205 238
9a5336ae 239\f
9a5336ae 240;;;; Keymap support.
be9b65ac
DL
241
242(defun undefined ()
243 (interactive)
244 (ding))
245
246;Prevent the \{...} documentation construct
247;from mentioning keys that run this command.
248(put 'undefined 'suppress-keymap t)
249
250(defun suppress-keymap (map &optional nodigits)
251 "Make MAP override all normally self-inserting keys to be undefined.
252Normally, as an exception, digits and minus-sign are set to make prefix args,
253but optional second arg NODIGITS non-nil treats them like other chars."
80e7b471 254 (substitute-key-definition 'self-insert-command 'undefined map global-map)
be9b65ac
DL
255 (or nodigits
256 (let (loop)
257 (define-key map "-" 'negative-argument)
258 ;; Make plain numbers do numeric args.
259 (setq loop ?0)
260 (while (<= loop ?9)
261 (define-key map (char-to-string loop) 'digit-argument)
262 (setq loop (1+ loop))))))
263
be9b65ac
DL
264;Moved to keymap.c
265;(defun copy-keymap (keymap)
266; "Return a copy of KEYMAP"
267; (while (not (keymapp keymap))
268; (setq keymap (signal 'wrong-type-argument (list 'keymapp keymap))))
269; (if (vectorp keymap)
270; (copy-sequence keymap)
271; (copy-alist keymap)))
272
f14dbba7
KH
273(defvar key-substitution-in-progress nil
274 "Used internally by substitute-key-definition.")
275
7f2c2edd 276(defun substitute-key-definition (olddef newdef keymap &optional oldmap prefix)
be9b65ac
DL
277 "Replace OLDDEF with NEWDEF for any keys in KEYMAP now defined as OLDDEF.
278In other words, OLDDEF is replaced with NEWDEF where ever it appears.
4656b314 279Alternatively, if optional fourth argument OLDMAP is specified, we redefine
ff77cf40 280in KEYMAP as NEWDEF those keys which are defined as OLDDEF in OLDMAP."
739f2672
GM
281 ;; Don't document PREFIX in the doc string because we don't want to
282 ;; advertise it. It's meant for recursive calls only. Here's its
283 ;; meaning
284
285 ;; If optional argument PREFIX is specified, it should be a key
286 ;; prefix, a string. Redefined bindings will then be bound to the
287 ;; original key, with PREFIX added at the front.
7f2c2edd
RS
288 (or prefix (setq prefix ""))
289 (let* ((scan (or oldmap keymap))
290 (vec1 (vector nil))
f14dbba7
KH
291 (prefix1 (vconcat prefix vec1))
292 (key-substitution-in-progress
293 (cons scan key-substitution-in-progress)))
7f2c2edd
RS
294 ;; Scan OLDMAP, finding each char or event-symbol that
295 ;; has any definition, and act on it with hack-key.
296 (while (consp scan)
297 (if (consp (car scan))
298 (let ((char (car (car scan)))
299 (defn (cdr (car scan))))
300 ;; The inside of this let duplicates exactly
301 ;; the inside of the following let that handles array elements.
302 (aset vec1 0 char)
303 (aset prefix1 (length prefix) char)
44d798af 304 (let (inner-def skipped)
7f2c2edd
RS
305 ;; Skip past menu-prompt.
306 (while (stringp (car-safe defn))
44d798af 307 (setq skipped (cons (car defn) skipped))
7f2c2edd 308 (setq defn (cdr defn)))
e025dddf
RS
309 ;; Skip past cached key-equivalence data for menu items.
310 (and (consp defn) (consp (car defn))
311 (setq defn (cdr defn)))
7f2c2edd 312 (setq inner-def defn)
e025dddf 313 ;; Look past a symbol that names a keymap.
7f2c2edd
RS
314 (while (and (symbolp inner-def)
315 (fboundp inner-def))
316 (setq inner-def (symbol-function inner-def)))
328a37ec
RS
317 (if (or (eq defn olddef)
318 ;; Compare with equal if definition is a key sequence.
319 ;; That is useful for operating on function-key-map.
320 (and (or (stringp defn) (vectorp defn))
321 (equal defn olddef)))
44d798af 322 (define-key keymap prefix1 (nconc (nreverse skipped) newdef))
f14dbba7 323 (if (and (keymapp defn)
350b7567
RS
324 ;; Avoid recursively scanning
325 ;; where KEYMAP does not have a submap.
afd9831b
RS
326 (let ((elt (lookup-key keymap prefix1)))
327 (or (null elt)
328 (keymapp elt)))
350b7567 329 ;; Avoid recursively rescanning keymap being scanned.
f14dbba7
KH
330 (not (memq inner-def
331 key-substitution-in-progress)))
e025dddf
RS
332 ;; If this one isn't being scanned already,
333 ;; scan it now.
7f2c2edd
RS
334 (substitute-key-definition olddef newdef keymap
335 inner-def
336 prefix1)))))
916cc49f 337 (if (vectorp (car scan))
7f2c2edd
RS
338 (let* ((array (car scan))
339 (len (length array))
340 (i 0))
341 (while (< i len)
342 (let ((char i) (defn (aref array i)))
343 ;; The inside of this let duplicates exactly
344 ;; the inside of the previous let.
345 (aset vec1 0 char)
346 (aset prefix1 (length prefix) char)
44d798af 347 (let (inner-def skipped)
7f2c2edd
RS
348 ;; Skip past menu-prompt.
349 (while (stringp (car-safe defn))
44d798af 350 (setq skipped (cons (car defn) skipped))
7f2c2edd 351 (setq defn (cdr defn)))
e025dddf
RS
352 (and (consp defn) (consp (car defn))
353 (setq defn (cdr defn)))
7f2c2edd
RS
354 (setq inner-def defn)
355 (while (and (symbolp inner-def)
356 (fboundp inner-def))
357 (setq inner-def (symbol-function inner-def)))
328a37ec
RS
358 (if (or (eq defn olddef)
359 (and (or (stringp defn) (vectorp defn))
360 (equal defn olddef)))
44d798af
RS
361 (define-key keymap prefix1
362 (nconc (nreverse skipped) newdef))
f14dbba7 363 (if (and (keymapp defn)
afd9831b
RS
364 (let ((elt (lookup-key keymap prefix1)))
365 (or (null elt)
366 (keymapp elt)))
f14dbba7
KH
367 (not (memq inner-def
368 key-substitution-in-progress)))
7f2c2edd
RS
369 (substitute-key-definition olddef newdef keymap
370 inner-def
371 prefix1)))))
97fd9abf
RS
372 (setq i (1+ i))))
373 (if (char-table-p (car scan))
374 (map-char-table
375 (function (lambda (char defn)
376 (let ()
377 ;; The inside of this let duplicates exactly
378 ;; the inside of the previous let,
379 ;; except that it uses set-char-table-range
380 ;; instead of define-key.
381 (aset vec1 0 char)
382 (aset prefix1 (length prefix) char)
383 (let (inner-def skipped)
384 ;; Skip past menu-prompt.
385 (while (stringp (car-safe defn))
386 (setq skipped (cons (car defn) skipped))
387 (setq defn (cdr defn)))
388 (and (consp defn) (consp (car defn))
389 (setq defn (cdr defn)))
390 (setq inner-def defn)
391 (while (and (symbolp inner-def)
392 (fboundp inner-def))
393 (setq inner-def (symbol-function inner-def)))
394 (if (or (eq defn olddef)
395 (and (or (stringp defn) (vectorp defn))
396 (equal defn olddef)))
9a5114ac
RS
397 (define-key keymap prefix1
398 (nconc (nreverse skipped) newdef))
97fd9abf
RS
399 (if (and (keymapp defn)
400 (let ((elt (lookup-key keymap prefix1)))
401 (or (null elt)
402 (keymapp elt)))
403 (not (memq inner-def
404 key-substitution-in-progress)))
405 (substitute-key-definition olddef newdef keymap
406 inner-def
407 prefix1)))))))
408 (car scan)))))
7f2c2edd 409 (setq scan (cdr scan)))))
9a5336ae 410
4ced66fd 411(defun define-key-after (keymap key definition &optional after)
4434d61b
RS
412 "Add binding in KEYMAP for KEY => DEFINITION, right after AFTER's binding.
413This is like `define-key' except that the binding for KEY is placed
414just after the binding for the event AFTER, instead of at the beginning
c34a9d34
RS
415of the map. Note that AFTER must be an event type (like KEY), NOT a command
416\(like DEFINITION).
417
4ced66fd 418If AFTER is t or omitted, the new binding goes at the end of the keymap.
08b1f8a1 419AFTER should be a single event type--a symbol or a character, not a sequence.
c34a9d34 420
4ced66fd 421Bindings are always added before any inherited map.
c34a9d34 422
4ced66fd
DL
423The order of bindings in a keymap matters when it is used as a menu."
424 (unless after (setq after t))
4434d61b
RS
425 (or (keymapp keymap)
426 (signal 'wrong-type-argument (list 'keymapp keymap)))
08b1f8a1
GM
427 (setq key
428 (if (<= (length key) 1) (aref key 0)
429 (setq keymap (lookup-key keymap
430 (apply 'vector
431 (butlast (mapcar 'identity key)))))
432 (aref key (1- (length key)))))
433 (let ((tail keymap) done inserted)
4434d61b
RS
434 (while (and (not done) tail)
435 ;; Delete any earlier bindings for the same key.
08b1f8a1 436 (if (eq (car-safe (car (cdr tail))) key)
4434d61b 437 (setcdr tail (cdr (cdr tail))))
08b1f8a1
GM
438 ;; If we hit an included map, go down that one.
439 (if (keymapp (car tail)) (setq tail (car tail)))
4434d61b
RS
440 ;; When we reach AFTER's binding, insert the new binding after.
441 ;; If we reach an inherited keymap, insert just before that.
113d28a8 442 ;; If we reach the end of this keymap, insert at the end.
c34a9d34
RS
443 (if (or (and (eq (car-safe (car tail)) after)
444 (not (eq after t)))
113d28a8
RS
445 (eq (car (cdr tail)) 'keymap)
446 (null (cdr tail)))
4434d61b 447 (progn
113d28a8
RS
448 ;; Stop the scan only if we find a parent keymap.
449 ;; Keep going past the inserted element
450 ;; so we can delete any duplications that come later.
451 (if (eq (car (cdr tail)) 'keymap)
452 (setq done t))
453 ;; Don't insert more than once.
454 (or inserted
08b1f8a1 455 (setcdr tail (cons (cons key definition) (cdr tail))))
113d28a8 456 (setq inserted t)))
4434d61b
RS
457 (setq tail (cdr tail)))))
458
51fa3961 459
d128fe85
RS
460(defmacro kbd (keys)
461 "Convert KEYS to the internal Emacs key representation.
462KEYS should be a string constant in the format used for
463saving keyboard macros (see `insert-kbd-macro')."
464 (read-kbd-macro keys))
465
8bed5e3d
RS
466(put 'keyboard-translate-table 'char-table-extra-slots 0)
467
9a5336ae
JB
468(defun keyboard-translate (from to)
469 "Translate character FROM to TO at a low level.
470This function creates a `keyboard-translate-table' if necessary
471and then modifies one entry in it."
8bed5e3d
RS
472 (or (char-table-p keyboard-translate-table)
473 (setq keyboard-translate-table
474 (make-char-table 'keyboard-translate-table nil)))
9a5336ae
JB
475 (aset keyboard-translate-table from to))
476
477\f
478;;;; The global keymap tree.
479
480;;; global-map, esc-map, and ctl-x-map have their values set up in
481;;; keymap.c; we just give them docstrings here.
482
483(defvar global-map nil
484 "Default global keymap mapping Emacs keyboard input into commands.
485The value is a keymap which is usually (but not necessarily) Emacs's
486global map.")
487
488(defvar esc-map nil
489 "Default keymap for ESC (meta) commands.
490The normal global definition of the character ESC indirects to this keymap.")
491
492(defvar ctl-x-map nil
493 "Default keymap for C-x commands.
494The normal global definition of the character C-x indirects to this keymap.")
495
496(defvar ctl-x-4-map (make-sparse-keymap)
03eeb110 497 "Keymap for subcommands of C-x 4.")
059184dd 498(defalias 'ctl-x-4-prefix ctl-x-4-map)
9a5336ae
JB
499(define-key ctl-x-map "4" 'ctl-x-4-prefix)
500
501(defvar ctl-x-5-map (make-sparse-keymap)
502 "Keymap for frame commands.")
059184dd 503(defalias 'ctl-x-5-prefix ctl-x-5-map)
9a5336ae
JB
504(define-key ctl-x-map "5" 'ctl-x-5-prefix)
505
0f03054a 506\f
9a5336ae
JB
507;;;; Event manipulation functions.
508
da16e648
KH
509;; The call to `read' is to ensure that the value is computed at load time
510;; and not compiled into the .elc file. The value is negative on most
511;; machines, but not on all!
512(defconst listify-key-sequence-1 (logior 128 (read "?\\M-\\^@")))
114137b8 513
cde6d7e3
RS
514(defun listify-key-sequence (key)
515 "Convert a key sequence to a list of events."
516 (if (vectorp key)
517 (append key nil)
518 (mapcar (function (lambda (c)
519 (if (> c 127)
114137b8 520 (logxor c listify-key-sequence-1)
cde6d7e3
RS
521 c)))
522 (append key nil))))
523
53e5a4e8
RS
524(defsubst eventp (obj)
525 "True if the argument is an event object."
526 (or (integerp obj)
527 (and (symbolp obj)
528 (get obj 'event-symbol-elements))
529 (and (consp obj)
530 (symbolp (car obj))
531 (get (car obj) 'event-symbol-elements))))
532
533(defun event-modifiers (event)
534 "Returns a list of symbols representing the modifier keys in event EVENT.
535The elements of the list may include `meta', `control',
32295976
RS
536`shift', `hyper', `super', `alt', `click', `double', `triple', `drag',
537and `down'."
53e5a4e8
RS
538 (let ((type event))
539 (if (listp type)
540 (setq type (car type)))
541 (if (symbolp type)
542 (cdr (get type 'event-symbol-elements))
543 (let ((list nil))
da16e648 544 (or (zerop (logand type ?\M-\^@))
53e5a4e8 545 (setq list (cons 'meta list)))
da16e648 546 (or (and (zerop (logand type ?\C-\^@))
53e5a4e8
RS
547 (>= (logand type 127) 32))
548 (setq list (cons 'control list)))
da16e648 549 (or (and (zerop (logand type ?\S-\^@))
53e5a4e8
RS
550 (= (logand type 255) (downcase (logand type 255))))
551 (setq list (cons 'shift list)))
da16e648 552 (or (zerop (logand type ?\H-\^@))
53e5a4e8 553 (setq list (cons 'hyper list)))
da16e648 554 (or (zerop (logand type ?\s-\^@))
53e5a4e8 555 (setq list (cons 'super list)))
da16e648 556 (or (zerop (logand type ?\A-\^@))
53e5a4e8
RS
557 (setq list (cons 'alt list)))
558 list))))
559
d63de416
RS
560(defun event-basic-type (event)
561 "Returns the basic type of the given event (all modifiers removed).
7a0485b2 562The value is a printing character (not upper case) or a symbol."
2b0f4ba5
JB
563 (if (consp event)
564 (setq event (car event)))
d63de416
RS
565 (if (symbolp event)
566 (car (get event 'event-symbol-elements))
567 (let ((base (logand event (1- (lsh 1 18)))))
568 (downcase (if (< base 32) (logior base 64) base)))))
569
0f03054a
RS
570(defsubst mouse-movement-p (object)
571 "Return non-nil if OBJECT is a mouse movement event."
572 (and (consp object)
573 (eq (car object) 'mouse-movement)))
574
575(defsubst event-start (event)
576 "Return the starting position of EVENT.
577If EVENT is a mouse press or a mouse click, this returns the location
578of the event.
579If EVENT is a drag, this returns the drag's starting position.
580The return value is of the form
e55c21be 581 (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
0f03054a
RS
582The `posn-' functions access elements of such lists."
583 (nth 1 event))
584
585(defsubst event-end (event)
586 "Return the ending location of EVENT. EVENT should be a click or drag event.
587If EVENT is a click event, this function is the same as `event-start'.
588The return value is of the form
e55c21be 589 (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
0f03054a 590The `posn-' functions access elements of such lists."
69b95560 591 (nth (if (consp (nth 2 event)) 2 1) event))
0f03054a 592
32295976
RS
593(defsubst event-click-count (event)
594 "Return the multi-click count of EVENT, a click or drag event.
595The return value is a positive integer."
596 (if (integerp (nth 2 event)) (nth 2 event) 1))
597
0f03054a
RS
598(defsubst posn-window (position)
599 "Return the window in POSITION.
600POSITION should be a list of the form
e55c21be 601 (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
0f03054a
RS
602as returned by the `event-start' and `event-end' functions."
603 (nth 0 position))
604
605(defsubst posn-point (position)
606 "Return the buffer location in POSITION.
607POSITION should be a list of the form
e55c21be 608 (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
0f03054a 609as returned by the `event-start' and `event-end' functions."
15db4e0e
JB
610 (if (consp (nth 1 position))
611 (car (nth 1 position))
612 (nth 1 position)))
0f03054a 613
e55c21be
RS
614(defsubst posn-x-y (position)
615 "Return the x and y coordinates in POSITION.
0f03054a 616POSITION should be a list of the form
e55c21be 617 (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
0f03054a
RS
618as returned by the `event-start' and `event-end' functions."
619 (nth 2 position))
620
ed627e08 621(defun posn-col-row (position)
dbbcac56 622 "Return the column and row in POSITION, measured in characters.
e55c21be
RS
623POSITION should be a list of the form
624 (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
ed627e08
RS
625as returned by the `event-start' and `event-end' functions.
626For a scroll-bar event, the result column is 0, and the row
627corresponds to the vertical position of the click in the scroll bar."
628 (let ((pair (nth 2 position))
629 (window (posn-window position)))
dbbcac56
KH
630 (if (eq (if (consp (nth 1 position))
631 (car (nth 1 position))
632 (nth 1 position))
ed627e08
RS
633 'vertical-scroll-bar)
634 (cons 0 (scroll-bar-scale pair (1- (window-height window))))
dbbcac56
KH
635 (if (eq (if (consp (nth 1 position))
636 (car (nth 1 position))
637 (nth 1 position))
ed627e08
RS
638 'horizontal-scroll-bar)
639 (cons (scroll-bar-scale pair (window-width window)) 0)
9ba60df9
RS
640 (let* ((frame (if (framep window) window (window-frame window)))
641 (x (/ (car pair) (frame-char-width frame)))
642 (y (/ (cdr pair) (frame-char-height frame))))
ed627e08 643 (cons x y))))))
e55c21be 644
0f03054a
RS
645(defsubst posn-timestamp (position)
646 "Return the timestamp of POSITION.
647POSITION should be a list of the form
e55c21be 648 (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
f415c00c 649as returned by the `event-start' and `event-end' functions."
0f03054a 650 (nth 3 position))
9a5336ae 651
0f03054a 652\f
9a5336ae
JB
653;;;; Obsolescent names for functions.
654
059184dd
ER
655(defalias 'dot 'point)
656(defalias 'dot-marker 'point-marker)
657(defalias 'dot-min 'point-min)
658(defalias 'dot-max 'point-max)
659(defalias 'window-dot 'window-point)
660(defalias 'set-window-dot 'set-window-point)
661(defalias 'read-input 'read-string)
662(defalias 'send-string 'process-send-string)
663(defalias 'send-region 'process-send-region)
664(defalias 'show-buffer 'set-window-buffer)
665(defalias 'buffer-flush-undo 'buffer-disable-undo)
666(defalias 'eval-current-buffer 'eval-buffer)
667(defalias 'compiled-function-p 'byte-code-function-p)
ae1cc031 668(defalias 'define-function 'defalias)
be9b65ac 669
0cba3a0f 670(defalias 'sref 'aref)
2598a293
SM
671(make-obsolete 'sref 'aref "20.4")
672(make-obsolete 'char-bytes "Now this function always returns 1" "20.4")
6bb762b3 673
676927b7
PJ
674(defun insert-string (&rest args)
675 "Mocklisp-compatibility insert function.
676Like the function `insert' except that any argument that is a number
677is converted into a string by expressing it in decimal."
678 (dolist (el args)
679 (insert (if (integerp el) (number-to-string el) el))))
680
681(make-obsolete 'insert-string 'insert "21.3")
682
9a5336ae
JB
683;; Some programs still use this as a function.
684(defun baud-rate ()
bcacc42c
RS
685 "Obsolete function returning the value of the `baud-rate' variable.
686Please convert your programs to use the variable `baud-rate' directly."
9a5336ae
JB
687 baud-rate)
688
0a5c0893
MB
689(defalias 'focus-frame 'ignore)
690(defalias 'unfocus-frame 'ignore)
9a5336ae
JB
691\f
692;;;; Alternate names for functions - these are not being phased out.
693
059184dd
ER
694(defalias 'string= 'string-equal)
695(defalias 'string< 'string-lessp)
696(defalias 'move-marker 'set-marker)
059184dd
ER
697(defalias 'rplaca 'setcar)
698(defalias 'rplacd 'setcdr)
eb8c3be9 699(defalias 'beep 'ding) ;preserve lingual purity
059184dd
ER
700(defalias 'indent-to-column 'indent-to)
701(defalias 'backward-delete-char 'delete-backward-char)
702(defalias 'search-forward-regexp (symbol-function 're-search-forward))
703(defalias 'search-backward-regexp (symbol-function 're-search-backward))
704(defalias 'int-to-string 'number-to-string)
024ae2c6 705(defalias 'store-match-data 'set-match-data)
d6c22d46 706;; These are the XEmacs names:
475fb2fb
KH
707(defalias 'point-at-eol 'line-end-position)
708(defalias 'point-at-bol 'line-beginning-position)
37f6661a
JB
709
710;;; Should this be an obsolete name? If you decide it should, you get
711;;; to go through all the sources and change them.
059184dd 712(defalias 'string-to-int 'string-to-number)
be9b65ac 713\f
9a5336ae 714;;;; Hook manipulation functions.
be9b65ac 715
0e4d378b
RS
716(defun make-local-hook (hook)
717 "Make the hook HOOK local to the current buffer.
71c78f01
RS
718The return value is HOOK.
719
c344cf32
SM
720You never need to call this function now that `add-hook' does it for you
721if its LOCAL argument is non-nil.
722
0e4d378b
RS
723When a hook is local, its local and global values
724work in concert: running the hook actually runs all the hook
725functions listed in *either* the local value *or* the global value
726of the hook variable.
727
08b1f8a1 728This function works by making t a member of the buffer-local value,
7dd1926e
RS
729which acts as a flag to run the hook functions in the default value as
730well. This works for all normal hooks, but does not work for most
731non-normal hooks yet. We will be changing the callers of non-normal
732hooks so that they can handle localness; this has to be done one by
733one.
734
735This function does nothing if HOOK is already local in the current
736buffer.
0e4d378b
RS
737
738Do not use `make-local-variable' to make a hook variable buffer-local."
739 (if (local-variable-p hook)
740 nil
741 (or (boundp hook) (set hook nil))
742 (make-local-variable hook)
71c78f01
RS
743 (set hook (list t)))
744 hook)
08b1f8a1 745(make-obsolete 'make-local-hook "Not necessary any more." "21.1")
0e4d378b
RS
746
747(defun add-hook (hook function &optional append local)
32295976
RS
748 "Add to the value of HOOK the function FUNCTION.
749FUNCTION is not added if already present.
750FUNCTION is added (if necessary) at the beginning of the hook list
751unless the optional argument APPEND is non-nil, in which case
752FUNCTION is added at the end.
753
0e4d378b
RS
754The optional fourth argument, LOCAL, if non-nil, says to modify
755the hook's buffer-local value rather than its default value.
61a3d8c4
RS
756This makes the hook buffer-local if needed, and it makes t a member
757of the buffer-local value. That acts as a flag to run the hook
758functions in the default value as well as in the local value.
0e4d378b 759
32295976
RS
760HOOK should be a symbol, and FUNCTION may be any valid function. If
761HOOK is void, it is first set to nil. If HOOK's value is a single
aa09b5ca 762function, it is changed to a list of functions."
be9b65ac 763 (or (boundp hook) (set hook nil))
0e4d378b 764 (or (default-boundp hook) (set-default hook nil))
08b1f8a1
GM
765 (if local (unless (local-variable-if-set-p hook)
766 (set (make-local-variable hook) (list t)))
8947a5e2
SM
767 ;; Detect the case where make-local-variable was used on a hook
768 ;; and do what we used to do.
769 (unless (and (consp (symbol-value hook)) (memq t (symbol-value hook)))
770 (setq local t)))
771 (let ((hook-value (if local (symbol-value hook) (default-value hook))))
772 ;; If the hook value is a single function, turn it into a list.
773 (when (or (not (listp hook-value)) (eq (car hook-value) 'lambda))
2248c40d 774 (setq hook-value (list hook-value)))
8947a5e2
SM
775 ;; Do the actual addition if necessary
776 (unless (member function hook-value)
777 (setq hook-value
778 (if append
779 (append hook-value (list function))
780 (cons function hook-value))))
781 ;; Set the actual variable
782 (if local (set hook hook-value) (set-default hook hook-value))))
0e4d378b
RS
783
784(defun remove-hook (hook function &optional local)
24980d16
RS
785 "Remove from the value of HOOK the function FUNCTION.
786HOOK should be a symbol, and FUNCTION may be any valid function. If
787FUNCTION isn't the value of HOOK, or, if FUNCTION doesn't appear in the
0e4d378b
RS
788list of hooks to run in HOOK, then nothing is done. See `add-hook'.
789
790The optional third argument, LOCAL, if non-nil, says to modify
791the hook's buffer-local value rather than its default value.
08b1f8a1 792This makes the hook buffer-local if needed."
8947a5e2
SM
793 (or (boundp hook) (set hook nil))
794 (or (default-boundp hook) (set-default hook nil))
08b1f8a1
GM
795 (if local (unless (local-variable-if-set-p hook)
796 (set (make-local-variable hook) (list t)))
8947a5e2
SM
797 ;; Detect the case where make-local-variable was used on a hook
798 ;; and do what we used to do.
799 (unless (and (consp (symbol-value hook)) (memq t (symbol-value hook)))
800 (setq local t)))
801 (let ((hook-value (if local (symbol-value hook) (default-value hook))))
e4da9c1c
SM
802 ;; Remove the function, for both the list and the non-list cases.
803 (if (or (not (listp hook-value)) (eq (car hook-value) 'lambda))
804 (if (equal hook-value function) (setq hook-value nil))
805 (setq hook-value (delete function (copy-sequence hook-value))))
8947a5e2
SM
806 ;; If the function is on the global hook, we need to shadow it locally
807 ;;(when (and local (member function (default-value hook))
808 ;; (not (member (cons 'not function) hook-value)))
809 ;; (push (cons 'not function) hook-value))
810 ;; Set the actual variable
1087f3e6
RS
811 (if (not local)
812 (set-default hook hook-value)
813 (if (equal hook-value '(t))
814 (kill-local-variable hook)
815 (set hook hook-value)))))
6e3af630 816
c8bfa689 817(defun add-to-list (list-var element &optional append)
8851c1f0 818 "Add to the value of LIST-VAR the element ELEMENT if it isn't there yet.
9f0b1f09 819The test for presence of ELEMENT is done with `equal'.
c8bfa689
MB
820If ELEMENT is added, it is added at the beginning of the list,
821unless the optional argument APPEND is non-nil, in which case
822ELEMENT is added at the end.
508bcbca 823
daebae3d
PJ
824The return value is the new value of LIST-VAR.
825
8851c1f0
RS
826If you want to use `add-to-list' on a variable that is not defined
827until a certain package is loaded, you should put the call to `add-to-list'
828into a hook function that will be run only after loading the package.
829`eval-after-load' provides one way to do this. In some cases
830other hooks, such as major mode hooks, can do the job."
15171a06
KH
831 (if (member element (symbol-value list-var))
832 (symbol-value list-var)
c8bfa689
MB
833 (set list-var
834 (if append
835 (append (symbol-value list-var) (list element))
836 (cons element (symbol-value list-var))))))
448a0170
MB
837
838\f
839;;; Load history
840
841(defvar symbol-file-load-history-loaded nil
842 "Non-nil means we have loaded the file `fns-VERSION.el' in `exec-directory'.
843That file records the part of `load-history' for preloaded files,
844which is cleared out before dumping to make Emacs smaller.")
845
846(defun load-symbol-file-load-history ()
847 "Load the file `fns-VERSION.el' in `exec-directory' if not already done.
848That file records the part of `load-history' for preloaded files,
849which is cleared out before dumping to make Emacs smaller."
850 (unless symbol-file-load-history-loaded
851 (load (expand-file-name
852 ;; fns-XX.YY.ZZ.el does not work on DOS filesystem.
853 (if (eq system-type 'ms-dos)
854 "fns.el"
855 (format "fns-%s.el" emacs-version))
856 exec-directory)
857 ;; The file name fns-%s.el already has a .el extension.
858 nil nil t)
859 (setq symbol-file-load-history-loaded t)))
860
861(defun symbol-file (function)
862 "Return the input source from which FUNCTION was loaded.
863The value is normally a string that was passed to `load':
864either an absolute file name, or a library name
865\(with no directory name and no `.el' or `.elc' at the end).
866It can also be nil, if the definition is not associated with any file."
867 (load-symbol-file-load-history)
868 (let ((files load-history)
869 file functions)
870 (while files
871 (if (memq function (cdr (car files)))
872 (setq file (car (car files)) files nil))
873 (setq files (cdr files)))
874 file))
875
be9b65ac 876\f
9a5336ae
JB
877;;;; Specifying things to do after certain files are loaded.
878
879(defun eval-after-load (file form)
880 "Arrange that, if FILE is ever loaded, FORM will be run at that time.
881This makes or adds to an entry on `after-load-alist'.
90914938 882If FILE is already loaded, evaluate FORM right now.
12c7071c 883It does nothing if FORM is already on the list for FILE.
19594307
DL
884FILE must match exactly. Normally FILE is the name of a library,
885with no directory or extension specified, since that is how `load'
a2d7836f
SM
886is normally called.
887FILE can also be a feature (i.e. a symbol), in which case FORM is
888evaluated whenever that feature is `provide'd."
12c7071c 889 (let ((elt (assoc file after-load-alist)))
a2d7836f
SM
890 ;; Make sure there is an element for FILE.
891 (unless elt (setq elt (list file)) (push elt after-load-alist))
892 ;; Add FORM to the element if it isn't there.
893 (unless (member form (cdr elt))
894 (nconc elt (list form))
895 ;; If the file has been loaded already, run FORM right away.
896 (if (if (symbolp file)
897 (featurep file)
898 ;; Make sure `load-history' contains the files dumped with
899 ;; Emacs for the case that FILE is one of them.
900 (load-symbol-file-load-history)
901 (assoc file load-history))
902 (eval form))))
9a5336ae
JB
903 form)
904
905(defun eval-next-after-load (file)
906 "Read the following input sexp, and run it whenever FILE is loaded.
907This makes or adds to an entry on `after-load-alist'.
908FILE should be the name of a library, with no directory name."
909 (eval-after-load file (read)))
910
911\f
912;;;; Input and display facilities.
913
77a5664f 914(defvar read-quoted-char-radix 8
1ba764de 915 "*Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
77a5664f
RS
916Legitimate radix values are 8, 10 and 16.")
917
918(custom-declare-variable-early
919 'read-quoted-char-radix 8
920 "*Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
1ba764de
RS
921Legitimate radix values are 8, 10 and 16."
922 :type '(choice (const 8) (const 10) (const 16))
923 :group 'editing-basics)
924
9a5336ae 925(defun read-quoted-char (&optional prompt)
2444730b
RS
926 "Like `read-char', but do not allow quitting.
927Also, if the first character read is an octal digit,
928we read any number of octal digits and return the
569b03f2 929specified character code. Any nondigit terminates the sequence.
1ba764de 930If the terminator is RET, it is discarded;
2444730b
RS
931any other terminator is used itself as input.
932
569b03f2
RS
933The optional argument PROMPT specifies a string to use to prompt the user.
934The variable `read-quoted-char-radix' controls which radix to use
935for numeric input."
2444730b
RS
936 (let ((message-log-max nil) done (first t) (code 0) char)
937 (while (not done)
938 (let ((inhibit-quit first)
42e636f0
KH
939 ;; Don't let C-h get the help message--only help function keys.
940 (help-char nil)
941 (help-form
942 "Type the special character you want to use,
2444730b 943or the octal character code.
1ba764de 944RET terminates the character code and is discarded;
2444730b 945any other non-digit terminates the character code and is then used as input."))
b7de4d62 946 (setq char (read-event (and prompt (format "%s-" prompt)) t))
9a5336ae 947 (if inhibit-quit (setq quit-flag nil)))
4867f7b2
RS
948 ;; Translate TAB key into control-I ASCII character, and so on.
949 (and char
950 (let ((translated (lookup-key function-key-map (vector char))))
bf896a1b 951 (if (arrayp translated)
4867f7b2 952 (setq char (aref translated 0)))))
9a5336ae 953 (cond ((null char))
1ba764de
RS
954 ((not (integerp char))
955 (setq unread-command-events (list char)
956 done t))
bf896a1b
RS
957 ((/= (logand char ?\M-\^@) 0)
958 ;; Turn a meta-character into a character with the 0200 bit set.
959 (setq code (logior (logand char (lognot ?\M-\^@)) 128)
960 done t))
1ba764de
RS
961 ((and (<= ?0 char) (< char (+ ?0 (min 10 read-quoted-char-radix))))
962 (setq code (+ (* code read-quoted-char-radix) (- char ?0)))
963 (and prompt (setq prompt (message "%s %c" prompt char))))
964 ((and (<= ?a (downcase char))
965 (< (downcase char) (+ ?a -10 (min 26 read-quoted-char-radix))))
92304bc8
RS
966 (setq code (+ (* code read-quoted-char-radix)
967 (+ 10 (- (downcase char) ?a))))
91a6acc3 968 (and prompt (setq prompt (message "%s %c" prompt char))))
1ba764de 969 ((and (not first) (eq char ?\C-m))
2444730b
RS
970 (setq done t))
971 ((not first)
972 (setq unread-command-events (list char)
973 done t))
974 (t (setq code char
975 done t)))
976 (setq first nil))
bf896a1b 977 code))
9a5336ae 978
44071d6b
RS
979(defun read-passwd (prompt &optional confirm default)
980 "Read a password, prompting with PROMPT. Echo `.' for each character typed.
e0e4cb7a 981End with RET, LFD, or ESC. DEL or C-h rubs out. C-u kills line.
44071d6b
RS
982Optional argument CONFIRM, if non-nil, then read it twice to make sure.
983Optional DEFAULT is a default password to use instead of empty input."
984 (if confirm
985 (let (success)
986 (while (not success)
987 (let ((first (read-passwd prompt nil default))
988 (second (read-passwd "Confirm password: " nil default)))
989 (if (equal first second)
fe10cef0
GM
990 (progn
991 (and (arrayp second) (fillarray second ?\0))
992 (setq success first))
993 (and (arrayp first) (fillarray first ?\0))
994 (and (arrayp second) (fillarray second ?\0))
44071d6b
RS
995 (message "Password not repeated accurately; please start over")
996 (sit-for 1))))
997 success)
998 (let ((pass nil)
999 (c 0)
1000 (echo-keystrokes 0)
1001 (cursor-in-echo-area t))
1002 (while (progn (message "%s%s"
1003 prompt
1004 (make-string (length pass) ?.))
42ccb7c8 1005 (setq c (read-char-exclusive nil t))
44071d6b 1006 (and (/= c ?\r) (/= c ?\n) (/= c ?\e)))
719349f6 1007 (clear-this-command-keys)
44071d6b 1008 (if (= c ?\C-u)
fe10cef0
GM
1009 (progn
1010 (and (arrayp pass) (fillarray pass ?\0))
1011 (setq pass ""))
44071d6b 1012 (if (and (/= c ?\b) (/= c ?\177))
fe10cef0
GM
1013 (let* ((new-char (char-to-string c))
1014 (new-pass (concat pass new-char)))
1015 (and (arrayp pass) (fillarray pass ?\0))
1016 (fillarray new-char ?\0)
1017 (setq c ?\0)
1018 (setq pass new-pass))
44071d6b 1019 (if (> (length pass) 0)
fe10cef0
GM
1020 (let ((new-pass (substring pass 0 -1)))
1021 (and (arrayp pass) (fillarray pass ?\0))
1022 (setq pass new-pass))))))
44071d6b
RS
1023 (message nil)
1024 (or pass default ""))))
e0e4cb7a 1025\f
69cae2d4
RS
1026(defmacro atomic-change-group (&rest body)
1027 "Perform BODY as an atomic change group.
1028This means that if BODY exits abnormally,
1029all of its changes to the current buffer are undone.
1030This works regadless of whether undo is enabled in the buffer.
1031
1032This mechanism is transparent to ordinary use of undo;
1033if undo is enabled in the buffer and BODY succeeds, the
1034user can undo the change normally."
1035 (let ((handle (make-symbol "--change-group-handle--"))
1036 (success (make-symbol "--change-group-success--")))
1037 `(let ((,handle (prepare-change-group))
1038 (,success nil))
1039 (unwind-protect
1040 (progn
1041 ;; This is inside the unwind-protect because
1042 ;; it enables undo if that was disabled; we need
1043 ;; to make sure that it gets disabled again.
1044 (activate-change-group ,handle)
1045 ,@body
1046 (setq ,success t))
1047 ;; Either of these functions will disable undo
1048 ;; if it was disabled before.
1049 (if ,success
1050 (accept-change-group ,handle)
1051 (cancel-change-group ,handle))))))
1052
1053(defun prepare-change-group (&optional buffer)
1054 "Return a handle for the current buffer's state, for a change group.
1055If you specify BUFFER, make a handle for BUFFER's state instead.
1056
1057Pass the handle to `activate-change-group' afterward to initiate
1058the actual changes of the change group.
1059
1060To finish the change group, call either `accept-change-group' or
1061`cancel-change-group' passing the same handle as argument. Call
1062`accept-change-group' to accept the changes in the group as final;
1063call `cancel-change-group' to undo them all. You should use
1064`unwind-protect' to make sure the group is always finished. The call
1065to `activate-change-group' should be inside the `unwind-protect'.
1066Once you finish the group, don't use the handle again--don't try to
1067finish the same group twice. For a simple example of correct use, see
1068the source code of `atomic-change-group'.
1069
1070The handle records only the specified buffer. To make a multibuffer
1071change group, call this function once for each buffer you want to
1072cover, then use `nconc' to combine the returned values, like this:
1073
1074 (nconc (prepare-change-group buffer-1)
1075 (prepare-change-group buffer-2))
1076
1077You can then activate that multibuffer change group with a single
1078call to `activate-change-group' and finish it with a single call
1079to `accept-change-group' or `cancel-change-group'."
1080
1081 (list (cons (current-buffer) buffer-undo-list)))
1082
1083(defun activate-change-group (handle)
1084 "Activate a change group made with `prepare-change-group' (which see)."
1085 (dolist (elt handle)
1086 (with-current-buffer (car elt)
1087 (if (eq buffer-undo-list t)
1088 (setq buffer-undo-list nil)))))
1089
1090(defun accept-change-group (handle)
1091 "Finish a change group made with `prepare-change-group' (which see).
1092This finishes the change group by accepting its changes as final."
1093 (dolist (elt handle)
1094 (with-current-buffer (car elt)
1095 (if (eq elt t)
1096 (setq buffer-undo-list t)))))
1097
1098(defun cancel-change-group (handle)
1099 "Finish a change group made with `prepare-change-group' (which see).
1100This finishes the change group by reverting all of its changes."
1101 (dolist (elt handle)
1102 (with-current-buffer (car elt)
1103 (setq elt (cdr elt))
1104 (let ((old-car
1105 (if (consp elt) (car elt)))
1106 (old-cdr
1107 (if (consp elt) (cdr elt))))
1108 ;; Temporarily truncate the undo log at ELT.
1109 (when (consp elt)
1110 (setcar elt nil) (setcdr elt nil))
1111 (unless (eq last-command 'undo) (undo-start))
1112 ;; Make sure there's no confusion.
1113 (when (and (consp elt) (not (eq elt (last pending-undo-list))))
1114 (error "Undoing to some unrelated state"))
1115 ;; Undo it all.
1116 (while pending-undo-list (undo-more 1))
1117 ;; Reset the modified cons cell ELT to its original content.
1118 (when (consp elt)
1119 (setcar elt old-car)
1120 (setcdr elt old-cdr))
1121 ;; Revert the undo info to what it was when we grabbed the state.
1122 (setq buffer-undo-list elt)))))
1123\f
a9d956be
RS
1124;; For compatibility.
1125(defalias 'redraw-modeline 'force-mode-line-update)
1126
9a5336ae 1127(defun force-mode-line-update (&optional all)
dc756612
RS
1128 "Force the mode line of the current buffer to be redisplayed.
1129With optional non-nil ALL, force redisplay of all mode lines."
9a5336ae
JB
1130 (if all (save-excursion (set-buffer (other-buffer))))
1131 (set-buffer-modified-p (buffer-modified-p)))
1132
aa3b4ded 1133(defun momentary-string-display (string pos &optional exit-char message)
be9b65ac
DL
1134 "Momentarily display STRING in the buffer at POS.
1135Display remains until next character is typed.
1136If the char is EXIT-CHAR (optional third arg, default is SPC) it is swallowed;
1137otherwise it is then available as input (as a command if nothing else).
1138Display MESSAGE (optional fourth arg) in the echo area.
1139If MESSAGE is nil, instructions to type EXIT-CHAR are displayed there."
1140 (or exit-char (setq exit-char ?\ ))
c306e0e0 1141 (let ((inhibit-read-only t)
ca2ec1c5
RS
1142 ;; Don't modify the undo list at all.
1143 (buffer-undo-list t)
be9b65ac
DL
1144 (modified (buffer-modified-p))
1145 (name buffer-file-name)
1146 insert-end)
1147 (unwind-protect
1148 (progn
1149 (save-excursion
1150 (goto-char pos)
1151 ;; defeat file locking... don't try this at home, kids!
1152 (setq buffer-file-name nil)
1153 (insert-before-markers string)
3eec84bf
RS
1154 (setq insert-end (point))
1155 ;; If the message end is off screen, recenter now.
024ae2c6 1156 (if (< (window-end nil t) insert-end)
3eec84bf
RS
1157 (recenter (/ (window-height) 2)))
1158 ;; If that pushed message start off the screen,
1159 ;; scroll to start it at the top of the screen.
1160 (move-to-window-line 0)
1161 (if (> (point) pos)
1162 (progn
1163 (goto-char pos)
1164 (recenter 0))))
be9b65ac
DL
1165 (message (or message "Type %s to continue editing.")
1166 (single-key-description exit-char))
3547c855 1167 (let ((char (read-event)))
be9b65ac 1168 (or (eq char exit-char)
dbc4e1c1 1169 (setq unread-command-events (list char)))))
be9b65ac
DL
1170 (if insert-end
1171 (save-excursion
1172 (delete-region pos insert-end)))
1173 (setq buffer-file-name name)
1174 (set-buffer-modified-p modified))))
1175
9a5336ae 1176\f
aa3b4ded
SM
1177;;;; Overlay operations
1178
1179(defun copy-overlay (o)
1180 "Return a copy of overlay O."
1181 (let ((o1 (make-overlay (overlay-start o) (overlay-end o)
1182 ;; FIXME: there's no easy way to find the
1183 ;; insertion-type of the two markers.
1184 (overlay-buffer o)))
1185 (props (overlay-properties o)))
1186 (while props
1187 (overlay-put o1 (pop props) (pop props)))
1188 o1))
1189
1190(defun remove-overlays (beg end name val)
1191 "Clear BEG and END of overlays whose property NAME has value VAL.
1192Overlays might be moved and or split."
1193 (if (< end beg)
1194 (setq beg (prog1 end (setq end beg))))
1195 (save-excursion
1196 (dolist (o (overlays-in beg end))
1197 (when (eq (overlay-get o name) val)
1198 ;; Either push this overlay outside beg...end
1199 ;; or split it to exclude beg...end
1200 ;; or delete it entirely (if it is contained in beg...end).
1201 (if (< (overlay-start o) beg)
1202 (if (> (overlay-end o) end)
1203 (progn
1204 (move-overlay (copy-overlay o)
1205 (overlay-start o) beg)
1206 (move-overlay o end (overlay-end o)))
1207 (move-overlay o (overlay-start o) beg))
1208 (if (> (overlay-end o) end)
1209 (move-overlay o end (overlay-end o))
1210 (delete-overlay o)))))))
c5802acf 1211\f
9a5336ae
JB
1212;;;; Miscellanea.
1213
448b61c9
RS
1214;; A number of major modes set this locally.
1215;; Give it a global value to avoid compiler warnings.
1216(defvar font-lock-defaults nil)
1217
4fb17037
RS
1218(defvar suspend-hook nil
1219 "Normal hook run by `suspend-emacs', before suspending.")
1220
1221(defvar suspend-resume-hook nil
1222 "Normal hook run by `suspend-emacs', after Emacs is continued.")
1223
784bc7cd
RS
1224(defvar temp-buffer-show-hook nil
1225 "Normal hook run by `with-output-to-temp-buffer' after displaying the buffer.
1226When the hook runs, the temporary buffer is current, and the window it
1227was displayed in is selected. This hook is normally set up with a
1228function to make the buffer read only, and find function names and
1229variable names in it, provided the major mode is still Help mode.")
1230
1231(defvar temp-buffer-setup-hook nil
1232 "Normal hook run by `with-output-to-temp-buffer' at the start.
1233When the hook runs, the temporary buffer is current.
1234This hook is normally set up with a function to put the buffer in Help
1235mode.")
1236
448b61c9
RS
1237;; Avoid compiler warnings about this variable,
1238;; which has a special meaning on certain system types.
1239(defvar buffer-file-type nil
1240 "Non-nil if the visited file is a binary file.
1241This variable is meaningful on MS-DOG and Windows NT.
1242On those systems, it is automatically local in every buffer.
1243On other systems, this variable is normally always nil.")
1244
a860d25f 1245;; This should probably be written in C (i.e., without using `walk-windows').
63503b24 1246(defun get-buffer-window-list (buffer &optional minibuf frame)
a860d25f 1247 "Return windows currently displaying BUFFER, or nil if none.
63503b24 1248See `walk-windows' for the meaning of MINIBUF and FRAME."
43c5ac8c 1249 (let ((buffer (if (bufferp buffer) buffer (get-buffer buffer))) windows)
a860d25f
SM
1250 (walk-windows (function (lambda (window)
1251 (if (eq (window-buffer window) buffer)
1252 (setq windows (cons window windows)))))
63503b24 1253 minibuf frame)
a860d25f
SM
1254 windows))
1255
f9269e19
RS
1256(defun ignore (&rest ignore)
1257 "Do nothing and return nil.
1258This function accepts any number of arguments, but ignores them."
c0f1a4f6 1259 (interactive)
9a5336ae
JB
1260 nil)
1261
1262(defun error (&rest args)
aa308ce2
RS
1263 "Signal an error, making error message by passing all args to `format'.
1264In Emacs, the convention is that error messages start with a capital
1265letter but *do not* end with a period. Please follow this convention
1266for the sake of consistency."
9a5336ae
JB
1267 (while t
1268 (signal 'error (list (apply 'format args)))))
1269
cef7ae6e 1270(defalias 'user-original-login-name 'user-login-name)
9a5336ae 1271
be9b65ac
DL
1272(defun start-process-shell-command (name buffer &rest args)
1273 "Start a program in a subprocess. Return the process object for it.
1274Args are NAME BUFFER COMMAND &rest COMMAND-ARGS.
1275NAME is name for process. It is modified if necessary to make it unique.
1276BUFFER is the buffer or (buffer-name) to associate with the process.
1277 Process output goes at end of that buffer, unless you specify
1278 an output stream or filter function to handle the output.
1279 BUFFER may be also nil, meaning that this process is not associated
1280 with any buffer
1281Third arg is command name, the name of a shell command.
1282Remaining arguments are the arguments for the command.
4f1d6310 1283Wildcards and redirection are handled as usual in the shell."
a247bf21
KH
1284 (cond
1285 ((eq system-type 'vax-vms)
1286 (apply 'start-process name buffer args))
b59f6d7a
RS
1287 ;; We used to use `exec' to replace the shell with the command,
1288 ;; but that failed to handle (...) and semicolon, etc.
a247bf21
KH
1289 (t
1290 (start-process name buffer shell-file-name shell-command-switch
b59f6d7a 1291 (mapconcat 'identity args " ")))))
93aca633
MB
1292
1293(defun call-process-shell-command (command &optional infile buffer display
1294 &rest args)
1295 "Execute the shell command COMMAND synchronously in separate process.
1296The remaining arguments are optional.
1297The program's input comes from file INFILE (nil means `/dev/null').
1298Insert output in BUFFER before point; t means current buffer;
1299 nil for BUFFER means discard it; 0 means discard and don't wait.
1300BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,
1301REAL-BUFFER says what to do with standard output, as above,
1302while STDERR-FILE says what to do with standard error in the child.
1303STDERR-FILE may be nil (discard standard error output),
1304t (mix it with ordinary output), or a file name string.
1305
1306Fourth arg DISPLAY non-nil means redisplay buffer as output is inserted.
1307Remaining arguments are strings passed as additional arguments for COMMAND.
1308Wildcards and redirection are handled as usual in the shell.
1309
1310If BUFFER is 0, `call-process-shell-command' returns immediately with value nil.
1311Otherwise it waits for COMMAND to terminate and returns a numeric exit
1312status or a signal description string.
1313If you quit, the process is killed with SIGINT, or SIGKILL if you quit again."
1314 (cond
1315 ((eq system-type 'vax-vms)
1316 (apply 'call-process command infile buffer display args))
1317 ;; We used to use `exec' to replace the shell with the command,
1318 ;; but that failed to handle (...) and semicolon, etc.
1319 (t
1320 (call-process shell-file-name
1321 infile buffer display
1322 shell-command-switch
1323 (mapconcat 'identity (cons command args) " ")))))
a7ed4c2a 1324\f
a7f284ec
RS
1325(defmacro with-current-buffer (buffer &rest body)
1326 "Execute the forms in BODY with BUFFER as the current buffer.
a2fdb55c
EN
1327The value returned is the value of the last form in BODY.
1328See also `with-temp-buffer'."
ce87039d
SM
1329 (cons 'save-current-buffer
1330 (cons (list 'set-buffer buffer)
1331 body)))
a7f284ec 1332
e5bb8a8c
SM
1333(defmacro with-temp-file (file &rest body)
1334 "Create a new buffer, evaluate BODY there, and write the buffer to FILE.
1335The value returned is the value of the last form in BODY.
a2fdb55c 1336See also `with-temp-buffer'."
a7ed4c2a 1337 (let ((temp-file (make-symbol "temp-file"))
a2fdb55c
EN
1338 (temp-buffer (make-symbol "temp-buffer")))
1339 `(let ((,temp-file ,file)
1340 (,temp-buffer
1341 (get-buffer-create (generate-new-buffer-name " *temp file*"))))
1342 (unwind-protect
1343 (prog1
1344 (with-current-buffer ,temp-buffer
e5bb8a8c 1345 ,@body)
a2fdb55c
EN
1346 (with-current-buffer ,temp-buffer
1347 (widen)
1348 (write-region (point-min) (point-max) ,temp-file nil 0)))
1349 (and (buffer-name ,temp-buffer)
1350 (kill-buffer ,temp-buffer))))))
1351
e5bb8a8c 1352(defmacro with-temp-message (message &rest body)
a600effe 1353 "Display MESSAGE temporarily if non-nil while BODY is evaluated.
e5bb8a8c
SM
1354The original message is restored to the echo area after BODY has finished.
1355The value returned is the value of the last form in BODY.
a600effe
SM
1356MESSAGE is written to the message log buffer if `message-log-max' is non-nil.
1357If MESSAGE is nil, the echo area and message log buffer are unchanged.
1358Use a MESSAGE of \"\" to temporarily clear the echo area."
110201c8
SM
1359 (let ((current-message (make-symbol "current-message"))
1360 (temp-message (make-symbol "with-temp-message")))
1361 `(let ((,temp-message ,message)
1362 (,current-message))
e5bb8a8c
SM
1363 (unwind-protect
1364 (progn
110201c8
SM
1365 (when ,temp-message
1366 (setq ,current-message (current-message))
aadf7ff3 1367 (message "%s" ,temp-message))
e5bb8a8c 1368 ,@body)
cad84646
RS
1369 (and ,temp-message
1370 (if ,current-message
1371 (message "%s" ,current-message)
1372 (message nil)))))))
e5bb8a8c
SM
1373
1374(defmacro with-temp-buffer (&rest body)
1375 "Create a temporary buffer, and evaluate BODY there like `progn'.
a2fdb55c
EN
1376See also `with-temp-file' and `with-output-to-string'."
1377 (let ((temp-buffer (make-symbol "temp-buffer")))
1378 `(let ((,temp-buffer
1379 (get-buffer-create (generate-new-buffer-name " *temp*"))))
1380 (unwind-protect
1381 (with-current-buffer ,temp-buffer
e5bb8a8c 1382 ,@body)
a2fdb55c
EN
1383 (and (buffer-name ,temp-buffer)
1384 (kill-buffer ,temp-buffer))))))
1385
5db7925d
RS
1386(defmacro with-output-to-string (&rest body)
1387 "Execute BODY, return the text it sent to `standard-output', as a string."
a2fdb55c
EN
1388 `(let ((standard-output
1389 (get-buffer-create (generate-new-buffer-name " *string-output*"))))
5db7925d
RS
1390 (let ((standard-output standard-output))
1391 ,@body)
a2fdb55c
EN
1392 (with-current-buffer standard-output
1393 (prog1
1394 (buffer-string)
1395 (kill-buffer nil)))))
2ec9c94e 1396
0764e16f
SM
1397(defmacro with-local-quit (&rest body)
1398 "Execute BODY with `inhibit-quit' temporarily bound to nil."
1399 `(condition-case nil
1400 (let ((inhibit-quit nil))
1401 ,@body)
1402 (quit (setq quit-flag t))))
1403
2ec9c94e
RS
1404(defmacro combine-after-change-calls (&rest body)
1405 "Execute BODY, but don't call the after-change functions till the end.
1406If BODY makes changes in the buffer, they are recorded
1407and the functions on `after-change-functions' are called several times
1408when BODY is finished.
31aa282e 1409The return value is the value of the last form in BODY.
2ec9c94e
RS
1410
1411If `before-change-functions' is non-nil, then calls to the after-change
1412functions can't be deferred, so in that case this macro has no effect.
1413
1414Do not alter `after-change-functions' or `before-change-functions'
1415in BODY."
1416 `(unwind-protect
1417 (let ((combine-after-change-calls t))
1418 . ,body)
1419 (combine-after-change-execute)))
1420
c834b52c 1421
a13fe4c5
SM
1422(defvar delay-mode-hooks nil
1423 "If non-nil, `run-mode-hooks' should delay running the hooks.")
1424(defvar delayed-mode-hooks nil
1425 "List of delayed mode hooks waiting to be run.")
1426(make-variable-buffer-local 'delayed-mode-hooks)
1427
1428(defun run-mode-hooks (&rest hooks)
1429 "Run mode hooks `delayed-mode-hooks' and HOOKS, or delay HOOKS.
1430Execution is delayed if `delay-mode-hooks' is non-nil.
1431Major mode functions should use this."
1432 (if delay-mode-hooks
1433 ;; Delaying case.
1434 (dolist (hook hooks)
1435 (push hook delayed-mode-hooks))
1436 ;; Normal case, just run the hook as before plus any delayed hooks.
1437 (setq hooks (nconc (nreverse delayed-mode-hooks) hooks))
1438 (setq delayed-mode-hooks nil)
1439 (apply 'run-hooks hooks)))
1440
1441(defmacro delay-mode-hooks (&rest body)
1442 "Execute BODY, but delay any `run-mode-hooks'.
1443Only affects hooks run in the current buffer."
1444 `(progn
1445 (make-local-variable 'delay-mode-hooks)
1446 (let ((delay-mode-hooks t))
1447 ,@body)))
1448
31ca596b
RS
1449;; PUBLIC: find if the current mode derives from another.
1450
1451(defun derived-mode-p (&rest modes)
1452 "Non-nil if the current major mode is derived from one of MODES.
1453Uses the `derived-mode-parent' property of the symbol to trace backwards."
1454 (let ((parent major-mode))
1455 (while (and (not (memq parent modes))
1456 (setq parent (get parent 'derived-mode-parent))))
1457 parent))
1458
7e8539cc
RS
1459(defmacro with-syntax-table (table &rest body)
1460 "Evaluate BODY with syntax table of current buffer set to a copy of TABLE.
1461The syntax table of the current buffer is saved, BODY is evaluated, and the
1462saved table is restored, even in case of an abnormal exit.
1463Value is what BODY returns."
b3f07093
RS
1464 (let ((old-table (make-symbol "table"))
1465 (old-buffer (make-symbol "buffer")))
7e8539cc
RS
1466 `(let ((,old-table (syntax-table))
1467 (,old-buffer (current-buffer)))
1468 (unwind-protect
1469 (progn
1470 (set-syntax-table (copy-syntax-table ,table))
1471 ,@body)
1472 (save-current-buffer
1473 (set-buffer ,old-buffer)
1474 (set-syntax-table ,old-table))))))
a2fdb55c 1475\f
c7ca41e6
RS
1476(defvar save-match-data-internal)
1477
1478;; We use save-match-data-internal as the local variable because
1479;; that works ok in practice (people should not use that variable elsewhere).
1480;; We used to use an uninterned symbol; the compiler handles that properly
1481;; now, but it generates slower code.
9a5336ae 1482(defmacro save-match-data (&rest body)
e4d03691
JB
1483 "Execute the BODY forms, restoring the global value of the match data.
1484The value returned is the value of the last form in BODY."
64ed733a
PE
1485 ;; It is better not to use backquote here,
1486 ;; because that makes a bootstrapping problem
1487 ;; if you need to recompile all the Lisp files using interpreted code.
1488 (list 'let
1489 '((save-match-data-internal (match-data)))
1490 (list 'unwind-protect
1491 (cons 'progn body)
1492 '(set-match-data save-match-data-internal))))
993713ce 1493
cd323f89 1494(defun match-string (num &optional string)
993713ce
SM
1495 "Return string of text matched by last search.
1496NUM specifies which parenthesized expression in the last regexp.
1497 Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
1498Zero means the entire text matched by the whole regexp or whole string.
1499STRING should be given if the last search was by `string-match' on STRING."
cd323f89
SM
1500 (if (match-beginning num)
1501 (if string
1502 (substring string (match-beginning num) (match-end num))
1503 (buffer-substring (match-beginning num) (match-end num)))))
58f950b4 1504
bb760c71
RS
1505(defun match-string-no-properties (num &optional string)
1506 "Return string of text matched by last search, without text properties.
1507NUM specifies which parenthesized expression in the last regexp.
1508 Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
1509Zero means the entire text matched by the whole regexp or whole string.
1510STRING should be given if the last search was by `string-match' on STRING."
1511 (if (match-beginning num)
1512 (if string
1513 (let ((result
1514 (substring string (match-beginning num) (match-end num))))
1515 (set-text-properties 0 (length result) nil result)
1516 result)
1517 (buffer-substring-no-properties (match-beginning num)
1518 (match-end num)))))
1519
edce3654
RS
1520(defun split-string (string &optional separators)
1521 "Splits STRING into substrings where there are matches for SEPARATORS.
1522Each match for SEPARATORS is a splitting point.
1523The substrings between the splitting points are made into a list
1524which is returned.
b222b786
RS
1525If SEPARATORS is absent, it defaults to \"[ \\f\\t\\n\\r\\v]+\".
1526
1527If there is match for SEPARATORS at the beginning of STRING, we do not
1528include a null substring for that. Likewise, if there is a match
b021ef18
DL
1529at the end of STRING, we don't include a null substring for that.
1530
1531Modifies the match data; use `save-match-data' if necessary."
edce3654
RS
1532 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
1533 (start 0)
b222b786 1534 notfirst
edce3654 1535 (list nil))
b222b786
RS
1536 (while (and (string-match rexp string
1537 (if (and notfirst
1538 (= start (match-beginning 0))
1539 (< start (length string)))
1540 (1+ start) start))
1541 (< (match-beginning 0) (length string)))
1542 (setq notfirst t)
7eb47123 1543 (or (eq (match-beginning 0) 0)
b222b786
RS
1544 (and (eq (match-beginning 0) (match-end 0))
1545 (eq (match-beginning 0) start))
edce3654
RS
1546 (setq list
1547 (cons (substring string start (match-beginning 0))
1548 list)))
1549 (setq start (match-end 0)))
1550 (or (eq start (length string))
1551 (setq list
1552 (cons (substring string start)
1553 list)))
1554 (nreverse list)))
1ccaea52
AI
1555
1556(defun subst-char-in-string (fromchar tochar string &optional inplace)
1557 "Replace FROMCHAR with TOCHAR in STRING each time it occurs.
1558Unless optional argument INPLACE is non-nil, return a new string."
e6e71807
SM
1559 (let ((i (length string))
1560 (newstr (if inplace string (copy-sequence string))))
1561 (while (> i 0)
1562 (setq i (1- i))
1563 (if (eq (aref newstr i) fromchar)
1564 (aset newstr i tochar)))
1565 newstr))
b021ef18 1566
1697159c
DL
1567(defun replace-regexp-in-string (regexp rep string &optional
1568 fixedcase literal subexp start)
b021ef18
DL
1569 "Replace all matches for REGEXP with REP in STRING.
1570
1571Return a new string containing the replacements.
1572
1573Optional arguments FIXEDCASE, LITERAL and SUBEXP are like the
1574arguments with the same names of function `replace-match'. If START
1575is non-nil, start replacements at that index in STRING.
1576
1577REP is either a string used as the NEWTEXT arg of `replace-match' or a
1578function. If it is a function it is applied to each match to generate
1579the replacement passed to `replace-match'; the match-data at this
1580point are such that match 0 is the function's argument.
1581
1697159c
DL
1582To replace only the first match (if any), make REGEXP match up to \\'
1583and replace a sub-expression, e.g.
1584 (replace-regexp-in-string \"\\(foo\\).*\\'\" \"bar\" \" foo foo\" nil nil 1)
1585 => \" bar foo\"
1586"
b021ef18
DL
1587
1588 ;; To avoid excessive consing from multiple matches in long strings,
1589 ;; don't just call `replace-match' continually. Walk down the
1590 ;; string looking for matches of REGEXP and building up a (reversed)
1591 ;; list MATCHES. This comprises segments of STRING which weren't
1592 ;; matched interspersed with replacements for segments that were.
08b1f8a1 1593 ;; [For a `large' number of replacements it's more efficient to
b021ef18
DL
1594 ;; operate in a temporary buffer; we can't tell from the function's
1595 ;; args whether to choose the buffer-based implementation, though it
1596 ;; might be reasonable to do so for long enough STRING.]
1597 (let ((l (length string))
1598 (start (or start 0))
1599 matches str mb me)
1600 (save-match-data
1601 (while (and (< start l) (string-match regexp string start))
1602 (setq mb (match-beginning 0)
1603 me (match-end 0))
a9853251
SM
1604 ;; If we matched the empty string, make sure we advance by one char
1605 (when (= me mb) (setq me (min l (1+ mb))))
1606 ;; Generate a replacement for the matched substring.
1607 ;; Operate only on the substring to minimize string consing.
1608 ;; Set up match data for the substring for replacement;
1609 ;; presumably this is likely to be faster than munging the
1610 ;; match data directly in Lisp.
1611 (string-match regexp (setq str (substring string mb me)))
1612 (setq matches
1613 (cons (replace-match (if (stringp rep)
1614 rep
1615 (funcall rep (match-string 0 str)))
1616 fixedcase literal str subexp)
1617 (cons (substring string start mb) ; unmatched prefix
1618 matches)))
1619 (setq start me))
b021ef18
DL
1620 ;; Reconstruct a string from the pieces.
1621 (setq matches (cons (substring string start l) matches)) ; leftover
1622 (apply #'concat (nreverse matches)))))
a7ed4c2a 1623\f
8af7df60
RS
1624(defun shell-quote-argument (argument)
1625 "Quote an argument for passing as argument to an inferior shell."
c1c74b43 1626 (if (eq system-type 'ms-dos)
8ee75d03
EZ
1627 ;; Quote using double quotes, but escape any existing quotes in
1628 ;; the argument with backslashes.
1629 (let ((result "")
1630 (start 0)
1631 end)
1632 (if (or (null (string-match "[^\"]" argument))
1633 (< (match-end 0) (length argument)))
1634 (while (string-match "[\"]" argument start)
1635 (setq end (match-beginning 0)
1636 result (concat result (substring argument start end)
1637 "\\" (substring argument end (1+ end)))
1638 start (1+ end))))
1639 (concat "\"" result (substring argument start) "\""))
c1c74b43
RS
1640 (if (eq system-type 'windows-nt)
1641 (concat "\"" argument "\"")
e1b65a6b
RS
1642 (if (equal argument "")
1643 "''"
1644 ;; Quote everything except POSIX filename characters.
1645 ;; This should be safe enough even for really weird shells.
1646 (let ((result "") (start 0) end)
1647 (while (string-match "[^-0-9a-zA-Z_./]" argument start)
1648 (setq end (match-beginning 0)
1649 result (concat result (substring argument start end)
1650 "\\" (substring argument end (1+ end)))
1651 start (1+ end)))
1652 (concat result (substring argument start)))))))
8af7df60 1653
297d863b 1654(defun make-syntax-table (&optional oldtable)
984f718a 1655 "Return a new syntax table.
0764e16f
SM
1656Create a syntax table which inherits from OLDTABLE (if non-nil) or
1657from `standard-syntax-table' otherwise."
1658 (let ((table (make-char-table 'syntax-table nil)))
1659 (set-char-table-parent table (or oldtable (standard-syntax-table)))
1660 table))
31aa282e
KH
1661
1662(defun add-to-invisibility-spec (arg)
1663 "Add elements to `buffer-invisibility-spec'.
1664See documentation for `buffer-invisibility-spec' for the kind of elements
1665that can be added."
1666 (cond
1667 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
1668 (setq buffer-invisibility-spec (list arg)))
1669 (t
11d431ad
KH
1670 (setq buffer-invisibility-spec
1671 (cons arg buffer-invisibility-spec)))))
31aa282e
KH
1672
1673(defun remove-from-invisibility-spec (arg)
1674 "Remove elements from `buffer-invisibility-spec'."
e93b8cbb 1675 (if (consp buffer-invisibility-spec)
071a2a71 1676 (setq buffer-invisibility-spec (delete arg buffer-invisibility-spec))))
baed0109
RS
1677\f
1678(defun global-set-key (key command)
1679 "Give KEY a global binding as COMMAND.
7bba1895
KH
1680COMMAND is the command definition to use; usually it is
1681a symbol naming an interactively-callable function.
1682KEY is a key sequence; noninteractively, it is a string or vector
1683of characters or event types, and non-ASCII characters with codes
1684above 127 (such as ISO Latin-1) can be included if you use a vector.
1685
1686Note that if KEY has a local binding in the current buffer,
1687that local binding will continue to shadow any global binding
1688that you make with this function."
baed0109 1689 (interactive "KSet key globally: \nCSet key %s to command: ")
a2f9aa84 1690 (or (vectorp key) (stringp key)
baed0109 1691 (signal 'wrong-type-argument (list 'arrayp key)))
ff663bbe 1692 (define-key (current-global-map) key command))
baed0109
RS
1693
1694(defun local-set-key (key command)
1695 "Give KEY a local binding as COMMAND.
7bba1895
KH
1696COMMAND is the command definition to use; usually it is
1697a symbol naming an interactively-callable function.
1698KEY is a key sequence; noninteractively, it is a string or vector
1699of characters or event types, and non-ASCII characters with codes
1700above 127 (such as ISO Latin-1) can be included if you use a vector.
1701
baed0109
RS
1702The binding goes in the current buffer's local map,
1703which in most cases is shared with all other buffers in the same major mode."
1704 (interactive "KSet key locally: \nCSet key %s locally to command: ")
1705 (let ((map (current-local-map)))
1706 (or map
1707 (use-local-map (setq map (make-sparse-keymap))))
a2f9aa84 1708 (or (vectorp key) (stringp key)
baed0109 1709 (signal 'wrong-type-argument (list 'arrayp key)))
ff663bbe 1710 (define-key map key command)))
984f718a 1711
baed0109
RS
1712(defun global-unset-key (key)
1713 "Remove global binding of KEY.
1714KEY is a string representing a sequence of keystrokes."
1715 (interactive "kUnset key globally: ")
1716 (global-set-key key nil))
1717
db2474b8 1718(defun local-unset-key (key)
baed0109
RS
1719 "Remove local binding of KEY.
1720KEY is a string representing a sequence of keystrokes."
1721 (interactive "kUnset key locally: ")
1722 (if (current-local-map)
db2474b8 1723 (local-set-key key nil))
baed0109
RS
1724 nil)
1725\f
4809d0dd
KH
1726;; We put this here instead of in frame.el so that it's defined even on
1727;; systems where frame.el isn't loaded.
1728(defun frame-configuration-p (object)
1729 "Return non-nil if OBJECT seems to be a frame configuration.
1730Any list whose car is `frame-configuration' is assumed to be a frame
1731configuration."
1732 (and (consp object)
1733 (eq (car object) 'frame-configuration)))
1734
a9a44ed1 1735(defun functionp (object)
0764e16f 1736 "Non-nil iff OBJECT is a type of object that can be called as a function."
a2d7836f 1737 (or (and (symbolp object) (fboundp object)
1cf72ff8 1738 (setq object (indirect-function object))
0764e16f 1739 (eq (car-safe object) 'autoload)
f1d37f3c 1740 (not (car-safe (cdr-safe (cdr-safe (cdr-safe (cdr-safe object)))))))
0764e16f 1741 (subrp object) (byte-code-function-p object)
60ab6064 1742 (eq (car-safe object) 'lambda)))
a9a44ed1 1743
f65fab59
GM
1744(defun interactive-form (function)
1745 "Return the interactive form of FUNCTION.
1746If function is a command (see `commandp'), value is a list of the form
d3200788 1747\(interactive SPEC). If function is not a command, return nil."
f65fab59
GM
1748 (setq function (indirect-function function))
1749 (when (commandp function)
1750 (cond ((byte-code-function-p function)
1751 (when (> (length function) 5)
1752 (let ((spec (aref function 5)))
1753 (if spec
1754 (list 'interactive spec)
1755 (list 'interactive)))))
1756 ((subrp function)
1757 (subr-interactive-form function))
1758 ((eq (car-safe function) 'lambda)
1759 (setq function (cddr function))
1760 (when (stringp (car function))
1761 (setq function (cdr function)))
1762 (let ((form (car function)))
a27b451e 1763 (when (eq (car-safe form) 'interactive)
f65fab59 1764 (copy-sequence form)))))))
630cc463 1765
d3a61a11 1766(defun assq-delete-all (key alist)
a62d6695
DL
1767 "Delete from ALIST all elements whose car is KEY.
1768Return the modified alist."
a62d6695
DL
1769 (let ((tail alist))
1770 (while tail
1771 (if (eq (car (car tail)) key)
1772 (setq alist (delq (car tail) alist)))
1773 (setq tail (cdr tail)))
1774 alist))
1775
cdd9f643
RS
1776(defun make-temp-file (prefix &optional dir-flag)
1777 "Create a temporary file.
1778The returned file name (created by appending some random characters at the end
1779of PREFIX, and expanding against `temporary-file-directory' if necessary,
1780is guaranteed to point to a newly created empty file.
1781You can then use `write-region' to write new data into the file.
1782
1783If DIR-FLAG is non-nil, create a new empty directory instead of a file."
1784 (let (file)
1785 (while (condition-case ()
1786 (progn
1787 (setq file
1788 (make-temp-name
1789 (expand-file-name prefix temporary-file-directory)))
1790 (if dir-flag
1791 (make-directory file)
1792 (write-region "" nil file nil 'silent nil 'excl))
1793 nil)
08b1f8a1 1794 (file-already-exists t))
cdd9f643
RS
1795 ;; the file was somehow created by someone else between
1796 ;; `make-temp-name' and `write-region', let's try again.
1797 nil)
1798 file))
1799
d7d47268 1800\f
c94f4677 1801(defun add-minor-mode (toggle name &optional keymap after toggle-fun)
d7d47268 1802 "Register a new minor mode.
c94f4677 1803
0b2cf11f
SM
1804This is an XEmacs-compatibility function. Use `define-minor-mode' instead.
1805
c94f4677
GM
1806TOGGLE is a symbol which is the name of a buffer-local variable that
1807is toggled on or off to say whether the minor mode is active or not.
1808
1809NAME specifies what will appear in the mode line when the minor mode
1810is active. NAME should be either a string starting with a space, or a
1811symbol whose value is such a string.
1812
1813Optional KEYMAP is the keymap for the minor mode that will be added
1814to `minor-mode-map-alist'.
1815
1816Optional AFTER specifies that TOGGLE should be added after AFTER
1817in `minor-mode-alist'.
1818
0b2cf11f
SM
1819Optional TOGGLE-FUN is an interactive function to toggle the mode.
1820It defaults to (and should by convention be) TOGGLE.
1821
1822If TOGGLE has a non-nil `:included' property, an entry for the mode is
1823included in the mode-line minor mode menu.
1824If TOGGLE has a `:menu-tag', that is used for the menu item's label."
1825 (unless toggle-fun (setq toggle-fun toggle))
0b2cf11f 1826 ;; Add the name to the minor-mode-alist.
c94f4677 1827 (when name
0b2cf11f
SM
1828 (let ((existing (assq toggle minor-mode-alist)))
1829 (when (and (stringp name) (not (get-text-property 0 'local-map name)))
d6c22d46 1830 (setq name
0c107014
GM
1831 (propertize name
1832 'local-map mode-line-minor-mode-keymap
1833 'help-echo "mouse-3: minor mode menu")))
0b2cf11f
SM
1834 (if existing
1835 (setcdr existing (list name))
1836 (let ((tail minor-mode-alist) found)
1837 (while (and tail (not found))
1838 (if (eq after (caar tail))
1839 (setq found tail)
1840 (setq tail (cdr tail))))
1841 (if found
1842 (let ((rest (cdr found)))
1843 (setcdr found nil)
1844 (nconc found (list (list toggle name)) rest))
1845 (setq minor-mode-alist (cons (list toggle name)
1846 minor-mode-alist)))))))
69cae2d4
RS
1847 ;; Add the toggle to the minor-modes menu if requested.
1848 (when (get toggle :included)
1849 (define-key mode-line-mode-menu
1850 (vector toggle)
1851 (list 'menu-item
1852 (concat
1853 (or (get toggle :menu-tag)
1854 (if (stringp name) name (symbol-name toggle)))
1855 (let ((mode-name (if (stringp name) name
1856 (if (symbolp name) (symbol-value name)))))
1857 (if mode-name
1858 (concat " (" mode-name ")"))))
1859 toggle-fun
1860 :button (cons :toggle toggle))))
1861
0b2cf11f 1862 ;; Add the map to the minor-mode-map-alist.
c94f4677
GM
1863 (when keymap
1864 (let ((existing (assq toggle minor-mode-map-alist)))
0b2cf11f
SM
1865 (if existing
1866 (setcdr existing keymap)
1867 (let ((tail minor-mode-map-alist) found)
1868 (while (and tail (not found))
1869 (if (eq after (caar tail))
1870 (setq found tail)
1871 (setq tail (cdr tail))))
1872 (if found
1873 (let ((rest (cdr found)))
1874 (setcdr found nil)
1875 (nconc found (list (cons toggle keymap)) rest))
1876 (setq minor-mode-map-alist (cons (cons toggle keymap)
1877 minor-mode-map-alist))))))))
d7d47268 1878
a13fe4c5
SM
1879;; Clones ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1880
1881(defun text-clone-maintain (ol1 after beg end &optional len)
1882 "Propagate the changes made under the overlay OL1 to the other clones.
1883This is used on the `modification-hooks' property of text clones."
1884 (when (and after (not undo-in-progress) (overlay-start ol1))
1885 (let ((margin (if (overlay-get ol1 'text-clone-spreadp) 1 0)))
1886 (setq beg (max beg (+ (overlay-start ol1) margin)))
1887 (setq end (min end (- (overlay-end ol1) margin)))
1888 (when (<= beg end)
1889 (save-excursion
1890 (when (overlay-get ol1 'text-clone-syntax)
1891 ;; Check content of the clone's text.
1892 (let ((cbeg (+ (overlay-start ol1) margin))
1893 (cend (- (overlay-end ol1) margin)))
1894 (goto-char cbeg)
1895 (save-match-data
1896 (if (not (re-search-forward
1897 (overlay-get ol1 'text-clone-syntax) cend t))
1898 ;; Mark the overlay for deletion.
1899 (overlay-put ol1 'text-clones nil)
1900 (when (< (match-end 0) cend)
1901 ;; Shrink the clone at its end.
1902 (setq end (min end (match-end 0)))
1903 (move-overlay ol1 (overlay-start ol1)
1904 (+ (match-end 0) margin)))
1905 (when (> (match-beginning 0) cbeg)
1906 ;; Shrink the clone at its beginning.
1907 (setq beg (max (match-beginning 0) beg))
1908 (move-overlay ol1 (- (match-beginning 0) margin)
1909 (overlay-end ol1)))))))
1910 ;; Now go ahead and update the clones.
1911 (let ((head (- beg (overlay-start ol1)))
1912 (tail (- (overlay-end ol1) end))
1913 (str (buffer-substring beg end))
1914 (nothing-left t)
1915 (inhibit-modification-hooks t))
1916 (dolist (ol2 (overlay-get ol1 'text-clones))
1917 (let ((oe (overlay-end ol2)))
1918 (unless (or (eq ol1 ol2) (null oe))
1919 (setq nothing-left nil)
1920 (let ((mod-beg (+ (overlay-start ol2) head)))
1921 ;;(overlay-put ol2 'modification-hooks nil)
1922 (goto-char (- (overlay-end ol2) tail))
1923 (unless (> mod-beg (point))
1924 (save-excursion (insert str))
1925 (delete-region mod-beg (point)))
1926 ;;(overlay-put ol2 'modification-hooks '(text-clone-maintain))
1927 ))))
1928 (if nothing-left (delete-overlay ol1))))))))
1929
1930(defun text-clone-create (start end &optional spreadp syntax)
1931 "Create a text clone of START...END at point.
1932Text clones are chunks of text that are automatically kept identical:
1933changes done to one of the clones will be immediately propagated to the other.
1934
1935The buffer's content at point is assumed to be already identical to
1936the one between START and END.
1937If SYNTAX is provided it's a regexp that describes the possible text of
1938the clones; the clone will be shrunk or killed if necessary to ensure that
1939its text matches the regexp.
1940If SPREADP is non-nil it indicates that text inserted before/after the
1941clone should be incorporated in the clone."
1942 ;; To deal with SPREADP we can either use an overlay with `nil t' along
1943 ;; with insert-(behind|in-front-of)-hooks or use a slightly larger overlay
1944 ;; (with a one-char margin at each end) with `t nil'.
1945 ;; We opted for a larger overlay because it behaves better in the case
1946 ;; where the clone is reduced to the empty string (we want the overlay to
1947 ;; stay when the clone's content is the empty string and we want to use
1948 ;; `evaporate' to make sure those overlays get deleted when needed).
1949 ;;
1950 (let* ((pt-end (+ (point) (- end start)))
1951 (start-margin (if (or (not spreadp) (bobp) (<= start (point-min)))
1952 0 1))
1953 (end-margin (if (or (not spreadp)
1954 (>= pt-end (point-max))
1955 (>= start (point-max)))
1956 0 1))
1957 (ol1 (make-overlay (- start start-margin) (+ end end-margin) nil t))
1958 (ol2 (make-overlay (- (point) start-margin) (+ pt-end end-margin) nil t))
1959 (dups (list ol1 ol2)))
1960 (overlay-put ol1 'modification-hooks '(text-clone-maintain))
1961 (when spreadp (overlay-put ol1 'text-clone-spreadp t))
1962 (when syntax (overlay-put ol1 'text-clone-syntax syntax))
1963 ;;(overlay-put ol1 'face 'underline)
1964 (overlay-put ol1 'evaporate t)
1965 (overlay-put ol1 'text-clones dups)
1966 ;;
1967 (overlay-put ol2 'modification-hooks '(text-clone-maintain))
1968 (when spreadp (overlay-put ol2 'text-clone-spreadp t))
1969 (when syntax (overlay-put ol2 'text-clone-syntax syntax))
1970 ;;(overlay-put ol2 'face 'underline)
1971 (overlay-put ol2 'evaporate t)
1972 (overlay-put ol2 'text-clones dups)))
1973
324cd947
PJ
1974(defun play-sound (sound)
1975 "SOUND is a list of the form `(sound KEYWORD VALUE...)'.
1976The following keywords are recognized:
1977
1978 :file FILE - read sound data from FILE. If FILE isn't an
1979absolute file name, it is searched in `data-directory'.
1980
1981 :data DATA - read sound data from string DATA.
1982
1983Exactly one of :file or :data must be present.
1984
1985 :volume VOL - set volume to VOL. VOL must an integer in the
1986range 0..100 or a float in the range 0..1.0. If not specified,
1987don't change the volume setting of the sound device.
1988
1989 :device DEVICE - play sound on DEVICE. If not specified,
1990a system-dependent default device name is used."
1991 (unless (fboundp 'play-sound-internal)
1992 (error "This Emacs binary lacks sound support"))
1993 (play-sound-internal sound))
1994
630cc463 1995;;; subr.el ends here