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