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