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