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