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