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