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