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