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