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