Some fixes to follow coding conventions.
[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
400 KEY must contain just one event type--that is to say, it must be a
401 string or vector of length 1, but AFTER should be a single event
402 type--a symbol or a character, not a sequence.
403
404 Bindings are always added before any inherited map.
405
406 The order of bindings in a keymap matters when it is used as a menu."
407 (unless after (setq after t))
408 (or (keymapp keymap)
409 (signal 'wrong-type-argument (list 'keymapp keymap)))
410 (if (> (length key) 1)
411 (error "multi-event key specified in `define-key-after'"))
412 (let ((tail keymap) done inserted
413 (first (aref key 0)))
414 (while (and (not done) tail)
415 ;; Delete any earlier bindings for the same key.
416 (if (eq (car-safe (car (cdr tail))) first)
417 (setcdr tail (cdr (cdr tail))))
418 ;; When we reach AFTER's binding, insert the new binding after.
419 ;; If we reach an inherited keymap, insert just before that.
420 ;; If we reach the end of this keymap, insert at the end.
421 (if (or (and (eq (car-safe (car tail)) after)
422 (not (eq after t)))
423 (eq (car (cdr tail)) 'keymap)
424 (null (cdr tail)))
425 (progn
426 ;; Stop the scan only if we find a parent keymap.
427 ;; Keep going past the inserted element
428 ;; so we can delete any duplications that come later.
429 (if (eq (car (cdr tail)) 'keymap)
430 (setq done t))
431 ;; Don't insert more than once.
432 (or inserted
433 (setcdr tail (cons (cons (aref key 0) definition) (cdr tail))))
434 (setq inserted t)))
435 (setq tail (cdr tail)))))
436
437 (defmacro kbd (keys)
438 "Convert KEYS to the internal Emacs key representation.
439 KEYS should be a string constant in the format used for
440 saving keyboard macros (see `insert-kbd-macro')."
441 (read-kbd-macro keys))
442
443 (put 'keyboard-translate-table 'char-table-extra-slots 0)
444
445 (defun keyboard-translate (from to)
446 "Translate character FROM to TO at a low level.
447 This function creates a `keyboard-translate-table' if necessary
448 and then modifies one entry in it."
449 (or (char-table-p keyboard-translate-table)
450 (setq keyboard-translate-table
451 (make-char-table 'keyboard-translate-table nil)))
452 (aset keyboard-translate-table from to))
453
454 \f
455 ;;;; The global keymap tree.
456
457 ;;; global-map, esc-map, and ctl-x-map have their values set up in
458 ;;; keymap.c; we just give them docstrings here.
459
460 (defvar global-map nil
461 "Default global keymap mapping Emacs keyboard input into commands.
462 The value is a keymap which is usually (but not necessarily) Emacs's
463 global map.")
464
465 (defvar esc-map nil
466 "Default keymap for ESC (meta) commands.
467 The normal global definition of the character ESC indirects to this keymap.")
468
469 (defvar ctl-x-map nil
470 "Default keymap for C-x commands.
471 The normal global definition of the character C-x indirects to this keymap.")
472
473 (defvar ctl-x-4-map (make-sparse-keymap)
474 "Keymap for subcommands of C-x 4")
475 (defalias 'ctl-x-4-prefix ctl-x-4-map)
476 (define-key ctl-x-map "4" 'ctl-x-4-prefix)
477
478 (defvar ctl-x-5-map (make-sparse-keymap)
479 "Keymap for frame commands.")
480 (defalias 'ctl-x-5-prefix ctl-x-5-map)
481 (define-key ctl-x-map "5" 'ctl-x-5-prefix)
482
483 \f
484 ;;;; Event manipulation functions.
485
486 ;; The call to `read' is to ensure that the value is computed at load time
487 ;; and not compiled into the .elc file. The value is negative on most
488 ;; machines, but not on all!
489 (defconst listify-key-sequence-1 (logior 128 (read "?\\M-\\^@")))
490
491 (defun listify-key-sequence (key)
492 "Convert a key sequence to a list of events."
493 (if (vectorp key)
494 (append key nil)
495 (mapcar (function (lambda (c)
496 (if (> c 127)
497 (logxor c listify-key-sequence-1)
498 c)))
499 (append key nil))))
500
501 (defsubst eventp (obj)
502 "True if the argument is an event object."
503 (or (integerp obj)
504 (and (symbolp obj)
505 (get obj 'event-symbol-elements))
506 (and (consp obj)
507 (symbolp (car obj))
508 (get (car obj) 'event-symbol-elements))))
509
510 (defun event-modifiers (event)
511 "Returns a list of symbols representing the modifier keys in event EVENT.
512 The elements of the list may include `meta', `control',
513 `shift', `hyper', `super', `alt', `click', `double', `triple', `drag',
514 and `down'."
515 (let ((type event))
516 (if (listp type)
517 (setq type (car type)))
518 (if (symbolp type)
519 (cdr (get type 'event-symbol-elements))
520 (let ((list nil))
521 (or (zerop (logand type ?\M-\^@))
522 (setq list (cons 'meta list)))
523 (or (and (zerop (logand type ?\C-\^@))
524 (>= (logand type 127) 32))
525 (setq list (cons 'control list)))
526 (or (and (zerop (logand type ?\S-\^@))
527 (= (logand type 255) (downcase (logand type 255))))
528 (setq list (cons 'shift list)))
529 (or (zerop (logand type ?\H-\^@))
530 (setq list (cons 'hyper list)))
531 (or (zerop (logand type ?\s-\^@))
532 (setq list (cons 'super list)))
533 (or (zerop (logand type ?\A-\^@))
534 (setq list (cons 'alt list)))
535 list))))
536
537 (defun event-basic-type (event)
538 "Returns the basic type of the given event (all modifiers removed).
539 The value is a printing character (not upper case) or a symbol."
540 (if (consp event)
541 (setq event (car event)))
542 (if (symbolp event)
543 (car (get event 'event-symbol-elements))
544 (let ((base (logand event (1- (lsh 1 18)))))
545 (downcase (if (< base 32) (logior base 64) base)))))
546
547 (defsubst mouse-movement-p (object)
548 "Return non-nil if OBJECT is a mouse movement event."
549 (and (consp object)
550 (eq (car object) 'mouse-movement)))
551
552 (defsubst event-start (event)
553 "Return the starting position of EVENT.
554 If EVENT is a mouse press or a mouse click, this returns the location
555 of the event.
556 If EVENT is a drag, this returns the drag's starting position.
557 The return value is of the form
558 (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
559 The `posn-' functions access elements of such lists."
560 (nth 1 event))
561
562 (defsubst event-end (event)
563 "Return the ending location of EVENT. EVENT should be a click or drag event.
564 If EVENT is a click event, this function is the same as `event-start'.
565 The return value is of the form
566 (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
567 The `posn-' functions access elements of such lists."
568 (nth (if (consp (nth 2 event)) 2 1) event))
569
570 (defsubst event-click-count (event)
571 "Return the multi-click count of EVENT, a click or drag event.
572 The return value is a positive integer."
573 (if (integerp (nth 2 event)) (nth 2 event) 1))
574
575 (defsubst posn-window (position)
576 "Return the window in POSITION.
577 POSITION should be a list of the form
578 (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
579 as returned by the `event-start' and `event-end' functions."
580 (nth 0 position))
581
582 (defsubst posn-point (position)
583 "Return the buffer location in POSITION.
584 POSITION should be a list of the form
585 (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
586 as returned by the `event-start' and `event-end' functions."
587 (if (consp (nth 1 position))
588 (car (nth 1 position))
589 (nth 1 position)))
590
591 (defsubst posn-x-y (position)
592 "Return the x and y coordinates in POSITION.
593 POSITION should be a list of the form
594 (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
595 as returned by the `event-start' and `event-end' functions."
596 (nth 2 position))
597
598 (defun posn-col-row (position)
599 "Return the column and row in POSITION, measured in characters.
600 POSITION should be a list of the form
601 (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
602 as returned by the `event-start' and `event-end' functions.
603 For a scroll-bar event, the result column is 0, and the row
604 corresponds to the vertical position of the click in the scroll bar."
605 (let ((pair (nth 2 position))
606 (window (posn-window position)))
607 (if (eq (if (consp (nth 1 position))
608 (car (nth 1 position))
609 (nth 1 position))
610 'vertical-scroll-bar)
611 (cons 0 (scroll-bar-scale pair (1- (window-height window))))
612 (if (eq (if (consp (nth 1 position))
613 (car (nth 1 position))
614 (nth 1 position))
615 'horizontal-scroll-bar)
616 (cons (scroll-bar-scale pair (window-width window)) 0)
617 (let* ((frame (if (framep window) window (window-frame window)))
618 (x (/ (car pair) (frame-char-width frame)))
619 (y (/ (cdr pair) (frame-char-height frame))))
620 (cons x y))))))
621
622 (defsubst posn-timestamp (position)
623 "Return the timestamp of POSITION.
624 POSITION should be a list of the form
625 (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
626 as returned by the `event-start' and `event-end' functions."
627 (nth 3 position))
628
629 \f
630 ;;;; Obsolescent names for functions.
631
632 (defalias 'dot 'point)
633 (defalias 'dot-marker 'point-marker)
634 (defalias 'dot-min 'point-min)
635 (defalias 'dot-max 'point-max)
636 (defalias 'window-dot 'window-point)
637 (defalias 'set-window-dot 'set-window-point)
638 (defalias 'read-input 'read-string)
639 (defalias 'send-string 'process-send-string)
640 (defalias 'send-region 'process-send-region)
641 (defalias 'show-buffer 'set-window-buffer)
642 (defalias 'buffer-flush-undo 'buffer-disable-undo)
643 (defalias 'eval-current-buffer 'eval-buffer)
644 (defalias 'compiled-function-p 'byte-code-function-p)
645 (defalias 'define-function 'defalias)
646
647 (defalias 'sref 'aref)
648 (make-obsolete 'sref 'aref "20.4")
649 (make-obsolete 'char-bytes "Now this function always returns 1" "20.4")
650
651 ;; Some programs still use this as a function.
652 (defun baud-rate ()
653 "Obsolete function returning the value of the `baud-rate' variable.
654 Please convert your programs to use the variable `baud-rate' directly."
655 baud-rate)
656
657 (defalias 'focus-frame 'ignore)
658 (defalias 'unfocus-frame 'ignore)
659 \f
660 ;;;; Alternate names for functions - these are not being phased out.
661
662 (defalias 'string= 'string-equal)
663 (defalias 'string< 'string-lessp)
664 (defalias 'move-marker 'set-marker)
665 (defalias 'not 'null)
666 (defalias 'rplaca 'setcar)
667 (defalias 'rplacd 'setcdr)
668 (defalias 'beep 'ding) ;preserve lingual purity
669 (defalias 'indent-to-column 'indent-to)
670 (defalias 'backward-delete-char 'delete-backward-char)
671 (defalias 'search-forward-regexp (symbol-function 're-search-forward))
672 (defalias 'search-backward-regexp (symbol-function 're-search-backward))
673 (defalias 'int-to-string 'number-to-string)
674 (defalias 'store-match-data 'set-match-data)
675 ;; These are the XEmacs names:
676 (defalias 'point-at-eol 'line-end-position)
677 (defalias 'point-at-bol 'line-beginning-position)
678
679 ;;; Should this be an obsolete name? If you decide it should, you get
680 ;;; to go through all the sources and change them.
681 (defalias 'string-to-int 'string-to-number)
682 \f
683 ;;;; Hook manipulation functions.
684
685 (defun make-local-hook (hook)
686 "Make the hook HOOK local to the current buffer.
687 The return value is HOOK.
688
689 You never need to call this function now that `add-hook' does it for you
690 if its LOCAL argument is non-nil.
691
692 When a hook is local, its local and global values
693 work in concert: running the hook actually runs all the hook
694 functions listed in *either* the local value *or* the global value
695 of the hook variable.
696
697 This function works by making `t' a member of the buffer-local value,
698 which acts as a flag to run the hook functions in the default value as
699 well. This works for all normal hooks, but does not work for most
700 non-normal hooks yet. We will be changing the callers of non-normal
701 hooks so that they can handle localness; this has to be done one by
702 one.
703
704 This function does nothing if HOOK is already local in the current
705 buffer.
706
707 Do not use `make-local-variable' to make a hook variable buffer-local."
708 (if (local-variable-p hook)
709 nil
710 (or (boundp hook) (set hook nil))
711 (make-local-variable hook)
712 (set hook (list t)))
713 hook)
714
715 (defun add-hook (hook function &optional append local)
716 "Add to the value of HOOK the function FUNCTION.
717 FUNCTION is not added if already present.
718 FUNCTION is added (if necessary) at the beginning of the hook list
719 unless the optional argument APPEND is non-nil, in which case
720 FUNCTION is added at the end.
721
722 The optional fourth argument, LOCAL, if non-nil, says to modify
723 the hook's buffer-local value rather than its default value.
724 This makes the hook buffer-local if needed.
725 To make a hook variable buffer-local, always use
726 `make-local-hook', not `make-local-variable'.
727
728 HOOK should be a symbol, and FUNCTION may be any valid function. If
729 HOOK is void, it is first set to nil. If HOOK's value is a single
730 function, it is changed to a list of functions."
731 (or (boundp hook) (set hook nil))
732 (or (default-boundp hook) (set-default hook nil))
733 (if local (unless (local-variable-if-set-p hook) (make-local-hook hook))
734 ;; Detect the case where make-local-variable was used on a hook
735 ;; and do what we used to do.
736 (unless (and (consp (symbol-value hook)) (memq t (symbol-value hook)))
737 (setq local t)))
738 (let ((hook-value (if local (symbol-value hook) (default-value hook))))
739 ;; If the hook value is a single function, turn it into a list.
740 (when (or (not (listp hook-value)) (eq (car hook-value) 'lambda))
741 (setq hook-value (list hook-value)))
742 ;; Do the actual addition if necessary
743 (unless (member function hook-value)
744 (setq hook-value
745 (if append
746 (append hook-value (list function))
747 (cons function hook-value))))
748 ;; Set the actual variable
749 (if local (set hook hook-value) (set-default hook hook-value))))
750
751 (defun remove-hook (hook function &optional local)
752 "Remove from the value of HOOK the function FUNCTION.
753 HOOK should be a symbol, and FUNCTION may be any valid function. If
754 FUNCTION isn't the value of HOOK, or, if FUNCTION doesn't appear in the
755 list of hooks to run in HOOK, then nothing is done. See `add-hook'.
756
757 The optional third argument, LOCAL, if non-nil, says to modify
758 the hook's buffer-local value rather than its default value.
759 This makes the hook buffer-local if needed.
760 To make a hook variable buffer-local, always use
761 `make-local-hook', not `make-local-variable'."
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) (make-local-hook hook))
765 ;; Detect the case where make-local-variable was used on a hook
766 ;; and do what we used to do.
767 (unless (and (consp (symbol-value hook)) (memq t (symbol-value hook)))
768 (setq local t)))
769 (let ((hook-value (if local (symbol-value hook) (default-value hook))))
770 ;; Remove the function, for both the list and the non-list cases.
771 (if (or (not (listp hook-value)) (eq (car hook-value) 'lambda))
772 (if (equal hook-value function) (setq hook-value nil))
773 (setq hook-value (delete function (copy-sequence hook-value))))
774 ;; If the function is on the global hook, we need to shadow it locally
775 ;;(when (and local (member function (default-value hook))
776 ;; (not (member (cons 'not function) hook-value)))
777 ;; (push (cons 'not function) hook-value))
778 ;; Set the actual variable
779 (if local (set hook hook-value) (set-default hook hook-value))))
780
781 (defun add-to-list (list-var element &optional append)
782 "Add to the value of LIST-VAR the element ELEMENT if it isn't there yet.
783 The test for presence of ELEMENT is done with `equal'.
784 If ELEMENT is added, it is added at the beginning of the list,
785 unless the optional argument APPEND is non-nil, in which case
786 ELEMENT is added at the end.
787
788 If you want to use `add-to-list' on a variable that is not defined
789 until a certain package is loaded, you should put the call to `add-to-list'
790 into a hook function that will be run only after loading the package.
791 `eval-after-load' provides one way to do this. In some cases
792 other hooks, such as major mode hooks, can do the job."
793 (if (member element (symbol-value list-var))
794 (symbol-value list-var)
795 (set list-var
796 (if append
797 (append (symbol-value list-var) (list element))
798 (cons element (symbol-value list-var))))))
799 \f
800 ;;;; Specifying things to do after certain files are loaded.
801
802 (defun eval-after-load (file form)
803 "Arrange that, if FILE is ever loaded, FORM will be run at that time.
804 This makes or adds to an entry on `after-load-alist'.
805 If FILE is already loaded, evaluate FORM right now.
806 It does nothing if FORM is already on the list for FILE.
807 FILE must match exactly. Normally FILE is the name of a library,
808 with no directory or extension specified, since that is how `load'
809 is normally called."
810 ;; Make sure `load-history' contains the files dumped with Emacs
811 ;; for the case that FILE is one of the files dumped with Emacs.
812 (load-symbol-file-load-history)
813 ;; Make sure there is an element for FILE.
814 (or (assoc file after-load-alist)
815 (setq after-load-alist (cons (list file) after-load-alist)))
816 ;; Add FORM to the element if it isn't there.
817 (let ((elt (assoc file after-load-alist)))
818 (or (member form (cdr elt))
819 (progn
820 (nconc elt (list form))
821 ;; If the file has been loaded already, run FORM right away.
822 (and (assoc file load-history)
823 (eval form)))))
824 form)
825
826 (defun eval-next-after-load (file)
827 "Read the following input sexp, and run it whenever FILE is loaded.
828 This makes or adds to an entry on `after-load-alist'.
829 FILE should be the name of a library, with no directory name."
830 (eval-after-load file (read)))
831
832 \f
833 ;;;; Input and display facilities.
834
835 (defvar read-quoted-char-radix 8
836 "*Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
837 Legitimate radix values are 8, 10 and 16.")
838
839 (custom-declare-variable-early
840 'read-quoted-char-radix 8
841 "*Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
842 Legitimate radix values are 8, 10 and 16."
843 :type '(choice (const 8) (const 10) (const 16))
844 :group 'editing-basics)
845
846 (defun read-quoted-char (&optional prompt)
847 "Like `read-char', but do not allow quitting.
848 Also, if the first character read is an octal digit,
849 we read any number of octal digits and return the
850 specified character code. Any nondigit terminates the sequence.
851 If the terminator is RET, it is discarded;
852 any other terminator is used itself as input.
853
854 The optional argument PROMPT specifies a string to use to prompt the user.
855 The variable `read-quoted-char-radix' controls which radix to use
856 for numeric input."
857 (let ((message-log-max nil) done (first t) (code 0) char)
858 (while (not done)
859 (let ((inhibit-quit first)
860 ;; Don't let C-h get the help message--only help function keys.
861 (help-char nil)
862 (help-form
863 "Type the special character you want to use,
864 or the octal character code.
865 RET terminates the character code and is discarded;
866 any other non-digit terminates the character code and is then used as input."))
867 (setq char (read-event (and prompt (format "%s-" prompt)) t))
868 (if inhibit-quit (setq quit-flag nil)))
869 ;; Translate TAB key into control-I ASCII character, and so on.
870 (and char
871 (let ((translated (lookup-key function-key-map (vector char))))
872 (if (arrayp translated)
873 (setq char (aref translated 0)))))
874 (cond ((null char))
875 ((not (integerp char))
876 (setq unread-command-events (list char)
877 done t))
878 ((/= (logand char ?\M-\^@) 0)
879 ;; Turn a meta-character into a character with the 0200 bit set.
880 (setq code (logior (logand char (lognot ?\M-\^@)) 128)
881 done t))
882 ((and (<= ?0 char) (< char (+ ?0 (min 10 read-quoted-char-radix))))
883 (setq code (+ (* code read-quoted-char-radix) (- char ?0)))
884 (and prompt (setq prompt (message "%s %c" prompt char))))
885 ((and (<= ?a (downcase char))
886 (< (downcase char) (+ ?a -10 (min 26 read-quoted-char-radix))))
887 (setq code (+ (* code read-quoted-char-radix)
888 (+ 10 (- (downcase char) ?a))))
889 (and prompt (setq prompt (message "%s %c" prompt char))))
890 ((and (not first) (eq char ?\C-m))
891 (setq done t))
892 ((not first)
893 (setq unread-command-events (list char)
894 done t))
895 (t (setq code char
896 done t)))
897 (setq first nil))
898 code))
899
900 (defun read-passwd (prompt &optional confirm default)
901 "Read a password, prompting with PROMPT. Echo `.' for each character typed.
902 End with RET, LFD, or ESC. DEL or C-h rubs out. C-u kills line.
903 Optional argument CONFIRM, if non-nil, then read it twice to make sure.
904 Optional DEFAULT is a default password to use instead of empty input."
905 (if confirm
906 (let (success)
907 (while (not success)
908 (let ((first (read-passwd prompt nil default))
909 (second (read-passwd "Confirm password: " nil default)))
910 (if (equal first second)
911 (progn
912 (and (arrayp second) (fillarray second ?\0))
913 (setq success first))
914 (and (arrayp first) (fillarray first ?\0))
915 (and (arrayp second) (fillarray second ?\0))
916 (message "Password not repeated accurately; please start over")
917 (sit-for 1))))
918 success)
919 (let ((pass nil)
920 (c 0)
921 (echo-keystrokes 0)
922 (cursor-in-echo-area t))
923 (while (progn (message "%s%s"
924 prompt
925 (make-string (length pass) ?.))
926 (setq c (read-char-exclusive nil t))
927 (and (/= c ?\r) (/= c ?\n) (/= c ?\e)))
928 (clear-this-command-keys)
929 (if (= c ?\C-u)
930 (progn
931 (and (arrayp pass) (fillarray pass ?\0))
932 (setq pass ""))
933 (if (and (/= c ?\b) (/= c ?\177))
934 (let* ((new-char (char-to-string c))
935 (new-pass (concat pass new-char)))
936 (and (arrayp pass) (fillarray pass ?\0))
937 (fillarray new-char ?\0)
938 (setq c ?\0)
939 (setq pass new-pass))
940 (if (> (length pass) 0)
941 (let ((new-pass (substring pass 0 -1)))
942 (and (arrayp pass) (fillarray pass ?\0))
943 (setq pass new-pass))))))
944 (message nil)
945 (or pass default ""))))
946 \f
947 (defun force-mode-line-update (&optional all)
948 "Force the mode-line of the current buffer to be redisplayed.
949 With optional non-nil ALL, force redisplay of all mode-lines."
950 (if all (save-excursion (set-buffer (other-buffer))))
951 (set-buffer-modified-p (buffer-modified-p)))
952
953 (defun momentary-string-display (string pos &optional exit-char message)
954 "Momentarily display STRING in the buffer at POS.
955 Display remains until next character is typed.
956 If the char is EXIT-CHAR (optional third arg, default is SPC) it is swallowed;
957 otherwise it is then available as input (as a command if nothing else).
958 Display MESSAGE (optional fourth arg) in the echo area.
959 If MESSAGE is nil, instructions to type EXIT-CHAR are displayed there."
960 (or exit-char (setq exit-char ?\ ))
961 (let ((inhibit-read-only t)
962 ;; Don't modify the undo list at all.
963 (buffer-undo-list t)
964 (modified (buffer-modified-p))
965 (name buffer-file-name)
966 insert-end)
967 (unwind-protect
968 (progn
969 (save-excursion
970 (goto-char pos)
971 ;; defeat file locking... don't try this at home, kids!
972 (setq buffer-file-name nil)
973 (insert-before-markers string)
974 (setq insert-end (point))
975 ;; If the message end is off screen, recenter now.
976 (if (< (window-end nil t) insert-end)
977 (recenter (/ (window-height) 2)))
978 ;; If that pushed message start off the screen,
979 ;; scroll to start it at the top of the screen.
980 (move-to-window-line 0)
981 (if (> (point) pos)
982 (progn
983 (goto-char pos)
984 (recenter 0))))
985 (message (or message "Type %s to continue editing.")
986 (single-key-description exit-char))
987 (let ((char (read-event)))
988 (or (eq char exit-char)
989 (setq unread-command-events (list char)))))
990 (if insert-end
991 (save-excursion
992 (delete-region pos insert-end)))
993 (setq buffer-file-name name)
994 (set-buffer-modified-p modified))))
995
996 \f
997 ;;;; Miscellanea.
998
999 ;; A number of major modes set this locally.
1000 ;; Give it a global value to avoid compiler warnings.
1001 (defvar font-lock-defaults nil)
1002
1003 (defvar suspend-hook nil
1004 "Normal hook run by `suspend-emacs', before suspending.")
1005
1006 (defvar suspend-resume-hook nil
1007 "Normal hook run by `suspend-emacs', after Emacs is continued.")
1008
1009 ;; Avoid compiler warnings about this variable,
1010 ;; which has a special meaning on certain system types.
1011 (defvar buffer-file-type nil
1012 "Non-nil if the visited file is a binary file.
1013 This variable is meaningful on MS-DOG and Windows NT.
1014 On those systems, it is automatically local in every buffer.
1015 On other systems, this variable is normally always nil.")
1016
1017 ;; This should probably be written in C (i.e., without using `walk-windows').
1018 (defun get-buffer-window-list (buffer &optional minibuf frame)
1019 "Return windows currently displaying BUFFER, or nil if none.
1020 See `walk-windows' for the meaning of MINIBUF and FRAME."
1021 (let ((buffer (if (bufferp buffer) buffer (get-buffer buffer))) windows)
1022 (walk-windows (function (lambda (window)
1023 (if (eq (window-buffer window) buffer)
1024 (setq windows (cons window windows)))))
1025 minibuf frame)
1026 windows))
1027
1028 (defun ignore (&rest ignore)
1029 "Do nothing and return nil.
1030 This function accepts any number of arguments, but ignores them."
1031 (interactive)
1032 nil)
1033
1034 (defun error (&rest args)
1035 "Signal an error, making error message by passing all args to `format'.
1036 In Emacs, the convention is that error messages start with a capital
1037 letter but *do not* end with a period. Please follow this convention
1038 for the sake of consistency."
1039 (while t
1040 (signal 'error (list (apply 'format args)))))
1041
1042 (defalias 'user-original-login-name 'user-login-name)
1043
1044 (defun start-process-shell-command (name buffer &rest args)
1045 "Start a program in a subprocess. Return the process object for it.
1046 Args are NAME BUFFER COMMAND &rest COMMAND-ARGS.
1047 NAME is name for process. It is modified if necessary to make it unique.
1048 BUFFER is the buffer or (buffer-name) to associate with the process.
1049 Process output goes at end of that buffer, unless you specify
1050 an output stream or filter function to handle the output.
1051 BUFFER may be also nil, meaning that this process is not associated
1052 with any buffer
1053 Third arg is command name, the name of a shell command.
1054 Remaining arguments are the arguments for the command.
1055 Wildcards and redirection are handled as usual in the shell."
1056 (cond
1057 ((eq system-type 'vax-vms)
1058 (apply 'start-process name buffer args))
1059 ;; We used to use `exec' to replace the shell with the command,
1060 ;; but that failed to handle (...) and semicolon, etc.
1061 (t
1062 (start-process name buffer shell-file-name shell-command-switch
1063 (mapconcat 'identity args " ")))))
1064 \f
1065 (defmacro with-current-buffer (buffer &rest body)
1066 "Execute the forms in BODY with BUFFER as the current buffer.
1067 The value returned is the value of the last form in BODY.
1068 See also `with-temp-buffer'."
1069 (cons 'save-current-buffer
1070 (cons (list 'set-buffer buffer)
1071 body)))
1072
1073 (defmacro with-temp-file (file &rest body)
1074 "Create a new buffer, evaluate BODY there, and write the buffer to FILE.
1075 The value returned is the value of the last form in BODY.
1076 See also `with-temp-buffer'."
1077 (let ((temp-file (make-symbol "temp-file"))
1078 (temp-buffer (make-symbol "temp-buffer")))
1079 `(let ((,temp-file ,file)
1080 (,temp-buffer
1081 (get-buffer-create (generate-new-buffer-name " *temp file*"))))
1082 (unwind-protect
1083 (prog1
1084 (with-current-buffer ,temp-buffer
1085 ,@body)
1086 (with-current-buffer ,temp-buffer
1087 (widen)
1088 (write-region (point-min) (point-max) ,temp-file nil 0)))
1089 (and (buffer-name ,temp-buffer)
1090 (kill-buffer ,temp-buffer))))))
1091
1092 (defmacro with-temp-message (message &rest body)
1093 "Display MESSAGE temporarily if non-nil while BODY is evaluated.
1094 The original message is restored to the echo area after BODY has finished.
1095 The value returned is the value of the last form in BODY.
1096 MESSAGE is written to the message log buffer if `message-log-max' is non-nil.
1097 If MESSAGE is nil, the echo area and message log buffer are unchanged.
1098 Use a MESSAGE of \"\" to temporarily clear the echo area."
1099 (let ((current-message (make-symbol "current-message"))
1100 (temp-message (make-symbol "with-temp-message")))
1101 `(let ((,temp-message ,message)
1102 (,current-message))
1103 (unwind-protect
1104 (progn
1105 (when ,temp-message
1106 (setq ,current-message (current-message))
1107 (message "%s" ,temp-message))
1108 ,@body)
1109 (and ,temp-message ,current-message
1110 (message "%s" ,current-message))))))
1111
1112 (defmacro with-temp-buffer (&rest body)
1113 "Create a temporary buffer, and evaluate BODY there like `progn'.
1114 See also `with-temp-file' and `with-output-to-string'."
1115 (let ((temp-buffer (make-symbol "temp-buffer")))
1116 `(let ((,temp-buffer
1117 (get-buffer-create (generate-new-buffer-name " *temp*"))))
1118 (unwind-protect
1119 (with-current-buffer ,temp-buffer
1120 ,@body)
1121 (and (buffer-name ,temp-buffer)
1122 (kill-buffer ,temp-buffer))))))
1123
1124 (defmacro with-output-to-string (&rest body)
1125 "Execute BODY, return the text it sent to `standard-output', as a string."
1126 `(let ((standard-output
1127 (get-buffer-create (generate-new-buffer-name " *string-output*"))))
1128 (let ((standard-output standard-output))
1129 ,@body)
1130 (with-current-buffer standard-output
1131 (prog1
1132 (buffer-string)
1133 (kill-buffer nil)))))
1134
1135 (defmacro combine-after-change-calls (&rest body)
1136 "Execute BODY, but don't call the after-change functions till the end.
1137 If BODY makes changes in the buffer, they are recorded
1138 and the functions on `after-change-functions' are called several times
1139 when BODY is finished.
1140 The return value is the value of the last form in BODY.
1141
1142 If `before-change-functions' is non-nil, then calls to the after-change
1143 functions can't be deferred, so in that case this macro has no effect.
1144
1145 Do not alter `after-change-functions' or `before-change-functions'
1146 in BODY."
1147 `(unwind-protect
1148 (let ((combine-after-change-calls t))
1149 . ,body)
1150 (combine-after-change-execute)))
1151
1152
1153 (defmacro with-syntax-table (table &rest body)
1154 "Evaluate BODY with syntax table of current buffer set to a copy of TABLE.
1155 The syntax table of the current buffer is saved, BODY is evaluated, and the
1156 saved table is restored, even in case of an abnormal exit.
1157 Value is what BODY returns."
1158 (let ((old-table (make-symbol "table"))
1159 (old-buffer (make-symbol "buffer")))
1160 `(let ((,old-table (syntax-table))
1161 (,old-buffer (current-buffer)))
1162 (unwind-protect
1163 (progn
1164 (set-syntax-table (copy-syntax-table ,table))
1165 ,@body)
1166 (save-current-buffer
1167 (set-buffer ,old-buffer)
1168 (set-syntax-table ,old-table))))))
1169 \f
1170 (defvar save-match-data-internal)
1171
1172 ;; We use save-match-data-internal as the local variable because
1173 ;; that works ok in practice (people should not use that variable elsewhere).
1174 ;; We used to use an uninterned symbol; the compiler handles that properly
1175 ;; now, but it generates slower code.
1176 (defmacro save-match-data (&rest body)
1177 "Execute the BODY forms, restoring the global value of the match data."
1178 ;; It is better not to use backquote here,
1179 ;; because that makes a bootstrapping problem
1180 ;; if you need to recompile all the Lisp files using interpreted code.
1181 (list 'let
1182 '((save-match-data-internal (match-data)))
1183 (list 'unwind-protect
1184 (cons 'progn body)
1185 '(set-match-data save-match-data-internal))))
1186
1187 (defun match-string (num &optional string)
1188 "Return string of text matched by last search.
1189 NUM specifies which parenthesized expression in the last regexp.
1190 Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
1191 Zero means the entire text matched by the whole regexp or whole string.
1192 STRING should be given if the last search was by `string-match' on STRING."
1193 (if (match-beginning num)
1194 (if string
1195 (substring string (match-beginning num) (match-end num))
1196 (buffer-substring (match-beginning num) (match-end num)))))
1197
1198 (defun match-string-no-properties (num &optional string)
1199 "Return string of text matched by last search, without text properties.
1200 NUM specifies which parenthesized expression in the last regexp.
1201 Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
1202 Zero means the entire text matched by the whole regexp or whole string.
1203 STRING should be given if the last search was by `string-match' on STRING."
1204 (if (match-beginning num)
1205 (if string
1206 (let ((result
1207 (substring string (match-beginning num) (match-end num))))
1208 (set-text-properties 0 (length result) nil result)
1209 result)
1210 (buffer-substring-no-properties (match-beginning num)
1211 (match-end num)))))
1212
1213 (defun split-string (string &optional separators)
1214 "Splits STRING into substrings where there are matches for SEPARATORS.
1215 Each match for SEPARATORS is a splitting point.
1216 The substrings between the splitting points are made into a list
1217 which is returned.
1218 If SEPARATORS is absent, it defaults to \"[ \\f\\t\\n\\r\\v]+\".
1219
1220 If there is match for SEPARATORS at the beginning of STRING, we do not
1221 include a null substring for that. Likewise, if there is a match
1222 at the end of STRING, we don't include a null substring for that.
1223
1224 Modifies the match data; use `save-match-data' if necessary."
1225 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
1226 (start 0)
1227 notfirst
1228 (list nil))
1229 (while (and (string-match rexp string
1230 (if (and notfirst
1231 (= start (match-beginning 0))
1232 (< start (length string)))
1233 (1+ start) start))
1234 (< (match-beginning 0) (length string)))
1235 (setq notfirst t)
1236 (or (eq (match-beginning 0) 0)
1237 (and (eq (match-beginning 0) (match-end 0))
1238 (eq (match-beginning 0) start))
1239 (setq list
1240 (cons (substring string start (match-beginning 0))
1241 list)))
1242 (setq start (match-end 0)))
1243 (or (eq start (length string))
1244 (setq list
1245 (cons (substring string start)
1246 list)))
1247 (nreverse list)))
1248
1249 (defun subst-char-in-string (fromchar tochar string &optional inplace)
1250 "Replace FROMCHAR with TOCHAR in STRING each time it occurs.
1251 Unless optional argument INPLACE is non-nil, return a new string."
1252 (let ((i (length string))
1253 (newstr (if inplace string (copy-sequence string))))
1254 (while (> i 0)
1255 (setq i (1- i))
1256 (if (eq (aref newstr i) fromchar)
1257 (aset newstr i tochar)))
1258 newstr))
1259
1260 (defun replace-regexp-in-string (regexp rep string &optional
1261 fixedcase literal subexp start)
1262 "Replace all matches for REGEXP with REP in STRING.
1263
1264 Return a new string containing the replacements.
1265
1266 Optional arguments FIXEDCASE, LITERAL and SUBEXP are like the
1267 arguments with the same names of function `replace-match'. If START
1268 is non-nil, start replacements at that index in STRING.
1269
1270 REP is either a string used as the NEWTEXT arg of `replace-match' or a
1271 function. If it is a function it is applied to each match to generate
1272 the replacement passed to `replace-match'; the match-data at this
1273 point are such that match 0 is the function's argument.
1274
1275 To replace only the first match (if any), make REGEXP match up to \\'
1276 and replace a sub-expression, e.g.
1277 (replace-regexp-in-string \"\\(foo\\).*\\'\" \"bar\" \" foo foo\" nil nil 1)
1278 => \" bar foo\"
1279 "
1280
1281 ;; To avoid excessive consing from multiple matches in long strings,
1282 ;; don't just call `replace-match' continually. Walk down the
1283 ;; string looking for matches of REGEXP and building up a (reversed)
1284 ;; list MATCHES. This comprises segments of STRING which weren't
1285 ;; matched interspersed with replacements for segments that were.
1286 ;; [For a `large' number of replacments it's more efficient to
1287 ;; operate in a temporary buffer; we can't tell from the function's
1288 ;; args whether to choose the buffer-based implementation, though it
1289 ;; might be reasonable to do so for long enough STRING.]
1290 (let ((l (length string))
1291 (start (or start 0))
1292 matches str mb me)
1293 (save-match-data
1294 (while (and (< start l) (string-match regexp string start))
1295 (setq mb (match-beginning 0)
1296 me (match-end 0))
1297 ;; If we matched the empty string, make sure we advance by one char
1298 (when (= me mb) (setq me (min l (1+ mb))))
1299 ;; Generate a replacement for the matched substring.
1300 ;; Operate only on the substring to minimize string consing.
1301 ;; Set up match data for the substring for replacement;
1302 ;; presumably this is likely to be faster than munging the
1303 ;; match data directly in Lisp.
1304 (string-match regexp (setq str (substring string mb me)))
1305 (setq matches
1306 (cons (replace-match (if (stringp rep)
1307 rep
1308 (funcall rep (match-string 0 str)))
1309 fixedcase literal str subexp)
1310 (cons (substring string start mb) ; unmatched prefix
1311 matches)))
1312 (setq start me))
1313 ;; Reconstruct a string from the pieces.
1314 (setq matches (cons (substring string start l) matches)) ; leftover
1315 (apply #'concat (nreverse matches)))))
1316 \f
1317 (defun shell-quote-argument (argument)
1318 "Quote an argument for passing as argument to an inferior shell."
1319 (if (eq system-type 'ms-dos)
1320 ;; Quote using double quotes, but escape any existing quotes in
1321 ;; the argument with backslashes.
1322 (let ((result "")
1323 (start 0)
1324 end)
1325 (if (or (null (string-match "[^\"]" argument))
1326 (< (match-end 0) (length argument)))
1327 (while (string-match "[\"]" argument start)
1328 (setq end (match-beginning 0)
1329 result (concat result (substring argument start end)
1330 "\\" (substring argument end (1+ end)))
1331 start (1+ end))))
1332 (concat "\"" result (substring argument start) "\""))
1333 (if (eq system-type 'windows-nt)
1334 (concat "\"" argument "\"")
1335 (if (equal argument "")
1336 "''"
1337 ;; Quote everything except POSIX filename characters.
1338 ;; This should be safe enough even for really weird shells.
1339 (let ((result "") (start 0) end)
1340 (while (string-match "[^-0-9a-zA-Z_./]" argument start)
1341 (setq end (match-beginning 0)
1342 result (concat result (substring argument start end)
1343 "\\" (substring argument end (1+ end)))
1344 start (1+ end)))
1345 (concat result (substring argument start)))))))
1346
1347 (defun make-syntax-table (&optional oldtable)
1348 "Return a new syntax table.
1349 If OLDTABLE is non-nil, copy OLDTABLE.
1350 Otherwise, create a syntax table which inherits
1351 all letters and control characters from the standard syntax table;
1352 other characters are copied from the standard syntax table."
1353 (if oldtable
1354 (copy-syntax-table oldtable)
1355 (let ((table (copy-syntax-table))
1356 i)
1357 (setq i 0)
1358 (while (<= i 31)
1359 (aset table i nil)
1360 (setq i (1+ i)))
1361 (setq i ?A)
1362 (while (<= i ?Z)
1363 (aset table i nil)
1364 (setq i (1+ i)))
1365 (setq i ?a)
1366 (while (<= i ?z)
1367 (aset table i nil)
1368 (setq i (1+ i)))
1369 (setq i 128)
1370 (while (<= i 255)
1371 (aset table i nil)
1372 (setq i (1+ i)))
1373 table)))
1374
1375 (defun add-to-invisibility-spec (arg)
1376 "Add elements to `buffer-invisibility-spec'.
1377 See documentation for `buffer-invisibility-spec' for the kind of elements
1378 that can be added."
1379 (cond
1380 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
1381 (setq buffer-invisibility-spec (list arg)))
1382 (t
1383 (setq buffer-invisibility-spec
1384 (cons arg buffer-invisibility-spec)))))
1385
1386 (defun remove-from-invisibility-spec (arg)
1387 "Remove elements from `buffer-invisibility-spec'."
1388 (if (consp buffer-invisibility-spec)
1389 (setq buffer-invisibility-spec (delete arg buffer-invisibility-spec))))
1390 \f
1391 (defun global-set-key (key command)
1392 "Give KEY a global binding as COMMAND.
1393 COMMAND is the command definition to use; usually it is
1394 a symbol naming an interactively-callable function.
1395 KEY is a key sequence; noninteractively, it is a string or vector
1396 of characters or event types, and non-ASCII characters with codes
1397 above 127 (such as ISO Latin-1) can be included if you use a vector.
1398
1399 Note that if KEY has a local binding in the current buffer,
1400 that local binding will continue to shadow any global binding
1401 that you make with this function."
1402 (interactive "KSet key globally: \nCSet key %s to command: ")
1403 (or (vectorp key) (stringp key)
1404 (signal 'wrong-type-argument (list 'arrayp key)))
1405 (define-key (current-global-map) key command))
1406
1407 (defun local-set-key (key command)
1408 "Give KEY a local 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 The binding goes in the current buffer's local map,
1416 which in most cases is shared with all other buffers in the same major mode."
1417 (interactive "KSet key locally: \nCSet key %s locally to command: ")
1418 (let ((map (current-local-map)))
1419 (or map
1420 (use-local-map (setq map (make-sparse-keymap))))
1421 (or (vectorp key) (stringp key)
1422 (signal 'wrong-type-argument (list 'arrayp key)))
1423 (define-key map key command)))
1424
1425 (defun global-unset-key (key)
1426 "Remove global binding of KEY.
1427 KEY is a string representing a sequence of keystrokes."
1428 (interactive "kUnset key globally: ")
1429 (global-set-key key nil))
1430
1431 (defun local-unset-key (key)
1432 "Remove local binding of KEY.
1433 KEY is a string representing a sequence of keystrokes."
1434 (interactive "kUnset key locally: ")
1435 (if (current-local-map)
1436 (local-set-key key nil))
1437 nil)
1438 \f
1439 ;; We put this here instead of in frame.el so that it's defined even on
1440 ;; systems where frame.el isn't loaded.
1441 (defun frame-configuration-p (object)
1442 "Return non-nil if OBJECT seems to be a frame configuration.
1443 Any list whose car is `frame-configuration' is assumed to be a frame
1444 configuration."
1445 (and (consp object)
1446 (eq (car object) 'frame-configuration)))
1447
1448 (defun functionp (object)
1449 "Non-nil if OBJECT is a type of object that can be called as a function."
1450 (or (subrp object) (byte-code-function-p object)
1451 (eq (car-safe object) 'lambda)
1452 (and (symbolp object) (fboundp object))))
1453
1454 (defun interactive-form (function)
1455 "Return the interactive form of FUNCTION.
1456 If function is a command (see `commandp'), value is a list of the form
1457 \(interactive SPEC). If function is not a command, return nil."
1458 (setq function (indirect-function function))
1459 (when (commandp function)
1460 (cond ((byte-code-function-p function)
1461 (when (> (length function) 5)
1462 (let ((spec (aref function 5)))
1463 (if spec
1464 (list 'interactive spec)
1465 (list 'interactive)))))
1466 ((subrp function)
1467 (subr-interactive-form function))
1468 ((eq (car-safe function) 'lambda)
1469 (setq function (cddr function))
1470 (when (stringp (car function))
1471 (setq function (cdr function)))
1472 (let ((form (car function)))
1473 (when (eq (car-safe form) 'interactive)
1474 (copy-sequence form)))))))
1475
1476 (defun assq-delete-all (key alist)
1477 "Delete from ALIST all elements whose car is KEY.
1478 Return the modified alist."
1479 (let ((tail alist))
1480 (while tail
1481 (if (eq (car (car tail)) key)
1482 (setq alist (delq (car tail) alist)))
1483 (setq tail (cdr tail)))
1484 alist))
1485
1486 (defun make-temp-file (prefix &optional dir-flag)
1487 "Create a temporary file.
1488 The returned file name (created by appending some random characters at the end
1489 of PREFIX, and expanding against `temporary-file-directory' if necessary,
1490 is guaranteed to point to a newly created empty file.
1491 You can then use `write-region' to write new data into the file.
1492
1493 If DIR-FLAG is non-nil, create a new empty directory instead of a file."
1494 (let (file)
1495 (while (condition-case ()
1496 (progn
1497 (setq file
1498 (make-temp-name
1499 (expand-file-name prefix temporary-file-directory)))
1500 (if dir-flag
1501 (make-directory file)
1502 (write-region "" nil file nil 'silent nil 'excl))
1503 nil)
1504 (file-already-exists t))
1505 ;; the file was somehow created by someone else between
1506 ;; `make-temp-name' and `write-region', let's try again.
1507 nil)
1508 file))
1509
1510 \f
1511 (defun add-minor-mode (toggle name &optional keymap after toggle-fun)
1512 "Register a new minor mode.
1513
1514 This is an XEmacs-compatibility function. Use `define-minor-mode' instead.
1515
1516 TOGGLE is a symbol which is the name of a buffer-local variable that
1517 is toggled on or off to say whether the minor mode is active or not.
1518
1519 NAME specifies what will appear in the mode line when the minor mode
1520 is active. NAME should be either a string starting with a space, or a
1521 symbol whose value is such a string.
1522
1523 Optional KEYMAP is the keymap for the minor mode that will be added
1524 to `minor-mode-map-alist'.
1525
1526 Optional AFTER specifies that TOGGLE should be added after AFTER
1527 in `minor-mode-alist'.
1528
1529 Optional TOGGLE-FUN is an interactive function to toggle the mode.
1530 It defaults to (and should by convention be) TOGGLE.
1531
1532 If TOGGLE has a non-nil `:included' property, an entry for the mode is
1533 included in the mode-line minor mode menu.
1534 If TOGGLE has a `:menu-tag', that is used for the menu item's label."
1535 (unless toggle-fun (setq toggle-fun toggle))
1536 ;; Add the toggle to the minor-modes menu if requested.
1537 (when (get toggle :included)
1538 (define-key mode-line-mode-menu
1539 (vector toggle)
1540 (list 'menu-item
1541 (or (get toggle :menu-tag)
1542 (if (stringp name) name (symbol-name toggle)))
1543 toggle-fun
1544 :button (cons :toggle toggle))))
1545 ;; Add the name to the minor-mode-alist.
1546 (when name
1547 (let ((existing (assq toggle minor-mode-alist)))
1548 (when (and (stringp name) (not (get-text-property 0 'local-map name)))
1549 (setq name
1550 (apply 'propertize name
1551 'local-map (make-mode-line-mouse2-map toggle-fun)
1552 (unless (get-text-property 0 'help-echo name)
1553 (list 'help-echo
1554 (format "mouse-2: turn off %S" toggle))))))
1555 (if existing
1556 (setcdr existing (list name))
1557 (let ((tail minor-mode-alist) found)
1558 (while (and tail (not found))
1559 (if (eq after (caar tail))
1560 (setq found tail)
1561 (setq tail (cdr tail))))
1562 (if found
1563 (let ((rest (cdr found)))
1564 (setcdr found nil)
1565 (nconc found (list (list toggle name)) rest))
1566 (setq minor-mode-alist (cons (list toggle name)
1567 minor-mode-alist)))))))
1568 ;; Add the map to the minor-mode-map-alist.
1569 (when keymap
1570 (let ((existing (assq toggle minor-mode-map-alist)))
1571 (if existing
1572 (setcdr existing keymap)
1573 (let ((tail minor-mode-map-alist) found)
1574 (while (and tail (not found))
1575 (if (eq after (caar tail))
1576 (setq found tail)
1577 (setq tail (cdr tail))))
1578 (if found
1579 (let ((rest (cdr found)))
1580 (setcdr found nil)
1581 (nconc found (list (cons toggle keymap)) rest))
1582 (setq minor-mode-map-alist (cons (cons toggle keymap)
1583 minor-mode-map-alist))))))))
1584
1585 ;; XEmacs compatibility/convenience.
1586 (if (fboundp 'play-sound)
1587 (defun play-sound-file (file &optional volume device)
1588 "Play sound stored in FILE.
1589 VOLUME and DEVICE correspond to the keywords of the sound
1590 specification for `play-sound'."
1591 (interactive "fPlay sound file: ")
1592 (let ((sound (list :file file)))
1593 (if volume
1594 (plist-put sound :volume volume))
1595 (if device
1596 (plist-put sound :device device))
1597 (push 'sound sound)
1598 (play-sound sound))))
1599
1600 ;;; subr.el ends here