*** empty log message ***
[emacs.git] / lisp / subr.el
blob2636ccadea97ccffdca717aa3c2d0f603024ab5a
1 ;;; subr.el --- basic lisp subroutines for Emacs
3 ;; Copyright (C) 1985, 86, 92, 94, 95, 99, 2000, 2001, 2002
4 ;; Free Software Foundation, Inc.
6 ;; Maintainer: FSF
7 ;; Keywords: internal
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software; you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs; see the file COPYING. If not, write to the
23 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
24 ;; Boston, MA 02111-1307, USA.
26 ;;; Commentary:
28 ;;; Code:
29 (defvar custom-declare-variable-list nil
30 "Record `defcustom' calls made before `custom.el' is loaded to handle them.
31 Each element of this list holds the arguments to one call to `defcustom'.")
33 ;; Use this, rather than defcustom, in subr.el and other files loaded
34 ;; before custom.el.
35 (defun custom-declare-variable-early (&rest arguments)
36 (setq custom-declare-variable-list
37 (cons arguments custom-declare-variable-list)))
40 (defun macro-declaration-function (macro decl)
41 "Process a declaration found in a macro definition.
42 This is set as the value of the variable `macro-declaration-function'.
43 MACRO is the name of the macro being defined.
44 DECL is a list `(declare ...)' containing the declarations.
45 The return value of this function is not used."
46 (dolist (d (cdr decl))
47 (cond ((and (consp d) (eq (car d) 'indent))
48 (put macro 'lisp-indent-function (cadr d)))
49 ((and (consp d) (eq (car d) 'debug))
50 (put macro 'edebug-form-spec (cadr d)))
52 (message "Unknown declaration %s" d)))))
54 (setq macro-declaration-function 'macro-declaration-function)
57 ;;;; Lisp language features.
59 (defalias 'not 'null)
61 (defmacro lambda (&rest cdr)
62 "Return a lambda expression.
63 A call of the form (lambda ARGS DOCSTRING INTERACTIVE BODY) is
64 self-quoting; the result of evaluating the lambda expression is the
65 expression itself. The lambda expression may then be treated as a
66 function, i.e., stored as the function value of a symbol, passed to
67 funcall or mapcar, etc.
69 ARGS should take the same form as an argument list for a `defun'.
70 DOCSTRING is an optional documentation string.
71 If present, it should describe how to call the function.
72 But documentation strings are usually not useful in nameless functions.
73 INTERACTIVE should be a call to the function `interactive', which see.
74 It may also be omitted.
75 BODY should be a list of lisp expressions."
76 ;; Note that this definition should not use backquotes; subr.el should not
77 ;; depend on backquote.el.
78 (list 'function (cons 'lambda cdr)))
80 (defmacro push (newelt listname)
81 "Add NEWELT to the list stored in the symbol LISTNAME.
82 This is equivalent to (setq LISTNAME (cons NEWELT LISTNAME)).
83 LISTNAME must be a symbol."
84 (list 'setq listname
85 (list 'cons newelt listname)))
87 (defmacro pop (listname)
88 "Return the first element of LISTNAME's value, and remove it from the list.
89 LISTNAME must be a symbol whose value is a list.
90 If the value is nil, `pop' returns nil but does not actually
91 change the list."
92 (list 'prog1 (list 'car listname)
93 (list 'setq listname (list 'cdr listname))))
95 (defmacro when (cond &rest body)
96 "If COND yields non-nil, do BODY, else return nil."
97 (list 'if cond (cons 'progn body)))
99 (defmacro unless (cond &rest body)
100 "If COND yields nil, do BODY, else return nil."
101 (cons 'if (cons cond (cons nil body))))
103 (defmacro dolist (spec &rest body)
104 "(dolist (VAR LIST [RESULT]) BODY...): loop over a list.
105 Evaluate BODY with VAR bound to each car from LIST, in turn.
106 Then evaluate RESULT to get return value, default nil."
107 (let ((temp (make-symbol "--dolist-temp--")))
108 (list 'let (list (list temp (nth 1 spec)) (car spec))
109 (list 'while temp
110 (list 'setq (car spec) (list 'car temp))
111 (cons 'progn
112 (append body
113 (list (list 'setq temp (list 'cdr temp))))))
114 (if (cdr (cdr spec))
115 (cons 'progn
116 (cons (list 'setq (car spec) nil) (cdr (cdr spec))))))))
118 (defmacro dotimes (spec &rest body)
119 "(dotimes (VAR COUNT [RESULT]) BODY...): loop a certain number of times.
120 Evaluate BODY with VAR bound to successive integers running from 0,
121 inclusive, to COUNT, exclusive. Then evaluate RESULT to get
122 the return value (nil if RESULT is omitted)."
123 (let ((temp (make-symbol "--dotimes-temp--")))
124 (list 'let (list (list temp (nth 1 spec)) (list (car spec) 0))
125 (list 'while (list '< (car spec) temp)
126 (cons 'progn
127 (append body (list (list 'setq (car spec)
128 (list '1+ (car spec)))))))
129 (if (cdr (cdr spec))
130 (car (cdr (cdr spec)))
131 nil))))
133 (defsubst caar (x)
134 "Return the car of the car of X."
135 (car (car x)))
137 (defsubst cadr (x)
138 "Return the car of the cdr of X."
139 (car (cdr x)))
141 (defsubst cdar (x)
142 "Return the cdr of the car of X."
143 (cdr (car x)))
145 (defsubst cddr (x)
146 "Return the cdr of the cdr of X."
147 (cdr (cdr x)))
149 (defun last (x &optional n)
150 "Return the last link of the list X. Its car is the last element.
151 If X is nil, return nil.
152 If N is non-nil, return the Nth-to-last link of X.
153 If N is bigger than the length of X, return X."
154 (if n
155 (let ((m 0) (p x))
156 (while (consp p)
157 (setq m (1+ m) p (cdr p)))
158 (if (<= n 0) p
159 (if (< n m) (nthcdr (- m n) x) x)))
160 (while (consp (cdr x))
161 (setq x (cdr x)))
164 (defun butlast (x &optional n)
165 "Returns a copy of LIST with the last N elements removed."
166 (if (and n (<= n 0)) x
167 (nbutlast (copy-sequence x) n)))
169 (defun nbutlast (x &optional n)
170 "Modifies LIST to remove the last N elements."
171 (let ((m (length x)))
172 (or n (setq n 1))
173 (and (< n m)
174 (progn
175 (if (> n 0) (setcdr (nthcdr (- (1- m) n) x) nil))
176 x))))
178 (defun remove (elt seq)
179 "Return a copy of SEQ with all occurrences of ELT removed.
180 SEQ must be a list, vector, or string. The comparison is done with `equal'."
181 (if (nlistp seq)
182 ;; If SEQ isn't a list, there's no need to copy SEQ because
183 ;; `delete' will return a new object.
184 (delete elt seq)
185 (delete elt (copy-sequence seq))))
187 (defun remq (elt list)
188 "Return a copy of LIST with all occurences of ELT removed.
189 The comparison is done with `eq'."
190 (if (memq elt list)
191 (delq elt (copy-sequence list))
192 list))
194 (defun assoc-default (key alist &optional test default)
195 "Find object KEY in a pseudo-alist ALIST.
196 ALIST is a list of conses or objects. Each element (or the element's car,
197 if it is a cons) is compared with KEY by evaluating (TEST (car elt) KEY).
198 If that is non-nil, the element matches;
199 then `assoc-default' returns the element's cdr, if it is a cons,
200 or DEFAULT if the element is not a cons.
202 If no element matches, the value is nil.
203 If TEST is omitted or nil, `equal' is used."
204 (let (found (tail alist) value)
205 (while (and tail (not found))
206 (let ((elt (car tail)))
207 (when (funcall (or test 'equal) (if (consp elt) (car elt) elt) key)
208 (setq found t value (if (consp elt) (cdr elt) default))))
209 (setq tail (cdr tail)))
210 value))
212 (defun assoc-ignore-case (key alist)
213 "Like `assoc', but ignores differences in case and text representation.
214 KEY must be a string. Upper-case and lower-case letters are treated as equal.
215 Unibyte strings are converted to multibyte for comparison."
216 (let (element)
217 (while (and alist (not element))
218 (if (eq t (compare-strings key 0 nil (car (car alist)) 0 nil t))
219 (setq element (car alist)))
220 (setq alist (cdr alist)))
221 element))
223 (defun assoc-ignore-representation (key alist)
224 "Like `assoc', but ignores differences in text representation.
225 KEY must be a string.
226 Unibyte strings are converted to multibyte for comparison."
227 (let (element)
228 (while (and alist (not element))
229 (if (eq t (compare-strings key 0 nil (car (car alist)) 0 nil))
230 (setq element (car alist)))
231 (setq alist (cdr alist)))
232 element))
234 (defun member-ignore-case (elt list)
235 "Like `member', but ignores differences in case and text representation.
236 ELT must be a string. Upper-case and lower-case letters are treated as equal.
237 Unibyte strings are converted to multibyte for comparison.
238 Non-strings in LIST are ignored."
239 (while (and list
240 (not (and (stringp (car list))
241 (eq t (compare-strings elt 0 nil (car list) 0 nil t)))))
242 (setq list (cdr list)))
243 list)
246 ;;;; Keymap support.
248 (defun undefined ()
249 (interactive)
250 (ding))
252 ;Prevent the \{...} documentation construct
253 ;from mentioning keys that run this command.
254 (put 'undefined 'suppress-keymap t)
256 (defun suppress-keymap (map &optional nodigits)
257 "Make MAP override all normally self-inserting keys to be undefined.
258 Normally, as an exception, digits and minus-sign are set to make prefix args,
259 but optional second arg NODIGITS non-nil treats them like other chars."
260 (substitute-key-definition 'self-insert-command 'undefined map global-map)
261 (or nodigits
262 (let (loop)
263 (define-key map "-" 'negative-argument)
264 ;; Make plain numbers do numeric args.
265 (setq loop ?0)
266 (while (<= loop ?9)
267 (define-key map (char-to-string loop) 'digit-argument)
268 (setq loop (1+ loop))))))
270 ;Moved to keymap.c
271 ;(defun copy-keymap (keymap)
272 ; "Return a copy of KEYMAP"
273 ; (while (not (keymapp keymap))
274 ; (setq keymap (signal 'wrong-type-argument (list 'keymapp keymap))))
275 ; (if (vectorp keymap)
276 ; (copy-sequence keymap)
277 ; (copy-alist keymap)))
279 (defvar key-substitution-in-progress nil
280 "Used internally by substitute-key-definition.")
282 (defun substitute-key-definition (olddef newdef keymap &optional oldmap prefix)
283 "Replace OLDDEF with NEWDEF for any keys in KEYMAP now defined as OLDDEF.
284 In other words, OLDDEF is replaced with NEWDEF where ever it appears.
285 Alternatively, if optional fourth argument OLDMAP is specified, we redefine
286 in KEYMAP as NEWDEF those keys which are defined as OLDDEF in OLDMAP."
287 ;; Don't document PREFIX in the doc string because we don't want to
288 ;; advertise it. It's meant for recursive calls only. Here's its
289 ;; meaning
291 ;; If optional argument PREFIX is specified, it should be a key
292 ;; prefix, a string. Redefined bindings will then be bound to the
293 ;; original key, with PREFIX added at the front.
294 (or prefix (setq prefix ""))
295 (let* ((scan (or oldmap keymap))
296 (vec1 (vector nil))
297 (prefix1 (vconcat prefix vec1))
298 (key-substitution-in-progress
299 (cons scan key-substitution-in-progress)))
300 ;; Scan OLDMAP, finding each char or event-symbol that
301 ;; has any definition, and act on it with hack-key.
302 (while (consp scan)
303 (if (consp (car scan))
304 (let ((char (car (car scan)))
305 (defn (cdr (car scan))))
306 ;; The inside of this let duplicates exactly
307 ;; the inside of the following let that handles array elements.
308 (aset vec1 0 char)
309 (aset prefix1 (length prefix) char)
310 (let (inner-def skipped)
311 ;; Skip past menu-prompt.
312 (while (stringp (car-safe defn))
313 (setq skipped (cons (car defn) skipped))
314 (setq defn (cdr defn)))
315 ;; Skip past cached key-equivalence data for menu items.
316 (and (consp defn) (consp (car defn))
317 (setq defn (cdr defn)))
318 (setq inner-def defn)
319 ;; Look past a symbol that names a keymap.
320 (while (and (symbolp inner-def)
321 (fboundp inner-def))
322 (setq inner-def (symbol-function inner-def)))
323 (if (or (eq defn olddef)
324 ;; Compare with equal if definition is a key sequence.
325 ;; That is useful for operating on function-key-map.
326 (and (or (stringp defn) (vectorp defn))
327 (equal defn olddef)))
328 (define-key keymap prefix1 (nconc (nreverse skipped) newdef))
329 (if (and (keymapp defn)
330 ;; Avoid recursively scanning
331 ;; where KEYMAP does not have a submap.
332 (let ((elt (lookup-key keymap prefix1)))
333 (or (null elt)
334 (keymapp elt)))
335 ;; Avoid recursively rescanning keymap being scanned.
336 (not (memq inner-def
337 key-substitution-in-progress)))
338 ;; If this one isn't being scanned already,
339 ;; scan it now.
340 (substitute-key-definition olddef newdef keymap
341 inner-def
342 prefix1)))))
343 (if (vectorp (car scan))
344 (let* ((array (car scan))
345 (len (length array))
346 (i 0))
347 (while (< i len)
348 (let ((char i) (defn (aref array i)))
349 ;; The inside of this let duplicates exactly
350 ;; the inside of the previous let.
351 (aset vec1 0 char)
352 (aset prefix1 (length prefix) char)
353 (let (inner-def skipped)
354 ;; Skip past menu-prompt.
355 (while (stringp (car-safe defn))
356 (setq skipped (cons (car defn) skipped))
357 (setq defn (cdr defn)))
358 (and (consp defn) (consp (car defn))
359 (setq defn (cdr defn)))
360 (setq inner-def defn)
361 (while (and (symbolp inner-def)
362 (fboundp inner-def))
363 (setq inner-def (symbol-function inner-def)))
364 (if (or (eq defn olddef)
365 (and (or (stringp defn) (vectorp defn))
366 (equal defn olddef)))
367 (define-key keymap prefix1
368 (nconc (nreverse skipped) newdef))
369 (if (and (keymapp defn)
370 (let ((elt (lookup-key keymap prefix1)))
371 (or (null elt)
372 (keymapp elt)))
373 (not (memq inner-def
374 key-substitution-in-progress)))
375 (substitute-key-definition olddef newdef keymap
376 inner-def
377 prefix1)))))
378 (setq i (1+ i))))
379 (if (char-table-p (car scan))
380 (map-char-table
381 (function (lambda (char defn)
382 (let ()
383 ;; The inside of this let duplicates exactly
384 ;; the inside of the previous let,
385 ;; except that it uses set-char-table-range
386 ;; instead of define-key.
387 (aset vec1 0 char)
388 (aset prefix1 (length prefix) char)
389 (let (inner-def skipped)
390 ;; Skip past menu-prompt.
391 (while (stringp (car-safe defn))
392 (setq skipped (cons (car defn) skipped))
393 (setq defn (cdr defn)))
394 (and (consp defn) (consp (car defn))
395 (setq defn (cdr defn)))
396 (setq inner-def defn)
397 (while (and (symbolp inner-def)
398 (fboundp inner-def))
399 (setq inner-def (symbol-function inner-def)))
400 (if (or (eq defn olddef)
401 (and (or (stringp defn) (vectorp defn))
402 (equal defn olddef)))
403 (define-key keymap prefix1
404 (nconc (nreverse skipped) newdef))
405 (if (and (keymapp defn)
406 (let ((elt (lookup-key keymap prefix1)))
407 (or (null elt)
408 (keymapp elt)))
409 (not (memq inner-def
410 key-substitution-in-progress)))
411 (substitute-key-definition olddef newdef keymap
412 inner-def
413 prefix1)))))))
414 (car scan)))))
415 (setq scan (cdr scan)))))
417 (defun define-key-after (keymap key definition &optional after)
418 "Add binding in KEYMAP for KEY => DEFINITION, right after AFTER's binding.
419 This is like `define-key' except that the binding for KEY is placed
420 just after the binding for the event AFTER, instead of at the beginning
421 of the map. Note that AFTER must be an event type (like KEY), NOT a command
422 \(like DEFINITION).
424 If AFTER is t or omitted, the new binding goes at the end of the keymap.
425 AFTER should be a single event type--a symbol or a character, not a sequence.
427 Bindings are always added before any inherited map.
429 The order of bindings in a keymap matters when it is used as a menu."
430 (unless after (setq after t))
431 (or (keymapp keymap)
432 (signal 'wrong-type-argument (list 'keymapp keymap)))
433 (setq key
434 (if (<= (length key) 1) (aref key 0)
435 (setq keymap (lookup-key keymap
436 (apply 'vector
437 (butlast (mapcar 'identity key)))))
438 (aref key (1- (length key)))))
439 (let ((tail keymap) done inserted)
440 (while (and (not done) tail)
441 ;; Delete any earlier bindings for the same key.
442 (if (eq (car-safe (car (cdr tail))) key)
443 (setcdr tail (cdr (cdr tail))))
444 ;; If we hit an included map, go down that one.
445 (if (keymapp (car tail)) (setq tail (car tail)))
446 ;; When we reach AFTER's binding, insert the new binding after.
447 ;; If we reach an inherited keymap, insert just before that.
448 ;; If we reach the end of this keymap, insert at the end.
449 (if (or (and (eq (car-safe (car tail)) after)
450 (not (eq after t)))
451 (eq (car (cdr tail)) 'keymap)
452 (null (cdr tail)))
453 (progn
454 ;; Stop the scan only if we find a parent keymap.
455 ;; Keep going past the inserted element
456 ;; so we can delete any duplications that come later.
457 (if (eq (car (cdr tail)) 'keymap)
458 (setq done t))
459 ;; Don't insert more than once.
460 (or inserted
461 (setcdr tail (cons (cons key definition) (cdr tail))))
462 (setq inserted t)))
463 (setq tail (cdr tail)))))
466 (defmacro kbd (keys)
467 "Convert KEYS to the internal Emacs key representation.
468 KEYS should be a string constant in the format used for
469 saving keyboard macros (see `insert-kbd-macro')."
470 (read-kbd-macro keys))
472 (put 'keyboard-translate-table 'char-table-extra-slots 0)
474 (defun keyboard-translate (from to)
475 "Translate character FROM to TO at a low level.
476 This function creates a `keyboard-translate-table' if necessary
477 and then modifies one entry in it."
478 (or (char-table-p keyboard-translate-table)
479 (setq keyboard-translate-table
480 (make-char-table 'keyboard-translate-table nil)))
481 (aset keyboard-translate-table from to))
484 ;;;; The global keymap tree.
486 ;;; global-map, esc-map, and ctl-x-map have their values set up in
487 ;;; keymap.c; we just give them docstrings here.
489 (defvar global-map nil
490 "Default global keymap mapping Emacs keyboard input into commands.
491 The value is a keymap which is usually (but not necessarily) Emacs's
492 global map.")
494 (defvar esc-map nil
495 "Default keymap for ESC (meta) commands.
496 The normal global definition of the character ESC indirects to this keymap.")
498 (defvar ctl-x-map nil
499 "Default keymap for C-x commands.
500 The normal global definition of the character C-x indirects to this keymap.")
502 (defvar ctl-x-4-map (make-sparse-keymap)
503 "Keymap for subcommands of C-x 4.")
504 (defalias 'ctl-x-4-prefix ctl-x-4-map)
505 (define-key ctl-x-map "4" 'ctl-x-4-prefix)
507 (defvar ctl-x-5-map (make-sparse-keymap)
508 "Keymap for frame commands.")
509 (defalias 'ctl-x-5-prefix ctl-x-5-map)
510 (define-key ctl-x-map "5" 'ctl-x-5-prefix)
513 ;;;; Event manipulation functions.
515 ;; The call to `read' is to ensure that the value is computed at load time
516 ;; and not compiled into the .elc file. The value is negative on most
517 ;; machines, but not on all!
518 (defconst listify-key-sequence-1 (logior 128 (read "?\\M-\\^@")))
520 (defun listify-key-sequence (key)
521 "Convert a key sequence to a list of events."
522 (if (vectorp key)
523 (append key nil)
524 (mapcar (function (lambda (c)
525 (if (> c 127)
526 (logxor c listify-key-sequence-1)
527 c)))
528 (append key nil))))
530 (defsubst eventp (obj)
531 "True if the argument is an event object."
532 (or (integerp obj)
533 (and (symbolp obj)
534 (get obj 'event-symbol-elements))
535 (and (consp obj)
536 (symbolp (car obj))
537 (get (car obj) 'event-symbol-elements))))
539 (defun event-modifiers (event)
540 "Returns a list of symbols representing the modifier keys in event EVENT.
541 The elements of the list may include `meta', `control',
542 `shift', `hyper', `super', `alt', `click', `double', `triple', `drag',
543 and `down'."
544 (let ((type event))
545 (if (listp type)
546 (setq type (car type)))
547 (if (symbolp type)
548 (cdr (get type 'event-symbol-elements))
549 (let ((list nil))
550 (or (zerop (logand type ?\M-\^@))
551 (setq list (cons 'meta list)))
552 (or (and (zerop (logand type ?\C-\^@))
553 (>= (logand type 127) 32))
554 (setq list (cons 'control list)))
555 (or (and (zerop (logand type ?\S-\^@))
556 (= (logand type 255) (downcase (logand type 255))))
557 (setq list (cons 'shift list)))
558 (or (zerop (logand type ?\H-\^@))
559 (setq list (cons 'hyper list)))
560 (or (zerop (logand type ?\s-\^@))
561 (setq list (cons 'super list)))
562 (or (zerop (logand type ?\A-\^@))
563 (setq list (cons 'alt list)))
564 list))))
566 (defun event-basic-type (event)
567 "Returns the basic type of the given event (all modifiers removed).
568 The value is a printing character (not upper case) or a symbol."
569 (if (consp event)
570 (setq event (car event)))
571 (if (symbolp event)
572 (car (get event 'event-symbol-elements))
573 (let ((base (logand event (1- (lsh 1 18)))))
574 (downcase (if (< base 32) (logior base 64) base)))))
576 (defsubst mouse-movement-p (object)
577 "Return non-nil if OBJECT is a mouse movement event."
578 (and (consp object)
579 (eq (car object) 'mouse-movement)))
581 (defsubst event-start (event)
582 "Return the starting position of EVENT.
583 If EVENT is a mouse press or a mouse click, this returns the location
584 of the event.
585 If EVENT is a drag, this returns the drag's starting position.
586 The return value is of the form
587 (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
588 The `posn-' functions access elements of such lists."
589 (nth 1 event))
591 (defsubst event-end (event)
592 "Return the ending location of EVENT. EVENT should be a click or drag event.
593 If EVENT is a click event, this function is the same as `event-start'.
594 The return value is of the form
595 (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
596 The `posn-' functions access elements of such lists."
597 (nth (if (consp (nth 2 event)) 2 1) event))
599 (defsubst event-click-count (event)
600 "Return the multi-click count of EVENT, a click or drag event.
601 The return value is a positive integer."
602 (if (integerp (nth 2 event)) (nth 2 event) 1))
604 (defsubst posn-window (position)
605 "Return the window in POSITION.
606 POSITION should be a list of the form
607 (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
608 as returned by the `event-start' and `event-end' functions."
609 (nth 0 position))
611 (defsubst posn-point (position)
612 "Return the buffer location in POSITION.
613 POSITION should be a list of the form
614 (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
615 as returned by the `event-start' and `event-end' functions."
616 (if (consp (nth 1 position))
617 (car (nth 1 position))
618 (nth 1 position)))
620 (defsubst posn-x-y (position)
621 "Return the x and y coordinates in POSITION.
622 POSITION should be a list of the form
623 (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
624 as returned by the `event-start' and `event-end' functions."
625 (nth 2 position))
627 (defun posn-col-row (position)
628 "Return the column and row in POSITION, measured in characters.
629 POSITION should be a list of the form
630 (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
631 as returned by the `event-start' and `event-end' functions.
632 For a scroll-bar event, the result column is 0, and the row
633 corresponds to the vertical position of the click in the scroll bar."
634 (let ((pair (nth 2 position))
635 (window (posn-window position)))
636 (if (eq (if (consp (nth 1 position))
637 (car (nth 1 position))
638 (nth 1 position))
639 'vertical-scroll-bar)
640 (cons 0 (scroll-bar-scale pair (1- (window-height window))))
641 (if (eq (if (consp (nth 1 position))
642 (car (nth 1 position))
643 (nth 1 position))
644 'horizontal-scroll-bar)
645 (cons (scroll-bar-scale pair (window-width window)) 0)
646 (let* ((frame (if (framep window) window (window-frame window)))
647 (x (/ (car pair) (frame-char-width frame)))
648 (y (/ (cdr pair) (frame-char-height frame))))
649 (cons x y))))))
651 (defsubst posn-timestamp (position)
652 "Return the timestamp of POSITION.
653 POSITION should be a list of the form
654 (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
655 as returned by the `event-start' and `event-end' functions."
656 (nth 3 position))
659 ;;;; Obsolescent names for functions.
661 (defalias 'dot 'point)
662 (defalias 'dot-marker 'point-marker)
663 (defalias 'dot-min 'point-min)
664 (defalias 'dot-max 'point-max)
665 (defalias 'window-dot 'window-point)
666 (defalias 'set-window-dot 'set-window-point)
667 (defalias 'read-input 'read-string)
668 (defalias 'send-string 'process-send-string)
669 (defalias 'send-region 'process-send-region)
670 (defalias 'show-buffer 'set-window-buffer)
671 (defalias 'buffer-flush-undo 'buffer-disable-undo)
672 (defalias 'eval-current-buffer 'eval-buffer)
673 (defalias 'compiled-function-p 'byte-code-function-p)
674 (defalias 'define-function 'defalias)
676 (defalias 'sref 'aref)
677 (make-obsolete 'sref 'aref "20.4")
678 (make-obsolete 'char-bytes "Now this function always returns 1" "20.4")
680 (defun insert-string (&rest args)
681 "Mocklisp-compatibility insert function.
682 Like the function `insert' except that any argument that is a number
683 is converted into a string by expressing it in decimal."
684 (dolist (el args)
685 (insert (if (integerp el) (number-to-string el) el))))
687 (make-obsolete 'insert-string 'insert "21.3")
689 ;; Some programs still use this as a function.
690 (defun baud-rate ()
691 "Obsolete function returning the value of the `baud-rate' variable.
692 Please convert your programs to use the variable `baud-rate' directly."
693 baud-rate)
695 (defalias 'focus-frame 'ignore)
696 (defalias 'unfocus-frame 'ignore)
698 ;;;; Alternate names for functions - these are not being phased out.
700 (defalias 'string= 'string-equal)
701 (defalias 'string< 'string-lessp)
702 (defalias 'move-marker 'set-marker)
703 (defalias 'rplaca 'setcar)
704 (defalias 'rplacd 'setcdr)
705 (defalias 'beep 'ding) ;preserve lingual purity
706 (defalias 'indent-to-column 'indent-to)
707 (defalias 'backward-delete-char 'delete-backward-char)
708 (defalias 'search-forward-regexp (symbol-function 're-search-forward))
709 (defalias 'search-backward-regexp (symbol-function 're-search-backward))
710 (defalias 'int-to-string 'number-to-string)
711 (defalias 'store-match-data 'set-match-data)
712 ;; These are the XEmacs names:
713 (defalias 'point-at-eol 'line-end-position)
714 (defalias 'point-at-bol 'line-beginning-position)
716 ;;; Should this be an obsolete name? If you decide it should, you get
717 ;;; to go through all the sources and change them.
718 (defalias 'string-to-int 'string-to-number)
720 ;;;; Hook manipulation functions.
722 (defun make-local-hook (hook)
723 "Make the hook HOOK local to the current buffer.
724 The return value is HOOK.
726 You never need to call this function now that `add-hook' does it for you
727 if its LOCAL argument is non-nil.
729 When a hook is local, its local and global values
730 work in concert: running the hook actually runs all the hook
731 functions listed in *either* the local value *or* the global value
732 of the hook variable.
734 This function works by making t a member of the buffer-local value,
735 which acts as a flag to run the hook functions in the default value as
736 well. This works for all normal hooks, but does not work for most
737 non-normal hooks yet. We will be changing the callers of non-normal
738 hooks so that they can handle localness; this has to be done one by
739 one.
741 This function does nothing if HOOK is already local in the current
742 buffer.
744 Do not use `make-local-variable' to make a hook variable buffer-local."
745 (if (local-variable-p hook)
747 (or (boundp hook) (set hook nil))
748 (make-local-variable hook)
749 (set hook (list t)))
750 hook)
751 (make-obsolete 'make-local-hook "Not necessary any more." "21.1")
753 (defun add-hook (hook function &optional append local)
754 "Add to the value of HOOK the function FUNCTION.
755 FUNCTION is not added if already present.
756 FUNCTION is added (if necessary) at the beginning of the hook list
757 unless the optional argument APPEND is non-nil, in which case
758 FUNCTION is added at the end.
760 The optional fourth argument, LOCAL, if non-nil, says to modify
761 the hook's buffer-local value rather than its default value.
762 This makes the hook buffer-local if needed, and it makes t a member
763 of the buffer-local value. That acts as a flag to run the hook
764 functions in the default value as well as in the local value.
766 HOOK should be a symbol, and FUNCTION may be any valid function. If
767 HOOK is void, it is first set to nil. If HOOK's value is a single
768 function, it is changed to a list of functions."
769 (or (boundp hook) (set hook nil))
770 (or (default-boundp hook) (set-default hook nil))
771 (if local (unless (local-variable-if-set-p hook)
772 (set (make-local-variable hook) (list t)))
773 ;; Detect the case where make-local-variable was used on a hook
774 ;; and do what we used to do.
775 (unless (and (consp (symbol-value hook)) (memq t (symbol-value hook)))
776 (setq local t)))
777 (let ((hook-value (if local (symbol-value hook) (default-value hook))))
778 ;; If the hook value is a single function, turn it into a list.
779 (when (or (not (listp hook-value)) (eq (car hook-value) 'lambda))
780 (setq hook-value (list hook-value)))
781 ;; Do the actual addition if necessary
782 (unless (member function hook-value)
783 (setq hook-value
784 (if append
785 (append hook-value (list function))
786 (cons function hook-value))))
787 ;; Set the actual variable
788 (if local (set hook hook-value) (set-default hook hook-value))))
790 (defun remove-hook (hook function &optional local)
791 "Remove from the value of HOOK the function FUNCTION.
792 HOOK should be a symbol, and FUNCTION may be any valid function. If
793 FUNCTION isn't the value of HOOK, or, if FUNCTION doesn't appear in the
794 list of hooks to run in HOOK, then nothing is done. See `add-hook'.
796 The optional third argument, LOCAL, if non-nil, says to modify
797 the hook's buffer-local value rather than its default value.
798 This makes the hook buffer-local if needed."
799 (or (boundp hook) (set hook nil))
800 (or (default-boundp hook) (set-default hook nil))
801 (if local (unless (local-variable-if-set-p hook)
802 (set (make-local-variable hook) (list t)))
803 ;; Detect the case where make-local-variable was used on a hook
804 ;; and do what we used to do.
805 (unless (and (consp (symbol-value hook)) (memq t (symbol-value hook)))
806 (setq local t)))
807 (let ((hook-value (if local (symbol-value hook) (default-value hook))))
808 ;; Remove the function, for both the list and the non-list cases.
809 (if (or (not (listp hook-value)) (eq (car hook-value) 'lambda))
810 (if (equal hook-value function) (setq hook-value nil))
811 (setq hook-value (delete function (copy-sequence hook-value))))
812 ;; If the function is on the global hook, we need to shadow it locally
813 ;;(when (and local (member function (default-value hook))
814 ;; (not (member (cons 'not function) hook-value)))
815 ;; (push (cons 'not function) hook-value))
816 ;; Set the actual variable
817 (if (not local)
818 (set-default hook hook-value)
819 (if (equal hook-value '(t))
820 (kill-local-variable hook)
821 (set hook hook-value)))))
823 (defun add-to-list (list-var element &optional append)
824 "Add to the value of LIST-VAR the element ELEMENT if it isn't there yet.
825 The test for presence of ELEMENT is done with `equal'.
826 If ELEMENT is added, it is added at the beginning of the list,
827 unless the optional argument APPEND is non-nil, in which case
828 ELEMENT is added at the end.
830 The return value is the new value of LIST-VAR.
832 If you want to use `add-to-list' on a variable that is not defined
833 until a certain package is loaded, you should put the call to `add-to-list'
834 into a hook function that will be run only after loading the package.
835 `eval-after-load' provides one way to do this. In some cases
836 other hooks, such as major mode hooks, can do the job."
837 (if (member element (symbol-value list-var))
838 (symbol-value list-var)
839 (set list-var
840 (if append
841 (append (symbol-value list-var) (list element))
842 (cons element (symbol-value list-var))))))
845 ;;; Load history
847 (defvar symbol-file-load-history-loaded nil
848 "Non-nil means we have loaded the file `fns-VERSION.el' in `exec-directory'.
849 That file records the part of `load-history' for preloaded files,
850 which is cleared out before dumping to make Emacs smaller.")
852 (defun load-symbol-file-load-history ()
853 "Load the file `fns-VERSION.el' in `exec-directory' if not already done.
854 That file records the part of `load-history' for preloaded files,
855 which is cleared out before dumping to make Emacs smaller."
856 (unless symbol-file-load-history-loaded
857 (load (expand-file-name
858 ;; fns-XX.YY.ZZ.el does not work on DOS filesystem.
859 (if (eq system-type 'ms-dos)
860 "fns.el"
861 (format "fns-%s.el" emacs-version))
862 exec-directory)
863 ;; The file name fns-%s.el already has a .el extension.
864 nil nil t)
865 (setq symbol-file-load-history-loaded t)))
867 (defun symbol-file (function)
868 "Return the input source from which FUNCTION was loaded.
869 The value is normally a string that was passed to `load':
870 either an absolute file name, or a library name
871 \(with no directory name and no `.el' or `.elc' at the end).
872 It can also be nil, if the definition is not associated with any file."
873 (load-symbol-file-load-history)
874 (let ((files load-history)
875 file functions)
876 (while files
877 (if (memq function (cdr (car files)))
878 (setq file (car (car files)) files nil))
879 (setq files (cdr files)))
880 file))
883 ;;;; Specifying things to do after certain files are loaded.
885 (defun eval-after-load (file form)
886 "Arrange that, if FILE is ever loaded, FORM will be run at that time.
887 This makes or adds to an entry on `after-load-alist'.
888 If FILE is already loaded, evaluate FORM right now.
889 It does nothing if FORM is already on the list for FILE.
890 FILE must match exactly. Normally FILE is the name of a library,
891 with no directory or extension specified, since that is how `load'
892 is normally called.
893 FILE can also be a feature (i.e. a symbol), in which case FORM is
894 evaluated whenever that feature is `provide'd."
895 (let ((elt (assoc file after-load-alist)))
896 ;; Make sure there is an element for FILE.
897 (unless elt (setq elt (list file)) (push elt after-load-alist))
898 ;; Add FORM to the element if it isn't there.
899 (unless (member form (cdr elt))
900 (nconc elt (list form))
901 ;; If the file has been loaded already, run FORM right away.
902 (if (if (symbolp file)
903 (featurep file)
904 ;; Make sure `load-history' contains the files dumped with
905 ;; Emacs for the case that FILE is one of them.
906 (load-symbol-file-load-history)
907 (assoc file load-history))
908 (eval form))))
909 form)
911 (defun eval-next-after-load (file)
912 "Read the following input sexp, and run it whenever FILE is loaded.
913 This makes or adds to an entry on `after-load-alist'.
914 FILE should be the name of a library, with no directory name."
915 (eval-after-load file (read)))
918 ;;;; Input and display facilities.
920 (defvar read-quoted-char-radix 8
921 "*Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
922 Legitimate radix values are 8, 10 and 16.")
924 (custom-declare-variable-early
925 'read-quoted-char-radix 8
926 "*Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
927 Legitimate radix values are 8, 10 and 16."
928 :type '(choice (const 8) (const 10) (const 16))
929 :group 'editing-basics)
931 (defun read-quoted-char (&optional prompt)
932 "Like `read-char', but do not allow quitting.
933 Also, if the first character read is an octal digit,
934 we read any number of octal digits and return the
935 specified character code. Any nondigit terminates the sequence.
936 If the terminator is RET, it is discarded;
937 any other terminator is used itself as input.
939 The optional argument PROMPT specifies a string to use to prompt the user.
940 The variable `read-quoted-char-radix' controls which radix to use
941 for numeric input."
942 (let ((message-log-max nil) done (first t) (code 0) char)
943 (while (not done)
944 (let ((inhibit-quit first)
945 ;; Don't let C-h get the help message--only help function keys.
946 (help-char nil)
947 (help-form
948 "Type the special character you want to use,
949 or the octal character code.
950 RET terminates the character code and is discarded;
951 any other non-digit terminates the character code and is then used as input."))
952 (setq char (read-event (and prompt (format "%s-" prompt)) t))
953 (if inhibit-quit (setq quit-flag nil)))
954 ;; Translate TAB key into control-I ASCII character, and so on.
955 (and char
956 (let ((translated (lookup-key function-key-map (vector char))))
957 (if (arrayp translated)
958 (setq char (aref translated 0)))))
959 (cond ((null char))
960 ((not (integerp char))
961 (setq unread-command-events (list char)
962 done t))
963 ((/= (logand char ?\M-\^@) 0)
964 ;; Turn a meta-character into a character with the 0200 bit set.
965 (setq code (logior (logand char (lognot ?\M-\^@)) 128)
966 done t))
967 ((and (<= ?0 char) (< char (+ ?0 (min 10 read-quoted-char-radix))))
968 (setq code (+ (* code read-quoted-char-radix) (- char ?0)))
969 (and prompt (setq prompt (message "%s %c" prompt char))))
970 ((and (<= ?a (downcase char))
971 (< (downcase char) (+ ?a -10 (min 26 read-quoted-char-radix))))
972 (setq code (+ (* code read-quoted-char-radix)
973 (+ 10 (- (downcase char) ?a))))
974 (and prompt (setq prompt (message "%s %c" prompt char))))
975 ((and (not first) (eq char ?\C-m))
976 (setq done t))
977 ((not first)
978 (setq unread-command-events (list char)
979 done t))
980 (t (setq code char
981 done t)))
982 (setq first nil))
983 code))
985 (defun read-passwd (prompt &optional confirm default)
986 "Read a password, prompting with PROMPT. Echo `.' for each character typed.
987 End with RET, LFD, or ESC. DEL or C-h rubs out. C-u kills line.
988 Optional argument CONFIRM, if non-nil, then read it twice to make sure.
989 Optional DEFAULT is a default password to use instead of empty input."
990 (if confirm
991 (let (success)
992 (while (not success)
993 (let ((first (read-passwd prompt nil default))
994 (second (read-passwd "Confirm password: " nil default)))
995 (if (equal first second)
996 (progn
997 (and (arrayp second) (fillarray second ?\0))
998 (setq success first))
999 (and (arrayp first) (fillarray first ?\0))
1000 (and (arrayp second) (fillarray second ?\0))
1001 (message "Password not repeated accurately; please start over")
1002 (sit-for 1))))
1003 success)
1004 (let ((pass nil)
1005 (c 0)
1006 (echo-keystrokes 0)
1007 (cursor-in-echo-area t))
1008 (while (progn (message "%s%s"
1009 prompt
1010 (make-string (length pass) ?.))
1011 (setq c (read-char-exclusive nil t))
1012 (and (/= c ?\r) (/= c ?\n) (/= c ?\e)))
1013 (clear-this-command-keys)
1014 (if (= c ?\C-u)
1015 (progn
1016 (and (arrayp pass) (fillarray pass ?\0))
1017 (setq pass ""))
1018 (if (and (/= c ?\b) (/= c ?\177))
1019 (let* ((new-char (char-to-string c))
1020 (new-pass (concat pass new-char)))
1021 (and (arrayp pass) (fillarray pass ?\0))
1022 (fillarray new-char ?\0)
1023 (setq c ?\0)
1024 (setq pass new-pass))
1025 (if (> (length pass) 0)
1026 (let ((new-pass (substring pass 0 -1)))
1027 (and (arrayp pass) (fillarray pass ?\0))
1028 (setq pass new-pass))))))
1029 (message nil)
1030 (or pass default ""))))
1032 ;;; Atomic change groups.
1034 (defmacro atomic-change-group (&rest body)
1035 "Perform BODY as an atomic change group.
1036 This means that if BODY exits abnormally,
1037 all of its changes to the current buffer are undone.
1038 This works regadless of whether undo is enabled in the buffer.
1040 This mechanism is transparent to ordinary use of undo;
1041 if undo is enabled in the buffer and BODY succeeds, the
1042 user can undo the change normally."
1043 (let ((handle (make-symbol "--change-group-handle--"))
1044 (success (make-symbol "--change-group-success--")))
1045 `(let ((,handle (prepare-change-group))
1046 (,success nil))
1047 (unwind-protect
1048 (progn
1049 ;; This is inside the unwind-protect because
1050 ;; it enables undo if that was disabled; we need
1051 ;; to make sure that it gets disabled again.
1052 (activate-change-group ,handle)
1053 ,@body
1054 (setq ,success t))
1055 ;; Either of these functions will disable undo
1056 ;; if it was disabled before.
1057 (if ,success
1058 (accept-change-group ,handle)
1059 (cancel-change-group ,handle))))))
1061 (defun prepare-change-group (&optional buffer)
1062 "Return a handle for the current buffer's state, for a change group.
1063 If you specify BUFFER, make a handle for BUFFER's state instead.
1065 Pass the handle to `activate-change-group' afterward to initiate
1066 the actual changes of the change group.
1068 To finish the change group, call either `accept-change-group' or
1069 `cancel-change-group' passing the same handle as argument. Call
1070 `accept-change-group' to accept the changes in the group as final;
1071 call `cancel-change-group' to undo them all. You should use
1072 `unwind-protect' to make sure the group is always finished. The call
1073 to `activate-change-group' should be inside the `unwind-protect'.
1074 Once you finish the group, don't use the handle again--don't try to
1075 finish the same group twice. For a simple example of correct use, see
1076 the source code of `atomic-change-group'.
1078 The handle records only the specified buffer. To make a multibuffer
1079 change group, call this function once for each buffer you want to
1080 cover, then use `nconc' to combine the returned values, like this:
1082 (nconc (prepare-change-group buffer-1)
1083 (prepare-change-group buffer-2))
1085 You can then activate that multibuffer change group with a single
1086 call to `activate-change-group' and finish it with a single call
1087 to `accept-change-group' or `cancel-change-group'."
1089 (list (cons (current-buffer) buffer-undo-list)))
1091 (defun activate-change-group (handle)
1092 "Activate a change group made with `prepare-change-group' (which see)."
1093 (dolist (elt handle)
1094 (with-current-buffer (car elt)
1095 (if (eq buffer-undo-list t)
1096 (setq buffer-undo-list nil)))))
1098 (defun accept-change-group (handle)
1099 "Finish a change group made with `prepare-change-group' (which see).
1100 This finishes the change group by accepting its changes as final."
1101 (dolist (elt handle)
1102 (with-current-buffer (car elt)
1103 (if (eq elt t)
1104 (setq buffer-undo-list t)))))
1106 (defun cancel-change-group (handle)
1107 "Finish a change group made with `prepare-change-group' (which see).
1108 This finishes the change group by reverting all of its changes."
1109 (dolist (elt handle)
1110 (with-current-buffer (car elt)
1111 (setq elt (cdr elt))
1112 (let ((old-car
1113 (if (consp elt) (car elt)))
1114 (old-cdr
1115 (if (consp elt) (cdr elt))))
1116 ;; Temporarily truncate the undo log at ELT.
1117 (when (consp elt)
1118 (setcar elt nil) (setcdr elt nil))
1119 (unless (eq last-command 'undo) (undo-start))
1120 ;; Make sure there's no confusion.
1121 (when (and (consp elt) (not (eq elt (last pending-undo-list))))
1122 (error "Undoing to some unrelated state"))
1123 ;; Undo it all.
1124 (while pending-undo-list (undo-more 1))
1125 ;; Reset the modified cons cell ELT to its original content.
1126 (when (consp elt)
1127 (setcar elt old-car)
1128 (setcdr elt old-cdr))
1129 ;; Revert the undo info to what it was when we grabbed the state.
1130 (setq buffer-undo-list elt)))))
1132 ;; For compatibility.
1133 (defalias 'redraw-modeline 'force-mode-line-update)
1135 (defun force-mode-line-update (&optional all)
1136 "Force the mode line of the current buffer to be redisplayed.
1137 With optional non-nil ALL, force redisplay of all mode lines."
1138 (if all (save-excursion (set-buffer (other-buffer))))
1139 (set-buffer-modified-p (buffer-modified-p)))
1141 (defun momentary-string-display (string pos &optional exit-char message)
1142 "Momentarily display STRING in the buffer at POS.
1143 Display remains until next character is typed.
1144 If the char is EXIT-CHAR (optional third arg, default is SPC) it is swallowed;
1145 otherwise it is then available as input (as a command if nothing else).
1146 Display MESSAGE (optional fourth arg) in the echo area.
1147 If MESSAGE is nil, instructions to type EXIT-CHAR are displayed there."
1148 (or exit-char (setq exit-char ?\ ))
1149 (let ((inhibit-read-only t)
1150 ;; Don't modify the undo list at all.
1151 (buffer-undo-list t)
1152 (modified (buffer-modified-p))
1153 (name buffer-file-name)
1154 insert-end)
1155 (unwind-protect
1156 (progn
1157 (save-excursion
1158 (goto-char pos)
1159 ;; defeat file locking... don't try this at home, kids!
1160 (setq buffer-file-name nil)
1161 (insert-before-markers string)
1162 (setq insert-end (point))
1163 ;; If the message end is off screen, recenter now.
1164 (if (< (window-end nil t) insert-end)
1165 (recenter (/ (window-height) 2)))
1166 ;; If that pushed message start off the screen,
1167 ;; scroll to start it at the top of the screen.
1168 (move-to-window-line 0)
1169 (if (> (point) pos)
1170 (progn
1171 (goto-char pos)
1172 (recenter 0))))
1173 (message (or message "Type %s to continue editing.")
1174 (single-key-description exit-char))
1175 (let ((char (read-event)))
1176 (or (eq char exit-char)
1177 (setq unread-command-events (list char)))))
1178 (if insert-end
1179 (save-excursion
1180 (delete-region pos insert-end)))
1181 (setq buffer-file-name name)
1182 (set-buffer-modified-p modified))))
1185 ;;;; Overlay operations
1187 (defun copy-overlay (o)
1188 "Return a copy of overlay O."
1189 (let ((o1 (make-overlay (overlay-start o) (overlay-end o)
1190 ;; FIXME: there's no easy way to find the
1191 ;; insertion-type of the two markers.
1192 (overlay-buffer o)))
1193 (props (overlay-properties o)))
1194 (while props
1195 (overlay-put o1 (pop props) (pop props)))
1196 o1))
1198 (defun remove-overlays (beg end name val)
1199 "Clear BEG and END of overlays whose property NAME has value VAL.
1200 Overlays might be moved and or split."
1201 (if (< end beg)
1202 (setq beg (prog1 end (setq end beg))))
1203 (save-excursion
1204 (dolist (o (overlays-in beg end))
1205 (when (eq (overlay-get o name) val)
1206 ;; Either push this overlay outside beg...end
1207 ;; or split it to exclude beg...end
1208 ;; or delete it entirely (if it is contained in beg...end).
1209 (if (< (overlay-start o) beg)
1210 (if (> (overlay-end o) end)
1211 (progn
1212 (move-overlay (copy-overlay o)
1213 (overlay-start o) beg)
1214 (move-overlay o end (overlay-end o)))
1215 (move-overlay o (overlay-start o) beg))
1216 (if (> (overlay-end o) end)
1217 (move-overlay o end (overlay-end o))
1218 (delete-overlay o)))))))
1220 ;;;; Miscellanea.
1222 ;; A number of major modes set this locally.
1223 ;; Give it a global value to avoid compiler warnings.
1224 (defvar font-lock-defaults nil)
1226 (defvar suspend-hook nil
1227 "Normal hook run by `suspend-emacs', before suspending.")
1229 (defvar suspend-resume-hook nil
1230 "Normal hook run by `suspend-emacs', after Emacs is continued.")
1232 (defvar temp-buffer-show-hook nil
1233 "Normal hook run by `with-output-to-temp-buffer' after displaying the buffer.
1234 When the hook runs, the temporary buffer is current, and the window it
1235 was displayed in is selected. This hook is normally set up with a
1236 function to make the buffer read only, and find function names and
1237 variable names in it, provided the major mode is still Help mode.")
1239 (defvar temp-buffer-setup-hook nil
1240 "Normal hook run by `with-output-to-temp-buffer' at the start.
1241 When the hook runs, the temporary buffer is current.
1242 This hook is normally set up with a function to put the buffer in Help
1243 mode.")
1245 ;; Avoid compiler warnings about this variable,
1246 ;; which has a special meaning on certain system types.
1247 (defvar buffer-file-type nil
1248 "Non-nil if the visited file is a binary file.
1249 This variable is meaningful on MS-DOG and Windows NT.
1250 On those systems, it is automatically local in every buffer.
1251 On other systems, this variable is normally always nil.")
1253 ;; This should probably be written in C (i.e., without using `walk-windows').
1254 (defun get-buffer-window-list (buffer &optional minibuf frame)
1255 "Return windows currently displaying BUFFER, or nil if none.
1256 See `walk-windows' for the meaning of MINIBUF and FRAME."
1257 (let ((buffer (if (bufferp buffer) buffer (get-buffer buffer))) windows)
1258 (walk-windows (function (lambda (window)
1259 (if (eq (window-buffer window) buffer)
1260 (setq windows (cons window windows)))))
1261 minibuf frame)
1262 windows))
1264 (defun ignore (&rest ignore)
1265 "Do nothing and return nil.
1266 This function accepts any number of arguments, but ignores them."
1267 (interactive)
1268 nil)
1270 (defun error (&rest args)
1271 "Signal an error, making error message by passing all args to `format'.
1272 In Emacs, the convention is that error messages start with a capital
1273 letter but *do not* end with a period. Please follow this convention
1274 for the sake of consistency."
1275 (while t
1276 (signal 'error (list (apply 'format args)))))
1278 (defalias 'user-original-login-name 'user-login-name)
1280 (defvar yank-excluded-properties)
1282 (defun remove-yank-excluded-properties (start end)
1283 "Remove `yank-excluded-properties' between START and END positions.
1284 Replaces `category' properties with their defined properties."
1285 (let ((inhibit-read-only t))
1286 ;; Replace any `category' property with the properties it stands for.
1287 (unless (memq yank-excluded-properties '(t nil))
1288 (save-excursion
1289 (goto-char start)
1290 (while (< (point) end)
1291 (let ((cat (get-text-property (point) 'category))
1292 run-end)
1293 (when cat
1294 (setq run-end
1295 (next-single-property-change (point) 'category nil end))
1296 (remove-list-of-text-properties (point) run-end '(category))
1297 (add-text-properties (point) run-end (symbol-plist cat))
1298 (goto-char (or run-end end)))
1299 (setq run-end
1300 (next-single-property-change (point) 'category nil end))
1301 (goto-char (or run-end end))))))
1302 (if (eq yank-excluded-properties t)
1303 (set-text-properties start end nil)
1304 (remove-list-of-text-properties start end
1305 yank-excluded-properties))))
1307 (defun insert-for-yank (&rest strings)
1308 "Insert STRINGS at point, stripping some text properties.
1309 Strip text properties from the inserted text
1310 according to `yank-excluded-properties'.
1311 Otherwise just like (insert STRINGS...)."
1312 (let ((opoint (point)))
1313 (apply 'insert strings)
1314 (remove-yank-excluded-properties opoint (point))))
1316 (defun insert-buffer-substring-no-properties (buf &optional start end)
1317 "Insert before point a substring of buffer BUFFER, without text properties.
1318 BUFFER may be a buffer or a buffer name.
1319 Arguments START and END are character numbers specifying the substring.
1320 They default to the beginning and the end of BUFFER."
1321 (let ((opoint (point)))
1322 (insert-buffer-substring buf start end)
1323 (let ((inhibit-read-only t))
1324 (set-text-properties opoint (point) nil))))
1326 (defun insert-buffer-substring-as-yank (buf &optional start end)
1327 "Insert before point a part of buffer BUFFER, stripping some text properties.
1328 BUFFER may be a buffer or a buffer name. Arguments START and END are
1329 character numbers specifying the substring. They default to the
1330 beginning and the end of BUFFER. Strip text properties from the
1331 inserted text according to `yank-excluded-properties'."
1332 (let ((opoint (point)))
1333 (insert-buffer-substring buf start end)
1334 (remove-yank-excluded-properties opoint (point))))
1337 ;; Synchronous shell commands.
1339 (defun start-process-shell-command (name buffer &rest args)
1340 "Start a program in a subprocess. Return the process object for it.
1341 Args are NAME BUFFER COMMAND &rest COMMAND-ARGS.
1342 NAME is name for process. It is modified if necessary to make it unique.
1343 BUFFER is the buffer or (buffer-name) to associate with the process.
1344 Process output goes at end of that buffer, unless you specify
1345 an output stream or filter function to handle the output.
1346 BUFFER may be also nil, meaning that this process is not associated
1347 with any buffer
1348 Third arg is command name, the name of a shell command.
1349 Remaining arguments are the arguments for the command.
1350 Wildcards and redirection are handled as usual in the shell."
1351 (cond
1352 ((eq system-type 'vax-vms)
1353 (apply 'start-process name buffer args))
1354 ;; We used to use `exec' to replace the shell with the command,
1355 ;; but that failed to handle (...) and semicolon, etc.
1357 (start-process name buffer shell-file-name shell-command-switch
1358 (mapconcat 'identity args " ")))))
1360 (defun call-process-shell-command (command &optional infile buffer display
1361 &rest args)
1362 "Execute the shell command COMMAND synchronously in separate process.
1363 The remaining arguments are optional.
1364 The program's input comes from file INFILE (nil means `/dev/null').
1365 Insert output in BUFFER before point; t means current buffer;
1366 nil for BUFFER means discard it; 0 means discard and don't wait.
1367 BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,
1368 REAL-BUFFER says what to do with standard output, as above,
1369 while STDERR-FILE says what to do with standard error in the child.
1370 STDERR-FILE may be nil (discard standard error output),
1371 t (mix it with ordinary output), or a file name string.
1373 Fourth arg DISPLAY non-nil means redisplay buffer as output is inserted.
1374 Remaining arguments are strings passed as additional arguments for COMMAND.
1375 Wildcards and redirection are handled as usual in the shell.
1377 If BUFFER is 0, `call-process-shell-command' returns immediately with value nil.
1378 Otherwise it waits for COMMAND to terminate and returns a numeric exit
1379 status or a signal description string.
1380 If you quit, the process is killed with SIGINT, or SIGKILL if you quit again."
1381 (cond
1382 ((eq system-type 'vax-vms)
1383 (apply 'call-process command infile buffer display args))
1384 ;; We used to use `exec' to replace the shell with the command,
1385 ;; but that failed to handle (...) and semicolon, etc.
1387 (call-process shell-file-name
1388 infile buffer display
1389 shell-command-switch
1390 (mapconcat 'identity (cons command args) " ")))))
1392 (defmacro with-current-buffer (buffer &rest body)
1393 "Execute the forms in BODY with BUFFER as the current buffer.
1394 The value returned is the value of the last form in BODY.
1395 See also `with-temp-buffer'."
1396 (cons 'save-current-buffer
1397 (cons (list 'set-buffer buffer)
1398 body)))
1400 (defmacro with-temp-file (file &rest body)
1401 "Create a new buffer, evaluate BODY there, and write the buffer to FILE.
1402 The value returned is the value of the last form in BODY.
1403 See also `with-temp-buffer'."
1404 (let ((temp-file (make-symbol "temp-file"))
1405 (temp-buffer (make-symbol "temp-buffer")))
1406 `(let ((,temp-file ,file)
1407 (,temp-buffer
1408 (get-buffer-create (generate-new-buffer-name " *temp file*"))))
1409 (unwind-protect
1410 (prog1
1411 (with-current-buffer ,temp-buffer
1412 ,@body)
1413 (with-current-buffer ,temp-buffer
1414 (widen)
1415 (write-region (point-min) (point-max) ,temp-file nil 0)))
1416 (and (buffer-name ,temp-buffer)
1417 (kill-buffer ,temp-buffer))))))
1419 (defmacro with-temp-message (message &rest body)
1420 "Display MESSAGE temporarily if non-nil while BODY is evaluated.
1421 The original message is restored to the echo area after BODY has finished.
1422 The value returned is the value of the last form in BODY.
1423 MESSAGE is written to the message log buffer if `message-log-max' is non-nil.
1424 If MESSAGE is nil, the echo area and message log buffer are unchanged.
1425 Use a MESSAGE of \"\" to temporarily clear the echo area."
1426 (let ((current-message (make-symbol "current-message"))
1427 (temp-message (make-symbol "with-temp-message")))
1428 `(let ((,temp-message ,message)
1429 (,current-message))
1430 (unwind-protect
1431 (progn
1432 (when ,temp-message
1433 (setq ,current-message (current-message))
1434 (message "%s" ,temp-message))
1435 ,@body)
1436 (and ,temp-message
1437 (if ,current-message
1438 (message "%s" ,current-message)
1439 (message nil)))))))
1441 (defmacro with-temp-buffer (&rest body)
1442 "Create a temporary buffer, and evaluate BODY there like `progn'.
1443 See also `with-temp-file' and `with-output-to-string'."
1444 (let ((temp-buffer (make-symbol "temp-buffer")))
1445 `(let ((,temp-buffer
1446 (get-buffer-create (generate-new-buffer-name " *temp*"))))
1447 (unwind-protect
1448 (with-current-buffer ,temp-buffer
1449 ,@body)
1450 (and (buffer-name ,temp-buffer)
1451 (kill-buffer ,temp-buffer))))))
1453 (defmacro with-output-to-string (&rest body)
1454 "Execute BODY, return the text it sent to `standard-output', as a string."
1455 `(let ((standard-output
1456 (get-buffer-create (generate-new-buffer-name " *string-output*"))))
1457 (let ((standard-output standard-output))
1458 ,@body)
1459 (with-current-buffer standard-output
1460 (prog1
1461 (buffer-string)
1462 (kill-buffer nil)))))
1464 (defmacro with-local-quit (&rest body)
1465 "Execute BODY with `inhibit-quit' temporarily bound to nil."
1466 `(condition-case nil
1467 (let ((inhibit-quit nil))
1468 ,@body)
1469 (quit (setq quit-flag t))))
1471 (defmacro combine-after-change-calls (&rest body)
1472 "Execute BODY, but don't call the after-change functions till the end.
1473 If BODY makes changes in the buffer, they are recorded
1474 and the functions on `after-change-functions' are called several times
1475 when BODY is finished.
1476 The return value is the value of the last form in BODY.
1478 If `before-change-functions' is non-nil, then calls to the after-change
1479 functions can't be deferred, so in that case this macro has no effect.
1481 Do not alter `after-change-functions' or `before-change-functions'
1482 in BODY."
1483 `(unwind-protect
1484 (let ((combine-after-change-calls t))
1485 . ,body)
1486 (combine-after-change-execute)))
1489 (defvar delay-mode-hooks nil
1490 "If non-nil, `run-mode-hooks' should delay running the hooks.")
1491 (defvar delayed-mode-hooks nil
1492 "List of delayed mode hooks waiting to be run.")
1493 (make-variable-buffer-local 'delayed-mode-hooks)
1495 (defun run-mode-hooks (&rest hooks)
1496 "Run mode hooks `delayed-mode-hooks' and HOOKS, or delay HOOKS.
1497 Execution is delayed if `delay-mode-hooks' is non-nil.
1498 Major mode functions should use this."
1499 (if delay-mode-hooks
1500 ;; Delaying case.
1501 (dolist (hook hooks)
1502 (push hook delayed-mode-hooks))
1503 ;; Normal case, just run the hook as before plus any delayed hooks.
1504 (setq hooks (nconc (nreverse delayed-mode-hooks) hooks))
1505 (setq delayed-mode-hooks nil)
1506 (apply 'run-hooks hooks)))
1508 (defmacro delay-mode-hooks (&rest body)
1509 "Execute BODY, but delay any `run-mode-hooks'.
1510 Only affects hooks run in the current buffer."
1511 `(progn
1512 (make-local-variable 'delay-mode-hooks)
1513 (let ((delay-mode-hooks t))
1514 ,@body)))
1516 ;; PUBLIC: find if the current mode derives from another.
1518 (defun derived-mode-p (&rest modes)
1519 "Non-nil if the current major mode is derived from one of MODES.
1520 Uses the `derived-mode-parent' property of the symbol to trace backwards."
1521 (let ((parent major-mode))
1522 (while (and (not (memq parent modes))
1523 (setq parent (get parent 'derived-mode-parent))))
1524 parent))
1526 (defmacro with-syntax-table (table &rest body)
1527 "Evaluate BODY with syntax table of current buffer set to a copy of TABLE.
1528 The syntax table of the current buffer is saved, BODY is evaluated, and the
1529 saved table is restored, even in case of an abnormal exit.
1530 Value is what BODY returns."
1531 (let ((old-table (make-symbol "table"))
1532 (old-buffer (make-symbol "buffer")))
1533 `(let ((,old-table (syntax-table))
1534 (,old-buffer (current-buffer)))
1535 (unwind-protect
1536 (progn
1537 (set-syntax-table (copy-syntax-table ,table))
1538 ,@body)
1539 (save-current-buffer
1540 (set-buffer ,old-buffer)
1541 (set-syntax-table ,old-table))))))
1543 ;;; Matching and substitution
1545 (defvar save-match-data-internal)
1547 ;; We use save-match-data-internal as the local variable because
1548 ;; that works ok in practice (people should not use that variable elsewhere).
1549 ;; We used to use an uninterned symbol; the compiler handles that properly
1550 ;; now, but it generates slower code.
1551 (defmacro save-match-data (&rest body)
1552 "Execute the BODY forms, restoring the global value of the match data.
1553 The value returned is the value of the last form in BODY."
1554 ;; It is better not to use backquote here,
1555 ;; because that makes a bootstrapping problem
1556 ;; if you need to recompile all the Lisp files using interpreted code.
1557 (list 'let
1558 '((save-match-data-internal (match-data)))
1559 (list 'unwind-protect
1560 (cons 'progn body)
1561 '(set-match-data save-match-data-internal))))
1563 (defun match-string (num &optional string)
1564 "Return string of text matched by last search.
1565 NUM specifies which parenthesized expression in the last regexp.
1566 Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
1567 Zero means the entire text matched by the whole regexp or whole string.
1568 STRING should be given if the last search was by `string-match' on STRING."
1569 (if (match-beginning num)
1570 (if string
1571 (substring string (match-beginning num) (match-end num))
1572 (buffer-substring (match-beginning num) (match-end num)))))
1574 (defun match-string-no-properties (num &optional string)
1575 "Return string of text matched by last search, without text properties.
1576 NUM specifies which parenthesized expression in the last regexp.
1577 Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
1578 Zero means the entire text matched by the whole regexp or whole string.
1579 STRING should be given if the last search was by `string-match' on STRING."
1580 (if (match-beginning num)
1581 (if string
1582 (let ((result
1583 (substring string (match-beginning num) (match-end num))))
1584 (set-text-properties 0 (length result) nil result)
1585 result)
1586 (buffer-substring-no-properties (match-beginning num)
1587 (match-end num)))))
1589 (defun split-string (string &optional separators)
1590 "Splits STRING into substrings where there are matches for SEPARATORS.
1591 Each match for SEPARATORS is a splitting point.
1592 The substrings between the splitting points are made into a list
1593 which is returned.
1594 If SEPARATORS is absent, it defaults to \"[ \\f\\t\\n\\r\\v]+\".
1596 If there is match for SEPARATORS at the beginning of STRING, we do not
1597 include a null substring for that. Likewise, if there is a match
1598 at the end of STRING, we don't include a null substring for that.
1600 Modifies the match data; use `save-match-data' if necessary."
1601 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
1602 (start 0)
1603 notfirst
1604 (list nil))
1605 (while (and (string-match rexp string
1606 (if (and notfirst
1607 (= start (match-beginning 0))
1608 (< start (length string)))
1609 (1+ start) start))
1610 (< (match-beginning 0) (length string)))
1611 (setq notfirst t)
1612 (or (eq (match-beginning 0) 0)
1613 (and (eq (match-beginning 0) (match-end 0))
1614 (eq (match-beginning 0) start))
1615 (setq list
1616 (cons (substring string start (match-beginning 0))
1617 list)))
1618 (setq start (match-end 0)))
1619 (or (eq start (length string))
1620 (setq list
1621 (cons (substring string start)
1622 list)))
1623 (nreverse list)))
1625 (defun subst-char-in-string (fromchar tochar string &optional inplace)
1626 "Replace FROMCHAR with TOCHAR in STRING each time it occurs.
1627 Unless optional argument INPLACE is non-nil, return a new string."
1628 (let ((i (length string))
1629 (newstr (if inplace string (copy-sequence string))))
1630 (while (> i 0)
1631 (setq i (1- i))
1632 (if (eq (aref newstr i) fromchar)
1633 (aset newstr i tochar)))
1634 newstr))
1636 (defun replace-regexp-in-string (regexp rep string &optional
1637 fixedcase literal subexp start)
1638 "Replace all matches for REGEXP with REP in STRING.
1640 Return a new string containing the replacements.
1642 Optional arguments FIXEDCASE, LITERAL and SUBEXP are like the
1643 arguments with the same names of function `replace-match'. If START
1644 is non-nil, start replacements at that index in STRING.
1646 REP is either a string used as the NEWTEXT arg of `replace-match' or a
1647 function. If it is a function it is applied to each match to generate
1648 the replacement passed to `replace-match'; the match-data at this
1649 point are such that match 0 is the function's argument.
1651 To replace only the first match (if any), make REGEXP match up to \\'
1652 and replace a sub-expression, e.g.
1653 (replace-regexp-in-string \"\\(foo\\).*\\'\" \"bar\" \" foo foo\" nil nil 1)
1654 => \" bar foo\"
1657 ;; To avoid excessive consing from multiple matches in long strings,
1658 ;; don't just call `replace-match' continually. Walk down the
1659 ;; string looking for matches of REGEXP and building up a (reversed)
1660 ;; list MATCHES. This comprises segments of STRING which weren't
1661 ;; matched interspersed with replacements for segments that were.
1662 ;; [For a `large' number of replacements it's more efficient to
1663 ;; operate in a temporary buffer; we can't tell from the function's
1664 ;; args whether to choose the buffer-based implementation, though it
1665 ;; might be reasonable to do so for long enough STRING.]
1666 (let ((l (length string))
1667 (start (or start 0))
1668 matches str mb me)
1669 (save-match-data
1670 (while (and (< start l) (string-match regexp string start))
1671 (setq mb (match-beginning 0)
1672 me (match-end 0))
1673 ;; If we matched the empty string, make sure we advance by one char
1674 (when (= me mb) (setq me (min l (1+ mb))))
1675 ;; Generate a replacement for the matched substring.
1676 ;; Operate only on the substring to minimize string consing.
1677 ;; Set up match data for the substring for replacement;
1678 ;; presumably this is likely to be faster than munging the
1679 ;; match data directly in Lisp.
1680 (string-match regexp (setq str (substring string mb me)))
1681 (setq matches
1682 (cons (replace-match (if (stringp rep)
1684 (funcall rep (match-string 0 str)))
1685 fixedcase literal str subexp)
1686 (cons (substring string start mb) ; unmatched prefix
1687 matches)))
1688 (setq start me))
1689 ;; Reconstruct a string from the pieces.
1690 (setq matches (cons (substring string start l) matches)) ; leftover
1691 (apply #'concat (nreverse matches)))))
1693 (defun shell-quote-argument (argument)
1694 "Quote an argument for passing as argument to an inferior shell."
1695 (if (eq system-type 'ms-dos)
1696 ;; Quote using double quotes, but escape any existing quotes in
1697 ;; the argument with backslashes.
1698 (let ((result "")
1699 (start 0)
1700 end)
1701 (if (or (null (string-match "[^\"]" argument))
1702 (< (match-end 0) (length argument)))
1703 (while (string-match "[\"]" argument start)
1704 (setq end (match-beginning 0)
1705 result (concat result (substring argument start end)
1706 "\\" (substring argument end (1+ end)))
1707 start (1+ end))))
1708 (concat "\"" result (substring argument start) "\""))
1709 (if (eq system-type 'windows-nt)
1710 (concat "\"" argument "\"")
1711 (if (equal argument "")
1712 "''"
1713 ;; Quote everything except POSIX filename characters.
1714 ;; This should be safe enough even for really weird shells.
1715 (let ((result "") (start 0) end)
1716 (while (string-match "[^-0-9a-zA-Z_./]" argument start)
1717 (setq end (match-beginning 0)
1718 result (concat result (substring argument start end)
1719 "\\" (substring argument end (1+ end)))
1720 start (1+ end)))
1721 (concat result (substring argument start)))))))
1723 (defun make-syntax-table (&optional oldtable)
1724 "Return a new syntax table.
1725 Create a syntax table which inherits from OLDTABLE (if non-nil) or
1726 from `standard-syntax-table' otherwise."
1727 (let ((table (make-char-table 'syntax-table nil)))
1728 (set-char-table-parent table (or oldtable (standard-syntax-table)))
1729 table))
1731 (defun add-to-invisibility-spec (arg)
1732 "Add elements to `buffer-invisibility-spec'.
1733 See documentation for `buffer-invisibility-spec' for the kind of elements
1734 that can be added."
1735 (cond
1736 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
1737 (setq buffer-invisibility-spec (list arg)))
1739 (setq buffer-invisibility-spec
1740 (cons arg buffer-invisibility-spec)))))
1742 (defun remove-from-invisibility-spec (arg)
1743 "Remove elements from `buffer-invisibility-spec'."
1744 (if (consp buffer-invisibility-spec)
1745 (setq buffer-invisibility-spec (delete arg buffer-invisibility-spec))))
1747 (defun global-set-key (key command)
1748 "Give KEY a global binding as COMMAND.
1749 COMMAND is the command definition to use; usually it is
1750 a symbol naming an interactively-callable function.
1751 KEY is a key sequence; noninteractively, it is a string or vector
1752 of characters or event types, and non-ASCII characters with codes
1753 above 127 (such as ISO Latin-1) can be included if you use a vector.
1755 Note that if KEY has a local binding in the current buffer,
1756 that local binding will continue to shadow any global binding
1757 that you make with this function."
1758 (interactive "KSet key globally: \nCSet key %s to command: ")
1759 (or (vectorp key) (stringp key)
1760 (signal 'wrong-type-argument (list 'arrayp key)))
1761 (define-key (current-global-map) key command))
1763 (defun local-set-key (key command)
1764 "Give KEY a local binding as COMMAND.
1765 COMMAND is the command definition to use; usually it is
1766 a symbol naming an interactively-callable function.
1767 KEY is a key sequence; noninteractively, it is a string or vector
1768 of characters or event types, and non-ASCII characters with codes
1769 above 127 (such as ISO Latin-1) can be included if you use a vector.
1771 The binding goes in the current buffer's local map,
1772 which in most cases is shared with all other buffers in the same major mode."
1773 (interactive "KSet key locally: \nCSet key %s locally to command: ")
1774 (let ((map (current-local-map)))
1775 (or map
1776 (use-local-map (setq map (make-sparse-keymap))))
1777 (or (vectorp key) (stringp key)
1778 (signal 'wrong-type-argument (list 'arrayp key)))
1779 (define-key map key command)))
1781 (defun global-unset-key (key)
1782 "Remove global binding of KEY.
1783 KEY is a string representing a sequence of keystrokes."
1784 (interactive "kUnset key globally: ")
1785 (global-set-key key nil))
1787 (defun local-unset-key (key)
1788 "Remove local binding of KEY.
1789 KEY is a string representing a sequence of keystrokes."
1790 (interactive "kUnset key locally: ")
1791 (if (current-local-map)
1792 (local-set-key key nil))
1793 nil)
1795 ;; We put this here instead of in frame.el so that it's defined even on
1796 ;; systems where frame.el isn't loaded.
1797 (defun frame-configuration-p (object)
1798 "Return non-nil if OBJECT seems to be a frame configuration.
1799 Any list whose car is `frame-configuration' is assumed to be a frame
1800 configuration."
1801 (and (consp object)
1802 (eq (car object) 'frame-configuration)))
1804 (defun functionp (object)
1805 "Non-nil iff OBJECT is a type of object that can be called as a function."
1806 (or (and (symbolp object) (fboundp object)
1807 (condition-case nil
1808 (setq object (indirect-function object))
1809 (error nil))
1810 (eq (car-safe object) 'autoload)
1811 (not (car-safe (cdr-safe (cdr-safe (cdr-safe (cdr-safe object)))))))
1812 (subrp object) (byte-code-function-p object)
1813 (eq (car-safe object) 'lambda)))
1815 (defun interactive-form (function)
1816 "Return the interactive form of FUNCTION.
1817 If function is a command (see `commandp'), value is a list of the form
1818 \(interactive SPEC). If function is not a command, return nil."
1819 (setq function (indirect-function function))
1820 (when (commandp function)
1821 (cond ((byte-code-function-p function)
1822 (when (> (length function) 5)
1823 (let ((spec (aref function 5)))
1824 (if spec
1825 (list 'interactive spec)
1826 (list 'interactive)))))
1827 ((subrp function)
1828 (subr-interactive-form function))
1829 ((eq (car-safe function) 'lambda)
1830 (setq function (cddr function))
1831 (when (stringp (car function))
1832 (setq function (cdr function)))
1833 (let ((form (car function)))
1834 (when (eq (car-safe form) 'interactive)
1835 (copy-sequence form)))))))
1837 (defun assq-delete-all (key alist)
1838 "Delete from ALIST all elements whose car is KEY.
1839 Return the modified alist."
1840 (let ((tail alist))
1841 (while tail
1842 (if (eq (car (car tail)) key)
1843 (setq alist (delq (car tail) alist)))
1844 (setq tail (cdr tail)))
1845 alist))
1847 (defun make-temp-file (prefix &optional dir-flag suffix)
1848 "Create a temporary file.
1849 The returned file name (created by appending some random characters at the end
1850 of PREFIX, and expanding against `temporary-file-directory' if necessary,
1851 is guaranteed to point to a newly created empty file.
1852 You can then use `write-region' to write new data into the file.
1854 If DIR-FLAG is non-nil, create a new empty directory instead of a file.
1856 If SUFFIX is non-nil, add that at the end of the file name."
1857 (let (file)
1858 (while (condition-case ()
1859 (progn
1860 (setq file
1861 (make-temp-name
1862 (expand-file-name prefix temporary-file-directory)))
1863 (if suffix
1864 (setq file (concat file suffix)))
1865 (if dir-flag
1866 (make-directory file)
1867 (write-region "" nil file nil 'silent nil 'excl))
1868 nil)
1869 (file-already-exists t))
1870 ;; the file was somehow created by someone else between
1871 ;; `make-temp-name' and `write-region', let's try again.
1872 nil)
1873 file))
1876 (defun add-minor-mode (toggle name &optional keymap after toggle-fun)
1877 "Register a new minor mode.
1879 This is an XEmacs-compatibility function. Use `define-minor-mode' instead.
1881 TOGGLE is a symbol which is the name of a buffer-local variable that
1882 is toggled on or off to say whether the minor mode is active or not.
1884 NAME specifies what will appear in the mode line when the minor mode
1885 is active. NAME should be either a string starting with a space, or a
1886 symbol whose value is such a string.
1888 Optional KEYMAP is the keymap for the minor mode that will be added
1889 to `minor-mode-map-alist'.
1891 Optional AFTER specifies that TOGGLE should be added after AFTER
1892 in `minor-mode-alist'.
1894 Optional TOGGLE-FUN is an interactive function to toggle the mode.
1895 It defaults to (and should by convention be) TOGGLE.
1897 If TOGGLE has a non-nil `:included' property, an entry for the mode is
1898 included in the mode-line minor mode menu.
1899 If TOGGLE has a `:menu-tag', that is used for the menu item's label."
1900 (unless toggle-fun (setq toggle-fun toggle))
1901 ;; Add the name to the minor-mode-alist.
1902 (when name
1903 (let ((existing (assq toggle minor-mode-alist)))
1904 (when (and (stringp name) (not (get-text-property 0 'local-map name)))
1905 (setq name
1906 (propertize name
1907 'local-map mode-line-minor-mode-keymap
1908 'help-echo "mouse-3: minor mode menu")))
1909 (if existing
1910 (setcdr existing (list name))
1911 (let ((tail minor-mode-alist) found)
1912 (while (and tail (not found))
1913 (if (eq after (caar tail))
1914 (setq found tail)
1915 (setq tail (cdr tail))))
1916 (if found
1917 (let ((rest (cdr found)))
1918 (setcdr found nil)
1919 (nconc found (list (list toggle name)) rest))
1920 (setq minor-mode-alist (cons (list toggle name)
1921 minor-mode-alist)))))))
1922 ;; Add the toggle to the minor-modes menu if requested.
1923 (when (get toggle :included)
1924 (define-key mode-line-mode-menu
1925 (vector toggle)
1926 (list 'menu-item
1927 (concat
1928 (or (get toggle :menu-tag)
1929 (if (stringp name) name (symbol-name toggle)))
1930 (let ((mode-name (if (stringp name) name
1931 (if (symbolp name) (symbol-value name)))))
1932 (if mode-name
1933 (concat " (" mode-name ")"))))
1934 toggle-fun
1935 :button (cons :toggle toggle))))
1937 ;; Add the map to the minor-mode-map-alist.
1938 (when keymap
1939 (let ((existing (assq toggle minor-mode-map-alist)))
1940 (if existing
1941 (setcdr existing keymap)
1942 (let ((tail minor-mode-map-alist) found)
1943 (while (and tail (not found))
1944 (if (eq after (caar tail))
1945 (setq found tail)
1946 (setq tail (cdr tail))))
1947 (if found
1948 (let ((rest (cdr found)))
1949 (setcdr found nil)
1950 (nconc found (list (cons toggle keymap)) rest))
1951 (setq minor-mode-map-alist (cons (cons toggle keymap)
1952 minor-mode-map-alist))))))))
1954 ;; Clones ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1956 (defun text-clone-maintain (ol1 after beg end &optional len)
1957 "Propagate the changes made under the overlay OL1 to the other clones.
1958 This is used on the `modification-hooks' property of text clones."
1959 (when (and after (not undo-in-progress) (overlay-start ol1))
1960 (let ((margin (if (overlay-get ol1 'text-clone-spreadp) 1 0)))
1961 (setq beg (max beg (+ (overlay-start ol1) margin)))
1962 (setq end (min end (- (overlay-end ol1) margin)))
1963 (when (<= beg end)
1964 (save-excursion
1965 (when (overlay-get ol1 'text-clone-syntax)
1966 ;; Check content of the clone's text.
1967 (let ((cbeg (+ (overlay-start ol1) margin))
1968 (cend (- (overlay-end ol1) margin)))
1969 (goto-char cbeg)
1970 (save-match-data
1971 (if (not (re-search-forward
1972 (overlay-get ol1 'text-clone-syntax) cend t))
1973 ;; Mark the overlay for deletion.
1974 (overlay-put ol1 'text-clones nil)
1975 (when (< (match-end 0) cend)
1976 ;; Shrink the clone at its end.
1977 (setq end (min end (match-end 0)))
1978 (move-overlay ol1 (overlay-start ol1)
1979 (+ (match-end 0) margin)))
1980 (when (> (match-beginning 0) cbeg)
1981 ;; Shrink the clone at its beginning.
1982 (setq beg (max (match-beginning 0) beg))
1983 (move-overlay ol1 (- (match-beginning 0) margin)
1984 (overlay-end ol1)))))))
1985 ;; Now go ahead and update the clones.
1986 (let ((head (- beg (overlay-start ol1)))
1987 (tail (- (overlay-end ol1) end))
1988 (str (buffer-substring beg end))
1989 (nothing-left t)
1990 (inhibit-modification-hooks t))
1991 (dolist (ol2 (overlay-get ol1 'text-clones))
1992 (let ((oe (overlay-end ol2)))
1993 (unless (or (eq ol1 ol2) (null oe))
1994 (setq nothing-left nil)
1995 (let ((mod-beg (+ (overlay-start ol2) head)))
1996 ;;(overlay-put ol2 'modification-hooks nil)
1997 (goto-char (- (overlay-end ol2) tail))
1998 (unless (> mod-beg (point))
1999 (save-excursion (insert str))
2000 (delete-region mod-beg (point)))
2001 ;;(overlay-put ol2 'modification-hooks '(text-clone-maintain))
2002 ))))
2003 (if nothing-left (delete-overlay ol1))))))))
2005 (defun text-clone-create (start end &optional spreadp syntax)
2006 "Create a text clone of START...END at point.
2007 Text clones are chunks of text that are automatically kept identical:
2008 changes done to one of the clones will be immediately propagated to the other.
2010 The buffer's content at point is assumed to be already identical to
2011 the one between START and END.
2012 If SYNTAX is provided it's a regexp that describes the possible text of
2013 the clones; the clone will be shrunk or killed if necessary to ensure that
2014 its text matches the regexp.
2015 If SPREADP is non-nil it indicates that text inserted before/after the
2016 clone should be incorporated in the clone."
2017 ;; To deal with SPREADP we can either use an overlay with `nil t' along
2018 ;; with insert-(behind|in-front-of)-hooks or use a slightly larger overlay
2019 ;; (with a one-char margin at each end) with `t nil'.
2020 ;; We opted for a larger overlay because it behaves better in the case
2021 ;; where the clone is reduced to the empty string (we want the overlay to
2022 ;; stay when the clone's content is the empty string and we want to use
2023 ;; `evaporate' to make sure those overlays get deleted when needed).
2025 (let* ((pt-end (+ (point) (- end start)))
2026 (start-margin (if (or (not spreadp) (bobp) (<= start (point-min)))
2027 0 1))
2028 (end-margin (if (or (not spreadp)
2029 (>= pt-end (point-max))
2030 (>= start (point-max)))
2031 0 1))
2032 (ol1 (make-overlay (- start start-margin) (+ end end-margin) nil t))
2033 (ol2 (make-overlay (- (point) start-margin) (+ pt-end end-margin) nil t))
2034 (dups (list ol1 ol2)))
2035 (overlay-put ol1 'modification-hooks '(text-clone-maintain))
2036 (when spreadp (overlay-put ol1 'text-clone-spreadp t))
2037 (when syntax (overlay-put ol1 'text-clone-syntax syntax))
2038 ;;(overlay-put ol1 'face 'underline)
2039 (overlay-put ol1 'evaporate t)
2040 (overlay-put ol1 'text-clones dups)
2042 (overlay-put ol2 'modification-hooks '(text-clone-maintain))
2043 (when spreadp (overlay-put ol2 'text-clone-spreadp t))
2044 (when syntax (overlay-put ol2 'text-clone-syntax syntax))
2045 ;;(overlay-put ol2 'face 'underline)
2046 (overlay-put ol2 'evaporate t)
2047 (overlay-put ol2 'text-clones dups)))
2049 (defun play-sound (sound)
2050 "SOUND is a list of the form `(sound KEYWORD VALUE...)'.
2051 The following keywords are recognized:
2053 :file FILE - read sound data from FILE. If FILE isn't an
2054 absolute file name, it is searched in `data-directory'.
2056 :data DATA - read sound data from string DATA.
2058 Exactly one of :file or :data must be present.
2060 :volume VOL - set volume to VOL. VOL must an integer in the
2061 range 0..100 or a float in the range 0..1.0. If not specified,
2062 don't change the volume setting of the sound device.
2064 :device DEVICE - play sound on DEVICE. If not specified,
2065 a system-dependent default device name is used."
2066 (unless (fboundp 'play-sound-internal)
2067 (error "This Emacs binary lacks sound support"))
2068 (play-sound-internal sound))
2070 ;;; subr.el ends here