(call-process-shell-command): New function.
[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 \f
801 ;;;; Specifying things to do after certain files are loaded.
802
803 (defun eval-after-load (file form)
804 "Arrange that, if FILE is ever loaded, FORM will be run at that time.
805 This makes or adds to an entry on `after-load-alist'.
806 If FILE is already loaded, evaluate FORM right now.
807 It does nothing if FORM is already on the list for FILE.
808 FILE must match exactly. Normally FILE is the name of a library,
809 with no directory or extension specified, since that is how `load'
810 is normally called."
811 ;; Make sure `load-history' contains the files dumped with Emacs
812 ;; for the case that FILE is one of the files dumped with Emacs.
813 (load-symbol-file-load-history)
814 ;; Make sure there is an element for FILE.
815 (or (assoc file after-load-alist)
816 (setq after-load-alist (cons (list file) after-load-alist)))
817 ;; Add FORM to the element if it isn't there.
818 (let ((elt (assoc file after-load-alist)))
819 (or (member form (cdr elt))
820 (progn
821 (nconc elt (list form))
822 ;; If the file has been loaded already, run FORM right away.
823 (and (assoc file load-history)
824 (eval form)))))
825 form)
826
827 (defun eval-next-after-load (file)
828 "Read the following input sexp, and run it whenever FILE is loaded.
829 This makes or adds to an entry on `after-load-alist'.
830 FILE should be the name of a library, with no directory name."
831 (eval-after-load file (read)))
832
833 \f
834 ;;;; Input and display facilities.
835
836 (defvar read-quoted-char-radix 8
837 "*Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
838 Legitimate radix values are 8, 10 and 16.")
839
840 (custom-declare-variable-early
841 'read-quoted-char-radix 8
842 "*Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
843 Legitimate radix values are 8, 10 and 16."
844 :type '(choice (const 8) (const 10) (const 16))
845 :group 'editing-basics)
846
847 (defun read-quoted-char (&optional prompt)
848 "Like `read-char', but do not allow quitting.
849 Also, if the first character read is an octal digit,
850 we read any number of octal digits and return the
851 specified character code. Any nondigit terminates the sequence.
852 If the terminator is RET, it is discarded;
853 any other terminator is used itself as input.
854
855 The optional argument PROMPT specifies a string to use to prompt the user.
856 The variable `read-quoted-char-radix' controls which radix to use
857 for numeric input."
858 (let ((message-log-max nil) done (first t) (code 0) char)
859 (while (not done)
860 (let ((inhibit-quit first)
861 ;; Don't let C-h get the help message--only help function keys.
862 (help-char nil)
863 (help-form
864 "Type the special character you want to use,
865 or the octal character code.
866 RET terminates the character code and is discarded;
867 any other non-digit terminates the character code and is then used as input."))
868 (setq char (read-event (and prompt (format "%s-" prompt)) t))
869 (if inhibit-quit (setq quit-flag nil)))
870 ;; Translate TAB key into control-I ASCII character, and so on.
871 (and char
872 (let ((translated (lookup-key function-key-map (vector char))))
873 (if (arrayp translated)
874 (setq char (aref translated 0)))))
875 (cond ((null char))
876 ((not (integerp char))
877 (setq unread-command-events (list char)
878 done t))
879 ((/= (logand char ?\M-\^@) 0)
880 ;; Turn a meta-character into a character with the 0200 bit set.
881 (setq code (logior (logand char (lognot ?\M-\^@)) 128)
882 done t))
883 ((and (<= ?0 char) (< char (+ ?0 (min 10 read-quoted-char-radix))))
884 (setq code (+ (* code read-quoted-char-radix) (- char ?0)))
885 (and prompt (setq prompt (message "%s %c" prompt char))))
886 ((and (<= ?a (downcase char))
887 (< (downcase char) (+ ?a -10 (min 26 read-quoted-char-radix))))
888 (setq code (+ (* code read-quoted-char-radix)
889 (+ 10 (- (downcase char) ?a))))
890 (and prompt (setq prompt (message "%s %c" prompt char))))
891 ((and (not first) (eq char ?\C-m))
892 (setq done t))
893 ((not first)
894 (setq unread-command-events (list char)
895 done t))
896 (t (setq code char
897 done t)))
898 (setq first nil))
899 code))
900
901 (defun read-passwd (prompt &optional confirm default)
902 "Read a password, prompting with PROMPT. Echo `.' for each character typed.
903 End with RET, LFD, or ESC. DEL or C-h rubs out. C-u kills line.
904 Optional argument CONFIRM, if non-nil, then read it twice to make sure.
905 Optional DEFAULT is a default password to use instead of empty input."
906 (if confirm
907 (let (success)
908 (while (not success)
909 (let ((first (read-passwd prompt nil default))
910 (second (read-passwd "Confirm password: " nil default)))
911 (if (equal first second)
912 (progn
913 (and (arrayp second) (fillarray second ?\0))
914 (setq success first))
915 (and (arrayp first) (fillarray first ?\0))
916 (and (arrayp second) (fillarray second ?\0))
917 (message "Password not repeated accurately; please start over")
918 (sit-for 1))))
919 success)
920 (let ((pass nil)
921 (c 0)
922 (echo-keystrokes 0)
923 (cursor-in-echo-area t))
924 (while (progn (message "%s%s"
925 prompt
926 (make-string (length pass) ?.))
927 (setq c (read-char-exclusive nil t))
928 (and (/= c ?\r) (/= c ?\n) (/= c ?\e)))
929 (clear-this-command-keys)
930 (if (= c ?\C-u)
931 (progn
932 (and (arrayp pass) (fillarray pass ?\0))
933 (setq pass ""))
934 (if (and (/= c ?\b) (/= c ?\177))
935 (let* ((new-char (char-to-string c))
936 (new-pass (concat pass new-char)))
937 (and (arrayp pass) (fillarray pass ?\0))
938 (fillarray new-char ?\0)
939 (setq c ?\0)
940 (setq pass new-pass))
941 (if (> (length pass) 0)
942 (let ((new-pass (substring pass 0 -1)))
943 (and (arrayp pass) (fillarray pass ?\0))
944 (setq pass new-pass))))))
945 (message nil)
946 (or pass default ""))))
947 \f
948 (defun force-mode-line-update (&optional all)
949 "Force the mode-line of the current buffer to be redisplayed.
950 With optional non-nil ALL, force redisplay of all mode-lines."
951 (if all (save-excursion (set-buffer (other-buffer))))
952 (set-buffer-modified-p (buffer-modified-p)))
953
954 (defun momentary-string-display (string pos &optional exit-char message)
955 "Momentarily display STRING in the buffer at POS.
956 Display remains until next character is typed.
957 If the char is EXIT-CHAR (optional third arg, default is SPC) it is swallowed;
958 otherwise it is then available as input (as a command if nothing else).
959 Display MESSAGE (optional fourth arg) in the echo area.
960 If MESSAGE is nil, instructions to type EXIT-CHAR are displayed there."
961 (or exit-char (setq exit-char ?\ ))
962 (let ((inhibit-read-only t)
963 ;; Don't modify the undo list at all.
964 (buffer-undo-list t)
965 (modified (buffer-modified-p))
966 (name buffer-file-name)
967 insert-end)
968 (unwind-protect
969 (progn
970 (save-excursion
971 (goto-char pos)
972 ;; defeat file locking... don't try this at home, kids!
973 (setq buffer-file-name nil)
974 (insert-before-markers string)
975 (setq insert-end (point))
976 ;; If the message end is off screen, recenter now.
977 (if (< (window-end nil t) insert-end)
978 (recenter (/ (window-height) 2)))
979 ;; If that pushed message start off the screen,
980 ;; scroll to start it at the top of the screen.
981 (move-to-window-line 0)
982 (if (> (point) pos)
983 (progn
984 (goto-char pos)
985 (recenter 0))))
986 (message (or message "Type %s to continue editing.")
987 (single-key-description exit-char))
988 (let ((char (read-event)))
989 (or (eq char exit-char)
990 (setq unread-command-events (list char)))))
991 (if insert-end
992 (save-excursion
993 (delete-region pos insert-end)))
994 (setq buffer-file-name name)
995 (set-buffer-modified-p modified))))
996
997 \f
998 ;;;; Miscellanea.
999
1000 ;; A number of major modes set this locally.
1001 ;; Give it a global value to avoid compiler warnings.
1002 (defvar font-lock-defaults nil)
1003
1004 (defvar suspend-hook nil
1005 "Normal hook run by `suspend-emacs', before suspending.")
1006
1007 (defvar suspend-resume-hook nil
1008 "Normal hook run by `suspend-emacs', after Emacs is continued.")
1009
1010 ;; Avoid compiler warnings about this variable,
1011 ;; which has a special meaning on certain system types.
1012 (defvar buffer-file-type nil
1013 "Non-nil if the visited file is a binary file.
1014 This variable is meaningful on MS-DOG and Windows NT.
1015 On those systems, it is automatically local in every buffer.
1016 On other systems, this variable is normally always nil.")
1017
1018 ;; This should probably be written in C (i.e., without using `walk-windows').
1019 (defun get-buffer-window-list (buffer &optional minibuf frame)
1020 "Return windows currently displaying BUFFER, or nil if none.
1021 See `walk-windows' for the meaning of MINIBUF and FRAME."
1022 (let ((buffer (if (bufferp buffer) buffer (get-buffer buffer))) windows)
1023 (walk-windows (function (lambda (window)
1024 (if (eq (window-buffer window) buffer)
1025 (setq windows (cons window windows)))))
1026 minibuf frame)
1027 windows))
1028
1029 (defun ignore (&rest ignore)
1030 "Do nothing and return nil.
1031 This function accepts any number of arguments, but ignores them."
1032 (interactive)
1033 nil)
1034
1035 (defun error (&rest args)
1036 "Signal an error, making error message by passing all args to `format'.
1037 In Emacs, the convention is that error messages start with a capital
1038 letter but *do not* end with a period. Please follow this convention
1039 for the sake of consistency."
1040 (while t
1041 (signal 'error (list (apply 'format args)))))
1042
1043 (defalias 'user-original-login-name 'user-login-name)
1044
1045 (defun start-process-shell-command (name buffer &rest args)
1046 "Start a program in a subprocess. Return the process object for it.
1047 Args are NAME BUFFER COMMAND &rest COMMAND-ARGS.
1048 NAME is name for process. It is modified if necessary to make it unique.
1049 BUFFER is the buffer or (buffer-name) to associate with the process.
1050 Process output goes at end of that buffer, unless you specify
1051 an output stream or filter function to handle the output.
1052 BUFFER may be also nil, meaning that this process is not associated
1053 with any buffer
1054 Third arg is command name, the name of a shell command.
1055 Remaining arguments are the arguments for the command.
1056 Wildcards and redirection are handled as usual in the shell."
1057 (cond
1058 ((eq system-type 'vax-vms)
1059 (apply 'start-process name buffer args))
1060 ;; We used to use `exec' to replace the shell with the command,
1061 ;; but that failed to handle (...) and semicolon, etc.
1062 (t
1063 (start-process name buffer shell-file-name shell-command-switch
1064 (mapconcat 'identity args " ")))))
1065
1066 (defun call-process-shell-command (command &optional infile buffer display
1067 &rest args)
1068 "Execute the shell command COMMAND synchronously in separate process.
1069 The remaining arguments are optional.
1070 The program's input comes from file INFILE (nil means `/dev/null').
1071 Insert output in BUFFER before point; t means current buffer;
1072 nil for BUFFER means discard it; 0 means discard and don't wait.
1073 BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,
1074 REAL-BUFFER says what to do with standard output, as above,
1075 while STDERR-FILE says what to do with standard error in the child.
1076 STDERR-FILE may be nil (discard standard error output),
1077 t (mix it with ordinary output), or a file name string.
1078
1079 Fourth arg DISPLAY non-nil means redisplay buffer as output is inserted.
1080 Remaining arguments are strings passed as additional arguments for COMMAND.
1081 Wildcards and redirection are handled as usual in the shell.
1082
1083 If BUFFER is 0, `call-process-shell-command' returns immediately with value nil.
1084 Otherwise it waits for COMMAND to terminate and returns a numeric exit
1085 status or a signal description string.
1086 If you quit, the process is killed with SIGINT, or SIGKILL if you quit again."
1087 (cond
1088 ((eq system-type 'vax-vms)
1089 (apply 'call-process command infile buffer display args))
1090 ;; We used to use `exec' to replace the shell with the command,
1091 ;; but that failed to handle (...) and semicolon, etc.
1092 (t
1093 (call-process shell-file-name
1094 infile buffer display
1095 shell-command-switch
1096 (mapconcat 'identity (cons command args) " ")))))
1097 \f
1098 (defmacro with-current-buffer (buffer &rest body)
1099 "Execute the forms in BODY with BUFFER as the current buffer.
1100 The value returned is the value of the last form in BODY.
1101 See also `with-temp-buffer'."
1102 (cons 'save-current-buffer
1103 (cons (list 'set-buffer buffer)
1104 body)))
1105
1106 (defmacro with-temp-file (file &rest body)
1107 "Create a new buffer, evaluate BODY there, and write the buffer to FILE.
1108 The value returned is the value of the last form in BODY.
1109 See also `with-temp-buffer'."
1110 (let ((temp-file (make-symbol "temp-file"))
1111 (temp-buffer (make-symbol "temp-buffer")))
1112 `(let ((,temp-file ,file)
1113 (,temp-buffer
1114 (get-buffer-create (generate-new-buffer-name " *temp file*"))))
1115 (unwind-protect
1116 (prog1
1117 (with-current-buffer ,temp-buffer
1118 ,@body)
1119 (with-current-buffer ,temp-buffer
1120 (widen)
1121 (write-region (point-min) (point-max) ,temp-file nil 0)))
1122 (and (buffer-name ,temp-buffer)
1123 (kill-buffer ,temp-buffer))))))
1124
1125 (defmacro with-temp-message (message &rest body)
1126 "Display MESSAGE temporarily if non-nil while BODY is evaluated.
1127 The original message is restored to the echo area after BODY has finished.
1128 The value returned is the value of the last form in BODY.
1129 MESSAGE is written to the message log buffer if `message-log-max' is non-nil.
1130 If MESSAGE is nil, the echo area and message log buffer are unchanged.
1131 Use a MESSAGE of \"\" to temporarily clear the echo area."
1132 (let ((current-message (make-symbol "current-message"))
1133 (temp-message (make-symbol "with-temp-message")))
1134 `(let ((,temp-message ,message)
1135 (,current-message))
1136 (unwind-protect
1137 (progn
1138 (when ,temp-message
1139 (setq ,current-message (current-message))
1140 (message "%s" ,temp-message))
1141 ,@body)
1142 (and ,temp-message ,current-message
1143 (message "%s" ,current-message))))))
1144
1145 (defmacro with-temp-buffer (&rest body)
1146 "Create a temporary buffer, and evaluate BODY there like `progn'.
1147 See also `with-temp-file' and `with-output-to-string'."
1148 (let ((temp-buffer (make-symbol "temp-buffer")))
1149 `(let ((,temp-buffer
1150 (get-buffer-create (generate-new-buffer-name " *temp*"))))
1151 (unwind-protect
1152 (with-current-buffer ,temp-buffer
1153 ,@body)
1154 (and (buffer-name ,temp-buffer)
1155 (kill-buffer ,temp-buffer))))))
1156
1157 (defmacro with-output-to-string (&rest body)
1158 "Execute BODY, return the text it sent to `standard-output', as a string."
1159 `(let ((standard-output
1160 (get-buffer-create (generate-new-buffer-name " *string-output*"))))
1161 (let ((standard-output standard-output))
1162 ,@body)
1163 (with-current-buffer standard-output
1164 (prog1
1165 (buffer-string)
1166 (kill-buffer nil)))))
1167
1168 (defmacro combine-after-change-calls (&rest body)
1169 "Execute BODY, but don't call the after-change functions till the end.
1170 If BODY makes changes in the buffer, they are recorded
1171 and the functions on `after-change-functions' are called several times
1172 when BODY is finished.
1173 The return value is the value of the last form in BODY.
1174
1175 If `before-change-functions' is non-nil, then calls to the after-change
1176 functions can't be deferred, so in that case this macro has no effect.
1177
1178 Do not alter `after-change-functions' or `before-change-functions'
1179 in BODY."
1180 `(unwind-protect
1181 (let ((combine-after-change-calls t))
1182 . ,body)
1183 (combine-after-change-execute)))
1184
1185
1186 (defmacro with-syntax-table (table &rest body)
1187 "Evaluate BODY with syntax table of current buffer set to a copy of TABLE.
1188 The syntax table of the current buffer is saved, BODY is evaluated, and the
1189 saved table is restored, even in case of an abnormal exit.
1190 Value is what BODY returns."
1191 (let ((old-table (make-symbol "table"))
1192 (old-buffer (make-symbol "buffer")))
1193 `(let ((,old-table (syntax-table))
1194 (,old-buffer (current-buffer)))
1195 (unwind-protect
1196 (progn
1197 (set-syntax-table (copy-syntax-table ,table))
1198 ,@body)
1199 (save-current-buffer
1200 (set-buffer ,old-buffer)
1201 (set-syntax-table ,old-table))))))
1202 \f
1203 (defvar save-match-data-internal)
1204
1205 ;; We use save-match-data-internal as the local variable because
1206 ;; that works ok in practice (people should not use that variable elsewhere).
1207 ;; We used to use an uninterned symbol; the compiler handles that properly
1208 ;; now, but it generates slower code.
1209 (defmacro save-match-data (&rest body)
1210 "Execute the BODY forms, restoring the global value of the match data."
1211 ;; It is better not to use backquote here,
1212 ;; because that makes a bootstrapping problem
1213 ;; if you need to recompile all the Lisp files using interpreted code.
1214 (list 'let
1215 '((save-match-data-internal (match-data)))
1216 (list 'unwind-protect
1217 (cons 'progn body)
1218 '(set-match-data save-match-data-internal))))
1219
1220 (defun match-string (num &optional string)
1221 "Return string of text matched by last search.
1222 NUM specifies which parenthesized expression in the last regexp.
1223 Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
1224 Zero means the entire text matched by the whole regexp or whole string.
1225 STRING should be given if the last search was by `string-match' on STRING."
1226 (if (match-beginning num)
1227 (if string
1228 (substring string (match-beginning num) (match-end num))
1229 (buffer-substring (match-beginning num) (match-end num)))))
1230
1231 (defun match-string-no-properties (num &optional string)
1232 "Return string of text matched by last search, without text properties.
1233 NUM specifies which parenthesized expression in the last regexp.
1234 Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
1235 Zero means the entire text matched by the whole regexp or whole string.
1236 STRING should be given if the last search was by `string-match' on STRING."
1237 (if (match-beginning num)
1238 (if string
1239 (let ((result
1240 (substring string (match-beginning num) (match-end num))))
1241 (set-text-properties 0 (length result) nil result)
1242 result)
1243 (buffer-substring-no-properties (match-beginning num)
1244 (match-end num)))))
1245
1246 (defun split-string (string &optional separators)
1247 "Splits STRING into substrings where there are matches for SEPARATORS.
1248 Each match for SEPARATORS is a splitting point.
1249 The substrings between the splitting points are made into a list
1250 which is returned.
1251 If SEPARATORS is absent, it defaults to \"[ \\f\\t\\n\\r\\v]+\".
1252
1253 If there is match for SEPARATORS at the beginning of STRING, we do not
1254 include a null substring for that. Likewise, if there is a match
1255 at the end of STRING, we don't include a null substring for that.
1256
1257 Modifies the match data; use `save-match-data' if necessary."
1258 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
1259 (start 0)
1260 notfirst
1261 (list nil))
1262 (while (and (string-match rexp string
1263 (if (and notfirst
1264 (= start (match-beginning 0))
1265 (< start (length string)))
1266 (1+ start) start))
1267 (< (match-beginning 0) (length string)))
1268 (setq notfirst t)
1269 (or (eq (match-beginning 0) 0)
1270 (and (eq (match-beginning 0) (match-end 0))
1271 (eq (match-beginning 0) start))
1272 (setq list
1273 (cons (substring string start (match-beginning 0))
1274 list)))
1275 (setq start (match-end 0)))
1276 (or (eq start (length string))
1277 (setq list
1278 (cons (substring string start)
1279 list)))
1280 (nreverse list)))
1281
1282 (defun subst-char-in-string (fromchar tochar string &optional inplace)
1283 "Replace FROMCHAR with TOCHAR in STRING each time it occurs.
1284 Unless optional argument INPLACE is non-nil, return a new string."
1285 (let ((i (length string))
1286 (newstr (if inplace string (copy-sequence string))))
1287 (while (> i 0)
1288 (setq i (1- i))
1289 (if (eq (aref newstr i) fromchar)
1290 (aset newstr i tochar)))
1291 newstr))
1292
1293 (defun replace-regexp-in-string (regexp rep string &optional
1294 fixedcase literal subexp start)
1295 "Replace all matches for REGEXP with REP in STRING.
1296
1297 Return a new string containing the replacements.
1298
1299 Optional arguments FIXEDCASE, LITERAL and SUBEXP are like the
1300 arguments with the same names of function `replace-match'. If START
1301 is non-nil, start replacements at that index in STRING.
1302
1303 REP is either a string used as the NEWTEXT arg of `replace-match' or a
1304 function. If it is a function it is applied to each match to generate
1305 the replacement passed to `replace-match'; the match-data at this
1306 point are such that match 0 is the function's argument.
1307
1308 To replace only the first match (if any), make REGEXP match up to \\'
1309 and replace a sub-expression, e.g.
1310 (replace-regexp-in-string \"\\(foo\\).*\\'\" \"bar\" \" foo foo\" nil nil 1)
1311 => \" bar foo\"
1312 "
1313
1314 ;; To avoid excessive consing from multiple matches in long strings,
1315 ;; don't just call `replace-match' continually. Walk down the
1316 ;; string looking for matches of REGEXP and building up a (reversed)
1317 ;; list MATCHES. This comprises segments of STRING which weren't
1318 ;; matched interspersed with replacements for segments that were.
1319 ;; [For a `large' number of replacements it's more efficient to
1320 ;; operate in a temporary buffer; we can't tell from the function's
1321 ;; args whether to choose the buffer-based implementation, though it
1322 ;; might be reasonable to do so for long enough STRING.]
1323 (let ((l (length string))
1324 (start (or start 0))
1325 matches str mb me)
1326 (save-match-data
1327 (while (and (< start l) (string-match regexp string start))
1328 (setq mb (match-beginning 0)
1329 me (match-end 0))
1330 ;; If we matched the empty string, make sure we advance by one char
1331 (when (= me mb) (setq me (min l (1+ mb))))
1332 ;; Generate a replacement for the matched substring.
1333 ;; Operate only on the substring to minimize string consing.
1334 ;; Set up match data for the substring for replacement;
1335 ;; presumably this is likely to be faster than munging the
1336 ;; match data directly in Lisp.
1337 (string-match regexp (setq str (substring string mb me)))
1338 (setq matches
1339 (cons (replace-match (if (stringp rep)
1340 rep
1341 (funcall rep (match-string 0 str)))
1342 fixedcase literal str subexp)
1343 (cons (substring string start mb) ; unmatched prefix
1344 matches)))
1345 (setq start me))
1346 ;; Reconstruct a string from the pieces.
1347 (setq matches (cons (substring string start l) matches)) ; leftover
1348 (apply #'concat (nreverse matches)))))
1349 \f
1350 (defun shell-quote-argument (argument)
1351 "Quote an argument for passing as argument to an inferior shell."
1352 (if (eq system-type 'ms-dos)
1353 ;; Quote using double quotes, but escape any existing quotes in
1354 ;; the argument with backslashes.
1355 (let ((result "")
1356 (start 0)
1357 end)
1358 (if (or (null (string-match "[^\"]" argument))
1359 (< (match-end 0) (length argument)))
1360 (while (string-match "[\"]" argument start)
1361 (setq end (match-beginning 0)
1362 result (concat result (substring argument start end)
1363 "\\" (substring argument end (1+ end)))
1364 start (1+ end))))
1365 (concat "\"" result (substring argument start) "\""))
1366 (if (eq system-type 'windows-nt)
1367 (concat "\"" argument "\"")
1368 (if (equal argument "")
1369 "''"
1370 ;; Quote everything except POSIX filename characters.
1371 ;; This should be safe enough even for really weird shells.
1372 (let ((result "") (start 0) end)
1373 (while (string-match "[^-0-9a-zA-Z_./]" argument start)
1374 (setq end (match-beginning 0)
1375 result (concat result (substring argument start end)
1376 "\\" (substring argument end (1+ end)))
1377 start (1+ end)))
1378 (concat result (substring argument start)))))))
1379
1380 (defun make-syntax-table (&optional oldtable)
1381 "Return a new syntax table.
1382 If OLDTABLE is non-nil, copy OLDTABLE.
1383 Otherwise, create a syntax table which inherits from the
1384 `standard-syntax-table'."
1385 (if oldtable
1386 (copy-syntax-table oldtable)
1387 (let ((table (make-char-table 'syntax-table nil)))
1388 (set-char-table-parent table (standard-syntax-table))
1389 table)))
1390
1391 (defun add-to-invisibility-spec (arg)
1392 "Add elements to `buffer-invisibility-spec'.
1393 See documentation for `buffer-invisibility-spec' for the kind of elements
1394 that can be added."
1395 (cond
1396 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
1397 (setq buffer-invisibility-spec (list arg)))
1398 (t
1399 (setq buffer-invisibility-spec
1400 (cons arg buffer-invisibility-spec)))))
1401
1402 (defun remove-from-invisibility-spec (arg)
1403 "Remove elements from `buffer-invisibility-spec'."
1404 (if (consp buffer-invisibility-spec)
1405 (setq buffer-invisibility-spec (delete arg buffer-invisibility-spec))))
1406 \f
1407 (defun global-set-key (key command)
1408 "Give KEY a global binding as COMMAND.
1409 COMMAND is the command definition to use; usually it is
1410 a symbol naming an interactively-callable function.
1411 KEY is a key sequence; noninteractively, it is a string or vector
1412 of characters or event types, and non-ASCII characters with codes
1413 above 127 (such as ISO Latin-1) can be included if you use a vector.
1414
1415 Note that if KEY has a local binding in the current buffer,
1416 that local binding will continue to shadow any global binding
1417 that you make with this function."
1418 (interactive "KSet key globally: \nCSet key %s to command: ")
1419 (or (vectorp key) (stringp key)
1420 (signal 'wrong-type-argument (list 'arrayp key)))
1421 (define-key (current-global-map) key command))
1422
1423 (defun local-set-key (key command)
1424 "Give KEY a local binding as COMMAND.
1425 COMMAND is the command definition to use; usually it is
1426 a symbol naming an interactively-callable function.
1427 KEY is a key sequence; noninteractively, it is a string or vector
1428 of characters or event types, and non-ASCII characters with codes
1429 above 127 (such as ISO Latin-1) can be included if you use a vector.
1430
1431 The binding goes in the current buffer's local map,
1432 which in most cases is shared with all other buffers in the same major mode."
1433 (interactive "KSet key locally: \nCSet key %s locally to command: ")
1434 (let ((map (current-local-map)))
1435 (or map
1436 (use-local-map (setq map (make-sparse-keymap))))
1437 (or (vectorp key) (stringp key)
1438 (signal 'wrong-type-argument (list 'arrayp key)))
1439 (define-key map key command)))
1440
1441 (defun global-unset-key (key)
1442 "Remove global binding of KEY.
1443 KEY is a string representing a sequence of keystrokes."
1444 (interactive "kUnset key globally: ")
1445 (global-set-key key nil))
1446
1447 (defun local-unset-key (key)
1448 "Remove local binding of KEY.
1449 KEY is a string representing a sequence of keystrokes."
1450 (interactive "kUnset key locally: ")
1451 (if (current-local-map)
1452 (local-set-key key nil))
1453 nil)
1454 \f
1455 ;; We put this here instead of in frame.el so that it's defined even on
1456 ;; systems where frame.el isn't loaded.
1457 (defun frame-configuration-p (object)
1458 "Return non-nil if OBJECT seems to be a frame configuration.
1459 Any list whose car is `frame-configuration' is assumed to be a frame
1460 configuration."
1461 (and (consp object)
1462 (eq (car object) 'frame-configuration)))
1463
1464 (defun functionp (object)
1465 "Non-nil if OBJECT is a type of object that can be called as a function."
1466 (or (subrp object) (byte-code-function-p object)
1467 (eq (car-safe object) 'lambda)
1468 (and (symbolp object) (fboundp object))))
1469
1470 (defun interactive-form (function)
1471 "Return the interactive form of FUNCTION.
1472 If function is a command (see `commandp'), value is a list of the form
1473 \(interactive SPEC). If function is not a command, return nil."
1474 (setq function (indirect-function function))
1475 (when (commandp function)
1476 (cond ((byte-code-function-p function)
1477 (when (> (length function) 5)
1478 (let ((spec (aref function 5)))
1479 (if spec
1480 (list 'interactive spec)
1481 (list 'interactive)))))
1482 ((subrp function)
1483 (subr-interactive-form function))
1484 ((eq (car-safe function) 'lambda)
1485 (setq function (cddr function))
1486 (when (stringp (car function))
1487 (setq function (cdr function)))
1488 (let ((form (car function)))
1489 (when (eq (car-safe form) 'interactive)
1490 (copy-sequence form)))))))
1491
1492 (defun assq-delete-all (key alist)
1493 "Delete from ALIST all elements whose car is KEY.
1494 Return the modified alist."
1495 (let ((tail alist))
1496 (while tail
1497 (if (eq (car (car tail)) key)
1498 (setq alist (delq (car tail) alist)))
1499 (setq tail (cdr tail)))
1500 alist))
1501
1502 (defun make-temp-file (prefix &optional dir-flag)
1503 "Create a temporary file.
1504 The returned file name (created by appending some random characters at the end
1505 of PREFIX, and expanding against `temporary-file-directory' if necessary,
1506 is guaranteed to point to a newly created empty file.
1507 You can then use `write-region' to write new data into the file.
1508
1509 If DIR-FLAG is non-nil, create a new empty directory instead of a file."
1510 (let (file)
1511 (while (condition-case ()
1512 (progn
1513 (setq file
1514 (make-temp-name
1515 (expand-file-name prefix temporary-file-directory)))
1516 (if dir-flag
1517 (make-directory file)
1518 (write-region "" nil file nil 'silent nil 'excl))
1519 nil)
1520 (file-already-exists t))
1521 ;; the file was somehow created by someone else between
1522 ;; `make-temp-name' and `write-region', let's try again.
1523 nil)
1524 file))
1525
1526 \f
1527 (defun add-minor-mode (toggle name &optional keymap after toggle-fun)
1528 "Register a new minor mode.
1529
1530 This is an XEmacs-compatibility function. Use `define-minor-mode' instead.
1531
1532 TOGGLE is a symbol which is the name of a buffer-local variable that
1533 is toggled on or off to say whether the minor mode is active or not.
1534
1535 NAME specifies what will appear in the mode line when the minor mode
1536 is active. NAME should be either a string starting with a space, or a
1537 symbol whose value is such a string.
1538
1539 Optional KEYMAP is the keymap for the minor mode that will be added
1540 to `minor-mode-map-alist'.
1541
1542 Optional AFTER specifies that TOGGLE should be added after AFTER
1543 in `minor-mode-alist'.
1544
1545 Optional TOGGLE-FUN is an interactive function to toggle the mode.
1546 It defaults to (and should by convention be) TOGGLE.
1547
1548 If TOGGLE has a non-nil `:included' property, an entry for the mode is
1549 included in the mode-line minor mode menu.
1550 If TOGGLE has a `:menu-tag', that is used for the menu item's label."
1551 (unless toggle-fun (setq toggle-fun toggle))
1552 ;; Add the toggle to the minor-modes menu if requested.
1553 (when (get toggle :included)
1554 (define-key mode-line-mode-menu
1555 (vector toggle)
1556 (list 'menu-item
1557 (or (get toggle :menu-tag)
1558 (if (stringp name) name (symbol-name toggle)))
1559 toggle-fun
1560 :button (cons :toggle toggle))))
1561 ;; Add the name to the minor-mode-alist.
1562 (when name
1563 (let ((existing (assq toggle minor-mode-alist)))
1564 (when (and (stringp name) (not (get-text-property 0 'local-map name)))
1565 (setq name
1566 (propertize name
1567 'local-map mode-line-minor-mode-keymap
1568 'help-echo "mouse-3: minor mode menu")))
1569 (if existing
1570 (setcdr existing (list name))
1571 (let ((tail minor-mode-alist) found)
1572 (while (and tail (not found))
1573 (if (eq after (caar tail))
1574 (setq found tail)
1575 (setq tail (cdr tail))))
1576 (if found
1577 (let ((rest (cdr found)))
1578 (setcdr found nil)
1579 (nconc found (list (list toggle name)) rest))
1580 (setq minor-mode-alist (cons (list toggle name)
1581 minor-mode-alist)))))))
1582 ;; Add the map to the minor-mode-map-alist.
1583 (when keymap
1584 (let ((existing (assq toggle minor-mode-map-alist)))
1585 (if existing
1586 (setcdr existing keymap)
1587 (let ((tail minor-mode-map-alist) found)
1588 (while (and tail (not found))
1589 (if (eq after (caar tail))
1590 (setq found tail)
1591 (setq tail (cdr tail))))
1592 (if found
1593 (let ((rest (cdr found)))
1594 (setcdr found nil)
1595 (nconc found (list (cons toggle keymap)) rest))
1596 (setq minor-mode-map-alist (cons (cons toggle keymap)
1597 minor-mode-map-alist))))))))
1598
1599 ;; XEmacs compatibility/convenience.
1600 (if (fboundp 'play-sound)
1601 (defun play-sound-file (file &optional volume device)
1602 "Play sound stored in FILE.
1603 VOLUME and DEVICE correspond to the keywords of the sound
1604 specification for `play-sound'."
1605 (interactive "fPlay sound file: ")
1606 (let ((sound (list :file file)))
1607 (if volume
1608 (plist-put sound :volume volume))
1609 (if device
1610 (plist-put sound :device device))
1611 (push 'sound sound)
1612 (play-sound sound))))
1613
1614 ;;; subr.el ends here