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