subr.el 48.8 KB
Newer Older
Eric S. Raymond's avatar
Eric S. Raymond committed
1
;;; subr.el --- basic lisp subroutines for Emacs
Eric S. Raymond's avatar
Eric S. Raymond committed
2

Erik Naggum's avatar
Erik Naggum committed
3
;; Copyright (C) 1985, 1986, 1992, 1994, 1995 Free Software Foundation, Inc.
David Lawrence's avatar
David Lawrence committed
4 5 6 7 8

;; This file is part of GNU Emacs.

;; GNU Emacs is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
Jim Blandy's avatar
Jim Blandy committed
9
;; the Free Software Foundation; either version 2, or (at your option)
David Lawrence's avatar
David Lawrence committed
10 11 12 13 14 15 16 17
;; any later version.

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
Erik Naggum's avatar
Erik Naggum committed
18 19 20
;; along with GNU Emacs; see the file COPYING.  If not, write to the
;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.
David Lawrence's avatar
David Lawrence committed
21

Eric S. Raymond's avatar
Eric S. Raymond committed
22
;;; Code:
23 24 25 26
(defvar custom-declare-variable-list nil
  "Record `defcustom' calls made before `custom.el' is loaded to handle them.
Each element of this list holds the arguments to one call to `defcustom'.")

Richard M. Stallman's avatar
Richard M. Stallman committed
27
;; Use this, rather than defcustom, in subr.el and other files loaded
28 29 30 31
;; before custom.el.
(defun custom-declare-variable-early (&rest arguments)
  (setq custom-declare-variable-list
	(cons arguments custom-declare-variable-list)))
32 33 34 35 36 37 38 39

;;;; Lisp language features.

(defmacro lambda (&rest cdr)
  "Return a lambda expression.
A call of the form (lambda ARGS DOCSTRING INTERACTIVE BODY) is
self-quoting; the result of evaluating the lambda expression is the
expression itself.  The lambda expression may then be treated as a
Richard M. Stallman's avatar
Richard M. Stallman committed
40 41 42
function, i.e., stored as the function value of a symbol, passed to
funcall or mapcar, etc.

43
ARGS should take the same form as an argument list for a `defun'.
Richard M. Stallman's avatar
Richard M. Stallman committed
44 45 46
DOCSTRING is an optional documentation string.
 If present, it should describe how to call the function.
 But documentation strings are usually not useful in nameless functions.
47 48 49 50 51 52 53
INTERACTIVE should be a call to the function `interactive', which see.
It may also be omitted.
BODY should be a list of lisp expressions."
  ;; Note that this definition should not use backquotes; subr.el should not
  ;; depend on backquote.el.
  (list 'function (cons 'lambda cdr)))

Richard M. Stallman's avatar
Richard M. Stallman committed
54
(defmacro push (newelt listname)
Richard M. Stallman's avatar
Richard M. Stallman committed
55
  "Add NEWELT to the list stored in the symbol LISTNAME.
Richard M. Stallman's avatar
Richard M. Stallman committed
56
This is equivalent to (setq LISTNAME (cons NEWELT LISTNAME)).
Richard M. Stallman's avatar
Richard M. Stallman committed
57
LISTNAME must be a symbol."
Dave Love's avatar
Dave Love committed
58 59
  (list 'setq listname
	(list 'cons newelt listname)))
Richard M. Stallman's avatar
Richard M. Stallman committed
60 61 62 63 64 65 66 67 68

(defmacro pop (listname)
  "Return the first element of LISTNAME's value, and remove it from the list.
LISTNAME must be a symbol whose value is a list.
If the value is nil, `pop' returns nil but does not actually
change the list."
  (list 'prog1 (list 'car listname)
	(list 'setq listname (list 'cdr listname))))

69 70 71
(defmacro when (cond &rest body)
  "(when COND BODY...): if COND yields non-nil, do BODY, else return nil."
  (list 'if cond (cons 'progn body)))
