Comment change.
[emacs.git] / lisp / subr.el
blob4d583944de90afff1160ba57f5d16a489418e25b
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:
25 ;;;; Lisp language features.
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.
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)))
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))
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))
58 ;;;; Keymap support.
60 (defun undefined ()
61 (interactive)
62 (ding))
64 ;Prevent the \{...} documentation construct
65 ;from mentioning keys that run this command.
66 (put 'undefined 'suppress-keymap t)
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))))))
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)))
91 (defvar key-substitution-in-progress nil
92 "Used internally by substitute-key-definition.")
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)))))
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).
229 If AFTER is t, the new binding goes at the end of the keymap.
231 KEY must contain just one event type--that is to say, it must be
232 a string or vector of length 1.
234 The order of bindings in a keymap matters when it is used as a menu."
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)))))
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))
271 (put 'keyboard-translate-table 'char-table-extra-slots 0)
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))
283 ;;;; The global keymap tree.
285 ;;; global-map, esc-map, and ctl-x-map have their values set up in
286 ;;; keymap.c; we just give them docstrings here.
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.")
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.")
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.")
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)
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)
312 ;;;; Event manipulation functions.
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-\\^@")))
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))))
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))))
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))))
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)))))
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)))
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))
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))
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))
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))
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)))
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))
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))))))
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))
458 ;;;; Obsolescent names for functions.
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)
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)
481 (defalias 'focus-frame 'ignore)
482 (defalias 'unfocus-frame 'ignore)
484 ;;;; Alternate names for functions - these are not being phased out.
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)
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)
504 ;;;; Hook manipulation functions.
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.
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.
520 This function does nothing if HOOK is already local in the current
521 buffer.
523 Do not use `make-local-variable' to make a hook variable buffer-local."
524 (if (local-variable-p hook)
526 (or (boundp hook) (set hook nil))
527 (make-local-variable hook)
528 (set hook (list t))))
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.
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'.
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)))))))
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'.
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)))))
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)))))
622 ;;;; Specifying things to do after certain files are loaded.
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)
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)))
650 ;;;; Input and display facilities.
652 (defcustom read-quoted-char-radix 8
653 "*Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
654 Legitimate radix values are 8, 10 and 16."
655 :type '(choice (const 8) (const 10) (const 16))
656 :group 'editing-basics)
658 (defun read-quoted-char (&optional prompt)
659 "Like `read-char', but do not allow quitting.
660 Also, if the first character read is an octal digit,
661 we read any number of octal digits and return the
662 soecified character code. Any nondigit terminates the sequence.
663 If the terminator is RET, it is discarded;
664 any other terminator is used itself as input.
666 The optional argument PROMPT specifies a string to use to prompt the user."
667 (let ((message-log-max nil) done (first t) (code 0) char)
668 (while (not done)
669 (let ((inhibit-quit first)
670 ;; Don't let C-h get the help message--only help function keys.
671 (help-char nil)
672 (help-form
673 "Type the special character you want to use,
674 or the octal character code.
675 RET terminates the character code and is discarded;
676 any other non-digit terminates the character code and is then used as input."))
677 (and prompt (message "%s-" prompt))
678 (setq char (read-event))
679 (if inhibit-quit (setq quit-flag nil)))
680 (cond ((null char))
681 ((not (integerp char))
682 (setq unread-command-events (list char)
683 done t))
684 ((and (<= ?0 char) (< char (+ ?0 (min 10 read-quoted-char-radix))))
685 (setq code (+ (* code read-quoted-char-radix) (- char ?0)))
686 (and prompt (setq prompt (message "%s %c" prompt char))))
687 ((and (<= ?a (downcase char))
688 (< (downcase char) (+ ?a -10 (min 26 read-quoted-char-radix))))
689 (setq code (+ (* code read-quoted-char-radix) (+ 10 (- char ?a))))
690 (and prompt (setq prompt (message "%s %c" prompt char))))
691 ((and (not first) (eq char ?\C-m))
692 (setq done t))
693 ((not first)
694 (setq unread-command-events (list char)
695 done t))
696 (t (setq code char
697 done t)))
698 (setq first nil))
699 ;; Turn a meta-character into a character with the 0200 bit set.
700 (logior (if (/= (logand code ?\M-\^@) 0) 128 0)
701 code)))
703 (defun force-mode-line-update (&optional all)
704 "Force the mode-line of the current buffer to be redisplayed.
705 With optional non-nil ALL, force redisplay of all mode-lines."
706 (if all (save-excursion (set-buffer (other-buffer))))
707 (set-buffer-modified-p (buffer-modified-p)))
709 (defun momentary-string-display (string pos &optional exit-char message)
710 "Momentarily display STRING in the buffer at POS.
711 Display remains until next character is typed.
712 If the char is EXIT-CHAR (optional third arg, default is SPC) it is swallowed;
713 otherwise it is then available as input (as a command if nothing else).
714 Display MESSAGE (optional fourth arg) in the echo area.
715 If MESSAGE is nil, instructions to type EXIT-CHAR are displayed there."
716 (or exit-char (setq exit-char ?\ ))
717 (let ((buffer-read-only nil)
718 ;; Don't modify the undo list at all.
719 (buffer-undo-list t)
720 (modified (buffer-modified-p))
721 (name buffer-file-name)
722 insert-end)
723 (unwind-protect
724 (progn
725 (save-excursion
726 (goto-char pos)
727 ;; defeat file locking... don't try this at home, kids!
728 (setq buffer-file-name nil)
729 (insert-before-markers string)
730 (setq insert-end (point))
731 ;; If the message end is off screen, recenter now.
732 (if (> (window-end) insert-end)
733 (recenter (/ (window-height) 2)))
734 ;; If that pushed message start off the screen,
735 ;; scroll to start it at the top of the screen.
736 (move-to-window-line 0)
737 (if (> (point) pos)
738 (progn
739 (goto-char pos)
740 (recenter 0))))
741 (message (or message "Type %s to continue editing.")
742 (single-key-description exit-char))
743 (let ((char (read-event)))
744 (or (eq char exit-char)
745 (setq unread-command-events (list char)))))
746 (if insert-end
747 (save-excursion
748 (delete-region pos insert-end)))
749 (setq buffer-file-name name)
750 (set-buffer-modified-p modified))))
753 ;;;; Miscellanea.
755 ;; A number of major modes set this locally.
756 ;; Give it a global value to avoid compiler warnings.
757 (defvar font-lock-defaults nil)
759 ;; Avoid compiler warnings about this variable,
760 ;; which has a special meaning on certain system types.
761 (defvar buffer-file-type nil
762 "Non-nil if the visited file is a binary file.
763 This variable is meaningful on MS-DOG and Windows NT.
764 On those systems, it is automatically local in every buffer.
765 On other systems, this variable is normally always nil.")
767 ;; This should probably be written in C (i.e., without using `walk-windows').
768 (defun get-buffer-window-list (buffer &optional minibuf frame)
769 "Return windows currently displaying BUFFER, or nil if none.
770 See `walk-windows' for the meaning of MINIBUF and FRAME."
771 (let ((buffer (if (bufferp buffer) buffer (get-buffer buffer))) windows)
772 (walk-windows (function (lambda (window)
773 (if (eq (window-buffer window) buffer)
774 (setq windows (cons window windows)))))
775 minibuf frame)
776 windows))
778 (defun ignore (&rest ignore)
779 "Do nothing and return nil.
780 This function accepts any number of arguments, but ignores them."
781 (interactive)
782 nil)
784 (defun error (&rest args)
785 "Signal an error, making error message by passing all args to `format'.
786 In Emacs, the convention is that error messages start with a capital
787 letter but *do not* end with a period. Please follow this convention
788 for the sake of consistency."
789 (while t
790 (signal 'error (list (apply 'format args)))))
792 (defalias 'user-original-login-name 'user-login-name)
794 (defun start-process-shell-command (name buffer &rest args)
795 "Start a program in a subprocess. Return the process object for it.
796 Args are NAME BUFFER COMMAND &rest COMMAND-ARGS.
797 NAME is name for process. It is modified if necessary to make it unique.
798 BUFFER is the buffer or (buffer-name) to associate with the process.
799 Process output goes at end of that buffer, unless you specify
800 an output stream or filter function to handle the output.
801 BUFFER may be also nil, meaning that this process is not associated
802 with any buffer
803 Third arg is command name, the name of a shell command.
804 Remaining arguments are the arguments for the command.
805 Wildcards and redirection are handled as usual in the shell."
806 (cond
807 ((eq system-type 'vax-vms)
808 (apply 'start-process name buffer args))
809 ;; We used to use `exec' to replace the shell with the command,
810 ;; but that failed to handle (...) and semicolon, etc.
812 (start-process name buffer shell-file-name shell-command-switch
813 (mapconcat 'identity args " ")))))
815 (defmacro with-current-buffer (buffer &rest body)
816 "Execute the forms in BODY with BUFFER as the current buffer.
817 The value returned is the value of the last form in BODY.
818 See also `with-temp-buffer'."
819 `(save-current-buffer
820 (set-buffer ,buffer)
821 ,@body))
823 (defmacro with-temp-file (file &rest forms)
824 "Create a new buffer, evaluate FORMS there, and write the buffer to FILE.
825 The value of the last form in FORMS is returned, like `progn'.
826 See also `with-temp-buffer'."
827 (let ((temp-file (make-symbol "temp-file"))
828 (temp-buffer (make-symbol "temp-buffer")))
829 `(let ((,temp-file ,file)
830 (,temp-buffer
831 (get-buffer-create (generate-new-buffer-name " *temp file*"))))
832 (unwind-protect
833 (prog1
834 (with-current-buffer ,temp-buffer
835 ,@forms)
836 (with-current-buffer ,temp-buffer
837 (widen)
838 (write-region (point-min) (point-max) ,temp-file nil 0)))
839 (and (buffer-name ,temp-buffer)
840 (kill-buffer ,temp-buffer))))))
842 (defmacro with-temp-buffer (&rest forms)
843 "Create a temporary buffer, and evaluate FORMS there like `progn'.
844 See also `with-temp-file' and `with-output-to-string'."
845 (let ((temp-buffer (make-symbol "temp-buffer")))
846 `(let ((,temp-buffer
847 (get-buffer-create (generate-new-buffer-name " *temp*"))))
848 (unwind-protect
849 (with-current-buffer ,temp-buffer
850 ,@forms)
851 (and (buffer-name ,temp-buffer)
852 (kill-buffer ,temp-buffer))))))
854 (defmacro with-output-to-string (&rest body)
855 "Execute BODY, return the text it sent to `standard-output', as a string."
856 `(let ((standard-output
857 (get-buffer-create (generate-new-buffer-name " *string-output*"))))
858 (let ((standard-output standard-output))
859 ,@body)
860 (with-current-buffer standard-output
861 (prog1
862 (buffer-string)
863 (kill-buffer nil)))))
865 (defmacro combine-after-change-calls (&rest body)
866 "Execute BODY, but don't call the after-change functions till the end.
867 If BODY makes changes in the buffer, they are recorded
868 and the functions on `after-change-functions' are called several times
869 when BODY is finished.
870 The return value is the value of the last form in BODY.
872 If `before-change-functions' is non-nil, then calls to the after-change
873 functions can't be deferred, so in that case this macro has no effect.
875 Do not alter `after-change-functions' or `before-change-functions'
876 in BODY."
877 `(unwind-protect
878 (let ((combine-after-change-calls t))
879 . ,body)
880 (combine-after-change-execute)))
883 (defvar save-match-data-internal)
885 ;; We use save-match-data-internal as the local variable because
886 ;; that works ok in practice (people should not use that variable elsewhere).
887 ;; We used to use an uninterned symbol; the compiler handles that properly
888 ;; now, but it generates slower code.
889 (defmacro save-match-data (&rest body)
890 "Execute the BODY forms, restoring the global value of the match data."
891 `(let ((save-match-data-internal (match-data)))
892 (unwind-protect
893 (progn ,@body)
894 (store-match-data save-match-data-internal))))
896 (defun match-string (num &optional string)
897 "Return string of text matched by last search.
898 NUM specifies which parenthesized expression in the last regexp.
899 Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
900 Zero means the entire text matched by the whole regexp or whole string.
901 STRING should be given if the last search was by `string-match' on STRING."
902 (if (match-beginning num)
903 (if string
904 (substring string (match-beginning num) (match-end num))
905 (buffer-substring (match-beginning num) (match-end num)))))
907 (defun split-string (string &optional separators)
908 "Splits STRING into substrings where there are matches for SEPARATORS.
909 Each match for SEPARATORS is a splitting point.
910 The substrings between the splitting points are made into a list
911 which is returned.
912 If SEPARATORS is absent, it defaults to \"[ \\f\\t\\n\\r\\v]+\"."
913 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
914 (start 0)
915 (list nil))
916 (while (string-match rexp string start)
917 (or (eq (match-beginning 0) 0)
918 (setq list
919 (cons (substring string start (match-beginning 0))
920 list)))
921 (setq start (match-end 0)))
922 (or (eq start (length string))
923 (setq list
924 (cons (substring string start)
925 list)))
926 (nreverse list)))
928 (defun shell-quote-argument (argument)
929 "Quote an argument for passing as argument to an inferior shell."
930 (if (eq system-type 'ms-dos)
931 ;; MS-DOS shells don't have quoting, so don't do any.
932 argument
933 (if (eq system-type 'windows-nt)
934 (concat "\"" argument "\"")
935 (if (equal argument "")
936 "''"
937 ;; Quote everything except POSIX filename characters.
938 ;; This should be safe enough even for really weird shells.
939 (let ((result "") (start 0) end)
940 (while (string-match "[^-0-9a-zA-Z_./]" argument start)
941 (setq end (match-beginning 0)
942 result (concat result (substring argument start end)
943 "\\" (substring argument end (1+ end)))
944 start (1+ end)))
945 (concat result (substring argument start)))))))
947 (defun make-syntax-table (&optional oldtable)
948 "Return a new syntax table.
949 If OLDTABLE is non-nil, copy OLDTABLE.
950 Otherwise, create a syntax table which inherits
951 all letters and control characters from the standard syntax table;
952 other characters are copied from the standard syntax table."
953 (if oldtable
954 (copy-syntax-table oldtable)
955 (let ((table (copy-syntax-table))
957 (setq i 0)
958 (while (<= i 31)
959 (aset table i nil)
960 (setq i (1+ i)))
961 (setq i ?A)
962 (while (<= i ?Z)
963 (aset table i nil)
964 (setq i (1+ i)))
965 (setq i ?a)
966 (while (<= i ?z)
967 (aset table i nil)
968 (setq i (1+ i)))
969 (setq i 128)
970 (while (<= i 255)
971 (aset table i nil)
972 (setq i (1+ i)))
973 table)))
975 (defun add-to-invisibility-spec (arg)
976 "Add elements to `buffer-invisibility-spec'.
977 See documentation for `buffer-invisibility-spec' for the kind of elements
978 that can be added."
979 (cond
980 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
981 (setq buffer-invisibility-spec (list arg)))
983 (setq buffer-invisibility-spec
984 (cons arg buffer-invisibility-spec)))))
986 (defun remove-from-invisibility-spec (arg)
987 "Remove elements from `buffer-invisibility-spec'."
988 (if buffer-invisibility-spec
989 (setq buffer-invisibility-spec (delete arg buffer-invisibility-spec))))
991 (defun global-set-key (key command)
992 "Give KEY a global binding as COMMAND.
993 COMMAND is a symbol naming an interactively-callable function.
994 KEY is a key sequence (a string or vector of characters or event types).
995 Non-ASCII characters with codes above 127 (such as ISO Latin-1)
996 can be included if you use a vector.
997 Note that if KEY has a local binding in the current buffer
998 that local binding will continue to shadow any global binding."
999 (interactive "KSet key globally: \nCSet key %s to command: ")
1000 (or (vectorp key) (stringp key)
1001 (signal 'wrong-type-argument (list 'arrayp key)))
1002 (define-key (current-global-map) key command)
1003 nil)
1005 (defun local-set-key (key command)
1006 "Give KEY a local binding as COMMAND.
1007 COMMAND is a symbol naming an interactively-callable function.
1008 KEY is a key sequence (a string or vector of characters or event types).
1009 Non-ASCII characters with codes above 127 (such as ISO Latin-1)
1010 can be included if you use a vector.
1011 The binding goes in the current buffer's local map,
1012 which in most cases is shared with all other buffers in the same major mode."
1013 (interactive "KSet key locally: \nCSet key %s locally to command: ")
1014 (let ((map (current-local-map)))
1015 (or map
1016 (use-local-map (setq map (make-sparse-keymap))))
1017 (or (vectorp key) (stringp key)
1018 (signal 'wrong-type-argument (list 'arrayp key)))
1019 (define-key map key command))
1020 nil)
1022 (defun global-unset-key (key)
1023 "Remove global binding of KEY.
1024 KEY is a string representing a sequence of keystrokes."
1025 (interactive "kUnset key globally: ")
1026 (global-set-key key nil))
1028 (defun local-unset-key (key)
1029 "Remove local binding of KEY.
1030 KEY is a string representing a sequence of keystrokes."
1031 (interactive "kUnset key locally: ")
1032 (if (current-local-map)
1033 (local-set-key key nil))
1034 nil)
1036 ;; We put this here instead of in frame.el so that it's defined even on
1037 ;; systems where frame.el isn't loaded.
1038 (defun frame-configuration-p (object)
1039 "Return non-nil if OBJECT seems to be a frame configuration.
1040 Any list whose car is `frame-configuration' is assumed to be a frame
1041 configuration."
1042 (and (consp object)
1043 (eq (car object) 'frame-configuration)))
1045 (defun functionp (object)
1046 "Non-nil of OBJECT is a type of object that can be called as a function."
1047 (or (subrp object) (compiled-function-p object)
1048 (eq (car-safe object) 'lambda)
1049 (and (symbolp object) (fboundp object))))
1051 ;; now in fns.c
1052 ;(defun nth (n list)
1053 ; "Returns the Nth element of LIST.
1054 ;N counts from zero. If LIST is not that long, nil is returned."
1055 ; (car (nthcdr n list)))
1057 ;(defun copy-alist (alist)
1058 ; "Return a copy of ALIST.
1059 ;This is a new alist which represents the same mapping
1060 ;from objects to objects, but does not share the alist structure with ALIST.
1061 ;The objects mapped (cars and cdrs of elements of the alist)
1062 ;are shared, however."
1063 ; (setq alist (copy-sequence alist))
1064 ; (let ((tail alist))
1065 ; (while tail
1066 ; (if (consp (car tail))
1067 ; (setcar tail (cons (car (car tail)) (cdr (car tail)))))
1068 ; (setq tail (cdr tail))))
1069 ; alist)
1071 ;;; subr.el ends here