(read-quoted-char): Read any number of octal digits,
[bpt/emacs.git] / lisp / subr.el
1 ;;; subr.el --- basic lisp subroutines for Emacs
2
3 ;; Copyright (C) 1985, 1986, 1992, 1994, 1995 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
24 \f
25 ;;;; Lisp language features.
26
27 (defmacro lambda (&rest cdr)
28 "Return a lambda expression.
29 A call of the form (lambda ARGS DOCSTRING INTERACTIVE BODY) is
30 self-quoting; the result of evaluating the lambda expression is the
31 expression itself. The lambda expression may then be treated as a
32 function, i.e., stored as the function value of a symbol, passed to
33 funcall or mapcar, etc.
34
35 ARGS should take the same form as an argument list for a `defun'.
36 DOCSTRING is an optional documentation string.
37 If present, it should describe how to call the function.
38 But documentation strings are usually not useful in nameless functions.
39 INTERACTIVE should be a call to the function `interactive', which see.
40 It may also be omitted.
41 BODY should be a list of lisp expressions."
42 ;; Note that this definition should not use backquotes; subr.el should not
43 ;; depend on backquote.el.
44 (list 'function (cons 'lambda cdr)))
45
46 (defmacro when (cond &rest body)
47 "(when COND BODY...): if COND yields non-nil, do BODY, else return nil."
48 (list 'if cond (cons 'progn body)))
49 (put 'when 'lisp-indent-function 1)
50 (put 'when 'edebug-form-spec '(&rest form))
51
52 (defmacro unless (cond &rest body)
53 "(unless COND BODY...): if COND yields nil, do BODY, else return nil."
54 (cons 'if (cons cond (cons nil body))))
55 (put 'unless 'lisp-indent-function 1)
56 (put 'unless 'edebug-form-spec '(&rest form))
57 \f
58 ;;;; Keymap support.
59
60 (defun undefined ()
61 (interactive)
62 (ding))
63
64 ;Prevent the \{...} documentation construct
65 ;from mentioning keys that run this command.
66 (put 'undefined 'suppress-keymap t)
67
68 (defun suppress-keymap (map &optional nodigits)
69 "Make MAP override all normally self-inserting keys to be undefined.
70 Normally, as an exception, digits and minus-sign are set to make prefix args,
71 but optional second arg NODIGITS non-nil treats them like other chars."
72 (substitute-key-definition 'self-insert-command 'undefined map global-map)
73 (or nodigits
74 (let (loop)
75 (define-key map "-" 'negative-argument)
76 ;; Make plain numbers do numeric args.
77 (setq loop ?0)
78 (while (<= loop ?9)
79 (define-key map (char-to-string loop) 'digit-argument)
80 (setq loop (1+ loop))))))
81
82 ;Moved to keymap.c
83 ;(defun copy-keymap (keymap)
84 ; "Return a copy of KEYMAP"
85 ; (while (not (keymapp keymap))
86 ; (setq keymap (signal 'wrong-type-argument (list 'keymapp keymap))))
87 ; (if (vectorp keymap)
88 ; (copy-sequence keymap)
89 ; (copy-alist keymap)))
90
91 (defvar key-substitution-in-progress nil
92 "Used internally by substitute-key-definition.")
93
94 (defun substitute-key-definition (olddef newdef keymap &optional oldmap prefix)
95 "Replace OLDDEF with NEWDEF for any keys in KEYMAP now defined as OLDDEF.
96 In other words, OLDDEF is replaced with NEWDEF where ever it appears.
97 If optional fourth argument OLDMAP is specified, we redefine
98 in KEYMAP as NEWDEF those chars which are defined as OLDDEF in OLDMAP."
99 (or prefix (setq prefix ""))
100 (let* ((scan (or oldmap keymap))
101 (vec1 (vector nil))
102 (prefix1 (vconcat prefix vec1))
103 (key-substitution-in-progress
104 (cons scan key-substitution-in-progress)))
105 ;; Scan OLDMAP, finding each char or event-symbol that
106 ;; has any definition, and act on it with hack-key.
107 (while (consp scan)
108 (if (consp (car scan))
109 (let ((char (car (car scan)))
110 (defn (cdr (car scan))))
111 ;; The inside of this let duplicates exactly
112 ;; the inside of the following let that handles array elements.
113 (aset vec1 0 char)
114 (aset prefix1 (length prefix) char)
115 (let (inner-def skipped)
116 ;; Skip past menu-prompt.
117 (while (stringp (car-safe defn))
118 (setq skipped (cons (car defn) skipped))
119 (setq defn (cdr defn)))
120 ;; Skip past cached key-equivalence data for menu items.
121 (and (consp defn) (consp (car defn))
122 (setq defn (cdr defn)))
123 (setq inner-def defn)
124 ;; Look past a symbol that names a keymap.
125 (while (and (symbolp inner-def)
126 (fboundp inner-def))
127 (setq inner-def (symbol-function inner-def)))
128 (if (or (eq defn olddef)
129 ;; Compare with equal if definition is a key sequence.
130 ;; That is useful for operating on function-key-map.
131 (and (or (stringp defn) (vectorp defn))
132 (equal defn olddef)))
133 (define-key keymap prefix1 (nconc (nreverse skipped) newdef))
134 (if (and (keymapp defn)
135 ;; Avoid recursively scanning
136 ;; where KEYMAP does not have a submap.
137 (let ((elt (lookup-key keymap prefix1)))
138 (or (null elt)
139 (keymapp elt)))
140 ;; Avoid recursively rescanning keymap being scanned.
141 (not (memq inner-def
142 key-substitution-in-progress)))
143 ;; If this one isn't being scanned already,
144 ;; scan it now.
145 (substitute-key-definition olddef newdef keymap
146 inner-def
147 prefix1)))))
148 (if (vectorp (car scan))
149 (let* ((array (car scan))
150 (len (length array))
151 (i 0))
152 (while (< i len)
153 (let ((char i) (defn (aref array i)))
154 ;; The inside of this let duplicates exactly
155 ;; the inside of the previous let.
156 (aset vec1 0 char)
157 (aset prefix1 (length prefix) char)
158 (let (inner-def skipped)
159 ;; Skip past menu-prompt.
160 (while (stringp (car-safe defn))
161 (setq skipped (cons (car defn) skipped))
162 (setq defn (cdr defn)))
163 (and (consp defn) (consp (car defn))
164 (setq defn (cdr defn)))
165 (setq inner-def defn)
166 (while (and (symbolp inner-def)
167 (fboundp inner-def))
168 (setq inner-def (symbol-function inner-def)))
169 (if (or (eq defn olddef)
170 (and (or (stringp defn) (vectorp defn))
171 (equal defn olddef)))
172 (define-key keymap prefix1
173 (nconc (nreverse skipped) newdef))
174 (if (and (keymapp defn)
175 (let ((elt (lookup-key keymap prefix1)))
176 (or (null elt)
177 (keymapp elt)))
178 (not (memq inner-def
179 key-substitution-in-progress)))
180 (substitute-key-definition olddef newdef keymap
181 inner-def
182 prefix1)))))
183 (setq i (1+ i))))
184 (if (char-table-p (car scan))
185 (map-char-table
186 (function (lambda (char defn)
187 (let ()
188 ;; The inside of this let duplicates exactly
189 ;; the inside of the previous let,
190 ;; except that it uses set-char-table-range
191 ;; instead of define-key.
192 (aset vec1 0 char)
193 (aset prefix1 (length prefix) char)
194 (let (inner-def skipped)
195 ;; Skip past menu-prompt.
196 (while (stringp (car-safe defn))
197 (setq skipped (cons (car defn) skipped))
198 (setq defn (cdr defn)))
199 (and (consp defn) (consp (car defn))
200 (setq defn (cdr defn)))
201 (setq inner-def defn)
202 (while (and (symbolp inner-def)
203 (fboundp inner-def))
204 (setq inner-def (symbol-function inner-def)))
205 (if (or (eq defn olddef)
206 (and (or (stringp defn) (vectorp defn))
207 (equal defn olddef)))
208 (define-key keymap prefix1
209 (nconc (nreverse skipped) newdef))
210 (if (and (keymapp defn)
211 (let ((elt (lookup-key keymap prefix1)))
212 (or (null elt)
213 (keymapp elt)))
214 (not (memq inner-def
215 key-substitution-in-progress)))
216 (substitute-key-definition olddef newdef keymap
217 inner-def
218 prefix1)))))))
219 (car scan)))))
220 (setq scan (cdr scan)))))
221
222 (defun define-key-after (keymap key definition after)
223 "Add binding in KEYMAP for KEY => DEFINITION, right after AFTER's binding.
224 This is like `define-key' except that the binding for KEY is placed
225 just after the binding for the event AFTER, instead of at the beginning
226 of the map. Note that AFTER must be an event type (like KEY), NOT a command
227 \(like DEFINITION).
228
229 If AFTER is t, the new binding goes at the end of the keymap.
230
231 KEY must contain just one event type--that is to say, it must be
232 a string or vector of length 1.
233
234 The order of bindings in a keymap matters when it is used as a menu."
235
236 (or (keymapp keymap)
237 (signal 'wrong-type-argument (list 'keymapp keymap)))
238 (if (> (length key) 1)
239 (error "multi-event key specified in `define-key-after'"))
240 (let ((tail keymap) done inserted
241 (first (aref key 0)))
242 (while (and (not done) tail)
243 ;; Delete any earlier bindings for the same key.
244 (if (eq (car-safe (car (cdr tail))) first)
245 (setcdr tail (cdr (cdr tail))))
246 ;; When we reach AFTER's binding, insert the new binding after.
247 ;; If we reach an inherited keymap, insert just before that.
248 ;; If we reach the end of this keymap, insert at the end.
249 (if (or (and (eq (car-safe (car tail)) after)
250 (not (eq after t)))
251 (eq (car (cdr tail)) 'keymap)
252 (null (cdr tail)))
253 (progn
254 ;; Stop the scan only if we find a parent keymap.
255 ;; Keep going past the inserted element
256 ;; so we can delete any duplications that come later.
257 (if (eq (car (cdr tail)) 'keymap)
258 (setq done t))
259 ;; Don't insert more than once.
260 (or inserted
261 (setcdr tail (cons (cons (aref key 0) definition) (cdr tail))))
262 (setq inserted t)))
263 (setq tail (cdr tail)))))
264
265 (defmacro kbd (keys)
266 "Convert KEYS to the internal Emacs key representation.
267 KEYS should be a string constant in the format used for
268 saving keyboard macros (see `insert-kbd-macro')."
269 (read-kbd-macro keys))
270
271 (put 'keyboard-translate-table 'char-table-extra-slots 0)
272
273 (defun keyboard-translate (from to)
274 "Translate character FROM to TO at a low level.
275 This function creates a `keyboard-translate-table' if necessary
276 and then modifies one entry in it."
277 (or (char-table-p keyboard-translate-table)
278 (setq keyboard-translate-table
279 (make-char-table 'keyboard-translate-table nil)))
280 (aset keyboard-translate-table from to))
281
282 \f
283 ;;;; The global keymap tree.
284
285 ;;; global-map, esc-map, and ctl-x-map have their values set up in
286 ;;; keymap.c; we just give them docstrings here.
287
288 (defvar global-map nil
289 "Default global keymap mapping Emacs keyboard input into commands.
290 The value is a keymap which is usually (but not necessarily) Emacs's
291 global map.")
292
293 (defvar esc-map nil
294 "Default keymap for ESC (meta) commands.
295 The normal global definition of the character ESC indirects to this keymap.")
296
297 (defvar ctl-x-map nil
298 "Default keymap for C-x commands.
299 The normal global definition of the character C-x indirects to this keymap.")
300
301 (defvar ctl-x-4-map (make-sparse-keymap)
302 "Keymap for subcommands of C-x 4")
303 (defalias 'ctl-x-4-prefix ctl-x-4-map)
304 (define-key ctl-x-map "4" 'ctl-x-4-prefix)
305
306 (defvar ctl-x-5-map (make-sparse-keymap)
307 "Keymap for frame commands.")
308 (defalias 'ctl-x-5-prefix ctl-x-5-map)
309 (define-key ctl-x-map "5" 'ctl-x-5-prefix)
310
311 \f
312 ;;;; Event manipulation functions.
313
314 ;; The call to `read' is to ensure that the value is computed at load time
315 ;; and not compiled into the .elc file. The value is negative on most
316 ;; machines, but not on all!
317 (defconst listify-key-sequence-1 (logior 128 (read "?\\M-\\^@")))
318
319 (defun listify-key-sequence (key)
320 "Convert a key sequence to a list of events."
321 (if (vectorp key)
322 (append key nil)
323 (mapcar (function (lambda (c)
324 (if (> c 127)
325 (logxor c listify-key-sequence-1)
326 c)))
327 (append key nil))))
328
329 (defsubst eventp (obj)
330 "True if the argument is an event object."
331 (or (integerp obj)
332 (and (symbolp obj)
333 (get obj 'event-symbol-elements))
334 (and (consp obj)
335 (symbolp (car obj))
336 (get (car obj) 'event-symbol-elements))))
337
338 (defun event-modifiers (event)
339 "Returns a list of symbols representing the modifier keys in event EVENT.
340 The elements of the list may include `meta', `control',
341 `shift', `hyper', `super', `alt', `click', `double', `triple', `drag',
342 and `down'."
343 (let ((type event))
344 (if (listp type)
345 (setq type (car type)))
346 (if (symbolp type)
347 (cdr (get type 'event-symbol-elements))
348 (let ((list nil))
349 (or (zerop (logand type ?\M-\^@))
350 (setq list (cons 'meta list)))
351 (or (and (zerop (logand type ?\C-\^@))
352 (>= (logand type 127) 32))
353 (setq list (cons 'control list)))
354 (or (and (zerop (logand type ?\S-\^@))
355 (= (logand type 255) (downcase (logand type 255))))
356 (setq list (cons 'shift list)))
357 (or (zerop (logand type ?\H-\^@))
358 (setq list (cons 'hyper list)))
359 (or (zerop (logand type ?\s-\^@))
360 (setq list (cons 'super list)))
361 (or (zerop (logand type ?\A-\^@))
362 (setq list (cons 'alt list)))
363 list))))
364
365 (defun event-basic-type (event)
366 "Returns the basic type of the given event (all modifiers removed).
367 The value is an ASCII printing character (not upper case) or a symbol."
368 (if (consp event)
369 (setq event (car event)))
370 (if (symbolp event)
371 (car (get event 'event-symbol-elements))
372 (let ((base (logand event (1- (lsh 1 18)))))
373 (downcase (if (< base 32) (logior base 64) base)))))
374
375 (defsubst mouse-movement-p (object)
376 "Return non-nil if OBJECT is a mouse movement event."
377 (and (consp object)
378 (eq (car object) 'mouse-movement)))
379
380 (defsubst event-start (event)
381 "Return the starting position of EVENT.
382 If EVENT is a mouse press or a mouse click, this returns the location
383 of the event.
384 If EVENT is a drag, this returns the drag's starting position.
385 The return value is of the form
386 (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
387 The `posn-' functions access elements of such lists."
388 (nth 1 event))
389
390 (defsubst event-end (event)
391 "Return the ending location of EVENT. EVENT should be a click or drag event.
392 If EVENT is a click event, this function is the same as `event-start'.
393 The return value is of the form
394 (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
395 The `posn-' functions access elements of such lists."
396 (nth (if (consp (nth 2 event)) 2 1) event))
397
398 (defsubst event-click-count (event)
399 "Return the multi-click count of EVENT, a click or drag event.
400 The return value is a positive integer."
401 (if (integerp (nth 2 event)) (nth 2 event) 1))
402
403 (defsubst posn-window (position)
404 "Return the window in POSITION.
405 POSITION should be a list of the form
406 (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
407 as returned by the `event-start' and `event-end' functions."
408 (nth 0 position))
409
410 (defsubst posn-point (position)
411 "Return the buffer location in POSITION.
412 POSITION should be a list of the form
413 (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
414 as returned by the `event-start' and `event-end' functions."
415 (if (consp (nth 1 position))
416 (car (nth 1 position))
417 (nth 1 position)))
418
419 (defsubst posn-x-y (position)
420 "Return the x and y coordinates in POSITION.
421 POSITION should be a list of the form
422 (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
423 as returned by the `event-start' and `event-end' functions."
424 (nth 2 position))
425
426 (defun posn-col-row (position)
427 "Return the column and row in POSITION, measured in characters.
428 POSITION should be a list of the form
429 (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
430 as returned by the `event-start' and `event-end' functions.
431 For a scroll-bar event, the result column is 0, and the row
432 corresponds to the vertical position of the click in the scroll bar."
433 (let ((pair (nth 2 position))
434 (window (posn-window position)))
435 (if (eq (if (consp (nth 1 position))
436 (car (nth 1 position))
437 (nth 1 position))
438 'vertical-scroll-bar)
439 (cons 0 (scroll-bar-scale pair (1- (window-height window))))
440 (if (eq (if (consp (nth 1 position))
441 (car (nth 1 position))
442 (nth 1 position))
443 'horizontal-scroll-bar)
444 (cons (scroll-bar-scale pair (window-width window)) 0)
445 (let* ((frame (if (framep window) window (window-frame window)))
446 (x (/ (car pair) (frame-char-width frame)))
447 (y (/ (cdr pair) (frame-char-height frame))))
448 (cons x y))))))
449
450 (defsubst posn-timestamp (position)
451 "Return the timestamp of POSITION.
452 POSITION should be a list of the form
453 (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
454 as returned by the `event-start' and `event-end' functions."
455 (nth 3 position))
456
457 \f
458 ;;;; Obsolescent names for functions.
459
460 (defalias 'dot 'point)
461 (defalias 'dot-marker 'point-marker)
462 (defalias 'dot-min 'point-min)
463 (defalias 'dot-max 'point-max)
464 (defalias 'window-dot 'window-point)
465 (defalias 'set-window-dot 'set-window-point)
466 (defalias 'read-input 'read-string)
467 (defalias 'send-string 'process-send-string)
468 (defalias 'send-region 'process-send-region)
469 (defalias 'show-buffer 'set-window-buffer)
470 (defalias 'buffer-flush-undo 'buffer-disable-undo)
471 (defalias 'eval-current-buffer 'eval-buffer)
472 (defalias 'compiled-function-p 'byte-code-function-p)
473 (defalias 'define-function 'defalias)
474
475 ;; Some programs still use this as a function.
476 (defun baud-rate ()
477 "Obsolete function returning the value of the `baud-rate' variable.
478 Please convert your programs to use the variable `baud-rate' directly."
479 baud-rate)
480
481 (defalias 'focus-frame 'ignore)
482 (defalias 'unfocus-frame 'ignore)
483 \f
484 ;;;; Alternate names for functions - these are not being phased out.
485
486 (defalias 'string= 'string-equal)
487 (defalias 'string< 'string-lessp)
488 (defalias 'move-marker 'set-marker)
489 (defalias 'not 'null)
490 (defalias 'rplaca 'setcar)
491 (defalias 'rplacd 'setcdr)
492 (defalias 'beep 'ding) ;preserve lingual purity
493 (defalias 'indent-to-column 'indent-to)
494 (defalias 'backward-delete-char 'delete-backward-char)
495 (defalias 'search-forward-regexp (symbol-function 're-search-forward))
496 (defalias 'search-backward-regexp (symbol-function 're-search-backward))
497 (defalias 'int-to-string 'number-to-string)
498 (defalias 'set-match-data 'store-match-data)
499
500 ;;; Should this be an obsolete name? If you decide it should, you get
501 ;;; to go through all the sources and change them.
502 (defalias 'string-to-int 'string-to-number)
503 \f
504 ;;;; Hook manipulation functions.
505
506 (defun make-local-hook (hook)
507 "Make the hook HOOK local to the current buffer.
508 When a hook is local, its local and global values
509 work in concert: running the hook actually runs all the hook
510 functions listed in *either* the local value *or* the global value
511 of the hook variable.
512
513 This function works by making `t' a member of the buffer-local value,
514 which acts as a flag to run the hook functions in the default value as
515 well. This works for all normal hooks, but does not work for most
516 non-normal hooks yet. We will be changing the callers of non-normal
517 hooks so that they can handle localness; this has to be done one by
518 one.
519
520 This function does nothing if HOOK is already local in the current
521 buffer.
522
523 Do not use `make-local-variable' to make a hook variable buffer-local."
524 (if (local-variable-p hook)
525 nil
526 (or (boundp hook) (set hook nil))
527 (make-local-variable hook)
528 (set hook (list t))))
529
530 (defun add-hook (hook function &optional append local)
531 "Add to the value of HOOK the function FUNCTION.
532 FUNCTION is not added if already present.
533 FUNCTION is added (if necessary) at the beginning of the hook list
534 unless the optional argument APPEND is non-nil, in which case
535 FUNCTION is added at the end.
536
537 The optional fourth argument, LOCAL, if non-nil, says to modify
538 the hook's buffer-local value rather than its default value.
539 This makes no difference if the hook is not buffer-local.
540 To make a hook variable buffer-local, always use
541 `make-local-hook', not `make-local-variable'.
542
543 HOOK should be a symbol, and FUNCTION may be any valid function. If
544 HOOK is void, it is first set to nil. If HOOK's value is a single
545 function, it is changed to a list of functions."
546 (or (boundp hook) (set hook nil))
547 (or (default-boundp hook) (set-default hook nil))
548 ;; If the hook value is a single function, turn it into a list.
549 (let ((old (symbol-value hook)))
550 (if (or (not (listp old)) (eq (car old) 'lambda))
551 (set hook (list old))))
552 (if (or local
553 ;; Detect the case where make-local-variable was used on a hook
554 ;; and do what we used to do.
555 (and (local-variable-if-set-p hook)
556 (not (memq t (symbol-value hook)))))
557 ;; Alter the local value only.
558 (or (if (consp function)
559 (member function (symbol-value hook))
560 (memq function (symbol-value hook)))
561 (set hook
562 (if append
563 (append (symbol-value hook) (list function))
564 (cons function (symbol-value hook)))))
565 ;; Alter the global value (which is also the only value,
566 ;; if the hook doesn't have a local value).
567 (or (if (consp function)
568 (member function (default-value hook))
569 (memq function (default-value hook)))
570 (set-default hook
571 (if append
572 (append (default-value hook) (list function))
573 (cons function (default-value hook)))))))
574
575 (defun remove-hook (hook function &optional local)
576 "Remove from the value of HOOK the function FUNCTION.
577 HOOK should be a symbol, and FUNCTION may be any valid function. If
578 FUNCTION isn't the value of HOOK, or, if FUNCTION doesn't appear in the
579 list of hooks to run in HOOK, then nothing is done. See `add-hook'.
580
581 The optional third argument, LOCAL, if non-nil, says to modify
582 the hook's buffer-local value rather than its default value.
583 This makes no difference if the hook is not buffer-local.
584 To make a hook variable buffer-local, always use
585 `make-local-hook', not `make-local-variable'."
586 (if (or (not (boundp hook)) ;unbound symbol, or
587 (not (default-boundp 'hook))
588 (null (symbol-value hook)) ;value is nil, or
589 (null function)) ;function is nil, then
590 nil ;Do nothing.
591 (if (or local
592 ;; Detect the case where make-local-variable was used on a hook
593 ;; and do what we used to do.
594 (and (local-variable-p hook)
595 (not (memq t (symbol-value hook)))))
596 (let ((hook-value (symbol-value hook)))
597 (if (consp hook-value)
598 (if (member function hook-value)
599 (setq hook-value (delete function (copy-sequence hook-value))))
600 (if (equal hook-value function)
601 (setq hook-value nil)))
602 (set hook hook-value))
603 (let ((hook-value (default-value hook)))
604 (if (consp hook-value)
605 (if (member function hook-value)
606 (setq hook-value (delete function (copy-sequence hook-value))))
607 (if (equal hook-value function)
608 (setq hook-value nil)))
609 (set-default hook hook-value)))))
610
611 (defun add-to-list (list-var element)
612 "Add to the value of LIST-VAR the element ELEMENT if it isn't there yet.
613 The test for presence of ELEMENT is done with `equal'.
614 If you want to use `add-to-list' on a variable that is not defined
615 until a certain package is loaded, you should put the call to `add-to-list'
616 into a hook function that will be run only after loading the package.
617 `eval-after-load' provides one way to do this. In some cases
618 other hooks, such as major mode hooks, can do the job."
619 (or (member element (symbol-value list-var))
620 (set list-var (cons element (symbol-value list-var)))))
621 \f
622 ;;;; Specifying things to do after certain files are loaded.
623
624 (defun eval-after-load (file form)
625 "Arrange that, if FILE is ever loaded, FORM will be run at that time.
626 This makes or adds to an entry on `after-load-alist'.
627 If FILE is already loaded, evaluate FORM right now.
628 It does nothing if FORM is already on the list for FILE.
629 FILE should be the name of a library, with no directory name."
630 ;; Make sure there is an element for FILE.
631 (or (assoc file after-load-alist)
632 (setq after-load-alist (cons (list file) after-load-alist)))
633 ;; Add FORM to the element if it isn't there.
634 (let ((elt (assoc file after-load-alist)))
635 (or (member form (cdr elt))
636 (progn
637 (nconc elt (list form))
638 ;; If the file has been loaded already, run FORM right away.
639 (and (assoc file load-history)
640 (eval form)))))
641 form)
642
643 (defun eval-next-after-load (file)
644 "Read the following input sexp, and run it whenever FILE is loaded.
645 This makes or adds to an entry on `after-load-alist'.
646 FILE should be the name of a library, with no directory name."
647 (eval-after-load file (read)))
648
649 \f
650 ;;;; Input and display facilities.
651
652 (defun read-quoted-char (&optional prompt)
653 "Like `read-char', but do not allow quitting.
654 Also, if the first character read is an octal digit,
655 we read any number of octal digits and return the
656 soecified character code. Any nondigit terminates the sequence.
657 If the terminator is a space, it is discarded;
658 any other terminator is used itself as input.
659
660 The optional argument PROMPT specifies a string to use to prompt the user."
661 (let ((message-log-max nil) done (first t) (code 0) char)
662 (while (not done)
663 (let ((inhibit-quit first)
664 ;; Don't let C-h get the help message--only help function keys.
665 (help-char nil)
666 (help-form
667 "Type the special character you want to use,
668 or the octal character code.
669 Space terminates the character code and is discarded;
670 any other non-digit terminates the character code and is then used as input."))
671 (and prompt (message "%s-" prompt))
672 (setq char (read-char))
673 (if inhibit-quit (setq quit-flag nil)))
674 (cond ((null char))
675 ((and (<= ?0 char) (<= char ?7))
676 (setq code (+ (* code 8) (- char ?0)))
677 (and prompt (setq prompt (message "%s %c" prompt char))))
678 ((and (not first) (eq char ?\ ))
679 (setq done t))
680 ((not first)
681 (setq unread-command-events (list char)
682 done t))
683 (t (setq code char
684 done t)))
685 (setq first nil))
686 ;; Turn a meta-character into a character with the 0200 bit set.
687 (logior (if (/= (logand code ?\M-\^@) 0) 128 0)
688 code)))
689
690 (defun force-mode-line-update (&optional all)
691 "Force the mode-line of the current buffer to be redisplayed.
692 With optional non-nil ALL, force redisplay of all mode-lines."
693 (if all (save-excursion (set-buffer (other-buffer))))
694 (set-buffer-modified-p (buffer-modified-p)))
695
696 (defun momentary-string-display (string pos &optional exit-char message)
697 "Momentarily display STRING in the buffer at POS.
698 Display remains until next character is typed.
699 If the char is EXIT-CHAR (optional third arg, default is SPC) it is swallowed;
700 otherwise it is then available as input (as a command if nothing else).
701 Display MESSAGE (optional fourth arg) in the echo area.
702 If MESSAGE is nil, instructions to type EXIT-CHAR are displayed there."
703 (or exit-char (setq exit-char ?\ ))
704 (let ((buffer-read-only nil)
705 ;; Don't modify the undo list at all.
706 (buffer-undo-list t)
707 (modified (buffer-modified-p))
708 (name buffer-file-name)
709 insert-end)
710 (unwind-protect
711 (progn
712 (save-excursion
713 (goto-char pos)
714 ;; defeat file locking... don't try this at home, kids!
715 (setq buffer-file-name nil)
716 (insert-before-markers string)
717 (setq insert-end (point))
718 ;; If the message end is off screen, recenter now.
719 (if (> (window-end) insert-end)
720 (recenter (/ (window-height) 2)))
721 ;; If that pushed message start off the screen,
722 ;; scroll to start it at the top of the screen.
723 (move-to-window-line 0)
724 (if (> (point) pos)
725 (progn
726 (goto-char pos)
727 (recenter 0))))
728 (message (or message "Type %s to continue editing.")
729 (single-key-description exit-char))
730 (let ((char (read-event)))
731 (or (eq char exit-char)
732 (setq unread-command-events (list char)))))
733 (if insert-end
734 (save-excursion
735 (delete-region pos insert-end)))
736 (setq buffer-file-name name)
737 (set-buffer-modified-p modified))))
738
739 \f
740 ;;;; Miscellanea.
741
742 ;; A number of major modes set this locally.
743 ;; Give it a global value to avoid compiler warnings.
744 (defvar font-lock-defaults nil)
745
746 ;; Avoid compiler warnings about this variable,
747 ;; which has a special meaning on certain system types.
748 (defvar buffer-file-type nil
749 "Non-nil if the visited file is a binary file.
750 This variable is meaningful on MS-DOG and Windows NT.
751 On those systems, it is automatically local in every buffer.
752 On other systems, this variable is normally always nil.")
753
754 ;; This should probably be written in C (i.e., without using `walk-windows').
755 (defun get-buffer-window-list (buffer &optional minibuf frame)
756 "Return windows currently displaying BUFFER, or nil if none.
757 See `walk-windows' for the meaning of MINIBUF and FRAME."
758 (let ((buffer (if (bufferp buffer) buffer (get-buffer buffer))) windows)
759 (walk-windows (function (lambda (window)
760 (if (eq (window-buffer window) buffer)
761 (setq windows (cons window windows)))))
762 minibuf frame)
763 windows))
764
765 (defun ignore (&rest ignore)
766 "Do nothing and return nil.
767 This function accepts any number of arguments, but ignores them."
768 (interactive)
769 nil)
770
771 (defun error (&rest args)
772 "Signal an error, making error message by passing all args to `format'.
773 In Emacs, the convention is that error messages start with a capital
774 letter but *do not* end with a period. Please follow this convention
775 for the sake of consistency."
776 (while t
777 (signal 'error (list (apply 'format args)))))
778
779 (defalias 'user-original-login-name 'user-login-name)
780
781 (defun start-process-shell-command (name buffer &rest args)
782 "Start a program in a subprocess. Return the process object for it.
783 Args are NAME BUFFER COMMAND &rest COMMAND-ARGS.
784 NAME is name for process. It is modified if necessary to make it unique.
785 BUFFER is the buffer or (buffer-name) to associate with the process.
786 Process output goes at end of that buffer, unless you specify
787 an output stream or filter function to handle the output.
788 BUFFER may be also nil, meaning that this process is not associated
789 with any buffer
790 Third arg is command name, the name of a shell command.
791 Remaining arguments are the arguments for the command.
792 Wildcards and redirection are handled as usual in the shell."
793 (cond
794 ((eq system-type 'vax-vms)
795 (apply 'start-process name buffer args))
796 ;; We used to use `exec' to replace the shell with the command,
797 ;; but that failed to handle (...) and semicolon, etc.
798 (t
799 (start-process name buffer shell-file-name shell-command-switch
800 (mapconcat 'identity args " ")))))
801 \f
802 (defmacro with-current-buffer (buffer &rest body)
803 "Execute the forms in BODY with BUFFER as the current buffer.
804 The value returned is the value of the last form in BODY.
805 See also `with-temp-buffer'."
806 `(save-current-buffer
807 (set-buffer ,buffer)
808 ,@body))
809
810 (defmacro with-temp-file (file &rest forms)
811 "Create a new buffer, evaluate FORMS there, and write the buffer to FILE.
812 The value of the last form in FORMS is returned, like `progn'.
813 See also `with-temp-buffer'."
814 (let ((temp-file (make-symbol "temp-file"))
815 (temp-buffer (make-symbol "temp-buffer")))
816 `(let ((,temp-file ,file)
817 (,temp-buffer
818 (get-buffer-create (generate-new-buffer-name " *temp file*"))))
819 (unwind-protect
820 (prog1
821 (with-current-buffer ,temp-buffer
822 ,@forms)
823 (with-current-buffer ,temp-buffer
824 (widen)
825 (write-region (point-min) (point-max) ,temp-file nil 0)))
826 (and (buffer-name ,temp-buffer)
827 (kill-buffer ,temp-buffer))))))
828
829 (defmacro with-temp-buffer (&rest forms)
830 "Create a temporary buffer, and evaluate FORMS there like `progn'.
831 See also `with-temp-file' and `with-output-to-string'."
832 (let ((temp-buffer (make-symbol "temp-buffer")))
833 `(let ((,temp-buffer
834 (get-buffer-create (generate-new-buffer-name " *temp*"))))
835 (unwind-protect
836 (with-current-buffer ,temp-buffer
837 ,@forms)
838 (and (buffer-name ,temp-buffer)
839 (kill-buffer ,temp-buffer))))))
840
841 (defmacro with-output-to-string (&rest body)
842 "Execute BODY, return the text it sent to `standard-output', as a string."
843 `(let ((standard-output
844 (get-buffer-create (generate-new-buffer-name " *string-output*"))))
845 (let ((standard-output standard-output))
846 ,@body)
847 (with-current-buffer standard-output
848 (prog1
849 (buffer-string)
850 (kill-buffer nil)))))
851
852 (defmacro combine-after-change-calls (&rest body)
853 "Execute BODY, but don't call the after-change functions till the end.
854 If BODY makes changes in the buffer, they are recorded
855 and the functions on `after-change-functions' are called several times
856 when BODY is finished.
857 The return value is the value of the last form in BODY.
858
859 If `before-change-functions' is non-nil, then calls to the after-change
860 functions can't be deferred, so in that case this macro has no effect.
861
862 Do not alter `after-change-functions' or `before-change-functions'
863 in BODY."
864 `(unwind-protect
865 (let ((combine-after-change-calls t))
866 . ,body)
867 (combine-after-change-execute)))
868
869 \f
870 (defvar save-match-data-internal)
871
872 ;; We use save-match-data-internal as the local variable because
873 ;; that works ok in practice (people should not use that variable elsewhere).
874 ;; We used to use an uninterned symbol; the compiler handles that properly
875 ;; now, but it generates slower code.
876 (defmacro save-match-data (&rest body)
877 "Execute the BODY forms, restoring the global value of the match data."
878 `(let ((save-match-data-internal (match-data)))
879 (unwind-protect
880 (progn ,@body)
881 (store-match-data save-match-data-internal))))
882
883 (defun match-string (num &optional string)
884 "Return string of text matched by last search.
885 NUM specifies which parenthesized expression in the last regexp.
886 Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
887 Zero means the entire text matched by the whole regexp or whole string.
888 STRING should be given if the last search was by `string-match' on STRING."
889 (if (match-beginning num)
890 (if string
891 (substring string (match-beginning num) (match-end num))
892 (buffer-substring (match-beginning num) (match-end num)))))
893
894 (defun split-string (string &optional separators)
895 "Splits STRING into substrings where there are matches for SEPARATORS.
896 Each match for SEPARATORS is a splitting point.
897 The substrings between the splitting points are made into a list
898 which is returned.
899 If SEPARATORS is absent, it defaults to \"[ \\f\\t\\n\\r\\v]+\"."
900 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
901 (start 0)
902 (list nil))
903 (while (string-match rexp string start)
904 (or (eq (match-beginning 0) 0)
905 (setq list
906 (cons (substring string start (match-beginning 0))
907 list)))
908 (setq start (match-end 0)))
909 (or (eq start (length string))
910 (setq list
911 (cons (substring string start)
912 list)))
913 (nreverse list)))
914 \f
915 (defun shell-quote-argument (argument)
916 "Quote an argument for passing as argument to an inferior shell."
917 (if (eq system-type 'ms-dos)
918 ;; MS-DOS shells don't have quoting, so don't do any.
919 argument
920 (if (eq system-type 'windows-nt)
921 (concat "\"" argument "\"")
922 (if (equal argument "")
923 "''"
924 ;; Quote everything except POSIX filename characters.
925 ;; This should be safe enough even for really weird shells.
926 (let ((result "") (start 0) end)
927 (while (string-match "[^-0-9a-zA-Z_./]" argument start)
928 (setq end (match-beginning 0)
929 result (concat result (substring argument start end)
930 "\\" (substring argument end (1+ end)))
931 start (1+ end)))
932 (concat result (substring argument start)))))))
933
934 (defun make-syntax-table (&optional oldtable)
935 "Return a new syntax table.
936 If OLDTABLE is non-nil, copy OLDTABLE.
937 Otherwise, create a syntax table which inherits
938 all letters and control characters from the standard syntax table;
939 other characters are copied from the standard syntax table."
940 (if oldtable
941 (copy-syntax-table oldtable)
942 (let ((table (copy-syntax-table))
943 i)
944 (setq i 0)
945 (while (<= i 31)
946 (aset table i nil)
947 (setq i (1+ i)))
948 (setq i ?A)
949 (while (<= i ?Z)
950 (aset table i nil)
951 (setq i (1+ i)))
952 (setq i ?a)
953 (while (<= i ?z)
954 (aset table i nil)
955 (setq i (1+ i)))
956 (setq i 128)
957 (while (<= i 255)
958 (aset table i nil)
959 (setq i (1+ i)))
960 table)))
961
962 (defun add-to-invisibility-spec (arg)
963 "Add elements to `buffer-invisibility-spec'.
964 See documentation for `buffer-invisibility-spec' for the kind of elements
965 that can be added."
966 (cond
967 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
968 (setq buffer-invisibility-spec (list arg)))
969 (t
970 (setq buffer-invisibility-spec
971 (cons arg buffer-invisibility-spec)))))
972
973 (defun remove-from-invisibility-spec (arg)
974 "Remove elements from `buffer-invisibility-spec'."
975 (if buffer-invisibility-spec
976 (setq buffer-invisibility-spec (delete arg buffer-invisibility-spec))))
977 \f
978 (defun global-set-key (key command)
979 "Give KEY a global binding as COMMAND.
980 COMMAND is a symbol naming an interactively-callable function.
981 KEY is a key sequence (a string or vector of characters or event types).
982 Non-ASCII characters with codes above 127 (such as ISO Latin-1)
983 can be included if you use a vector.
984 Note that if KEY has a local binding in the current buffer
985 that local binding will continue to shadow any global binding."
986 (interactive "KSet key globally: \nCSet key %s to command: ")
987 (or (vectorp key) (stringp key)
988 (signal 'wrong-type-argument (list 'arrayp key)))
989 (define-key (current-global-map) key command)
990 nil)
991
992 (defun local-set-key (key command)
993 "Give KEY a local binding as COMMAND.
994 COMMAND is a symbol naming an interactively-callable function.
995 KEY is a key sequence (a string or vector of characters or event types).
996 Non-ASCII characters with codes above 127 (such as ISO Latin-1)
997 can be included if you use a vector.
998 The binding goes in the current buffer's local map,
999 which in most cases is shared with all other buffers in the same major mode."
1000 (interactive "KSet key locally: \nCSet key %s locally to command: ")
1001 (let ((map (current-local-map)))
1002 (or map
1003 (use-local-map (setq map (make-sparse-keymap))))
1004 (or (vectorp key) (stringp key)
1005 (signal 'wrong-type-argument (list 'arrayp key)))
1006 (define-key map key command))
1007 nil)
1008
1009 (defun global-unset-key (key)
1010 "Remove global binding of KEY.
1011 KEY is a string representing a sequence of keystrokes."
1012 (interactive "kUnset key globally: ")
1013 (global-set-key key nil))
1014
1015 (defun local-unset-key (key)
1016 "Remove local binding of KEY.
1017 KEY is a string representing a sequence of keystrokes."
1018 (interactive "kUnset key locally: ")
1019 (if (current-local-map)
1020 (local-set-key key nil))
1021 nil)
1022 \f
1023 ;; We put this here instead of in frame.el so that it's defined even on
1024 ;; systems where frame.el isn't loaded.
1025 (defun frame-configuration-p (object)
1026 "Return non-nil if OBJECT seems to be a frame configuration.
1027 Any list whose car is `frame-configuration' is assumed to be a frame
1028 configuration."
1029 (and (consp object)
1030 (eq (car object) 'frame-configuration)))
1031
1032 (defun functionp (object)
1033 "Non-nil of OBJECT is a type of object that can be called as a function."
1034 (or (subrp object) (compiled-function-p object)
1035 (eq (car-safe object) 'lambda)
1036 (and (symbolp object) (fboundp object))))
1037
1038 ;; now in fns.c
1039 ;(defun nth (n list)
1040 ; "Returns the Nth element of LIST.
1041 ;N counts from zero. If LIST is not that long, nil is returned."
1042 ; (car (nthcdr n list)))
1043 ;
1044 ;(defun copy-alist (alist)
1045 ; "Return a copy of ALIST.
1046 ;This is a new alist which represents the same mapping
1047 ;from objects to objects, but does not share the alist structure with ALIST.
1048 ;The objects mapped (cars and cdrs of elements of the alist)
1049 ;are shared, however."
1050 ; (setq alist (copy-sequence alist))
1051 ; (let ((tail alist))
1052 ; (while tail
1053 ; (if (consp (car tail))
1054 ; (setcar tail (cons (car (car tail)) (cdr (car tail)))))
1055 ; (setq tail (cdr tail))))
1056 ; alist)
1057
1058 ;;; subr.el ends here