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