Update to use new tutorial facility.
[emacs.git] / lisp / subr.el
blobfb03b7ad1ba4d2a4b583ad7cdfa4d3f81021a7ca
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 local (set hook hook-value) (set-default hook hook-value))))
813 (defun add-to-list (list-var element &optional append)
814 "Add to the value of LIST-VAR the element ELEMENT if it isn't there yet.
815 The test for presence of ELEMENT is done with `equal'.
816 If ELEMENT is added, it is added at the beginning of the list,
817 unless the optional argument APPEND is non-nil, in which case
818 ELEMENT is added at the end.
820 The return value is the new value of LIST-VAR.
822 If you want to use `add-to-list' on a variable that is not defined
823 until a certain package is loaded, you should put the call to `add-to-list'
824 into a hook function that will be run only after loading the package.
825 `eval-after-load' provides one way to do this. In some cases
826 other hooks, such as major mode hooks, can do the job."
827 (if (member element (symbol-value list-var))
828 (symbol-value list-var)
829 (set list-var
830 (if append
831 (append (symbol-value list-var) (list element))
832 (cons element (symbol-value list-var))))))
835 ;;; Load history
837 (defvar symbol-file-load-history-loaded nil
838 "Non-nil means we have loaded the file `fns-VERSION.el' in `exec-directory'.
839 That file records the part of `load-history' for preloaded files,
840 which is cleared out before dumping to make Emacs smaller.")
842 (defun load-symbol-file-load-history ()
843 "Load the file `fns-VERSION.el' in `exec-directory' if not already done.
844 That file records the part of `load-history' for preloaded files,
845 which is cleared out before dumping to make Emacs smaller."
846 (unless symbol-file-load-history-loaded
847 (load (expand-file-name
848 ;; fns-XX.YY.ZZ.el does not work on DOS filesystem.
849 (if (eq system-type 'ms-dos)
850 "fns.el"
851 (format "fns-%s.el" emacs-version))
852 exec-directory)
853 ;; The file name fns-%s.el already has a .el extension.
854 nil nil t)
855 (setq symbol-file-load-history-loaded t)))
857 (defun symbol-file (function)
858 "Return the input source from which FUNCTION was loaded.
859 The value is normally a string that was passed to `load':
860 either an absolute file name, or a library name
861 \(with no directory name and no `.el' or `.elc' at the end).
862 It can also be nil, if the definition is not associated with any file."
863 (load-symbol-file-load-history)
864 (let ((files load-history)
865 file functions)
866 (while files
867 (if (memq function (cdr (car files)))
868 (setq file (car (car files)) files nil))
869 (setq files (cdr files)))
870 file))
873 ;;;; Specifying things to do after certain files are loaded.
875 (defun eval-after-load (file form)
876 "Arrange that, if FILE is ever loaded, FORM will be run at that time.
877 This makes or adds to an entry on `after-load-alist'.
878 If FILE is already loaded, evaluate FORM right now.
879 It does nothing if FORM is already on the list for FILE.
880 FILE must match exactly. Normally FILE is the name of a library,
881 with no directory or extension specified, since that is how `load'
882 is normally called.
883 FILE can also be a feature (i.e. a symbol), in which case FORM is
884 evaluated whenever that feature is `provide'd."
885 (let ((elt (assoc file after-load-alist)))
886 ;; Make sure there is an element for FILE.
887 (unless elt (setq elt (list file)) (push elt after-load-alist))
888 ;; Add FORM to the element if it isn't there.
889 (unless (member form (cdr elt))
890 (nconc elt (list form))
891 ;; If the file has been loaded already, run FORM right away.
892 (if (if (symbolp file)
893 (featurep file)
894 ;; Make sure `load-history' contains the files dumped with
895 ;; Emacs for the case that FILE is one of them.
896 (load-symbol-file-load-history)
897 (assoc file load-history))
898 (eval form))))
899 form)
901 (defun eval-next-after-load (file)
902 "Read the following input sexp, and run it whenever FILE is loaded.
903 This makes or adds to an entry on `after-load-alist'.
904 FILE should be the name of a library, with no directory name."
905 (eval-after-load file (read)))
908 ;;;; Input and display facilities.
910 (defvar read-quoted-char-radix 8
911 "*Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
912 Legitimate radix values are 8, 10 and 16.")
914 (custom-declare-variable-early
915 'read-quoted-char-radix 8
916 "*Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
917 Legitimate radix values are 8, 10 and 16."
918 :type '(choice (const 8) (const 10) (const 16))
919 :group 'editing-basics)
921 (defun read-quoted-char (&optional prompt)
922 "Like `read-char', but do not allow quitting.
923 Also, if the first character read is an octal digit,
924 we read any number of octal digits and return the
925 specified character code. Any nondigit terminates the sequence.
926 If the terminator is RET, it is discarded;
927 any other terminator is used itself as input.
929 The optional argument PROMPT specifies a string to use to prompt the user.
930 The variable `read-quoted-char-radix' controls which radix to use
931 for numeric input."
932 (let ((message-log-max nil) done (first t) (code 0) char)
933 (while (not done)
934 (let ((inhibit-quit first)
935 ;; Don't let C-h get the help message--only help function keys.
936 (help-char nil)
937 (help-form
938 "Type the special character you want to use,
939 or the octal character code.
940 RET terminates the character code and is discarded;
941 any other non-digit terminates the character code and is then used as input."))
942 (setq char (read-event (and prompt (format "%s-" prompt)) t))
943 (if inhibit-quit (setq quit-flag nil)))
944 ;; Translate TAB key into control-I ASCII character, and so on.
945 (and char
946 (let ((translated (lookup-key function-key-map (vector char))))
947 (if (arrayp translated)
948 (setq char (aref translated 0)))))
949 (cond ((null char))
950 ((not (integerp char))
951 (setq unread-command-events (list char)
952 done t))
953 ((/= (logand char ?\M-\^@) 0)
954 ;; Turn a meta-character into a character with the 0200 bit set.
955 (setq code (logior (logand char (lognot ?\M-\^@)) 128)
956 done t))
957 ((and (<= ?0 char) (< char (+ ?0 (min 10 read-quoted-char-radix))))
958 (setq code (+ (* code read-quoted-char-radix) (- char ?0)))
959 (and prompt (setq prompt (message "%s %c" prompt char))))
960 ((and (<= ?a (downcase char))
961 (< (downcase char) (+ ?a -10 (min 26 read-quoted-char-radix))))
962 (setq code (+ (* code read-quoted-char-radix)
963 (+ 10 (- (downcase char) ?a))))
964 (and prompt (setq prompt (message "%s %c" prompt char))))
965 ((and (not first) (eq char ?\C-m))
966 (setq done t))
967 ((not first)
968 (setq unread-command-events (list char)
969 done t))
970 (t (setq code char
971 done t)))
972 (setq first nil))
973 code))
975 (defun read-passwd (prompt &optional confirm default)
976 "Read a password, prompting with PROMPT. Echo `.' for each character typed.
977 End with RET, LFD, or ESC. DEL or C-h rubs out. C-u kills line.
978 Optional argument CONFIRM, if non-nil, then read it twice to make sure.
979 Optional DEFAULT is a default password to use instead of empty input."
980 (if confirm
981 (let (success)
982 (while (not success)
983 (let ((first (read-passwd prompt nil default))
984 (second (read-passwd "Confirm password: " nil default)))
985 (if (equal first second)
986 (progn
987 (and (arrayp second) (fillarray second ?\0))
988 (setq success first))
989 (and (arrayp first) (fillarray first ?\0))
990 (and (arrayp second) (fillarray second ?\0))
991 (message "Password not repeated accurately; please start over")
992 (sit-for 1))))
993 success)
994 (let ((pass nil)
995 (c 0)
996 (echo-keystrokes 0)
997 (cursor-in-echo-area t))
998 (while (progn (message "%s%s"
999 prompt
1000 (make-string (length pass) ?.))
1001 (setq c (read-char-exclusive nil t))
1002 (and (/= c ?\r) (/= c ?\n) (/= c ?\e)))
1003 (clear-this-command-keys)
1004 (if (= c ?\C-u)
1005 (progn
1006 (and (arrayp pass) (fillarray pass ?\0))
1007 (setq pass ""))
1008 (if (and (/= c ?\b) (/= c ?\177))
1009 (let* ((new-char (char-to-string c))
1010 (new-pass (concat pass new-char)))
1011 (and (arrayp pass) (fillarray pass ?\0))
1012 (fillarray new-char ?\0)
1013 (setq c ?\0)
1014 (setq pass new-pass))
1015 (if (> (length pass) 0)
1016 (let ((new-pass (substring pass 0 -1)))
1017 (and (arrayp pass) (fillarray pass ?\0))
1018 (setq pass new-pass))))))
1019 (message nil)
1020 (or pass default ""))))
1022 (defmacro atomic-change-group (&rest body)
1023 "Perform BODY as an atomic change group.
1024 This means that if BODY exits abnormally,
1025 all of its changes to the current buffer are undone.
1026 This works regadless of whether undo is enabled in the buffer.
1028 This mechanism is transparent to ordinary use of undo;
1029 if undo is enabled in the buffer and BODY succeeds, the
1030 user can undo the change normally."
1031 (let ((handle (make-symbol "--change-group-handle--"))
1032 (success (make-symbol "--change-group-success--")))
1033 `(let ((,handle (prepare-change-group))
1034 (,success nil))
1035 (unwind-protect
1036 (progn
1037 ;; This is inside the unwind-protect because
1038 ;; it enables undo if that was disabled; we need
1039 ;; to make sure that it gets disabled again.
1040 (activate-change-group ,handle)
1041 ,@body
1042 (setq ,success t))
1043 ;; Either of these functions will disable undo
1044 ;; if it was disabled before.
1045 (if ,success
1046 (accept-change-group ,handle)
1047 (cancel-change-group ,handle))))))
1049 (defun prepare-change-group (&optional buffer)
1050 "Return a handle for the current buffer's state, for a change group.
1051 If you specify BUFFER, make a handle for BUFFER's state instead.
1053 Pass the handle to `activate-change-group' afterward to initiate
1054 the actual changes of the change group.
1056 To finish the change group, call either `accept-change-group' or
1057 `cancel-change-group' passing the same handle as argument. Call
1058 `accept-change-group' to accept the changes in the group as final;
1059 call `cancel-change-group' to undo them all. You should use
1060 `unwind-protect' to make sure the group is always finished. The call
1061 to `activate-change-group' should be inside the `unwind-protect'.
1062 Once you finish the group, don't use the handle again--don't try to
1063 finish the same group twice. For a simple example of correct use, see
1064 the source code of `atomic-change-group'.
1066 The handle records only the specified buffer. To make a multibuffer
1067 change group, call this function once for each buffer you want to
1068 cover, then use `nconc' to combine the returned values, like this:
1070 (nconc (prepare-change-group buffer-1)
1071 (prepare-change-group buffer-2))
1073 You can then activate that multibuffer change group with a single
1074 call to `activate-change-group' and finish it with a single call
1075 to `accept-change-group' or `cancel-change-group'."
1077 (list (cons (current-buffer) buffer-undo-list)))
1079 (defun activate-change-group (handle)
1080 "Activate a change group made with `prepare-change-group' (which see)."
1081 (dolist (elt handle)
1082 (with-current-buffer (car elt)
1083 (if (eq buffer-undo-list t)
1084 (setq buffer-undo-list nil)))))
1086 (defun accept-change-group (handle)
1087 "Finish a change group made with `prepare-change-group' (which see).
1088 This finishes the change group by accepting its changes as final."
1089 (dolist (elt handle)
1090 (with-current-buffer (car elt)
1091 (if (eq elt t)
1092 (setq buffer-undo-list t)))))
1094 (defun cancel-change-group (handle)
1095 "Finish a change group made with `prepare-change-group' (which see).
1096 This finishes the change group by reverting all of its changes."
1097 (dolist (elt handle)
1098 (with-current-buffer (car elt)
1099 (setq elt (cdr elt))
1100 (let ((old-car
1101 (if (consp elt) (car elt)))
1102 (old-cdr
1103 (if (consp elt) (cdr elt))))
1104 ;; Temporarily truncate the undo log at ELT.
1105 (when (consp elt)
1106 (setcar elt nil) (setcdr elt nil))
1107 (unless (eq last-command 'undo) (undo-start))
1108 ;; Make sure there's no confusion.
1109 (when (and (consp elt) (not (eq elt (last pending-undo-list))))
1110 (error "Undoing to some unrelated state"))
1111 ;; Undo it all.
1112 (while pending-undo-list (undo-more 1))
1113 ;; Reset the modified cons cell ELT to its original content.
1114 (when (consp elt)
1115 (setcar elt old-car)
1116 (setcdr elt old-cdr))
1117 ;; Revert the undo info to what it was when we grabbed the state.
1118 (setq buffer-undo-list elt)))))
1120 ;; For compatibility.
1121 (defalias 'redraw-modeline 'force-mode-line-update)
1123 (defun force-mode-line-update (&optional all)
1124 "Force the mode line of the current buffer to be redisplayed.
1125 With optional non-nil ALL, force redisplay of all mode lines."
1126 (if all (save-excursion (set-buffer (other-buffer))))
1127 (set-buffer-modified-p (buffer-modified-p)))
1129 (defun momentary-string-display (string pos &optional exit-char message)
1130 "Momentarily display STRING in the buffer at POS.
1131 Display remains until next character is typed.
1132 If the char is EXIT-CHAR (optional third arg, default is SPC) it is swallowed;
1133 otherwise it is then available as input (as a command if nothing else).
1134 Display MESSAGE (optional fourth arg) in the echo area.
1135 If MESSAGE is nil, instructions to type EXIT-CHAR are displayed there."
1136 (or exit-char (setq exit-char ?\ ))
1137 (let ((inhibit-read-only t)
1138 ;; Don't modify the undo list at all.
1139 (buffer-undo-list t)
1140 (modified (buffer-modified-p))
1141 (name buffer-file-name)
1142 insert-end)
1143 (unwind-protect
1144 (progn
1145 (save-excursion
1146 (goto-char pos)
1147 ;; defeat file locking... don't try this at home, kids!
1148 (setq buffer-file-name nil)
1149 (insert-before-markers string)
1150 (setq insert-end (point))
1151 ;; If the message end is off screen, recenter now.
1152 (if (< (window-end nil t) insert-end)
1153 (recenter (/ (window-height) 2)))
1154 ;; If that pushed message start off the screen,
1155 ;; scroll to start it at the top of the screen.
1156 (move-to-window-line 0)
1157 (if (> (point) pos)
1158 (progn
1159 (goto-char pos)
1160 (recenter 0))))
1161 (message (or message "Type %s to continue editing.")
1162 (single-key-description exit-char))
1163 (let ((char (read-event)))
1164 (or (eq char exit-char)
1165 (setq unread-command-events (list char)))))
1166 (if insert-end
1167 (save-excursion
1168 (delete-region pos insert-end)))
1169 (setq buffer-file-name name)
1170 (set-buffer-modified-p modified))))
1173 ;;;; Overlay operations
1175 (defun copy-overlay (o)
1176 "Return a copy of overlay O."
1177 (let ((o1 (make-overlay (overlay-start o) (overlay-end o)
1178 ;; FIXME: there's no easy way to find the
1179 ;; insertion-type of the two markers.
1180 (overlay-buffer o)))
1181 (props (overlay-properties o)))
1182 (while props
1183 (overlay-put o1 (pop props) (pop props)))
1184 o1))
1186 (defun remove-overlays (beg end name val)
1187 "Clear BEG and END of overlays whose property NAME has value VAL.
1188 Overlays might be moved and or split."
1189 (if (< end beg)
1190 (setq beg (prog1 end (setq end beg))))
1191 (save-excursion
1192 (dolist (o (overlays-in beg end))
1193 (when (eq (overlay-get o name) val)
1194 ;; Either push this overlay outside beg...end
1195 ;; or split it to exclude beg...end
1196 ;; or delete it entirely (if it is contained in beg...end).
1197 (if (< (overlay-start o) beg)
1198 (if (> (overlay-end o) end)
1199 (progn
1200 (move-overlay (copy-overlay o)
1201 (overlay-start o) beg)
1202 (move-overlay o end (overlay-end o)))
1203 (move-overlay o (overlay-start o) beg))
1204 (if (> (overlay-end o) end)
1205 (move-overlay o end (overlay-end o))
1206 (delete-overlay o)))))))
1208 ;;;; Miscellanea.
1210 ;; A number of major modes set this locally.
1211 ;; Give it a global value to avoid compiler warnings.
1212 (defvar font-lock-defaults nil)
1214 (defvar suspend-hook nil
1215 "Normal hook run by `suspend-emacs', before suspending.")
1217 (defvar suspend-resume-hook nil
1218 "Normal hook run by `suspend-emacs', after Emacs is continued.")
1220 (defvar temp-buffer-show-hook nil
1221 "Normal hook run by `with-output-to-temp-buffer' after displaying the buffer.
1222 When the hook runs, the temporary buffer is current, and the window it
1223 was displayed in is selected. This hook is normally set up with a
1224 function to make the buffer read only, and find function names and
1225 variable names in it, provided the major mode is still Help mode.")
1227 (defvar temp-buffer-setup-hook nil
1228 "Normal hook run by `with-output-to-temp-buffer' at the start.
1229 When the hook runs, the temporary buffer is current.
1230 This hook is normally set up with a function to put the buffer in Help
1231 mode.")
1233 ;; Avoid compiler warnings about this variable,
1234 ;; which has a special meaning on certain system types.
1235 (defvar buffer-file-type nil
1236 "Non-nil if the visited file is a binary file.
1237 This variable is meaningful on MS-DOG and Windows NT.
1238 On those systems, it is automatically local in every buffer.
1239 On other systems, this variable is normally always nil.")
1241 ;; This should probably be written in C (i.e., without using `walk-windows').
1242 (defun get-buffer-window-list (buffer &optional minibuf frame)
1243 "Return windows currently displaying BUFFER, or nil if none.
1244 See `walk-windows' for the meaning of MINIBUF and FRAME."
1245 (let ((buffer (if (bufferp buffer) buffer (get-buffer buffer))) windows)
1246 (walk-windows (function (lambda (window)
1247 (if (eq (window-buffer window) buffer)
1248 (setq windows (cons window windows)))))
1249 minibuf frame)
1250 windows))
1252 (defun ignore (&rest ignore)
1253 "Do nothing and return nil.
1254 This function accepts any number of arguments, but ignores them."
1255 (interactive)
1256 nil)
1258 (defun error (&rest args)
1259 "Signal an error, making error message by passing all args to `format'.
1260 In Emacs, the convention is that error messages start with a capital
1261 letter but *do not* end with a period. Please follow this convention
1262 for the sake of consistency."
1263 (while t
1264 (signal 'error (list (apply 'format args)))))
1266 (defalias 'user-original-login-name 'user-login-name)
1268 (defun start-process-shell-command (name buffer &rest args)
1269 "Start a program in a subprocess. Return the process object for it.
1270 Args are NAME BUFFER COMMAND &rest COMMAND-ARGS.
1271 NAME is name for process. It is modified if necessary to make it unique.
1272 BUFFER is the buffer or (buffer-name) to associate with the process.
1273 Process output goes at end of that buffer, unless you specify
1274 an output stream or filter function to handle the output.
1275 BUFFER may be also nil, meaning that this process is not associated
1276 with any buffer
1277 Third arg is command name, the name of a shell command.
1278 Remaining arguments are the arguments for the command.
1279 Wildcards and redirection are handled as usual in the shell."
1280 (cond
1281 ((eq system-type 'vax-vms)
1282 (apply 'start-process name buffer args))
1283 ;; We used to use `exec' to replace the shell with the command,
1284 ;; but that failed to handle (...) and semicolon, etc.
1286 (start-process name buffer shell-file-name shell-command-switch
1287 (mapconcat 'identity args " ")))))
1289 (defun call-process-shell-command (command &optional infile buffer display
1290 &rest args)
1291 "Execute the shell command COMMAND synchronously in separate process.
1292 The remaining arguments are optional.
1293 The program's input comes from file INFILE (nil means `/dev/null').
1294 Insert output in BUFFER before point; t means current buffer;
1295 nil for BUFFER means discard it; 0 means discard and don't wait.
1296 BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,
1297 REAL-BUFFER says what to do with standard output, as above,
1298 while STDERR-FILE says what to do with standard error in the child.
1299 STDERR-FILE may be nil (discard standard error output),
1300 t (mix it with ordinary output), or a file name string.
1302 Fourth arg DISPLAY non-nil means redisplay buffer as output is inserted.
1303 Remaining arguments are strings passed as additional arguments for COMMAND.
1304 Wildcards and redirection are handled as usual in the shell.
1306 If BUFFER is 0, `call-process-shell-command' returns immediately with value nil.
1307 Otherwise it waits for COMMAND to terminate and returns a numeric exit
1308 status or a signal description string.
1309 If you quit, the process is killed with SIGINT, or SIGKILL if you quit again."
1310 (cond
1311 ((eq system-type 'vax-vms)
1312 (apply 'call-process command infile buffer display args))
1313 ;; We used to use `exec' to replace the shell with the command,
1314 ;; but that failed to handle (...) and semicolon, etc.
1316 (call-process shell-file-name
1317 infile buffer display
1318 shell-command-switch
1319 (mapconcat 'identity (cons command args) " ")))))
1321 (defmacro with-current-buffer (buffer &rest body)
1322 "Execute the forms in BODY with BUFFER as the current buffer.
1323 The value returned is the value of the last form in BODY.
1324 See also `with-temp-buffer'."
1325 (cons 'save-current-buffer
1326 (cons (list 'set-buffer buffer)
1327 body)))
1329 (defmacro with-temp-file (file &rest body)
1330 "Create a new buffer, evaluate BODY there, and write the buffer to FILE.
1331 The value returned is the value of the last form in BODY.
1332 See also `with-temp-buffer'."
1333 (let ((temp-file (make-symbol "temp-file"))
1334 (temp-buffer (make-symbol "temp-buffer")))
1335 `(let ((,temp-file ,file)
1336 (,temp-buffer
1337 (get-buffer-create (generate-new-buffer-name " *temp file*"))))
1338 (unwind-protect
1339 (prog1
1340 (with-current-buffer ,temp-buffer
1341 ,@body)
1342 (with-current-buffer ,temp-buffer
1343 (widen)
1344 (write-region (point-min) (point-max) ,temp-file nil 0)))
1345 (and (buffer-name ,temp-buffer)
1346 (kill-buffer ,temp-buffer))))))
1348 (defmacro with-temp-message (message &rest body)
1349 "Display MESSAGE temporarily if non-nil while BODY is evaluated.
1350 The original message is restored to the echo area after BODY has finished.
1351 The value returned is the value of the last form in BODY.
1352 MESSAGE is written to the message log buffer if `message-log-max' is non-nil.
1353 If MESSAGE is nil, the echo area and message log buffer are unchanged.
1354 Use a MESSAGE of \"\" to temporarily clear the echo area."
1355 (let ((current-message (make-symbol "current-message"))
1356 (temp-message (make-symbol "with-temp-message")))
1357 `(let ((,temp-message ,message)
1358 (,current-message))
1359 (unwind-protect
1360 (progn
1361 (when ,temp-message
1362 (setq ,current-message (current-message))
1363 (message "%s" ,temp-message))
1364 ,@body)
1365 (and ,temp-message
1366 (if ,current-message
1367 (message "%s" ,current-message)
1368 (message nil)))))))
1370 (defmacro with-temp-buffer (&rest body)
1371 "Create a temporary buffer, and evaluate BODY there like `progn'.
1372 See also `with-temp-file' and `with-output-to-string'."
1373 (let ((temp-buffer (make-symbol "temp-buffer")))
1374 `(let ((,temp-buffer
1375 (get-buffer-create (generate-new-buffer-name " *temp*"))))
1376 (unwind-protect
1377 (with-current-buffer ,temp-buffer
1378 ,@body)
1379 (and (buffer-name ,temp-buffer)
1380 (kill-buffer ,temp-buffer))))))
1382 (defmacro with-output-to-string (&rest body)
1383 "Execute BODY, return the text it sent to `standard-output', as a string."
1384 `(let ((standard-output
1385 (get-buffer-create (generate-new-buffer-name " *string-output*"))))
1386 (let ((standard-output standard-output))
1387 ,@body)
1388 (with-current-buffer standard-output
1389 (prog1
1390 (buffer-string)
1391 (kill-buffer nil)))))
1393 (defmacro with-local-quit (&rest body)
1394 "Execute BODY with `inhibit-quit' temporarily bound to nil."
1395 `(condition-case nil
1396 (let ((inhibit-quit nil))
1397 ,@body)
1398 (quit (setq quit-flag t))))
1400 (defmacro combine-after-change-calls (&rest body)
1401 "Execute BODY, but don't call the after-change functions till the end.
1402 If BODY makes changes in the buffer, they are recorded
1403 and the functions on `after-change-functions' are called several times
1404 when BODY is finished.
1405 The return value is the value of the last form in BODY.
1407 If `before-change-functions' is non-nil, then calls to the after-change
1408 functions can't be deferred, so in that case this macro has no effect.
1410 Do not alter `after-change-functions' or `before-change-functions'
1411 in BODY."
1412 `(unwind-protect
1413 (let ((combine-after-change-calls t))
1414 . ,body)
1415 (combine-after-change-execute)))
1418 (defvar delay-mode-hooks nil
1419 "If non-nil, `run-mode-hooks' should delay running the hooks.")
1420 (defvar delayed-mode-hooks nil
1421 "List of delayed mode hooks waiting to be run.")
1422 (make-variable-buffer-local 'delayed-mode-hooks)
1424 (defun run-mode-hooks (&rest hooks)
1425 "Run mode hooks `delayed-mode-hooks' and HOOKS, or delay HOOKS.
1426 Execution is delayed if `delay-mode-hooks' is non-nil.
1427 Major mode functions should use this."
1428 (if delay-mode-hooks
1429 ;; Delaying case.
1430 (dolist (hook hooks)
1431 (push hook delayed-mode-hooks))
1432 ;; Normal case, just run the hook as before plus any delayed hooks.
1433 (setq hooks (nconc (nreverse delayed-mode-hooks) hooks))
1434 (setq delayed-mode-hooks nil)
1435 (apply 'run-hooks hooks)))
1437 (defmacro delay-mode-hooks (&rest body)
1438 "Execute BODY, but delay any `run-mode-hooks'.
1439 Only affects hooks run in the current buffer."
1440 `(progn
1441 (make-local-variable 'delay-mode-hooks)
1442 (let ((delay-mode-hooks t))
1443 ,@body)))
1445 ;; PUBLIC: find if the current mode derives from another.
1447 (defun derived-mode-p (&rest modes)
1448 "Non-nil if the current major mode is derived from one of MODES.
1449 Uses the `derived-mode-parent' property of the symbol to trace backwards."
1450 (let ((parent major-mode))
1451 (while (and (not (memq parent modes))
1452 (setq parent (get parent 'derived-mode-parent))))
1453 parent))
1455 (defmacro with-syntax-table (table &rest body)
1456 "Evaluate BODY with syntax table of current buffer set to a copy of TABLE.
1457 The syntax table of the current buffer is saved, BODY is evaluated, and the
1458 saved table is restored, even in case of an abnormal exit.
1459 Value is what BODY returns."
1460 (let ((old-table (make-symbol "table"))
1461 (old-buffer (make-symbol "buffer")))
1462 `(let ((,old-table (syntax-table))
1463 (,old-buffer (current-buffer)))
1464 (unwind-protect
1465 (progn
1466 (set-syntax-table (copy-syntax-table ,table))
1467 ,@body)
1468 (save-current-buffer
1469 (set-buffer ,old-buffer)
1470 (set-syntax-table ,old-table))))))
1472 (defvar save-match-data-internal)
1474 ;; We use save-match-data-internal as the local variable because
1475 ;; that works ok in practice (people should not use that variable elsewhere).
1476 ;; We used to use an uninterned symbol; the compiler handles that properly
1477 ;; now, but it generates slower code.
1478 (defmacro save-match-data (&rest body)
1479 "Execute the BODY forms, restoring the global value of the match data.
1480 The value returned is the value of the last form in BODY."
1481 ;; It is better not to use backquote here,
1482 ;; because that makes a bootstrapping problem
1483 ;; if you need to recompile all the Lisp files using interpreted code.
1484 (list 'let
1485 '((save-match-data-internal (match-data)))
1486 (list 'unwind-protect
1487 (cons 'progn body)
1488 '(set-match-data save-match-data-internal))))
1490 (defun match-string (num &optional string)
1491 "Return string of text matched by last search.
1492 NUM specifies which parenthesized expression in the last regexp.
1493 Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
1494 Zero means the entire text matched by the whole regexp or whole string.
1495 STRING should be given if the last search was by `string-match' on STRING."
1496 (if (match-beginning num)
1497 (if string
1498 (substring string (match-beginning num) (match-end num))
1499 (buffer-substring (match-beginning num) (match-end num)))))
1501 (defun match-string-no-properties (num &optional string)
1502 "Return string of text matched by last search, without text properties.
1503 NUM specifies which parenthesized expression in the last regexp.
1504 Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
1505 Zero means the entire text matched by the whole regexp or whole string.
1506 STRING should be given if the last search was by `string-match' on STRING."
1507 (if (match-beginning num)
1508 (if string
1509 (let ((result
1510 (substring string (match-beginning num) (match-end num))))
1511 (set-text-properties 0 (length result) nil result)
1512 result)
1513 (buffer-substring-no-properties (match-beginning num)
1514 (match-end num)))))
1516 (defun split-string (string &optional separators)
1517 "Splits STRING into substrings where there are matches for SEPARATORS.
1518 Each match for SEPARATORS is a splitting point.
1519 The substrings between the splitting points are made into a list
1520 which is returned.
1521 If SEPARATORS is absent, it defaults to \"[ \\f\\t\\n\\r\\v]+\".
1523 If there is match for SEPARATORS at the beginning of STRING, we do not
1524 include a null substring for that. Likewise, if there is a match
1525 at the end of STRING, we don't include a null substring for that.
1527 Modifies the match data; use `save-match-data' if necessary."
1528 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
1529 (start 0)
1530 notfirst
1531 (list nil))
1532 (while (and (string-match rexp string
1533 (if (and notfirst
1534 (= start (match-beginning 0))
1535 (< start (length string)))
1536 (1+ start) start))
1537 (< (match-beginning 0) (length string)))
1538 (setq notfirst t)
1539 (or (eq (match-beginning 0) 0)
1540 (and (eq (match-beginning 0) (match-end 0))
1541 (eq (match-beginning 0) start))
1542 (setq list
1543 (cons (substring string start (match-beginning 0))
1544 list)))
1545 (setq start (match-end 0)))
1546 (or (eq start (length string))
1547 (setq list
1548 (cons (substring string start)
1549 list)))
1550 (nreverse list)))
1552 (defun subst-char-in-string (fromchar tochar string &optional inplace)
1553 "Replace FROMCHAR with TOCHAR in STRING each time it occurs.
1554 Unless optional argument INPLACE is non-nil, return a new string."
1555 (let ((i (length string))
1556 (newstr (if inplace string (copy-sequence string))))
1557 (while (> i 0)
1558 (setq i (1- i))
1559 (if (eq (aref newstr i) fromchar)
1560 (aset newstr i tochar)))
1561 newstr))
1563 (defun replace-regexp-in-string (regexp rep string &optional
1564 fixedcase literal subexp start)
1565 "Replace all matches for REGEXP with REP in STRING.
1567 Return a new string containing the replacements.
1569 Optional arguments FIXEDCASE, LITERAL and SUBEXP are like the
1570 arguments with the same names of function `replace-match'. If START
1571 is non-nil, start replacements at that index in STRING.
1573 REP is either a string used as the NEWTEXT arg of `replace-match' or a
1574 function. If it is a function it is applied to each match to generate
1575 the replacement passed to `replace-match'; the match-data at this
1576 point are such that match 0 is the function's argument.
1578 To replace only the first match (if any), make REGEXP match up to \\'
1579 and replace a sub-expression, e.g.
1580 (replace-regexp-in-string \"\\(foo\\).*\\'\" \"bar\" \" foo foo\" nil nil 1)
1581 => \" bar foo\"
1584 ;; To avoid excessive consing from multiple matches in long strings,
1585 ;; don't just call `replace-match' continually. Walk down the
1586 ;; string looking for matches of REGEXP and building up a (reversed)
1587 ;; list MATCHES. This comprises segments of STRING which weren't
1588 ;; matched interspersed with replacements for segments that were.
1589 ;; [For a `large' number of replacements it's more efficient to
1590 ;; operate in a temporary buffer; we can't tell from the function's
1591 ;; args whether to choose the buffer-based implementation, though it
1592 ;; might be reasonable to do so for long enough STRING.]
1593 (let ((l (length string))
1594 (start (or start 0))
1595 matches str mb me)
1596 (save-match-data
1597 (while (and (< start l) (string-match regexp string start))
1598 (setq mb (match-beginning 0)
1599 me (match-end 0))
1600 ;; If we matched the empty string, make sure we advance by one char
1601 (when (= me mb) (setq me (min l (1+ mb))))
1602 ;; Generate a replacement for the matched substring.
1603 ;; Operate only on the substring to minimize string consing.
1604 ;; Set up match data for the substring for replacement;
1605 ;; presumably this is likely to be faster than munging the
1606 ;; match data directly in Lisp.
1607 (string-match regexp (setq str (substring string mb me)))
1608 (setq matches
1609 (cons (replace-match (if (stringp rep)
1611 (funcall rep (match-string 0 str)))
1612 fixedcase literal str subexp)
1613 (cons (substring string start mb) ; unmatched prefix
1614 matches)))
1615 (setq start me))
1616 ;; Reconstruct a string from the pieces.
1617 (setq matches (cons (substring string start l) matches)) ; leftover
1618 (apply #'concat (nreverse matches)))))
1620 (defun shell-quote-argument (argument)
1621 "Quote an argument for passing as argument to an inferior shell."
1622 (if (eq system-type 'ms-dos)
1623 ;; Quote using double quotes, but escape any existing quotes in
1624 ;; the argument with backslashes.
1625 (let ((result "")
1626 (start 0)
1627 end)
1628 (if (or (null (string-match "[^\"]" argument))
1629 (< (match-end 0) (length argument)))
1630 (while (string-match "[\"]" argument start)
1631 (setq end (match-beginning 0)
1632 result (concat result (substring argument start end)
1633 "\\" (substring argument end (1+ end)))
1634 start (1+ end))))
1635 (concat "\"" result (substring argument start) "\""))
1636 (if (eq system-type 'windows-nt)
1637 (concat "\"" argument "\"")
1638 (if (equal argument "")
1639 "''"
1640 ;; Quote everything except POSIX filename characters.
1641 ;; This should be safe enough even for really weird shells.
1642 (let ((result "") (start 0) end)
1643 (while (string-match "[^-0-9a-zA-Z_./]" argument start)
1644 (setq end (match-beginning 0)
1645 result (concat result (substring argument start end)
1646 "\\" (substring argument end (1+ end)))
1647 start (1+ end)))
1648 (concat result (substring argument start)))))))
1650 (defun make-syntax-table (&optional oldtable)
1651 "Return a new syntax table.
1652 Create a syntax table which inherits from OLDTABLE (if non-nil) or
1653 from `standard-syntax-table' otherwise."
1654 (let ((table (make-char-table 'syntax-table nil)))
1655 (set-char-table-parent table (or oldtable (standard-syntax-table)))
1656 table))
1658 (defun add-to-invisibility-spec (arg)
1659 "Add elements to `buffer-invisibility-spec'.
1660 See documentation for `buffer-invisibility-spec' for the kind of elements
1661 that can be added."
1662 (cond
1663 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
1664 (setq buffer-invisibility-spec (list arg)))
1666 (setq buffer-invisibility-spec
1667 (cons arg buffer-invisibility-spec)))))
1669 (defun remove-from-invisibility-spec (arg)
1670 "Remove elements from `buffer-invisibility-spec'."
1671 (if (consp buffer-invisibility-spec)
1672 (setq buffer-invisibility-spec (delete arg buffer-invisibility-spec))))
1674 (defun global-set-key (key command)
1675 "Give KEY a global binding as COMMAND.
1676 COMMAND is the command definition to use; usually it is
1677 a symbol naming an interactively-callable function.
1678 KEY is a key sequence; noninteractively, it is a string or vector
1679 of characters or event types, and non-ASCII characters with codes
1680 above 127 (such as ISO Latin-1) can be included if you use a vector.
1682 Note that if KEY has a local binding in the current buffer,
1683 that local binding will continue to shadow any global binding
1684 that you make with this function."
1685 (interactive "KSet key globally: \nCSet key %s to command: ")
1686 (or (vectorp key) (stringp key)
1687 (signal 'wrong-type-argument (list 'arrayp key)))
1688 (define-key (current-global-map) key command))
1690 (defun local-set-key (key command)
1691 "Give KEY a local binding as COMMAND.
1692 COMMAND is the command definition to use; usually it is
1693 a symbol naming an interactively-callable function.
1694 KEY is a key sequence; noninteractively, it is a string or vector
1695 of characters or event types, and non-ASCII characters with codes
1696 above 127 (such as ISO Latin-1) can be included if you use a vector.
1698 The binding goes in the current buffer's local map,
1699 which in most cases is shared with all other buffers in the same major mode."
1700 (interactive "KSet key locally: \nCSet key %s locally to command: ")
1701 (let ((map (current-local-map)))
1702 (or map
1703 (use-local-map (setq map (make-sparse-keymap))))
1704 (or (vectorp key) (stringp key)
1705 (signal 'wrong-type-argument (list 'arrayp key)))
1706 (define-key map key command)))
1708 (defun global-unset-key (key)
1709 "Remove global binding of KEY.
1710 KEY is a string representing a sequence of keystrokes."
1711 (interactive "kUnset key globally: ")
1712 (global-set-key key nil))
1714 (defun local-unset-key (key)
1715 "Remove local binding of KEY.
1716 KEY is a string representing a sequence of keystrokes."
1717 (interactive "kUnset key locally: ")
1718 (if (current-local-map)
1719 (local-set-key key nil))
1720 nil)
1722 ;; We put this here instead of in frame.el so that it's defined even on
1723 ;; systems where frame.el isn't loaded.
1724 (defun frame-configuration-p (object)
1725 "Return non-nil if OBJECT seems to be a frame configuration.
1726 Any list whose car is `frame-configuration' is assumed to be a frame
1727 configuration."
1728 (and (consp object)
1729 (eq (car object) 'frame-configuration)))
1731 (defun functionp (object)
1732 "Non-nil iff OBJECT is a type of object that can be called as a function."
1733 (or (and (symbolp object) (fboundp object)
1734 (setq object (indirect-function object))
1735 (eq (car-safe object) 'autoload)
1736 (not (car-safe (cdr-safe (cdr-safe (cdr-safe (cdr-safe object)))))))
1737 (subrp object) (byte-code-function-p object)
1738 (eq (car-safe object) 'lambda)))
1740 (defun interactive-form (function)
1741 "Return the interactive form of FUNCTION.
1742 If function is a command (see `commandp'), value is a list of the form
1743 \(interactive SPEC). If function is not a command, return nil."
1744 (setq function (indirect-function function))
1745 (when (commandp function)
1746 (cond ((byte-code-function-p function)
1747 (when (> (length function) 5)
1748 (let ((spec (aref function 5)))
1749 (if spec
1750 (list 'interactive spec)
1751 (list 'interactive)))))
1752 ((subrp function)
1753 (subr-interactive-form function))
1754 ((eq (car-safe function) 'lambda)
1755 (setq function (cddr function))
1756 (when (stringp (car function))
1757 (setq function (cdr function)))
1758 (let ((form (car function)))
1759 (when (eq (car-safe form) 'interactive)
1760 (copy-sequence form)))))))
1762 (defun assq-delete-all (key alist)
1763 "Delete from ALIST all elements whose car is KEY.
1764 Return the modified alist."
1765 (let ((tail alist))
1766 (while tail
1767 (if (eq (car (car tail)) key)
1768 (setq alist (delq (car tail) alist)))
1769 (setq tail (cdr tail)))
1770 alist))
1772 (defun make-temp-file (prefix &optional dir-flag)
1773 "Create a temporary file.
1774 The returned file name (created by appending some random characters at the end
1775 of PREFIX, and expanding against `temporary-file-directory' if necessary,
1776 is guaranteed to point to a newly created empty file.
1777 You can then use `write-region' to write new data into the file.
1779 If DIR-FLAG is non-nil, create a new empty directory instead of a file."
1780 (let (file)
1781 (while (condition-case ()
1782 (progn
1783 (setq file
1784 (make-temp-name
1785 (expand-file-name prefix temporary-file-directory)))
1786 (if dir-flag
1787 (make-directory file)
1788 (write-region "" nil file nil 'silent nil 'excl))
1789 nil)
1790 (file-already-exists t))
1791 ;; the file was somehow created by someone else between
1792 ;; `make-temp-name' and `write-region', let's try again.
1793 nil)
1794 file))
1797 (defun add-minor-mode (toggle name &optional keymap after toggle-fun)
1798 "Register a new minor mode.
1800 This is an XEmacs-compatibility function. Use `define-minor-mode' instead.
1802 TOGGLE is a symbol which is the name of a buffer-local variable that
1803 is toggled on or off to say whether the minor mode is active or not.
1805 NAME specifies what will appear in the mode line when the minor mode
1806 is active. NAME should be either a string starting with a space, or a
1807 symbol whose value is such a string.
1809 Optional KEYMAP is the keymap for the minor mode that will be added
1810 to `minor-mode-map-alist'.
1812 Optional AFTER specifies that TOGGLE should be added after AFTER
1813 in `minor-mode-alist'.
1815 Optional TOGGLE-FUN is an interactive function to toggle the mode.
1816 It defaults to (and should by convention be) TOGGLE.
1818 If TOGGLE has a non-nil `:included' property, an entry for the mode is
1819 included in the mode-line minor mode menu.
1820 If TOGGLE has a `:menu-tag', that is used for the menu item's label."
1821 (unless toggle-fun (setq toggle-fun toggle))
1822 ;; Add the name to the minor-mode-alist.
1823 (when name
1824 (let ((existing (assq toggle minor-mode-alist)))
1825 (when (and (stringp name) (not (get-text-property 0 'local-map name)))
1826 (setq name
1827 (propertize name
1828 'local-map mode-line-minor-mode-keymap
1829 'help-echo "mouse-3: minor mode menu")))
1830 (if existing
1831 (setcdr existing (list name))
1832 (let ((tail minor-mode-alist) found)
1833 (while (and tail (not found))
1834 (if (eq after (caar tail))
1835 (setq found tail)
1836 (setq tail (cdr tail))))
1837 (if found
1838 (let ((rest (cdr found)))
1839 (setcdr found nil)
1840 (nconc found (list (list toggle name)) rest))
1841 (setq minor-mode-alist (cons (list toggle name)
1842 minor-mode-alist)))))))
1843 ;; Add the toggle to the minor-modes menu if requested.
1844 (when (get toggle :included)
1845 (define-key mode-line-mode-menu
1846 (vector toggle)
1847 (list 'menu-item
1848 (concat
1849 (or (get toggle :menu-tag)
1850 (if (stringp name) name (symbol-name toggle)))
1851 (let ((mode-name (if (stringp name) name
1852 (if (symbolp name) (symbol-value name)))))
1853 (if mode-name
1854 (concat " (" mode-name ")"))))
1855 toggle-fun
1856 :button (cons :toggle toggle))))
1858 ;; Add the map to the minor-mode-map-alist.
1859 (when keymap
1860 (let ((existing (assq toggle minor-mode-map-alist)))
1861 (if existing
1862 (setcdr existing keymap)
1863 (let ((tail minor-mode-map-alist) found)
1864 (while (and tail (not found))
1865 (if (eq after (caar tail))
1866 (setq found tail)
1867 (setq tail (cdr tail))))
1868 (if found
1869 (let ((rest (cdr found)))
1870 (setcdr found nil)
1871 (nconc found (list (cons toggle keymap)) rest))
1872 (setq minor-mode-map-alist (cons (cons toggle keymap)
1873 minor-mode-map-alist))))))))
1875 ;; Clones ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1877 (defun text-clone-maintain (ol1 after beg end &optional len)
1878 "Propagate the changes made under the overlay OL1 to the other clones.
1879 This is used on the `modification-hooks' property of text clones."
1880 (when (and after (not undo-in-progress) (overlay-start ol1))
1881 (let ((margin (if (overlay-get ol1 'text-clone-spreadp) 1 0)))
1882 (setq beg (max beg (+ (overlay-start ol1) margin)))
1883 (setq end (min end (- (overlay-end ol1) margin)))
1884 (when (<= beg end)
1885 (save-excursion
1886 (when (overlay-get ol1 'text-clone-syntax)
1887 ;; Check content of the clone's text.
1888 (let ((cbeg (+ (overlay-start ol1) margin))
1889 (cend (- (overlay-end ol1) margin)))
1890 (goto-char cbeg)
1891 (save-match-data
1892 (if (not (re-search-forward
1893 (overlay-get ol1 'text-clone-syntax) cend t))
1894 ;; Mark the overlay for deletion.
1895 (overlay-put ol1 'text-clones nil)
1896 (when (< (match-end 0) cend)
1897 ;; Shrink the clone at its end.
1898 (setq end (min end (match-end 0)))
1899 (move-overlay ol1 (overlay-start ol1)
1900 (+ (match-end 0) margin)))
1901 (when (> (match-beginning 0) cbeg)
1902 ;; Shrink the clone at its beginning.
1903 (setq beg (max (match-beginning 0) beg))
1904 (move-overlay ol1 (- (match-beginning 0) margin)
1905 (overlay-end ol1)))))))
1906 ;; Now go ahead and update the clones.
1907 (let ((head (- beg (overlay-start ol1)))
1908 (tail (- (overlay-end ol1) end))
1909 (str (buffer-substring beg end))
1910 (nothing-left t)
1911 (inhibit-modification-hooks t))
1912 (dolist (ol2 (overlay-get ol1 'text-clones))
1913 (let ((oe (overlay-end ol2)))
1914 (unless (or (eq ol1 ol2) (null oe))
1915 (setq nothing-left nil)
1916 (let ((mod-beg (+ (overlay-start ol2) head)))
1917 ;;(overlay-put ol2 'modification-hooks nil)
1918 (goto-char (- (overlay-end ol2) tail))
1919 (unless (> mod-beg (point))
1920 (save-excursion (insert str))
1921 (delete-region mod-beg (point)))
1922 ;;(overlay-put ol2 'modification-hooks '(text-clone-maintain))
1923 ))))
1924 (if nothing-left (delete-overlay ol1))))))))
1926 (defun text-clone-create (start end &optional spreadp syntax)
1927 "Create a text clone of START...END at point.
1928 Text clones are chunks of text that are automatically kept identical:
1929 changes done to one of the clones will be immediately propagated to the other.
1931 The buffer's content at point is assumed to be already identical to
1932 the one between START and END.
1933 If SYNTAX is provided it's a regexp that describes the possible text of
1934 the clones; the clone will be shrunk or killed if necessary to ensure that
1935 its text matches the regexp.
1936 If SPREADP is non-nil it indicates that text inserted before/after the
1937 clone should be incorporated in the clone."
1938 ;; To deal with SPREADP we can either use an overlay with `nil t' along
1939 ;; with insert-(behind|in-front-of)-hooks or use a slightly larger overlay
1940 ;; (with a one-char margin at each end) with `t nil'.
1941 ;; We opted for a larger overlay because it behaves better in the case
1942 ;; where the clone is reduced to the empty string (we want the overlay to
1943 ;; stay when the clone's content is the empty string and we want to use
1944 ;; `evaporate' to make sure those overlays get deleted when needed).
1946 (let* ((pt-end (+ (point) (- end start)))
1947 (start-margin (if (or (not spreadp) (bobp) (<= start (point-min)))
1948 0 1))
1949 (end-margin (if (or (not spreadp)
1950 (>= pt-end (point-max))
1951 (>= start (point-max)))
1952 0 1))
1953 (ol1 (make-overlay (- start start-margin) (+ end end-margin) nil t))
1954 (ol2 (make-overlay (- (point) start-margin) (+ pt-end end-margin) nil t))
1955 (dups (list ol1 ol2)))
1956 (overlay-put ol1 'modification-hooks '(text-clone-maintain))
1957 (when spreadp (overlay-put ol1 'text-clone-spreadp t))
1958 (when syntax (overlay-put ol1 'text-clone-syntax syntax))
1959 ;;(overlay-put ol1 'face 'underline)
1960 (overlay-put ol1 'evaporate t)
1961 (overlay-put ol1 'text-clones dups)
1963 (overlay-put ol2 'modification-hooks '(text-clone-maintain))
1964 (when spreadp (overlay-put ol2 'text-clone-spreadp t))
1965 (when syntax (overlay-put ol2 'text-clone-syntax syntax))
1966 ;;(overlay-put ol2 'face 'underline)
1967 (overlay-put ol2 'evaporate t)
1968 (overlay-put ol2 'text-clones dups)))
1970 ;;; subr.el ends here