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