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