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