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