72 73
(put 'when 'lisp-indent-function 1)
(put 'when 'edebug-form-spec '(&rest form))
74

75 76 77
(defmacro unless (cond &rest body)
  "(unless COND BODY...): if COND yields nil, do BODY, else return nil."
  (cons 'if (cons cond (cons nil body))))
78 79
(put 'unless 'lisp-indent-function 1)
(put 'unless 'edebug-form-spec '(&rest form))
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95

(defsubst caar (x)
  "Return the car of the car of X."
  (car (car x)))

(defsubst cadr (x)
  "Return the car of the cdr of X."
  (car (cdr x)))

(defsubst cdar (x)
  "Return the cdr of the car of X."
  (cdr (car x)))

(defsubst cddr (x)
  "Return the cdr of the cdr of X."
  (cdr (cdr x)))
Richard M. Stallman's avatar
Richard M. Stallman committed
96

97 98 99 100 101 102 103 104 105 106 107 108 109 110
(defun last (x &optional n)
  "Return the last link of the list X.  Its car is the last element.
If X is nil, return nil.
If N is non-nil, return the Nth-to-last link of X.
If N is bigger than the length of X, return X."
  (if n
      (let ((m 0) (p x))
	(while (consp p)
	  (setq m (1+ m) p (cdr p)))
	(if (<= n 0) p
	  (if (< n m) (nthcdr (- m n) x) x)))
    (while (cdr x)
      (setq x (cdr x)))
    x))
111

112 113 114 115 116 117
(defun assoc-default (key alist &optional test default)
  "Find object KEY in a pseudo-alist ALIST.
ALIST is a list of conses or objects.  Each element (or the element's car,
if it is a cons) is compared with KEY by evaluating (TEST (car elt) KEY).
If that is non-nil, the element matches;
then `assoc-default' returns the element's cdr, if it is a cons,
118
or DEFAULT if the element is not a cons.
119 120 121 122 123 124 125 126 127 128

If no element matches, the value is nil.
If TEST is omitted or nil, `equal' is used."
  (let (found (tail alist) value)
    (while (and tail (not found))
      (let ((elt (car tail)))
	(when (funcall (or test 'equal) (if (consp elt) (car elt) elt) key)
	  (setq found t value (if (consp elt) (cdr elt) default))))
      (setq tail (cdr tail)))
    value))
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150

(defun assoc-ignore-case (key alist)
  "Like `assoc', but ignores differences in case and text representation.
KEY must be a string.  Upper-case and lower-case letters are treated as equal.
Unibyte strings are converted to multibyte for comparison."
  (let (element)
    (while (and alist (not element))
      (if (eq t (compare-strings key 0 nil (car (car alist)) 0 nil t))
	  (setq element (car alist)))
      (setq alist (cdr alist)))
    element))

(defun assoc-ignore-representation (key alist)
  "Like `assoc', but ignores differences in text representation.
KEY must be a string.  
Unibyte strings are converted to multibyte for comparison."
  (let (element)
    (while (and alist (not element))
      (if (eq t (compare-strings key 0 nil (car (car alist)) 0 nil))
	  (setq element (car alist)))
      (setq alist (cdr alist)))
    element))
151 152

;;;; Keymap support.
David Lawrence's avatar
David Lawrence committed
153 154 155 156 157 158 159 160 161 162 163 164 165

(defun undefined ()
  (interactive)
  (ding))

;Prevent the \{...} documentation construct
;from mentioning keys that run this command.
(put 'undefined 'suppress-keymap t)

(defun suppress-keymap (map &optional nodigits)
  "Make MAP override all normally self-inserting keys to be undefined.
Normally, as an exception, digits and minus-sign are set to make prefix args,
but optional second arg NODIGITS non-nil treats them like other chars."
166
  (substitute-key-definition 'self-insert-command 'undefined map global-map)
David Lawrence's avatar
David Lawrence committed
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
  (or nodigits
      (let (loop)
	(define-key map "-" 'negative-argument)
	;; Make plain numbers do numeric args.
	(setq loop ?0)
	(while (<= loop ?9)
	  (define-key map (char-to-string loop) 'digit-argument)
	  (setq loop (1+ loop))))))

;Moved to keymap.c
;(defun copy-keymap (keymap)
;  "Return a copy of KEYMAP"  
;  (while (not (keymapp keymap))
;    (setq keymap (signal 'wrong-type-argument (list 'keymapp keymap))))
;  (if (vectorp keymap)
;      (copy-sequence keymap)
;      (copy-alist keymap)))

185 186 187
(defvar key-substitution-in-progress nil
 "Used internally by substitute-key-definition.")

Richard M. Stallman's avatar
Richard M. Stallman committed
188
(defun substitute-key-definition (olddef newdef keymap &optional oldmap prefix)
David Lawrence's avatar
David Lawrence committed
189 190
  "Replace OLDDEF with NEWDEF for any keys in KEYMAP now defined as OLDDEF.
In other words, OLDDEF is replaced with NEWDEF where ever it appears.
Richard M. Stallman's avatar
Richard M. Stallman committed
191 192 193 194 195
If optional fourth argument OLDMAP is specified, we redefine
in KEYMAP as NEWDEF those chars which are defined as OLDDEF in OLDMAP."
  (or prefix (setq prefix ""))
  (let* ((scan (or oldmap keymap))
	 (vec1 (vector nil))
196 197 198
	 (prefix1 (vconcat prefix vec1))
	 (key-substitution-in-progress
	  (cons scan key-substitution-in-progress)))
Richard M. Stallman's avatar
Richard M. Stallman committed
199 200 201 202 203 204 205 206 207 208
    ;; Scan OLDMAP, finding each char or event-symbol that
    ;; has any definition, and act on it with hack-key.
    (while (consp scan)
      (if (consp (car scan))
	  (let ((char (car (car scan)))
		(defn (cdr (car scan))))
	    ;; The inside of this let duplicates exactly
	    ;; the inside of the following let that handles array elements.
	    (aset vec1 0 char)
	    (aset prefix1 (length prefix) char)
209
	    (let (inner-def skipped)
Richard M. Stallman's avatar
Richard M. Stallman committed
210 211
	      ;; Skip past menu-prompt.
	      (while (stringp (car-safe defn))
212
		(setq skipped (cons (car defn) skipped))
Richard M. Stallman's avatar
Richard M. Stallman committed
213
		(setq defn (cdr defn)))
214 215 216
	      ;; Skip past cached key-equivalence data for menu items.
	      (and (consp defn) (consp (car defn))
		   (setq defn (cdr defn)))
Richard M. Stallman's avatar
Richard M. Stallman committed
217
	      (setq inner-def defn)
218
	      ;; Look past a symbol that names a keymap.
Richard M. Stallman's avatar
Richard M. Stallman committed
219 220 221
	      (while (and (symbolp inner-def)
			  (fboundp inner-def))
		(setq inner-def (symbol-function inner-def)))
222 223 224 225 226
	      (if (or (eq defn olddef)
		      ;; Compare with equal if definition is a key sequence.
		      ;; That is useful for operating on function-key-map.
		      (and (or (stringp defn) (vectorp defn))
			   (equal defn olddef)))
227
		  (define-key keymap prefix1 (nconc (nreverse skipped) newdef))
228
		(if (and (keymapp defn)
229 230
			 ;; Avoid recursively scanning
			 ;; where KEYMAP does not have a submap.
231 232 233
			 (let ((elt (lookup-key keymap prefix1)))
			   (or (null elt)
			       (keymapp elt)))
234
			 ;; Avoid recursively rescanning keymap being scanned.
235 236
			 (not (memq inner-def
				    key-substitution-in-progress)))
237 238
		    ;; If this one isn't being scanned already,
		    ;; scan it now.
Richard M. Stallman's avatar
Richard M. Stallman committed
239 240 241
		    (substitute-key-definition olddef newdef keymap
					       inner-def
					       prefix1)))))
242
	(if (vectorp (car scan))
Richard M. Stallman's avatar
Richard M. Stallman committed
243 244 245 246 247 248 249 250 251
	    (let* ((array (car scan))
		   (len (length array))
		   (i 0))
	      (while (< i len)
		(let ((char i) (defn (aref array i)))
		  ;; The inside of this let duplicates exactly
		  ;; the inside of the previous let.
		  (aset vec1 0 char)
		  (aset prefix1 (length prefix) char)
252
		  (let (inner-def skipped)
Richard M. Stallman's avatar
Richard M. Stallman committed
253 254
		    ;; Skip past menu-prompt.
		    (while (stringp (car-safe defn))
255
		      (setq skipped (cons (car defn) skipped))
Richard M. Stallman's avatar
Richard M. Stallman committed
256
		      (setq defn (cdr defn)))
257 258
		    (and (consp defn) (consp (car defn))
			 (setq defn (cdr defn)))
Richard M. Stallman's avatar
Richard M. Stallman committed
259 260 261 262
		    (setq inner-def defn)
		    (while (and (symbolp inner-def)
				(fboundp inner-def))
		      (setq inner-def (symbol-function inner-def)))
263 264 265
		    (if (or (eq defn olddef)
			    (and (or (stringp defn) (vectorp defn))
				 (equal defn olddef)))
266 267
			(define-key keymap prefix1
			  (nconc (nreverse skipped) newdef))
268
		      (if (and (keymapp defn)
269 270 271
			       (let ((elt (lookup-key keymap prefix1)))
				 (or (null elt)
				     (keymapp elt)))
272 273
			       (not (memq inner-def
					  key-substitution-in-progress)))
Richard M. Stallman's avatar
Richard M. Stallman committed
274 275 276
			  (substitute-key-definition olddef newdef keymap
						     inner-def
						     prefix1)))))
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
		(setq i (1+ i))))
	  (if (char-table-p (car scan))
	      (map-char-table
	       (function (lambda (char defn)
			   (let ()
			     ;; The inside of this let duplicates exactly
			     ;; the inside of the previous let,
			     ;; except that it uses set-char-table-range
			     ;; instead of define-key.
			     (aset vec1 0 char)
			     (aset prefix1 (length prefix) char)
			     (let (inner-def skipped)
			       ;; Skip past menu-prompt.
			       (while (stringp (car-safe defn))
				 (setq skipped (cons (car defn) skipped))
				 (setq defn (cdr defn)))
			       (and (consp defn) (consp (car defn))
				    (setq defn (cdr defn)))
			       (setq inner-def defn)
			       (while (and (symbolp inner-def)
					   (fboundp inner-def))
				 (setq inner-def (symbol-function inner-def)))
			       (if (or (eq defn olddef)
				       (and (or (stringp defn) (vectorp defn))
					    (equal defn olddef)))
302 303
				   (define-key keymap prefix1
				     (nconc (nreverse skipped) newdef))
304 305 306 307 308 309 310 311 312 313
				 (if (and (keymapp defn)
					  (let ((elt (lookup-key keymap prefix1)))
					    (or (null elt)
						(keymapp elt)))
					  (not (memq inner-def
						     key-substitution-in-progress)))
				     (substitute-key-definition olddef newdef keymap
								inner-def
								prefix1)))))))
	       (car scan)))))
Richard M. Stallman's avatar
Richard M. Stallman committed
314
      (setq scan (cdr scan)))))
315

316
(defun define-key-after (keymap key definition after)
317 318 319
  "Add binding in KEYMAP for KEY => DEFINITION, right after AFTER's binding.
This is like `define-key' except that the binding for KEY is placed
just after the binding for the event AFTER, instead of at the beginning
320 321 322 323 324
of the map.  Note that AFTER must be an event type (like KEY), NOT a command
\(like DEFINITION).

If AFTER is t, the new binding goes at the end of the keymap.

325
KEY must contain just one event type--that is to say, it must be
326 327 328 329
a string or vector of length 1.

The order of bindings in a keymap matters when it is used as a menu."

330 331
  (or (keymapp keymap)
      (signal 'wrong-type-argument (list 'keymapp keymap)))
332
  (if (> (length key) 1)
333
      (error "multi-event key specified in `define-key-after'"))
334
  (let ((tail keymap) done inserted
335 336 337 338 339 340 341
	(first (aref key 0)))
    (while (and (not done) tail)
      ;; Delete any earlier bindings for the same key.
      (if (eq (car-safe (car (cdr tail))) first)
	  (setcdr tail (cdr (cdr tail))))
      ;; When we reach AFTER's binding, insert the new binding after.
      ;; If we reach an inherited keymap, insert just before that.
342
      ;; If we reach the end of this keymap, insert at the end.
343 344
      (if (or (and (eq (car-safe (car tail)) after)
		   (not (eq after t)))
345 346
	      (eq (car (cdr tail)) 'keymap)
	      (null (cdr tail)))
347
	  (progn
348 349 350 351 352 353 354 355 356
	    ;; Stop the scan only if we find a parent keymap.
	    ;; Keep going past the inserted element
	    ;; so we can delete any duplications that come later.
	    (if (eq (car (cdr tail)) 'keymap)
		(setq done t))
	    ;; Don't insert more than once.
	    (or inserted
		(setcdr tail (cons (cons (aref key 0) definition) (cdr tail))))
	    (setq inserted t)))
357 358
      (setq tail (cdr tail)))))

Richard M. Stallman's avatar
Richard M. Stallman committed
359 360 361 362 363 364
(defmacro kbd (keys)
  "Convert KEYS to the internal Emacs key representation.
KEYS should be a string constant in the format used for
saving keyboard macros (see `insert-kbd-macro')."
  (read-kbd-macro keys))

365 366
(put 'keyboard-translate-table 'char-table-extra-slots 0)

367 368 369 370
(defun keyboard-translate (from to)
  "Translate character FROM to TO at a low level.
This function creates a `keyboard-translate-table' if necessary
and then modifies one entry in it."
371 372 373
  (or (char-table-p keyboard-translate-table)
      (setq keyboard-translate-table
	    (make-char-table 'keyboard-translate-table nil)))
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
  (aset keyboard-translate-table from to))


;;;; The global keymap tree.  

;;; global-map, esc-map, and ctl-x-map have their values set up in
;;; keymap.c; we just give them docstrings here.

(defvar global-map nil
  "Default global keymap mapping Emacs keyboard input into commands.
The value is a keymap which is usually (but not necessarily) Emacs's
global map.")

(defvar esc-map nil
  "Default keymap for ESC (meta) commands.
The normal global definition of the character ESC indirects to this keymap.")

(defvar ctl-x-map nil
  "Default keymap for C-x commands.
The normal global definition of the character C-x indirects to this keymap.")

(defvar ctl-x-4-map (make-sparse-keymap)
  "Keymap for subcommands of C-x 4")
397
(defalias 'ctl-x-4-prefix ctl-x-4-map)
398 399 400 401
(define-key ctl-x-map "4" 'ctl-x-4-prefix)

(defvar ctl-x-5-map (make-sparse-keymap)
  "Keymap for frame commands.")
402
(defalias 'ctl-x-5-prefix ctl-x-5-map)
403 404
(define-key ctl-x-map "5" 'ctl-x-5-prefix)

405

406 407
;;;; Event manipulation functions.

408 409 410 411
;; The call to `read' is to ensure that the value is computed at load time
;; and not compiled into the .elc file.  The value is negative on most
;; machines, but not on all!
(defconst listify-key-sequence-1 (logior 128 (read "?\\M-\\^@")))
412

413 414 415 416 417 418
(defun listify-key-sequence (key)
  "Convert a key sequence to a list of events."
  (if (vectorp key)
      (append key nil)
    (mapcar (function (lambda (c)
			(if (> c 127)
419
			    (logxor c listify-key-sequence-1)
420 421 422
			  c)))
	    (append key nil))))

423 424 425 426 427 428 429 430 431 432 433 434
(defsubst eventp (obj)
  "True if the argument is an event object."
  (or (integerp obj)
      (and (symbolp obj)
	   (get obj 'event-symbol-elements))
      (and (consp obj)
	   (symbolp (car obj))
	   (get (car obj) 'event-symbol-elements))))

(defun event-modifiers (event)
  "Returns a list of symbols representing the modifier keys in event EVENT.
The elements of the list may include `meta', `control',
435 436
`shift', `hyper', `super', `alt', `click', `double', `triple', `drag',
and `down'."
437 438 439 440 441 442
  (let ((type event))
    (if (listp type)
	(setq type (car type)))
    (if (symbolp type)
	(cdr (get type 'event-symbol-elements))
      (let ((list nil))
443
	(or (zerop (logand type ?\M-\^@))
444
	    (setq list (cons 'meta list)))
445
	(or (and (zerop (logand type ?\C-\^@))
446 447
		 (>= (logand type 127) 32))
	    (setq list (cons 'control list)))
448
	(or (and (zerop (logand type ?\S-\^@))
449 450
		 (= (logand type 255) (downcase (logand type 255))))
	    (setq list (cons 'shift list)))
451
	(or (zerop (logand type ?\H-\^@))
452
	    (setq list (cons 'hyper list)))
453
	(or (zerop (logand type ?\s-\^@))
454
	    (setq list (cons 'super list)))
455
	(or (zerop (logand type ?\A-\^@))
456 457 458
	    (setq list (cons 'alt list)))
	list))))

459 460 461
(defun event-basic-type (event)
  "Returns the basic type of the given event (all modifiers removed).
The value is an ASCII printing character (not upper case) or a symbol."
462 463
  (if (consp event)
      (setq event (car event)))
464 465 466 467 468
  (if (symbolp event)
      (car (get event 'event-symbol-elements))
    (let ((base (logand event (1- (lsh 1 18)))))
      (downcase (if (< base 32) (logior base 64) base)))))

469 470 471 472 473 474 475 476 477 478 479
(defsubst mouse-movement-p (object)
  "Return non-nil if OBJECT is a mouse movement event."
  (and (consp object)
       (eq (car object) 'mouse-movement)))

(defsubst event-start (event)
  "Return the starting position of EVENT.
If EVENT is a mouse press or a mouse click, this returns the location
of the event.
If EVENT is a drag, this returns the drag's starting position.
The return value is of the form
480
   (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
481 482 483 484 485 486 487
The `posn-' functions access elements of such lists."
  (nth 1 event))

(defsubst event-end (event)
  "Return the ending location of EVENT.  EVENT should be a click or drag event.
If EVENT is a click event, this function is the same as `event-start'.
The return value is of the form
488
   (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
489
The `posn-' functions access elements of such lists."
490
  (nth (if (consp (nth 2 event)) 2 1) event))
491

492 493 494 495 496
(defsubst event-click-count (event)
  "Return the multi-click count of EVENT, a click or drag event.
The return value is a positive integer."
  (if (integerp (nth 2 event)) (nth 2 event) 1))

497 498 499
(defsubst posn-window (position)
  "Return the window in POSITION.
POSITION should be a list of the form
500
   (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
501 502 503 504 505 506
as returned by the `event-start' and `event-end' functions."
  (nth 0 position))

(defsubst posn-point (position)
  "Return the buffer location in POSITION.
POSITION should be a list of the form
507
   (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
508
as returned by the `event-start' and `event-end' functions."
509 510 511
  (if (consp (nth 1 position))
      (car (nth 1 position))
    (nth 1 position)))
512

513 514
(defsubst posn-x-y (position)
  "Return the x and y coordinates in POSITION.
515
POSITION should be a list of the form
516
   (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
517 518 519
as returned by the `event-start' and `event-end' functions."
  (nth 2 position))

520
(defun posn-col-row (position)
521
  "Return the column and row in POSITION, measured in characters.
522 523
POSITION should be a list of the form
   (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
524 525 526 527 528
as returned by the `event-start' and `event-end' functions.
For a scroll-bar event, the result column is 0, and the row
corresponds to the vertical position of the click in the scroll bar."
  (let ((pair   (nth 2 position))
	(window (posn-window position)))
529 530 531
    (if (eq (if (consp (nth 1 position))
		(car (nth 1 position))
	      (nth 1 position))
532 533
	    'vertical-scroll-bar)
	(cons 0 (scroll-bar-scale pair (1- (window-height window))))
534 535 536
      (if (eq (if (consp (nth 1 position))
		  (car (nth 1 position))
		(nth 1 position))
537 538
	      'horizontal-scroll-bar)
	  (cons (scroll-bar-scale pair (window-width window)) 0)
539 540 541
	(let* ((frame (if (framep window) window (window-frame window)))
	       (x (/ (car pair) (frame-char-width frame)))
	       (y (/ (cdr pair) (frame-char-height frame))))
542
	  (cons x y))))))
543

544 545 546
(defsubst posn-timestamp (position)
  "Return the timestamp of POSITION.
POSITION should be a list of the form
547
   (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
548
as returned by the `event-start' and `event-end' functions."
549
  (nth 3 position))
550

David Lawrence's avatar
David Lawrence committed
551

552 553
;;;; Obsolescent names for functions.

554 555 556 557 558 559 560 561 562 563 564 565 566
(defalias 'dot 'point)
(defalias 'dot-marker 'point-marker)
(defalias 'dot-min 'point-min)
(defalias 'dot-max 'point-max)
(defalias 'window-dot 'window-point)
(defalias 'set-window-dot 'set-window-point)
(defalias 'read-input 'read-string)
(defalias 'send-string 'process-send-string)
(defalias 'send-region 'process-send-region)
(defalias 'show-buffer 'set-window-buffer)
(defalias 'buffer-flush-undo 'buffer-disable-undo)
(defalias 'eval-current-buffer 'eval-buffer)
(defalias 'compiled-function-p 'byte-code-function-p)
567
(defalias 'define-function 'defalias)
David Lawrence's avatar
David Lawrence committed
568

569 570 571
(defalias 'sref 'aref)
(make-obsolete 'sref 'aref)
(make-obsolete 'char-bytes "Now this function always returns 1")
Richard M. Stallman's avatar
Richard M. Stallman committed
572

573 574
;; Some programs still use this as a function.
(defun baud-rate ()
Richard M. Stallman's avatar
Richard M. Stallman committed
575 576
  "Obsolete function returning the value of the `baud-rate' variable.
Please convert your programs to use the variable `baud-rate' directly."
577 578
  baud-rate)

579 580
(defalias 'focus-frame 'ignore)
(defalias 'unfocus-frame 'ignore)
581 582 583

;;;; Alternate names for functions - these are not being phased out.

584 585 586 587 588 589
(defalias 'string= 'string-equal)
(defalias 'string< 'string-lessp)
(defalias 'move-marker 'set-marker)
(defalias 'not 'null)
(defalias 'rplaca 'setcar)
(defalias 'rplacd 'setcdr)
590
(defalias 'beep 'ding) ;preserve lingual purity
591 592 593 594 595
(defalias 'indent-to-column 'indent-to)
(defalias 'backward-delete-char 'delete-backward-char)
(defalias 'search-forward-regexp (symbol-function 're-search-forward))
(defalias 'search-backward-regexp (symbol-function 're-search-backward))
(defalias 'int-to-string 'number-to-string)
596
(defalias 'store-match-data 'set-match-data)
597 598
(defalias 'point-at-eol 'line-end-position)
(defalias 'point-at-bol 'line-beginning-position)
599 600 601

;;; Should this be an obsolete name?  If you decide it should, you get
;;; to go through all the sources and change them.
602
(defalias 'string-to-int 'string-to-number)
David Lawrence's avatar
David Lawrence committed
603

604
;;;; Hook manipulation functions.
David Lawrence's avatar
David Lawrence committed
605

606 607
(defun make-local-hook (hook)
  "Make the hook HOOK local to the current buffer.
608 609
The return value is HOOK.

610 611 612 613 614
When a hook is local, its local and global values
work in concert: running the hook actually runs all the hook
functions listed in *either* the local value *or* the global value
of the hook variable.

615 616 617 618 619 620 621 622 623
This function works by making `t' a member of the buffer-local value,
which acts as a flag to run the hook functions in the default value as
well.  This works for all normal hooks, but does not work for most
non-normal hooks yet.  We will be changing the callers of non-normal
hooks so that they can handle localness; this has to be done one by
one.

This function does nothing if HOOK is already local in the current
buffer.
624 625 626 627 628 629

Do not use `make-local-variable' to make a hook variable buffer-local."
  (if (local-variable-p hook)
      nil
    (or (boundp hook) (set hook nil))
    (make-local-variable hook)
630 631
    (set hook (list t)))
  hook)
632 633

(defun add-hook (hook function &optional append local)
634 635 636 637 638 639
  "Add to the value of HOOK the function FUNCTION.
FUNCTION is not added if already present.
FUNCTION is added (if necessary) at the beginning of the hook list
unless the optional argument APPEND is non-nil, in which case
FUNCTION is added at the end.

640 641 642 643 644 645
The optional fourth argument, LOCAL, if non-nil, says to modify
the hook's buffer-local value rather than its default value.
This makes no difference if the hook is not buffer-local.
To make a hook variable buffer-local, always use
`make-local-hook', not `make-local-variable'.

646 647
HOOK should be a symbol, and FUNCTION may be any valid function.  If
HOOK is void, it is first set to nil.  If HOOK's value is a single
648
function, it is changed to a list of functions."
David Lawrence's avatar
David Lawrence committed
649
  (or (boundp hook) (set hook nil))
650
  (or (default-boundp hook) (set-default hook nil))
651 652 653 654
  ;; If the hook value is a single function, turn it into a list.
  (let ((old (symbol-value hook)))
    (if (or (not (listp old)) (eq (car old) 'lambda))
	(set hook (list old))))
655 656 657
  (if (or local
	  ;; Detect the case where make-local-variable was used on a hook
	  ;; and do what we used to do.
658
	  (and (local-variable-if-set-p hook)
659
	       (not (memq t (symbol-value hook)))))
660
      ;; Alter the local value only.
661
      (or (if (or (consp function) (byte-code-function-p function))
662 663 664 665 666 667 668 669
	      (member function (symbol-value hook))
	    (memq function (symbol-value hook)))
	  (set hook 
	       (if append
		   (append (symbol-value hook) (list function))
		 (cons function (symbol-value hook)))))
    ;; Alter the global value (which is also the only value,
    ;; if the hook doesn't have a local value).
670
    (or (if (or (consp function) (byte-code-function-p function))
671 672 673 674 675 676 677 678
	    (member function (default-value hook))
	  (memq function (default-value hook)))
	(set-default hook 
		     (if append
			 (append (default-value hook) (list function))
		       (cons function (default-value hook)))))))

(defun remove-hook (hook function &optional local)
679 680 681
  "Remove from the value of HOOK the function FUNCTION.
HOOK should be a symbol, and FUNCTION may be any valid function.  If
FUNCTION isn't the value of HOOK, or, if FUNCTION doesn't appear in the
682 683 684 685 686 687 688
list of hooks to run in HOOK, then nothing is done.  See `add-hook'.

The optional third argument, LOCAL, if non-nil, says to modify
the hook's buffer-local value rather than its default value.
This makes no difference if the hook is not buffer-local.
To make a hook variable buffer-local, always use
`make-local-hook', not `make-local-variable'."
689
  (if (or (not (boundp hook))		;unbound symbol, or
Dave Love's avatar
Dave Love committed
690
	  (not (default-boundp hook))
691 692 693
	  (null (symbol-value hook))	;value is nil, or
	  (null function))		;function is nil, then
      nil				;Do nothing.
694 695 696 697
    (if (or local
	    ;; Detect the case where make-local-variable was used on a hook
	    ;; and do what we used to do.
	    (and (local-variable-p hook)
698 699
		  (consp (symbol-value hook))
		  (not (memq t (symbol-value hook)))))
700 701 702 703 704 705 706 707
	(let ((hook-value (symbol-value hook)))
	  (if (consp hook-value)
	      (if (member function hook-value)
		  (setq hook-value (delete function (copy-sequence hook-value))))
	    (if (equal hook-value function)
		(setq hook-value nil)))
	  (set hook hook-value))
      (let ((hook-value (default-value hook)))
708
	(if (and (consp hook-value) (not (functionp hook-value)))
709 710 711 712 713
	    (if (member function hook-value)
		(setq hook-value (delete function (copy-sequence hook-value))))
	  (if (equal hook-value function)
	      (setq hook-value nil)))
	(set-default hook hook-value)))))
714 715

(defun add-to-list (list-var element)
Richard M. Stallman's avatar
Richard M. Stallman committed
716
  "Add to the value of LIST-VAR the element ELEMENT if it isn't there yet.
Karl Heuer's avatar
Karl Heuer committed
717
The test for presence of ELEMENT is done with `equal'.
Richard M. Stallman's avatar
Richard M. Stallman committed
718 719
If ELEMENT is added, it is added at the beginning of the list.

Richard M. Stallman's avatar
Richard M. Stallman committed
720 721 722 723 724
If you want to use `add-to-list' on a variable that is not defined
until a certain package is loaded, you should put the call to `add-to-list'
into a hook function that will be run only after loading the package.
`eval-after-load' provides one way to do this.  In some cases
other hooks, such as major mode hooks, can do the job."
725 726 727
  (if (member element (symbol-value list-var))
      (symbol-value list-var)
    (set list-var (cons element (symbol-value list-var)))))
David Lawrence's avatar
David Lawrence committed
728

729 730 731 732 733
;;;; Specifying things to do after certain files are loaded.

(defun eval-after-load (file form)
  "Arrange that, if FILE is ever loaded, FORM will be run at that time.
This makes or adds to an entry on `after-load-alist'.
734
If FILE is already loaded, evaluate FORM right now.
735
It does nothing if FORM is already on the list for FILE.
736
FILE should be the name of a library, with no directory name."
737
  ;; Make sure there is an element for FILE.
738 739
  (or (assoc file after-load-alist)
      (setq after-load-alist (cons (list file) after-load-alist)))
740
  ;; Add FORM to the element if it isn't there.
741 742
  (let ((elt (assoc file after-load-alist)))
    (or (member form (cdr elt))
743 744 745 746 747
	(progn
	  (nconc elt (list form))
	  ;; If the file has been loaded already, run FORM right away.
	  (and (assoc file load-history)
	       (eval form)))))
748 749 750 751 752 753 754 755 756 757 758
  form)

(defun eval-next-after-load (file)
  "Read the following input sexp, and run it whenever FILE is loaded.
This makes or adds to an entry on `after-load-alist'.
FILE should be the name of a library, with no directory name."
  (eval-after-load file (read)))


;;;; Input and display facilities.

759
(defvar read-quoted-char-radix 8
760
  "*Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
761 762 763 764 765
Legitimate radix values are 8, 10 and 16.")

(custom-declare-variable-early
 'read-quoted-char-radix 8 
 "*Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
766 767 768 769
Legitimate radix values are 8, 10 and 16."
  :type '(choice (const 8) (const 10) (const 16))
  :group 'editing-basics)

770
(defun read-quoted-char (&optional prompt)
771 772 773
  "Like `read-char', but do not allow quitting.
Also, if the first character read is an octal digit,
we read any number of octal digits and return the
774
specified character code.  Any nondigit terminates the sequence.
775
If the terminator is RET, it is discarded;
776 777
any other terminator is used itself as input.

778 779 780
The optional argument PROMPT specifies a string to use to prompt the user.
The variable `read-quoted-char-radix' controls which radix to use
for numeric input."
781 782 783
  (let ((message-log-max nil) done (first t) (code 0) char)
    (while (not done)
      (let ((inhibit-quit first)
784 785 786 787
	    ;; Don't let C-h get the help message--only help function keys.
	    (help-char nil)
	    (help-form
	     "Type the special character you want to use,
788
or the octal character code.
789
RET terminates the character code and is discarded;
790
any other non-digit terminates the character code and is then used as input."))
791
	(setq char (read-event (and prompt (format "%s-" prompt)) t))
792
	(if inhibit-quit (setq quit-flag nil)))
793 794 795
      ;; Translate TAB key into control-I ASCII character, and so on.
      (and char
	   (let ((translated (lookup-key function-key-map (vector char))))
796
	     (if (arrayp translated)
797
		 (setq char (aref translated 0)))))
798
      (cond ((null char))
799 800 801
	    ((not (integerp char))
	     (setq unread-command-events (list char)
		   done t))
802 803 804 805
	    ((/= (logand char ?\M-\^@) 0)
	     ;; Turn a meta-character into a character with the 0200 bit set.
	     (setq code (logior (logand char (lognot ?\M-\^@)) 128)
		   done t))
806 807 808 809 810
	    ((and (<= ?0 char) (< char (+ ?0 (min 10 read-quoted-char-radix))))
	     (setq code (+ (* code read-quoted-char-radix) (- char ?0)))
	     (and prompt (setq prompt (message "%s %c" prompt char))))
	    ((and (<= ?a (downcase char))
		  (< (downcase char) (+ ?a -10 (min 26 read-quoted-char-radix))))
811 812
	     (setq code (+ (* code read-quoted-char-radix)
			   (+ 10 (- (downcase char) ?a))))
813
	     (and prompt (setq prompt (message "%s %c" prompt char))))
814
	    ((and (not first) (eq char ?\C-m))
815 816 817 818 819 820 821
	     (setq done t))
	    ((not first)
	     (setq unread-command-events (list char)
		   done t))
	    (t (setq code char
		     done t)))
      (setq first nil))
822
    code))
823

824 825
(defun read-passwd (prompt &optional confirm default)
  "Read a password, prompting with PROMPT.  Echo `.' for each character typed.
826
End with RET, LFD, or ESC.  DEL or C-h rubs out.  C-u kills line.
827 828 829 830 831 832 833 834 835 836 837 838
Optional argument CONFIRM, if non-nil, then read it twice to make sure.
Optional DEFAULT is a default password to use instead of empty input."
  (if confirm
      (let (success)
	(while (not success)
	  (let ((first (read-passwd prompt nil default))
		(second (read-passwd "Confirm password: " nil default)))
	    (if (equal first second)
		(setq success first)
	      (message "Password not repeated accurately; please start over")
	      (sit-for 1))))
	success)
839
    (clear-this-command-keys)
840 841 842 843 844 845 846
    (let ((pass nil)
	  (c 0)
	  (echo-keystrokes 0)
	  (cursor-in-echo-area t))
      (while (progn (message "%s%s"
			     prompt
			     (make-string (length pass) ?.))
847
		    (setq c (read-char nil t))
848 849 850 851 852 853 854 855 856
		    (and (/= c ?\r) (/= c ?\n) (/= c ?\e)))
	(if (= c ?\C-u)
	    (setq pass "")
	  (if (and (/= c ?\b) (/= c ?\177))
	      (setq pass (concat pass (char-to-string c)))
	    (if (> (length pass) 0)
		(setq pass (substring pass 0 -1))))))
      (message nil)
      (or pass default ""))))
857

858 859
(defun force-mode-line-update (&optional all)
  "Force the mode-line of the current buffer to be redisplayed.
860
With optional non-nil ALL, force redisplay of all mode-lines."
861 862 863
  (if all (save-excursion (set-buffer (other-buffer))))
  (set-buffer-modified-p (buffer-modified-p)))

David Lawrence's avatar
David Lawrence committed
864 865 866 867 868 869 870 871
(defun momentary-string-display (string pos &optional exit-char message) 
  "Momentarily display STRING in the buffer at POS.
Display remains until next character is typed.
If the char is EXIT-CHAR (optional third arg, default is SPC) it is swallowed;
otherwise it is then available as input (as a command if nothing else).
Display MESSAGE (optional fourth arg) in the echo area.
If MESSAGE is nil, instructions to type EXIT-CHAR are displayed there."
  (or exit-char (setq exit-char ?\ ))
872
  (let ((inhibit-read-only t)
873 874
	;; Don't modify the undo list at all.
	(buffer-undo-list t)
David Lawrence's avatar
David Lawrence committed
875 876 877 878 879 880 881 882 883 884
	(modified (buffer-modified-p))
	(name buffer-file-name)
	insert-end)
    (unwind-protect
	(progn
	  (save-excursion
	    (goto-char pos)
	    ;; defeat file locking... don't try this at home, kids!
	    (setq buffer-file-name nil)
	    (insert-before-markers string)
885 886
	    (setq insert-end (point))
	    ;; If the message end is off screen, recenter now.
887
	    (if (< (window-end nil t) insert-end)
888 889 890 891 892 893 894 895
		(recenter (/ (window-height) 2)))
	    ;; If that pushed message start off the screen,
	    ;; scroll to start it at the top of the screen.
	    (move-to-window-line 0)
	    (if (> (point) pos)
		(progn
		  (goto-char pos)
		  (recenter 0))))
David Lawrence's avatar
David Lawrence committed
896 897
	  (message (or message "Type %s to continue editing.")
		   (single-key-description exit-char))
898
	  (let ((char (read-event)))
David Lawrence's avatar
David Lawrence committed
899
	    (or (eq char exit-char)
Jim Blandy's avatar
Jim Blandy committed
900
		(setq unread-command-events (list char)))))
David Lawrence's avatar
David Lawrence committed
901 902 903 904 905 906
      (if insert-end
	  (save-excursion
	    (delete-region pos insert-end)))
      (setq buffer-file-name name)
      (set-buffer-modified-p modified))))

907 908 909

;;;; Miscellanea.

910 911 912 913
;; A number of major modes set this locally.
;; Give it a global value to avoid compiler warnings.
(defvar font-lock-defaults nil)

914 915 916 917 918 919
(defvar suspend-hook nil
  "Normal hook run by `suspend-emacs', before suspending.")

(defvar suspend-resume-hook nil
  "Normal hook run by `suspend-emacs', after Emacs is continued.")

920 921 922 923 924 925 926 927
;; Avoid compiler warnings about this variable,
;; which has a special meaning on certain system types.
(defvar buffer-file-type nil
  "Non-nil if the visited file is a binary file.
This variable is meaningful on MS-DOG and Windows NT.
On those systems, it is automatically local in every buffer.
On other systems, this variable is normally always nil.")

Simon Marshall's avatar
Simon Marshall committed
928
;; This should probably be written in C (i.e., without using `walk-windows').
929
(defun get-buffer-window-list (buffer &optional minibuf frame)
Simon Marshall's avatar
Simon Marshall committed
930
  "Return windows currently displaying BUFFER, or nil if none.
931
See `walk-windows' for the meaning of MINIBUF and FRAME."
932
  (let ((buffer (if (bufferp buffer) buffer (get-buffer buffer))) windows)
Simon Marshall's avatar
Simon Marshall committed
933 934 935
    (walk-windows (function (lambda (window)
			      (if (eq (window-buffer window) buffer)
				  (setq windows (cons window windows)))))
936
		  minibuf frame)
Simon Marshall's avatar
Simon Marshall committed
937 938
    windows))

939 940 941
(defun ignore (&rest ignore)
  "Do nothing and return nil.
This function accepts any number of arguments, but ignores them."
942
  (interactive)
943 944 945
  nil)

(defun error (&rest args)
Richard M. Stallman's avatar
Richard M. Stallman committed
946 947 948 949
  "Signal an error, making error message by passing all args to `format'.
In Emacs, the convention is that error messages start with a capital
letter but *do not* end with a period.  Please follow this convention
for the sake of consistency."
950 951 952
  (while t
    (signal 'error (list (apply 'format args)))))

953
(defalias 'user-original-login-name 'user-login-name)
954

David Lawrence's avatar
David Lawrence committed
955 956 957 958 959 960 961 962 963 964 965
(defun start-process-shell-command (name buffer &rest args)
  "Start a program in a subprocess.  Return the process object for it.
Args are NAME BUFFER COMMAND &rest COMMAND-ARGS.
NAME is name for process.  It is modified if necessary to make it unique.
BUFFER is the buffer or (buffer-name) to associate with the process.
 Process output goes at end of that buffer, unless you specify
 an output stream or filter function to handle the output.
 BUFFER may be also nil, meaning that this process is not associated
 with any buffer
Third arg is command name, the name of a shell command.
Remaining arguments are the arguments for the command.
966
Wildcards and redirection are handled as usual in the shell."
967 968 969
  (cond
   ((eq system-type 'vax-vms)
    (apply 'start-process name buffer args))
970 971
   ;; We used to use `exec' to replace the shell with the command,
   ;; but that failed to handle (...) and semicolon, etc.
972 973
   (t
    (start-process name buffer shell-file-name shell-command-switch
974
		   (mapconcat 'identity args " ")))))
975

976 977
(defmacro with-current-buffer (buffer &rest body)
  "Execute the forms in BODY with BUFFER as the current buffer.
978 979
The value returned is the value of the last form in BODY.
See also `with-temp-buffer'."
980 981
  `(save-current-buffer
    (set-buffer ,buffer)
982
    ,@body))
983

Simon Marshall's avatar
Simon Marshall committed
984 985 986
(defmacro with-temp-file (file &rest body)
  "Create a new buffer, evaluate BODY there, and write the buffer to FILE.
The value returned is the value of the last form in BODY.
987
See also `with-temp-buffer'."
988
  (let ((temp-file (make-symbol "temp-file"))
989 990 991 992 993 994 995
	(temp-buffer (make-symbol "temp-buffer")))
    `(let ((,temp-file ,file)
	   (,temp-buffer
	    (get-buffer-create (generate-new-buffer-name " *temp file*"))))
       (unwind-protect
	   (prog1
	       (with-current-buffer ,temp-buffer
Simon Marshall's avatar
Simon Marshall committed
996
		 ,@body)
997 998 999 1000 1001 1002
	     (with-current-buffer ,temp-buffer
	       (widen)
	       (write-region (point-min) (point-max) ,temp-file nil 0)))
	 (and (buffer-name ,temp-buffer)
	      (kill-buffer ,temp-buffer))))))

Simon Marshall's avatar
Simon Marshall committed
1003
(defmacro with-temp-message (message &rest body)
Simon Marshall's avatar
Simon Marshall committed
1004
  "Display MESSAGE temporarily if non-nil while BODY is evaluated.
Simon Marshall's avatar
Simon Marshall committed
1005 1006
The original message is restored to the echo area after BODY has finished.
The value returned is the value of the last form in BODY.
Simon Marshall's avatar
Simon Marshall committed
1007 1008 1009
MESSAGE is written to the message log buffer if `message-log-max' is non-nil.
If MESSAGE is nil, the echo area and message log buffer are unchanged.
Use a MESSAGE of \"\" to temporarily clear the echo area."
1010 1011 1012 1013
  (let ((current-message (make-symbol "current-message"))
	(temp-message (make-symbol "with-temp-message")))
    `(let ((,temp-message ,message)
	   (,current-message))
Simon Marshall's avatar
Simon Marshall committed
1014 1015
       (unwind-protect
	   (progn
1016 1017
	     (when ,temp-message
	       (setq ,current-message (current-message))
1018
	       (message "%s" ,temp-message))
Simon Marshall's avatar
Simon Marshall committed
1019
	     ,@body)
1020 1021
	 (and ,temp-message ,current-message
	      (message