1;;; subr.el --- basic lisp subroutines for Emacs
2
3;; Copyright (C) 1985, 1986, 1992, 1994, 1995, 1999, 2000, 2001, 2002, 2003,
4;;   2004, 2005, 2006, 2007 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., 51 Franklin Street, Fifth Floor,
24;; Boston, MA 02110-1301, 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.
31Each 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
40;;;; Basic Lisp macros.
41
42(defalias 'not 'null)
43
44(defmacro noreturn (form)
45  "Evaluate FORM, expecting it not to return.
46If FORM does return, signal an error."
47  `(prog1 ,form
48     (error "Form marked with `noreturn' did return")))
49
50(defmacro 1value (form)
51  "Evaluate FORM, expecting a constant return value.
52This is the global do-nothing version.  There is also `testcover-1value'
53that complains if FORM ever does return differing values."
54  form)
55
56(defmacro def-edebug-spec (symbol spec)
57  "Set the `edebug-form-spec' property of SYMBOL according to SPEC.
58Both SYMBOL and SPEC are unevaluated.  The SPEC can be 0, t, a symbol
59\(naming a function), or a list."
60  `(put (quote ,symbol) 'edebug-form-spec (quote ,spec)))
61
62(defmacro lambda (&rest cdr)
63  "Return a lambda expression.
64A call of the form (lambda ARGS DOCSTRING INTERACTIVE BODY) is
65self-quoting; the result of evaluating the lambda expression is the
66expression itself.  The lambda expression may then be treated as a
67function, i.e., stored as the function value of a symbol, passed to
68`funcall' or `mapcar', etc.
69
70ARGS should take the same form as an argument list for a `defun'.
71DOCSTRING is an optional documentation string.
72 If present, it should describe how to call the function.
73 But documentation strings are usually not useful in nameless functions.
74INTERACTIVE should be a call to the function `interactive', which see.
75It may also be omitted.
76BODY should be a list of Lisp expressions.
77
78\(fn ARGS [DOCSTRING] [INTERACTIVE] BODY)"
79  ;; Note that this definition should not use backquotes; subr.el should not
80  ;; depend on backquote.el.
81  (list 'function (cons 'lambda cdr)))
82
83(defmacro push (newelt listname)
84  "Add NEWELT to the list stored in the symbol LISTNAME.
85This is equivalent to (setq LISTNAME (cons NEWELT LISTNAME)).
86LISTNAME must be a symbol."
87  (declare (debug (form sexp)))
88  (list 'setq listname
89	(list 'cons newelt listname)))
90
91(defmacro pop (listname)
92  "Return the first element of LISTNAME's value, and remove it from the list.
93LISTNAME must be a symbol whose value is a list.
94If the value is nil, `pop' returns nil but does not actually
95change the list."
96  (declare (debug (sexp)))
97  (list 'car
98	(list 'prog1 listname
99	      (list 'setq listname (list 'cdr listname)))))
100
101(defmacro when (cond &rest body)
102  "If COND yields non-nil, do BODY, else return nil.
103When COND yields non-nil, eval BODY forms sequentially and return
104value of last one, or nil if there are none.
105
106\(fn COND BODY ...)"
107  (declare (indent 1) (debug t))
108  (list 'if cond (cons 'progn body)))
109
110(defmacro unless (cond &rest body)
111  "If COND yields nil, do BODY, else return nil.
112When COND yields nil, eval BODY forms sequentially and return
113value of last one, or nil if there are none.
114
115\(fn COND BODY ...)"
116  (declare (indent 1) (debug t))
117  (cons 'if (cons cond (cons nil body))))
118
119(defvar --dolist-tail-- nil
120  "Temporary variable used in `dolist' expansion.")
121
122(defmacro dolist (spec &rest body)
123  "Loop over a list.
124Evaluate BODY with VAR bound to each car from LIST, in turn.
125Then evaluate RESULT to get return value, default nil.
126
127\(fn (VAR LIST [RESULT]) BODY...)"
128  (declare (indent 1) (debug ((symbolp form &optional form) body)))
129  ;; It would be cleaner to create an uninterned symbol,
130  ;; but that uses a lot more space when many functions in many files
131  ;; use dolist.
132  (let ((temp '--dolist-tail--))
133    `(let ((,temp ,(nth 1 spec))
134	   ,(car spec))
135       (while ,temp
136	 (setq ,(car spec) (car ,temp))
137	 ,@body
138	 (setq ,temp (cdr ,temp)))
139       ,@(if (cdr (cdr spec))
140	     `((setq ,(car spec) nil) ,@(cdr (cdr spec)))))))
141
142(defvar --dotimes-limit-- nil
143  "Temporary variable used in `dotimes' expansion.")
144
145(defmacro dotimes (spec &rest body)
146  "Loop a certain number of times.
147Evaluate BODY with VAR bound to successive integers running from 0,
148inclusive, to COUNT, exclusive.  Then evaluate RESULT to get
149the return value (nil if RESULT is omitted).
150
151\(fn (VAR COUNT [RESULT]) BODY...)"
152  (declare (indent 1) (debug dolist))
153  ;; It would be cleaner to create an uninterned symbol,
154  ;; but that uses a lot more space when many functions in many files
155  ;; use dotimes.
156  (let ((temp '--dotimes-limit--)
157	(start 0)
158	(end (nth 1 spec)))
159    `(let ((,temp ,end)
160	   (,(car spec) ,start))
161       (while (< ,(car spec) ,temp)
162	 ,@body
163	 (setq ,(car spec) (1+ ,(car spec))))
164       ,@(cdr (cdr spec)))))
165
166(defmacro declare (&rest specs)
167  "Do not evaluate any arguments and return nil.
168Treated as a declaration when used at the right place in a
169`defmacro' form.  \(See Info anchor `(elisp)Definition of declare'.)"
170  nil)
171
172;;;; Basic Lisp functions.
173
174(defun ignore (&rest ignore)
175  "Do nothing and return nil.
176This function accepts any number of arguments, but ignores them."
177  (interactive)
178  nil)
179
180(defun error (&rest args)
181  "Signal an error, making error message by passing all args to `format'.
182In Emacs, the convention is that error messages start with a capital
183letter but *do not* end with a period.  Please follow this convention
184for the sake of consistency."
185  (while t
186    (signal 'error (list (apply 'format args)))))
187
188;; We put this here instead of in frame.el so that it's defined even on
189;; systems where frame.el isn't loaded.
190(defun frame-configuration-p (object)
191  "Return non-nil if OBJECT seems to be a frame configuration.
192Any list whose car is `frame-configuration' is assumed to be a frame
193configuration."
194  (and (consp object)
195       (eq (car object) 'frame-configuration)))
196
197(defun functionp (object)
198  "Non-nil if OBJECT is any kind of function or a special form.
199Also non-nil if OBJECT is a symbol and its function definition is
200\(recursively) a function or special form.  This does not include
201macros."
202  (or (and (symbolp object) (fboundp object)
203	   (condition-case nil
204	       (setq object (indirect-function object))
205	     (error nil))
206	   (eq (car-safe object) 'autoload)
207	   (not (car-safe (cdr-safe (cdr-safe (cdr-safe (cdr-safe object)))))))
208      (subrp object) (byte-code-function-p object)
209      (eq (car-safe object) 'lambda)))
210
211;;;; List functions.
212
213(defsubst caar (x)
214  "Return the car of the car of X."
215  (car (car x)))
216
217(defsubst cadr (x)
218  "Return the car of the cdr of X."
219  (car (cdr x)))
220
221(defsubst cdar (x)
222  "Return the cdr of the car of X."
223  (cdr (car x)))
224
225(defsubst cddr (x)
226  "Return the cdr of the cdr of X."
227  (cdr (cdr x)))
228
229(defun last (list &optional n)
230  "Return the last link of LIST.  Its car is the last element.
231If LIST is nil, return nil.
232If N is non-nil, return the Nth-to-last link of LIST.
233If N is bigger than the length of LIST, return LIST."
234  (if n
235      (let ((m 0) (p list))
236	(while (consp p)
237	  (setq m (1+ m) p (cdr p)))
238	(if (<= n 0) p
239	  (if (< n m) (nthcdr (- m n) list) list)))
240    (while (consp (cdr list))
241      (setq list (cdr list)))
242    list))
243
244(defun butlast (list &optional n)
245  "Return a copy of LIST with the last N elements removed."
246  (if (and n (<= n 0)) list
247    (nbutlast (copy-sequence list) n)))
248
249(defun nbutlast (list &optional n)
250  "Modifies LIST to remove the last N elements."
251  (let ((m (length list)))
252    (or n (setq n 1))
253    (and (< n m)
254	 (progn
255	   (if (> n 0) (setcdr (nthcdr (- (1- m) n) list) nil))
256	   list))))
257
258(defun delete-dups (list)
259  "Destructively remove `equal' duplicates from LIST.
260Store the result in LIST and return it.  LIST must be a proper list.
261Of several `equal' occurrences of an element in LIST, the first
262one is kept."
263  (let ((tail list))
264    (while tail
265      (setcdr tail (delete (car tail) (cdr tail)))
266      (setq tail (cdr tail))))
267  list)
268
269(defun number-sequence (from &optional to inc)
270  "Return a sequence of numbers from FROM to TO (both inclusive) as a list.
271INC is the increment used between numbers in the sequence and defaults to 1.
272So, the Nth element of the list is \(+ FROM \(* N INC)) where N counts from
273zero.  TO is only included if there is an N for which TO = FROM + N * INC.
274If TO is nil or numerically equal to FROM, return \(FROM).
275If INC is positive and TO is less than FROM, or INC is negative
276and TO is larger than FROM, return nil.
277If INC is zero and TO is neither nil nor numerically equal to
278FROM, signal an error.
279
280This function is primarily designed for integer arguments.
281Nevertheless, FROM, TO and INC can be integer or float.  However,
282floating point arithmetic is inexact.  For instance, depending on
283the machine, it may quite well happen that
284\(number-sequence 0.4 0.6 0.2) returns the one element list \(0.4),
285whereas \(number-sequence 0.4 0.8 0.2) returns a list with three
286elements.  Thus, if some of the arguments are floats and one wants
287to make sure that TO is included, one may have to explicitly write
288TO as \(+ FROM \(* N INC)) or use a variable whose value was
289computed with this exact expression.  Alternatively, you can,
290of course, also replace TO with a slightly larger value
291\(or a slightly more negative value if INC is negative)."
292  (if (or (not to) (= from to))
293      (list from)
294    (or inc (setq inc 1))
295    (when (zerop inc) (error "The increment can not be zero"))
296    (let (seq (n 0) (next from))
297      (if (> inc 0)
298          (while (<= next to)
299            (setq seq (cons next seq)
300                  n (1+ n)
301                  next (+ from (* n inc))))
302        (while (>= next to)
303          (setq seq (cons next seq)
304                n (1+ n)
305                next (+ from (* n inc)))))
306      (nreverse seq))))
307
308(defun copy-tree (tree &optional vecp)
309  "Make a copy of TREE.
310If TREE is a cons cell, this recursively copies both its car and its cdr.
311Contrast to `copy-sequence', which copies only along the cdrs.  With second
312argument VECP, this copies vectors as well as conses."
313  (if (consp tree)
314      (let (result)
315	(while (consp tree)
316	  (let ((newcar (car tree)))
317	    (if (or (consp (car tree)) (and vecp (vectorp (car tree))))
318		(setq newcar (copy-tree (car tree) vecp)))
319	    (push newcar result))
320	  (setq tree (cdr tree)))
321	(nconc (nreverse result) tree))
322    (if (and vecp (vectorp tree))
323	(let ((i (length (setq tree (copy-sequence tree)))))
324	  (while (>= (setq i (1- i)) 0)
325	    (aset tree i (copy-tree (aref tree i) vecp)))
326	  tree)
327      tree)))
328
329;;;; Various list-search functions.
330
331(defun assoc-default (key alist &optional test default)
332  "Find object KEY in a pseudo-alist ALIST.
333ALIST is a list of conses or objects.  Each element (or the element's car,
334if it is a cons) is compared with KEY by evaluating (TEST (car elt) KEY).
335If that is non-nil, the element matches;
336then `assoc-default' returns the element's cdr, if it is a cons,
337or DEFAULT if the element is not a cons.
338
339If no element matches, the value is nil.
340If TEST is omitted or nil, `equal' is used."
341  (let (found (tail alist) value)
342    (while (and tail (not found))
343      (let ((elt (car tail)))
344	(when (funcall (or test 'equal) (if (consp elt) (car elt) elt) key)
345	  (setq found t value (if (consp elt) (cdr elt) default))))
346      (setq tail (cdr tail)))
347    value))
348
349(make-obsolete 'assoc-ignore-case 'assoc-string)
350(defun assoc-ignore-case (key alist)
351  "Like `assoc', but ignores differences in case and text representation.
352KEY must be a string.  Upper-case and lower-case letters are treated as equal.
353Unibyte strings are converted to multibyte for comparison."
354  (assoc-string key alist t))
355
356(make-obsolete 'assoc-ignore-representation 'assoc-string)
357(defun assoc-ignore-representation (key alist)
358  "Like `assoc', but ignores differences in text representation.
359KEY must be a string.
360Unibyte strings are converted to multibyte for comparison."
361  (assoc-string key alist nil))
362
363(defun member-ignore-case (elt list)
364  "Like `member', but ignores differences in case and text representation.
365ELT must be a string.  Upper-case and lower-case letters are treated as equal.
366Unibyte strings are converted to multibyte for comparison.
367Non-strings in LIST are ignored."
368  (while (and list
369	      (not (and (stringp (car list))
370			(eq t (compare-strings elt 0 nil (car list) 0 nil t)))))
371    (setq list (cdr list)))
372  list)
373
374(defun assq-delete-all (key alist)
375  "Delete from ALIST all elements whose car is `eq' to KEY.
376Return the modified alist.
377Elements of ALIST that are not conses are ignored."
378  (while (and (consp (car alist))
379	      (eq (car (car alist)) key))
380    (setq alist (cdr alist)))
381  (let ((tail alist) tail-cdr)
382    (while (setq tail-cdr (cdr tail))
383      (if (and (consp (car tail-cdr))
384	       (eq (car (car tail-cdr)) key))
385	  (setcdr tail (cdr tail-cdr))
386	(setq tail tail-cdr))))
387  alist)
388
389(defun rassq-delete-all (value alist)
390  "Delete from ALIST all elements whose cdr is `eq' to VALUE.
391Return the modified alist.
392Elements of ALIST that are not conses are ignored."
393  (while (and (consp (car alist))
394	      (eq (cdr (car alist)) value))
395    (setq alist (cdr alist)))
396  (let ((tail alist) tail-cdr)
397    (while (setq tail-cdr (cdr tail))
398      (if (and (consp (car tail-cdr))
399	       (eq (cdr (car tail-cdr)) value))
400	  (setcdr tail (cdr tail-cdr))
401	(setq tail tail-cdr))))
402  alist)
403
404(defun remove (elt seq)
405  "Return a copy of SEQ with all occurrences of ELT removed.
406SEQ must be a list, vector, or string.  The comparison is done with `equal'."
407  (if (nlistp seq)
408      ;; If SEQ isn't a list, there's no need to copy SEQ because
409      ;; `delete' will return a new object.
410      (delete elt seq)
411    (delete elt (copy-sequence seq))))
412
413(defun remq (elt list)
414  "Return LIST with all occurrences of ELT removed.
415The comparison is done with `eq'.  Contrary to `delq', this does not use
416side-effects, and the argument LIST is not modified."
417  (if (memq elt list)
418      (delq elt (copy-sequence list))
419    list))
420
421;;;; Keymap support.
422
423(defmacro kbd (keys)
424  "Convert KEYS to the internal Emacs key representation.
425KEYS should be a string constant in the format used for
426saving keyboard macros (see `edmacro-mode')."
427  (read-kbd-macro keys))
428
429(defun undefined ()
430  (interactive)
431  (ding))
432
433;; Prevent the \{...} documentation construct
434;; from mentioning keys that run this command.
435(put 'undefined 'suppress-keymap t)
436
437(defun suppress-keymap (map &optional nodigits)
438  "Make MAP override all normally self-inserting keys to be undefined.
439Normally, as an exception, digits and minus-sign are set to make prefix args,
440but optional second arg NODIGITS non-nil treats them like other chars."
441  (define-key map [remap self-insert-command] 'undefined)
442  (or nodigits
443      (let (loop)
444	(define-key map "-" 'negative-argument)
445	;; Make plain numbers do numeric args.
446	(setq loop ?0)
447	(while (<= loop ?9)
448	  (define-key map (char-to-string loop) 'digit-argument)
449	  (setq loop (1+ loop))))))
450
451(defun define-key-after (keymap key definition &optional after)
452  "Add binding in KEYMAP for KEY => DEFINITION, right after AFTER's binding.
453This is like `define-key' except that the binding for KEY is placed
454just after the binding for the event AFTER, instead of at the beginning
455of the map.  Note that AFTER must be an event type (like KEY), NOT a command
456\(like DEFINITION).
457
458If AFTER is t or omitted, the new binding goes at the end of the keymap.
459AFTER should be a single event type--a symbol or a character, not a sequence.
460
461Bindings are always added before any inherited map.
462
463The order of bindings in a keymap matters when it is used as a menu."
464  (unless after (setq after t))
465  (or (keymapp keymap)
466      (signal 'wrong-type-argument (list 'keymapp keymap)))
467  (setq key
468	(if (<= (length key) 1) (aref key 0)
469	  (setq keymap (lookup-key keymap
470				   (apply 'vector
471					  (butlast (mapcar 'identity key)))))
472	  (aref key (1- (length key)))))
473  (let ((tail keymap) done inserted)
474    (while (and (not done) tail)
475      ;; Delete any earlier bindings for the same key.
476      (if (eq (car-safe (car (cdr tail))) key)
477	  (setcdr tail (cdr (cdr tail))))
478      ;; If we hit an included map, go down that one.
479      (if (keymapp (car tail)) (setq tail (car tail)))
480      ;; When we reach AFTER's binding, insert the new binding after.
481      ;; If we reach an inherited keymap, insert just before that.
482      ;; If we reach the end of this keymap, insert at the end.
483      (if (or (and (eq (car-safe (car tail)) after)
484		   (not (eq after t)))
485	      (eq (car (cdr tail)) 'keymap)
486	      (null (cdr tail)))
487	  (progn
488	    ;; Stop the scan only if we find a parent keymap.
489	    ;; Keep going past the inserted element
490	    ;; so we can delete any duplications that come later.
491	    (if (eq (car (cdr tail)) 'keymap)
492		(setq done t))
493	    ;; Don't insert more than once.
494	    (or inserted
495		(setcdr tail (cons (cons key definition) (cdr tail))))
496	    (setq inserted t)))
497      (setq tail (cdr tail)))))
498
499(defun map-keymap-internal (function keymap &optional sort-first)
500  "Implement `map-keymap' with sorting.
501Don't call this function; it is for internal use only."
502  (if sort-first
503      (let (list)
504	(map-keymap (lambda (a b) (push (cons a b) list))
505		    keymap)
506	(setq list (sort list
507			 (lambda (a b)
508			   (setq a (car a) b (car b))
509			   (if (integerp a)
510			       (if (integerp b) (< a b)
511				 t)
512			     (if (integerp b) t
513			       (string< a b))))))
514	(dolist (p list)
515	  (funcall function (car p) (cdr p))))
516    (map-keymap function keymap)))
517
518(put 'keyboard-translate-table 'char-table-extra-slots 0)
519
520(defun keyboard-translate (from to)
521  "Translate character FROM to TO at a low level.
522This function creates a `keyboard-translate-table' if necessary
523and then modifies one entry in it."
524  (or (char-table-p keyboard-translate-table)
525      (setq keyboard-translate-table
526	    (make-char-table 'keyboard-translate-table nil)))
527  (aset keyboard-translate-table from to))
528
529;;;; Key binding commands.
530
531(defun global-set-key (key command)
532  "Give KEY a global binding as COMMAND.
533COMMAND is the command definition to use; usually it is
534a symbol naming an interactively-callable function.
535KEY is a key sequence; noninteractively, it is a string or vector
536of characters or event types, and non-ASCII characters with codes
537above 127 (such as ISO Latin-1) can be included if you use a vector.
538
539Note that if KEY has a local binding in the current buffer,
540that local binding will continue to shadow any global binding
541that you make with this function."
542  (interactive "KSet key globally: \nCSet key %s to command: ")
543  (or (vectorp key) (stringp key)
544      (signal 'wrong-type-argument (list 'arrayp key)))
545  (define-key (current-global-map) key command))
546
547(defun local-set-key (key command)
548  "Give KEY a local binding as COMMAND.
549COMMAND is the command definition to use; usually it is
550a symbol naming an interactively-callable function.
551KEY is a key sequence; noninteractively, it is a string or vector
552of characters or event types, and non-ASCII characters with codes
553above 127 (such as ISO Latin-1) can be included if you use a vector.
554
555The binding goes in the current buffer's local map,
556which in most cases is shared with all other buffers in the same major mode."
557  (interactive "KSet key locally: \nCSet key %s locally to command: ")
558  (let ((map (current-local-map)))
559    (or map
560	(use-local-map (setq map (make-sparse-keymap))))
561    (or (vectorp key) (stringp key)
562	(signal 'wrong-type-argument (list 'arrayp key)))
563    (define-key map key command)))
564
565(defun global-unset-key (key)
566  "Remove global binding of KEY.
567KEY is a string or vector representing a sequence of keystrokes."
568  (interactive "kUnset key globally: ")
569  (global-set-key key nil))
570
571(defun local-unset-key (key)
572  "Remove local binding of KEY.
573KEY is a string or vector representing a sequence of keystrokes."
574  (interactive "kUnset key locally: ")
575  (if (current-local-map)
576      (local-set-key key nil))
577  nil)
578
579;;;; substitute-key-definition and its subroutines.
580
581(defvar key-substitution-in-progress nil
582  "Used internally by `substitute-key-definition'.")
583
584(defun substitute-key-definition (olddef newdef keymap &optional oldmap prefix)
585  "Replace OLDDEF with NEWDEF for any keys in KEYMAP now defined as OLDDEF.
586In other words, OLDDEF is replaced with NEWDEF where ever it appears.
587Alternatively, if optional fourth argument OLDMAP is specified, we redefine
588in KEYMAP as NEWDEF those keys which are defined as OLDDEF in OLDMAP.
589
590If you don't specify OLDMAP, you can usually get the same results
591in a cleaner way with command remapping, like this:
592  \(define-key KEYMAP [remap OLDDEF] NEWDEF)
593\n(fn OLDDEF NEWDEF KEYMAP &optional OLDMAP)"
594  ;; Don't document PREFIX in the doc string because we don't want to
595  ;; advertise it.  It's meant for recursive calls only.  Here's its
596  ;; meaning
597
598  ;; If optional argument PREFIX is specified, it should be a key
599  ;; prefix, a string.  Redefined bindings will then be bound to the
600  ;; original key, with PREFIX added at the front.
601  (or prefix (setq prefix ""))
602  (let* ((scan (or oldmap keymap))
603	 (prefix1 (vconcat prefix [nil]))
604	 (key-substitution-in-progress
605	  (cons scan key-substitution-in-progress)))
606    ;; Scan OLDMAP, finding each char or event-symbol that
607    ;; has any definition, and act on it with hack-key.
608    (map-keymap
609     (lambda (char defn)
610       (aset prefix1 (length prefix) char)
611       (substitute-key-definition-key defn olddef newdef prefix1 keymap))
612     scan)))
613
614(defun substitute-key-definition-key (defn olddef newdef prefix keymap)
615  (let (inner-def skipped menu-item)
616    ;; Find the actual command name within the binding.
617    (if (eq (car-safe defn) 'menu-item)
618	(setq menu-item defn defn (nth 2 defn))
619      ;; Skip past menu-prompt.
620      (while (stringp (car-safe defn))
621	(push (pop defn) skipped))
622      ;; Skip past cached key-equivalence data for menu items.
623      (if (consp (car-safe defn))
624	  (setq defn (cdr defn))))
625    (if (or (eq defn olddef)
626	    ;; Compare with equal if definition is a key sequence.
627	    ;; That is useful for operating on function-key-map.
628	    (and (or (stringp defn) (vectorp defn))
629		 (equal defn olddef)))
630	(define-key keymap prefix
631	  (if menu-item
632	      (let ((copy (copy-sequence menu-item)))
633		(setcar (nthcdr 2 copy) newdef)
634		copy)
635	    (nconc (nreverse skipped) newdef)))
636      ;; Look past a symbol that names a keymap.
637      (setq inner-def
638	    (or (indirect-function defn t) defn))
639      ;; For nested keymaps, we use `inner-def' rather than `defn' so as to
640      ;; avoid autoloading a keymap.  This is mostly done to preserve the
641      ;; original non-autoloading behavior of pre-map-keymap times.
642      (if (and (keymapp inner-def)
643	       ;; Avoid recursively scanning
644	       ;; where KEYMAP does not have a submap.
645	       (let ((elt (lookup-key keymap prefix)))
646		 (or (null elt) (natnump elt) (keymapp elt)))
647	       ;; Avoid recursively rescanning keymap being scanned.
648	       (not (memq inner-def key-substitution-in-progress)))
649	  ;; If this one isn't being scanned already, scan it now.
650	  (substitute-key-definition olddef newdef keymap inner-def prefix)))))
651
652
653;;;; The global keymap tree.
654
655;;; global-map, esc-map, and ctl-x-map have their values set up in
656;;; keymap.c; we just give them docstrings here.
657
658(defvar global-map nil
659  "Default global keymap mapping Emacs keyboard input into commands.
660The value is a keymap which is usually (but not necessarily) Emacs's
661global map.")
662
663(defvar esc-map nil
664  "Default keymap for ESC (meta) commands.
665The normal global definition of the character ESC indirects to this keymap.")
666
667(defvar ctl-x-map nil
668  "Default keymap for C-x commands.
669The normal global definition of the character C-x indirects to this keymap.")
670
671(defvar ctl-x-4-map (make-sparse-keymap)
672  "Keymap for subcommands of C-x 4.")
673(defalias 'ctl-x-4-prefix ctl-x-4-map)
674(define-key ctl-x-map "4" 'ctl-x-4-prefix)
675
676(defvar ctl-x-5-map (make-sparse-keymap)
677  "Keymap for frame commands.")
678(defalias 'ctl-x-5-prefix ctl-x-5-map)
679(define-key ctl-x-map "5" 'ctl-x-5-prefix)
680
681
682;;;; Event manipulation functions.
683
684;; The call to `read' is to ensure that the value is computed at load time
685;; and not compiled into the .elc file.  The value is negative on most
686;; machines, but not on all!
687(defconst listify-key-sequence-1 (logior 128 (read "?\\M-\\^@")))
688
689(defun listify-key-sequence (key)
690  "Convert a key sequence to a list of events."
691  (if (vectorp key)
692      (append key nil)
693    (mapcar (function (lambda (c)
694			(if (> c 127)
695			    (logxor c listify-key-sequence-1)
696			  c)))
697	    key)))
698
699(defsubst eventp (obj)
700  "True if the argument is an event object."
701  (or (and (integerp obj)
702	   ;; Filter out integers too large to be events.
703	   ;; M is the biggest modifier.
704	   (zerop (logand obj (lognot (1- (lsh ?\M-\^@ 1)))))
705	   (char-valid-p (event-basic-type obj)))
706      (and (symbolp obj)
707	   (get obj 'event-symbol-elements))
708      (and (consp obj)
709	   (symbolp (car obj))
710	   (get (car obj) 'event-symbol-elements))))
711
712(defun event-modifiers (event)
713  "Return a list of symbols representing the modifier keys in event EVENT.
714The elements of the list may include `meta', `control',
715`shift', `hyper', `super', `alt', `click', `double', `triple', `drag',
716and `down'.
717EVENT may be an event or an event type.  If EVENT is a symbol
718that has never been used in an event that has been read as input
719in the current Emacs session, then this function can return nil,
720even when EVENT actually has modifiers."
721  (let ((type event))
722    (if (listp type)
723	(setq type (car type)))
724    (if (symbolp type)
725	(cdr (get type 'event-symbol-elements))
726      (let ((list nil)
727	    (char (logand type (lognot (logior ?\M-\^@ ?\C-\^@ ?\S-\^@
728					       ?\H-\^@ ?\s-\^@ ?\A-\^@)))))
729	(if (not (zerop (logand type ?\M-\^@)))
730	    (push 'meta list))
731	(if (or (not (zerop (logand type ?\C-\^@)))
732		(< char 32))
733	    (push 'control list))
734	(if (or (not (zerop (logand type ?\S-\^@)))
735		(/= char (downcase char)))
736	    (push 'shift list))
737	(or (zerop (logand type ?\H-\^@))
738	    (push 'hyper list))
739	(or (zerop (logand type ?\s-\^@))
740	    (push 'super list))
741	(or (zerop (logand type ?\A-\^@))
742	    (push 'alt list))
743	list))))
744
745(defun event-basic-type (event)
746  "Return the basic type of the given event (all modifiers removed).
747The value is a printing character (not upper case) or a symbol.
748EVENT may be an event or an event type.  If EVENT is a symbol
749that has never been used in an event that has been read as input
750in the current Emacs session, then this function may return nil."
751  (if (consp event)
752      (setq event (car event)))
753  (if (symbolp event)
754      (car (get event 'event-symbol-elements))
755    (let* ((base (logand event (1- ?\A-\^@)))
756	   (uncontrolled (if (< base 32) (logior base 64) base)))
757      ;; There are some numbers that are invalid characters and
758      ;; cause `downcase' to get an error.
759      (condition-case ()
760	  (downcase uncontrolled)
761	(error uncontrolled)))))
762
763(defsubst mouse-movement-p (object)
764  "Return non-nil if OBJECT is a mouse movement event."
765  (eq (car-safe object) 'mouse-movement))
766
767(defsubst event-start (event)
768  "Return the starting position of EVENT.
769If EVENT is a mouse or key press or a mouse click, this returns the location
770of the event.
771If EVENT is a drag, this returns the drag's starting position.
772The return value is of the form
773   (WINDOW AREA-OR-POS (X . Y) TIMESTAMP OBJECT POS (COL . ROW)
774    IMAGE (DX . DY) (WIDTH . HEIGHT))
775The `posn-' functions access elements of such lists."
776  (if (consp event) (nth 1 event)
777    (list (selected-window) (point) '(0 . 0) 0)))
778
779(defsubst event-end (event)
780  "Return the ending location of EVENT.
781EVENT should be a click, drag, or key press event.
782If EVENT is a click event, this function is the same as `event-start'.
783The return value is of the form
784   (WINDOW AREA-OR-POS (X . Y) TIMESTAMP OBJECT POS (COL . ROW)
785    IMAGE (DX . DY) (WIDTH . HEIGHT))
786The `posn-' functions access elements of such lists."
787  (if (consp event) (nth (if (consp (nth 2 event)) 2 1) event)
788    (list (selected-window) (point) '(0 . 0) 0)))
789
790(defsubst event-click-count (event)
791  "Return the multi-click count of EVENT, a click or drag event.
792The return value is a positive integer."
793  (if (and (consp event) (integerp (nth 2 event))) (nth 2 event) 1))
794
795;;;; Extracting fields of the positions in an event.
796
797(defsubst posn-window (position)
798  "Return the window in POSITION.
799POSITION should be a list of the form returned by the `event-start'
800and `event-end' functions."
801  (nth 0 position))
802
803(defsubst posn-area (position)
804  "Return the window area recorded in POSITION, or nil for the text area.
805POSITION should be a list of the form returned by the `event-start'
806and `event-end' functions."
807  (let ((area (if (consp (nth 1 position))
808		  (car (nth 1 position))
809		(nth 1 position))))
810    (and (symbolp area) area)))
811
812(defsubst posn-point (position)
813  "Return the buffer location in POSITION.
814POSITION should be a list of the form returned by the `event-start'
815and `event-end' functions."
816  (or (nth 5 position)
817      (if (consp (nth 1 position))
818	  (car (nth 1 position))
819	(nth 1 position))))
820
821(defun posn-set-point (position)
822  "Move point to POSITION.
823Select the corresponding window as well."
824  (if (not (windowp (posn-window position)))
825      (error "Position not in text area of window"))
826  (select-window (posn-window position))
827  (if (numberp (posn-point position))
828      (goto-char (posn-point position))))
829
830(defsubst posn-x-y (position)
831  "Return the x and y coordinates in POSITION.
832POSITION should be a list of the form returned by the `event-start'
833and `event-end' functions."
834  (nth 2 position))
835
836(defun posn-col-row (position)
837  "Return the nominal column and row in POSITION, measured in characters.
838The column and row values are approximations calculated from the x
839and y coordinates in POSITION and the frame's default character width
840and height.
841For a scroll-bar event, the result column is 0, and the row
842corresponds to the vertical position of the click in the scroll bar.
843POSITION should be a list of the form returned by the `event-start'
844and `event-end' functions."
845  (let* ((pair   (posn-x-y position))
846	 (window (posn-window position))
847	 (area   (posn-area position)))
848    (cond
849     ((null window)
850      '(0 . 0))
851     ((eq area 'vertical-scroll-bar)
852      (cons 0 (scroll-bar-scale pair (1- (window-height window)))))
853     ((eq area 'horizontal-scroll-bar)
854      (cons (scroll-bar-scale pair (window-width window)) 0))
855     (t
856      (let* ((frame (if (framep window) window (window-frame window)))
857	     (x (/ (car pair) (frame-char-width frame)))
858	     (y (/ (cdr pair) (+ (frame-char-height frame)
859				 (or (frame-parameter frame 'line-spacing)
860				     default-line-spacing
861				     0)))))
862	(cons x y))))))
863
864(defun posn-actual-col-row (position)
865  "Return the actual column and row in POSITION, measured in characters.
866These are the actual row number in the window and character number in that row.
867Return nil if POSITION does not contain the actual position; in that case
868`posn-col-row' can be used to get approximate values.
869POSITION should be a list of the form returned by the `event-start'
870and `event-end' functions."
871  (nth 6 position))
872
873(defsubst posn-timestamp (position)
874  "Return the timestamp of POSITION.
875POSITION should be a list of the form returned by the `event-start'
876and `event-end' functions."
877  (nth 3 position))
878
879(defsubst posn-string (position)
880  "Return the string object of POSITION.
881Value is a cons (STRING . STRING-POS), or nil if not a string.
882POSITION should be a list of the form returned by the `event-start'
883and `event-end' functions."
884  (nth 4 position))
885
886(defsubst posn-image (position)
887  "Return the image object of POSITION.
888Value is a list (image ...), or nil if not an image.
889POSITION should be a list of the form returned by the `event-start'
890and `event-end' functions."
891  (nth 7 position))
892
893(defsubst posn-object (position)
894  "Return the object (image or string) of POSITION.
895Value is a list (image ...) for an image object, a cons cell
896\(STRING . STRING-POS) for a string object, and nil for a buffer position.
897POSITION should be a list of the form returned by the `event-start'
898and `event-end' functions."
899  (or (posn-image position) (posn-string position)))
900
901(defsubst posn-object-x-y (position)
902  "Return the x and y coordinates relative to the object of POSITION.
903POSITION should be a list of the form returned by the `event-start'
904and `event-end' functions."
905  (nth 8 position))
906
907(defsubst posn-object-width-height (position)
908  "Return the pixel width and height of the object of POSITION.
909POSITION should be a list of the form returned by the `event-start'
910and `event-end' functions."
911  (nth 9 position))
912
913
914;;;; Obsolescent names for functions.
915
916(define-obsolete-function-alias 'window-dot 'window-point "22.1")
917(define-obsolete-function-alias 'set-window-dot 'set-window-point "22.1")
918(define-obsolete-function-alias 'read-input 'read-string "22.1")
919(define-obsolete-function-alias 'show-buffer 'set-window-buffer "22.1")
920(define-obsolete-function-alias 'eval-current-buffer 'eval-buffer "22.1")
921(define-obsolete-function-alias 'string-to-int 'string-to-number "22.1")
922
923(make-obsolete 'char-bytes "now always returns 1." "20.4")
924
925(defun insert-string (&rest args)
926  "Mocklisp-compatibility insert function.
927Like the function `insert' except that any argument that is a number
928is converted into a string by expressing it in decimal."
929  (dolist (el args)
930    (insert (if (integerp el) (number-to-string el) el))))
931(make-obsolete 'insert-string 'insert "22.1")
932
933(defun makehash (&optional test) (make-hash-table :test (or test 'eql)))
934(make-obsolete 'makehash 'make-hash-table "22.1")
935
936;; Some programs still use this as a function.
937(defun baud-rate ()
938  "Return the value of the `baud-rate' variable."
939  baud-rate)
940(make-obsolete 'baud-rate "use the `baud-rate' variable instead." "before 19.15")
941
942;; These are used by VM and some old programs
943(defalias 'focus-frame 'ignore "")
944(make-obsolete 'focus-frame "it does nothing." "22.1")
945(defalias 'unfocus-frame 'ignore "")
946(make-obsolete 'unfocus-frame "it does nothing." "22.1")
947
948
949;;;; Obsolescence declarations for variables, and aliases.
950
951(make-obsolete-variable 'directory-sep-char "do not use it." "21.1")
952(make-obsolete-variable
953 'mode-line-inverse-video
954 "use the appropriate faces instead."
955 "21.1")
956(make-obsolete-variable
957 'unread-command-char
958 "use `unread-command-events' instead.  That variable is a list of events
959to reread, so it now uses nil to mean `no event', instead of -1."
960 "before 19.15")
961
962;; Lisp manual only updated in 22.1.
963(define-obsolete-variable-alias 'executing-macro 'executing-kbd-macro
964  "before 19.34")
965
966(defvaralias 'x-lost-selection-hooks 'x-lost-selection-functions)
967(make-obsolete-variable 'x-lost-selection-hooks
968			'x-lost-selection-functions "22.1")
969(defvaralias 'x-sent-selection-hooks 'x-sent-selection-functions)
970(make-obsolete-variable 'x-sent-selection-hooks
971			'x-sent-selection-functions "22.1")
972
973(defvaralias 'messages-buffer-max-lines 'message-log-max)
974
975;;;; Alternate names for functions - these are not being phased out.
976
977(defalias 'send-string 'process-send-string)
978(defalias 'send-region 'process-send-region)
979(defalias 'string= 'string-equal)
980(defalias 'string< 'string-lessp)
981(defalias 'move-marker 'set-marker)
982(defalias 'rplaca 'setcar)
983(defalias 'rplacd 'setcdr)
984(defalias 'beep 'ding) ;preserve lingual purity
985(defalias 'indent-to-column 'indent-to)
986(defalias 'backward-delete-char 'delete-backward-char)
987(defalias 'search-forward-regexp (symbol-function 're-search-forward))
988(defalias 'search-backward-regexp (symbol-function 're-search-backward))
989(defalias 'int-to-string 'number-to-string)
990(defalias 'store-match-data 'set-match-data)
991(defalias 'make-variable-frame-localizable 'make-variable-frame-local)
992;; These are the XEmacs names:
993(defalias 'point-at-eol 'line-end-position)
994(defalias 'point-at-bol 'line-beginning-position)
995
996(defalias 'user-original-login-name 'user-login-name)
997
998
999;;;; Hook manipulation functions.
1000
1001(defun make-local-hook (hook)
1002  "Make the hook HOOK local to the current buffer.
1003The return value is HOOK.
1004
1005You never need to call this function now that `add-hook' does it for you
1006if its LOCAL argument is non-nil.
1007
1008When a hook is local, its local and global values
1009work in concert: running the hook actually runs all the hook
1010functions listed in *either* the local value *or* the global value
1011of the hook variable.
1012
1013This function works by making t a member of the buffer-local value,
1014which acts as a flag to run the hook functions in the default value as
1015well.  This works for all normal hooks, but does not work for most
1016non-normal hooks yet.  We will be changing the callers of non-normal
1017hooks so that they can handle localness; this has to be done one by
1018one.
1019
1020This function does nothing if HOOK is already local in the current
1021buffer.
1022
1023Do not use `make-local-variable' to make a hook variable buffer-local."
1024  (if (local-variable-p hook)
1025      nil
1026    (or (boundp hook) (set hook nil))
1027    (make-local-variable hook)
1028    (set hook (list t)))
1029  hook)
1030(make-obsolete 'make-local-hook "not necessary any more." "21.1")
1031
1032(defun add-hook (hook function &optional append local)
1033  "Add to the value of HOOK the function FUNCTION.
1034FUNCTION is not added if already present.
1035FUNCTION is added (if necessary) at the beginning of the hook list
1036unless the optional argument APPEND is non-nil, in which case
1037FUNCTION is added at the end.
1038
1039The optional fourth argument, LOCAL, if non-nil, says to modify
1040the hook's buffer-local value rather than its default value.
1041This makes the hook buffer-local if needed, and it makes t a member
1042of the buffer-local value.  That acts as a flag to run the hook
1043functions in the default value as well as in the local value.
1044
1045HOOK should be a symbol, and FUNCTION may be any valid function.  If
1046HOOK is void, it is first set to nil.  If HOOK's value is a single
1047function, it is changed to a list of functions."
1048  (or (boundp hook) (set hook nil))
1049  (or (default-boundp hook) (set-default hook nil))
1050  (if local (unless (local-variable-if-set-p hook)
1051	      (set (make-local-variable hook) (list t)))
1052    ;; Detect the case where make-local-variable was used on a hook
1053    ;; and do what we used to do.
1054    (unless (and (consp (symbol-value hook)) (memq t (symbol-value hook)))
1055      (setq local t)))
1056  (let ((hook-value (if local (symbol-value hook) (default-value hook))))
1057    ;; If the hook value is a single function, turn it into a list.
1058    (when (or (not (listp hook-value)) (eq (car hook-value) 'lambda))
1059      (setq hook-value (list hook-value)))
1060    ;; Do the actual addition if necessary
1061    (unless (member function hook-value)
1062      (setq hook-value
1063	    (if append
1064		(append hook-value (list function))
1065	      (cons function hook-value))))
1066    ;; Set the actual variable
1067    (if local (set hook hook-value) (set-default hook hook-value))))
1068
1069(defun remove-hook (hook function &optional local)
1070  "Remove from the value of HOOK the function FUNCTION.
1071HOOK should be a symbol, and FUNCTION may be any valid function.  If
1072FUNCTION isn't the value of HOOK, or, if FUNCTION doesn't appear in the
1073list of hooks to run in HOOK, then nothing is done.  See `add-hook'.
1074
1075The optional third argument, LOCAL, if non-nil, says to modify
1076the hook's buffer-local value rather than its default value."
1077  (or (boundp hook) (set hook nil))
1078  (or (default-boundp hook) (set-default hook nil))
1079  ;; Do nothing if LOCAL is t but this hook has no local binding.
1080  (unless (and local (not (local-variable-p hook)))
1081    ;; Detect the case where make-local-variable was used on a hook
1082    ;; and do what we used to do.
1083    (when (and (local-variable-p hook)
1084	       (not (and (consp (symbol-value hook))
1085			 (memq t (symbol-value hook)))))
1086      (setq local t))
1087    (let ((hook-value (if local (symbol-value hook) (default-value hook))))
1088      ;; Remove the function, for both the list and the non-list cases.
1089      (if (or (not (listp hook-value)) (eq (car hook-value) 'lambda))
1090	  (if (equal hook-value function) (setq hook-value nil))
1091	(setq hook-value (delete function (copy-sequence hook-value))))
1092      ;; If the function is on the global hook, we need to shadow it locally
1093      ;;(when (and local (member function (default-value hook))
1094      ;;	       (not (member (cons 'not function) hook-value)))
1095      ;;  (push (cons 'not function) hook-value))
1096      ;; Set the actual variable
1097      (if (not local)
1098	  (set-default hook hook-value)
1099	(if (equal hook-value '(t))
1100	    (kill-local-variable hook)
1101	  (set hook hook-value))))))
1102
1103(defun add-to-list (list-var element &optional append compare-fn)
1104  "Add ELEMENT to the value of LIST-VAR if it isn't there yet.
1105The test for presence of ELEMENT is done with `equal',
1106or with COMPARE-FN if that's non-nil.
1107If ELEMENT is added, it is added at the beginning of the list,
1108unless the optional argument APPEND is non-nil, in which case
1109ELEMENT is added at the end.
1110
1111The return value is the new value of LIST-VAR.
1112
1113If you want to use `add-to-list' on a variable that is not defined
1114until a certain package is loaded, you should put the call to `add-to-list'
1115into a hook function that will be run only after loading the package.
1116`eval-after-load' provides one way to do this.  In some cases
1117other hooks, such as major mode hooks, can do the job."
1118  (if (cond
1119       ((null compare-fn)
1120	(member element (symbol-value list-var)))
1121       ((eq compare-fn 'eq)
1122	(memq element (symbol-value list-var)))
1123       ((eq compare-fn 'eql)
1124	(memql element (symbol-value list-var)))
1125       (t
1126	(let ((lst (symbol-value list-var)))
1127	  (while (and lst
1128		      (not (funcall compare-fn element (car lst))))
1129	    (setq lst (cdr lst)))
1130          lst)))
1131      (symbol-value list-var)
1132    (set list-var
1133	 (if append
1134	     (append (symbol-value list-var) (list element))
1135	   (cons element (symbol-value list-var))))))
1136
1137
1138(defun add-to-ordered-list (list-var element &optional order)
1139  "Add ELEMENT to the value of LIST-VAR if it isn't there yet.
1140The test for presence of ELEMENT is done with `eq'.
1141
1142The resulting list is reordered so that the elements are in the
1143order given by each element's numeric list order.  Elements
1144without a numeric list order are placed at the end of the list.
1145
1146If the third optional argument ORDER is a number (integer or
1147float), set the element's list order to the given value.  If
1148ORDER is nil or omitted, do not change the numeric order of
1149ELEMENT.  If ORDER has any other value, remove the numeric order
1150of ELEMENT if it has one.
1151
1152The list order for each element is stored in LIST-VAR's
1153`list-order' property.
1154
1155The return value is the new value of LIST-VAR."
1156  (let ((ordering (get list-var 'list-order)))
1157    (unless ordering
1158      (put list-var 'list-order
1159           (setq ordering (make-hash-table :weakness 'key :test 'eq))))
1160    (when order
1161      (puthash element (and (numberp order) order) ordering))
1162    (unless (memq element (symbol-value list-var))
1163      (set list-var (cons element (symbol-value list-var))))
1164    (set list-var (sort (symbol-value list-var)
1165			(lambda (a b)
1166			  (let ((oa (gethash a ordering))
1167				(ob (gethash b ordering)))
1168			    (if (and oa ob)
1169				(< oa ob)
1170			      oa)))))))
1171
1172(defun add-to-history (history-var newelt &optional maxelt keep-all)
1173  "Add NEWELT to the history list stored in the variable HISTORY-VAR.
1174Return the new history list.
1175If MAXELT is non-nil, it specifies the maximum length of the history.
1176Otherwise, the maximum history length is the value of the `history-length'
1177property on symbol HISTORY-VAR, if set, or the value of the `history-length'
1178variable.
1179Remove duplicates of NEWELT if `history-delete-duplicates' is non-nil.
1180If optional fourth arg KEEP-ALL is non-nil, add NEWELT to history even
1181if it is empty or a duplicate."
1182  (unless maxelt
1183    (setq maxelt (or (get history-var 'history-length)
1184		     history-length)))
1185  (let ((history (symbol-value history-var))
1186	tail)
1187    (when (and (listp history)
1188	       (or keep-all
1189		   (not (stringp newelt))
1190		   (> (length newelt) 0))
1191	       (or keep-all
1192		   (not (equal (car history) newelt))))
1193      (if history-delete-duplicates
1194	  (delete newelt history))
1195      (setq history (cons newelt history))
1196      (when (integerp maxelt)
1197	(if (= 0 maxelt)
1198	    (setq history nil)
1199	  (setq tail (nthcdr (1- maxelt) history))
1200	  (when (consp tail)
1201	    (setcdr tail nil)))))
1202    (set history-var history)))
1203
1204
1205;;;; Mode hooks.
1206
1207(defvar delay-mode-hooks nil
1208  "If non-nil, `run-mode-hooks' should delay running the hooks.")
1209(defvar delayed-mode-hooks nil
1210  "List of delayed mode hooks waiting to be run.")
1211(make-variable-buffer-local 'delayed-mode-hooks)
1212(put 'delay-mode-hooks 'permanent-local t)
1213
1214(defvar after-change-major-mode-hook nil
1215  "Normal hook run at the very end of major mode functions.")
1216
1217(defun run-mode-hooks (&rest hooks)
1218  "Run mode hooks `delayed-mode-hooks' and HOOKS, or delay HOOKS.
1219Execution is delayed if `delay-mode-hooks' is non-nil.
1220If `delay-mode-hooks' is nil, run `after-change-major-mode-hook'
1221after running the mode hooks.
1222Major mode functions should use this."
1223  (if delay-mode-hooks
1224      ;; Delaying case.
1225      (dolist (hook hooks)
1226	(push hook delayed-mode-hooks))
1227    ;; Normal case, just run the hook as before plus any delayed hooks.
1228    (setq hooks (nconc (nreverse delayed-mode-hooks) hooks))
1229    (setq delayed-mode-hooks nil)
1230    (apply 'run-hooks hooks)
1231    (run-hooks 'after-change-major-mode-hook)))
1232
1233(defmacro delay-mode-hooks (&rest body)
1234  "Execute BODY, but delay any `run-mode-hooks'.
1235These hooks will be executed by the first following call to
1236`run-mode-hooks' that occurs outside any `delayed-mode-hooks' form.
1237Only affects hooks run in the current buffer."
1238  (declare (debug t) (indent 0))
1239  `(progn
1240     (make-local-variable 'delay-mode-hooks)
1241     (let ((delay-mode-hooks t))
1242       ,@body)))
1243
1244;; PUBLIC: find if the current mode derives from another.
1245
1246(defun derived-mode-p (&rest modes)
1247  "Non-nil if the current major mode is derived from one of MODES.
1248Uses the `derived-mode-parent' property of the symbol to trace backwards."
1249  (let ((parent major-mode))
1250    (while (and (not (memq parent modes))
1251		(setq parent (get parent 'derived-mode-parent))))
1252    parent))
1253
1254;;;; Minor modes.
1255
1256;; If a minor mode is not defined with define-minor-mode,
1257;; add it here explicitly.
1258;; isearch-mode is deliberately excluded, since you should
1259;; not call it yourself.
1260(defvar minor-mode-list '(auto-save-mode auto-fill-mode abbrev-mode
1261					 overwrite-mode view-mode
1262                                         hs-minor-mode)
1263  "List of all minor mode functions.")
1264
1265(defun add-minor-mode (toggle name &optional keymap after toggle-fun)
1266  "Register a new minor mode.
1267
1268This is an XEmacs-compatibility function.  Use `define-minor-mode' instead.
1269
1270TOGGLE is a symbol which is the name of a buffer-local variable that
1271is toggled on or off to say whether the minor mode is active or not.
1272
1273NAME specifies what will appear in the mode line when the minor mode
1274is active.  NAME should be either a string starting with a space, or a
1275symbol whose value is such a string.
1276
1277Optional KEYMAP is the keymap for the minor mode that will be added
1278to `minor-mode-map-alist'.
1279
1280Optional AFTER specifies that TOGGLE should be added after AFTER
1281in `minor-mode-alist'.
1282
1283Optional TOGGLE-FUN is an interactive function to toggle the mode.
1284It defaults to (and should by convention be) TOGGLE.
1285
1286If TOGGLE has a non-nil `:included' property, an entry for the mode is
1287included in the mode-line minor mode menu.
1288If TOGGLE has a `:menu-tag', that is used for the menu item's label."
1289  (unless (memq toggle minor-mode-list)
1290    (push toggle minor-mode-list))
1291
1292  (unless toggle-fun (setq toggle-fun toggle))
1293  (unless (eq toggle-fun toggle)
1294    (put toggle :minor-mode-function toggle-fun))
1295  ;; Add the name to the minor-mode-alist.
1296  (when name
1297    (let ((existing (assq toggle minor-mode-alist)))
1298      (if existing
1299	  (setcdr existing (list name))
1300	(let ((tail minor-mode-alist) found)
1301	  (while (and tail (not found))
1302	    (if (eq after (caar tail))
1303		(setq found tail)
1304	      (setq tail (cdr tail))))
1305	  (if found
1306	      (let ((rest (cdr found)))
1307		(setcdr found nil)
1308		(nconc found (list (list toggle name)) rest))
1309	    (setq minor-mode-alist (cons (list toggle name)
1310					 minor-mode-alist)))))))
1311  ;; Add the toggle to the minor-modes menu if requested.
1312  (when (get toggle :included)
1313    (define-key mode-line-mode-menu
1314      (vector toggle)
1315      (list 'menu-item
1316	    (concat
1317	     (or (get toggle :menu-tag)
1318		 (if (stringp name) name (symbol-name toggle)))
1319	     (let ((mode-name (if (symbolp name) (symbol-value name))))
1320	       (if (and (stringp mode-name) (string-match "[^ ]+" mode-name))
1321		   (concat " (" (match-string 0 mode-name) ")"))))
1322	    toggle-fun
1323	    :button (cons :toggle toggle))))
1324
1325  ;; Add the map to the minor-mode-map-alist.
1326  (when keymap
1327    (let ((existing (assq toggle minor-mode-map-alist)))
1328      (if existing
1329	  (setcdr existing keymap)
1330	(let ((tail minor-mode-map-alist) found)
1331	  (while (and tail (not found))
1332	    (if (eq after (caar tail))
1333		(setq found tail)
1334	      (setq tail (cdr tail))))
1335	  (if found
1336	      (let ((rest (cdr found)))
1337		(setcdr found nil)
1338		(nconc found (list (cons toggle keymap)) rest))
1339	    (setq minor-mode-map-alist (cons (cons toggle keymap)
1340					     minor-mode-map-alist))))))))
1341
1342;;; Load history
1343
1344;; (defvar symbol-file-load-history-loaded nil
1345;;   "Non-nil means we have loaded the file `fns-VERSION.el' in `exec-directory'.
1346;; That file records the part of `load-history' for preloaded files,
1347;; which is cleared out before dumping to make Emacs smaller.")
1348
1349;; (defun load-symbol-file-load-history ()
1350;;   "Load the file `fns-VERSION.el' in `exec-directory' if not already done.
1351;; That file records the part of `load-history' for preloaded files,
1352;; which is cleared out before dumping to make Emacs smaller."
1353;;   (unless symbol-file-load-history-loaded
1354;;     (load (expand-file-name
1355;; 	   ;; fns-XX.YY.ZZ.el does not work on DOS filesystem.
1356;; 	   (if (eq system-type 'ms-dos)
1357;; 	       "fns.el"
1358;; 	     (format "fns-%s.el" emacs-version))
1359;; 	   exec-directory)
1360;; 	  ;; The file name fns-%s.el already has a .el extension.
1361;; 	  nil nil t)
1362;;     (setq symbol-file-load-history-loaded t)))
1363
1364(defun symbol-file (symbol &optional type)
1365  "Return the input source in which SYMBOL was defined.
1366The value is an absolute file name.
1367It can also be nil, if the definition is not associated with any file.
1368
1369If TYPE is nil, then any kind of definition is acceptable.
1370If TYPE is `defun' or `defvar', that specifies function
1371definition only or variable definition only.
1372`defface' specifies a face definition only."
1373  (if (and (or (null type) (eq type 'defun))
1374	   (symbolp symbol) (fboundp symbol)
1375	   (eq 'autoload (car-safe (symbol-function symbol))))
1376      (nth 1 (symbol-function symbol))
1377    (let ((files load-history)
1378	  file)
1379      (while files
1380	(if (if type
1381		(if (eq type 'defvar)
1382		    ;; Variables are present just as their names.
1383		    (member symbol (cdr (car files)))
1384		  ;; Other types are represented as (TYPE . NAME).
1385		  (member (cons type symbol) (cdr (car files))))
1386	      ;; We accept all types, so look for variable def
1387	      ;; and then for any other kind.
1388	      (or (member symbol (cdr (car files)))
1389		  (rassq symbol (cdr (car files)))))
1390	    (setq file (car (car files)) files nil))
1391	(setq files (cdr files)))
1392      file)))
1393
1394;;;###autoload
1395(defun locate-library (library &optional nosuffix path interactive-call)
1396  "Show the precise file name of Emacs library LIBRARY.
1397This command searches the directories in `load-path' like `\\[load-library]'
1398to find the file that `\\[load-library] RET LIBRARY RET' would load.
1399Optional second arg NOSUFFIX non-nil means don't add suffixes `load-suffixes'
1400to the specified name LIBRARY.
1401
1402If the optional third arg PATH is specified, that list of directories
1403is used instead of `load-path'.
1404
1405When called from a program, the file name is normaly returned as a
1406string.  When run interactively, the argument INTERACTIVE-CALL is t,
1407and the file name is displayed in the echo area."
1408  (interactive (list (completing-read "Locate library: "
1409				      'locate-file-completion
1410				      (cons load-path (get-load-suffixes)))
1411		     nil nil
1412		     t))
1413  (let ((file (locate-file library
1414			   (or path load-path)
1415			   (append (unless nosuffix (get-load-suffixes))
1416				   load-file-rep-suffixes))))
1417    (if interactive-call
1418	(if file
1419	    (message "Library is file %s" (abbreviate-file-name file))
1420	  (message "No library %s in search path" library)))
1421    file))
1422
1423
1424;;;; Specifying things to do later.
1425
1426(defmacro eval-at-startup (&rest body)
1427  "Make arrangements to evaluate BODY when Emacs starts up.
1428If this is run after Emacs startup, evaluate BODY immediately.
1429Always returns nil.
1430
1431This works by adding a function to `before-init-hook'.
1432That function's doc string says which file created it."
1433  `(progn
1434     (if command-line-processed
1435	 (progn . ,body)
1436       (add-hook 'before-init-hook
1437		 '(lambda () ,(concat "From " (or load-file-name "no file"))
1438		    . ,body)
1439		 t))
1440     nil))
1441
1442(defun load-history-regexp (file)
1443  "Form a regexp to find FILE in `load-history'.
1444FILE, a string, is described in the function `eval-after-load'."
1445  (if (file-name-absolute-p file)
1446      (setq file (file-truename file)))
1447  (concat (if (file-name-absolute-p file) "\\`" "\\(\\`\\|/\\)")
1448	  (regexp-quote file)
1449	  (if (file-name-extension file)
1450	      ""
1451	    ;; Note: regexp-opt can't be used here, since we need to call
1452	    ;; this before Emacs has been fully started.  2006-05-21
1453	    (concat "\\(" (mapconcat 'regexp-quote load-suffixes "\\|") "\\)?"))
1454	  "\\(" (mapconcat 'regexp-quote jka-compr-load-suffixes "\\|")
1455	  "\\)?\\'"))
1456
1457(defun load-history-filename-element (file-regexp)
1458  "Get the first elt of `load-history' whose car matches FILE-REGEXP.
1459Return nil if there isn't one."
1460  (let* ((loads load-history)
1461	 (load-elt (and loads (car loads))))
1462    (save-match-data
1463      (while (and loads
1464		  (or (null (car load-elt))
1465		      (not (string-match file-regexp (car load-elt)))))
1466	(setq loads (cdr loads)
1467	      load-elt (and loads (car loads)))))
1468    load-elt))
1469
1470(defun eval-after-load (file form)
1471  "Arrange that, if FILE is ever loaded, FORM will be run at that time.
1472If FILE is already loaded, evaluate FORM right now.
1473
1474If a matching file is loaded again, FORM will be evaluated again.
1475
1476If FILE is a string, it may be either an absolute or a relative file
1477name, and may have an extension \(e.g. \".el\") or may lack one, and
1478additionally may or may not have an extension denoting a compressed
1479format \(e.g. \".gz\").
1480
1481When FILE is absolute, this first converts it to a true name by chasing
1482symbolic links.  Only a file of this name \(see next paragraph regarding
1483extensions) will trigger the evaluation of FORM.  When FILE is relative,
1484a file whose absolute true name ends in FILE will trigger evaluation.
1485
1486When FILE lacks an extension, a file name with any extension will trigger
1487evaluation.  Otherwise, its extension must match FILE's.  A further
1488extension for a compressed format \(e.g. \".gz\") on FILE will not affect
1489this name matching.
1490
1491Alternatively, FILE can be a feature (i.e. a symbol), in which case FORM
1492is evaluated whenever that feature is `provide'd.
1493
1494Usually FILE is just a library name like \"font-lock\" or a feature name
1495like 'font-lock.
1496
1497This function makes or adds to an entry on `after-load-alist'."
1498  ;; Add this FORM into after-load-alist (regardless of whether we'll be
1499  ;; evaluating it now).
1500  (let* ((regexp-or-feature
1501	  (if (stringp file) (load-history-regexp file) file))
1502	 (elt (assoc regexp-or-feature after-load-alist)))
1503    (unless elt
1504      (setq elt (list regexp-or-feature))
1505      (push elt after-load-alist))
1506    ;; Add FORM to the element unless it's already there.
1507    (unless (member form (cdr elt))
1508      (nconc elt (list form)))
1509
1510    ;; Is there an already loaded file whose name (or `provide' name)
1511    ;; matches FILE?
1512    (if (if (stringp file)
1513	    (load-history-filename-element regexp-or-feature)
1514	  (featurep file))
1515	(eval form))))
1516
1517(defun do-after-load-evaluation (abs-file)
1518  "Evaluate all `eval-after-load' forms, if any, for ABS-FILE.
1519ABS-FILE, a string, should be the absolute true name of a file just loaded."
1520  (let ((after-load-elts after-load-alist)
1521	a-l-element file-elements file-element form)
1522    (while after-load-elts
1523      (setq a-l-element (car after-load-elts)
1524	    after-load-elts (cdr after-load-elts))
1525      (when (and (stringp (car a-l-element))
1526		 (string-match (car a-l-element) abs-file))
1527	(while (setq a-l-element (cdr a-l-element)) ; discard the file name
1528	  (setq form (car a-l-element))
1529	  (eval form))))))
1530
1531(defun eval-next-after-load (file)
1532  "Read the following input sexp, and run it whenever FILE is loaded.
1533This makes or adds to an entry on `after-load-alist'.
1534FILE should be the name of a library, with no directory name."
1535  (eval-after-load file (read)))
1536
1537;;;; Process stuff.
1538
1539;; open-network-stream is a wrapper around make-network-process.
1540
1541(when (featurep 'make-network-process)
1542  (defun open-network-stream (name buffer host service)
1543    "Open a TCP connection for a service to a host.
1544Returns a subprocess-object to represent the connection.
1545Input and output work as for subprocesses; `delete-process' closes it.
1546
1547Args are NAME BUFFER HOST SERVICE.
1548NAME is name for process.  It is modified if necessary to make it unique.
1549BUFFER is the buffer (or buffer name) to associate with the process.
1550 Process output goes at end of that buffer, unless you specify
1551 an output stream or filter function to handle the output.
1552 BUFFER may be also nil, meaning that this process is not associated
1553 with any buffer.
1554HOST is name of the host to connect to, or its IP address.
1555SERVICE is name of the service desired, or an integer specifying
1556 a port number to connect to."
1557    (make-network-process :name name :buffer buffer
1558				     :host host :service service)))
1559
1560;; compatibility
1561
1562(make-obsolete
1563 'process-kill-without-query
1564 "use `process-query-on-exit-flag' or `set-process-query-on-exit-flag'."
1565 "22.1")
1566(defun process-kill-without-query (process &optional flag)
1567  "Say no query needed if PROCESS is running when Emacs is exited.
1568Optional second argument if non-nil says to require a query.
1569Value is t if a query was formerly required."
1570  (let ((old (process-query-on-exit-flag process)))
1571    (set-process-query-on-exit-flag process nil)
1572    old))
1573
1574;; process plist management
1575
1576(defun process-get (process propname)
1577  "Return the value of PROCESS' PROPNAME property.
1578This is the last value stored with `(process-put PROCESS PROPNAME VALUE)'."
1579  (plist-get (process-plist process) propname))
1580
1581(defun process-put (process propname value)
1582  "Change PROCESS' PROPNAME property to VALUE.
1583It can be retrieved with `(process-get PROCESS PROPNAME)'."
1584  (set-process-plist process
1585		     (plist-put (process-plist process) propname value)))
1586
1587
1588;;;; Input and display facilities.
1589
1590(defvar read-quoted-char-radix 8
1591  "*Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
1592Legitimate radix values are 8, 10 and 16.")
1593
1594(custom-declare-variable-early
1595 'read-quoted-char-radix 8
1596 "*Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
1597Legitimate radix values are 8, 10 and 16."
1598 :type '(choice (const 8) (const 10) (const 16))
1599 :group 'editing-basics)
1600
1601(defun read-quoted-char (&optional prompt)
1602  "Like `read-char', but do not allow quitting.
1603Also, if the first character read is an octal digit,
1604we read any number of octal digits and return the
1605specified character code.  Any nondigit terminates the sequence.
1606If the terminator is RET, it is discarded;
1607any other terminator is used itself as input.
1608
1609The optional argument PROMPT specifies a string to use to prompt the user.
1610The variable `read-quoted-char-radix' controls which radix to use
1611for numeric input."
1612  (let ((message-log-max nil) done (first t) (code 0) char translated)
1613    (while (not done)
1614      (let ((inhibit-quit first)
1615	    ;; Don't let C-h get the help message--only help function keys.
1616	    (help-char nil)
1617	    (help-form
1618	     "Type the special character you want to use,
1619or the octal character code.
1620RET terminates the character code and is discarded;
1621any other non-digit terminates the character code and is then used as input."))
1622	(setq char (read-event (and prompt (format "%s-" prompt)) t))
1623	(if inhibit-quit (setq quit-flag nil)))
1624      ;; Translate TAB key into control-I ASCII character, and so on.
1625      ;; Note: `read-char' does it using the `ascii-character' property.
1626      ;; We could try and use read-key-sequence instead, but then C-q ESC
1627      ;; or C-q C-x might not return immediately since ESC or C-x might be
1628      ;; bound to some prefix in function-key-map or key-translation-map.
1629      (setq translated char)
1630      (let ((translation (lookup-key function-key-map (vector char))))
1631	(if (arrayp translation)
1632	    (setq translated (aref translation 0))))
1633      (cond ((null translated))
1634	    ((not (integerp translated))
1635	     (setq unread-command-events (list char)
1636		   done t))
1637	    ((/= (logand translated ?\M-\^@) 0)
1638	     ;; Turn a meta-character into a character with the 0200 bit set.
1639	     (setq code (logior (logand translated (lognot ?\M-\^@)) 128)
1640		   done t))
1641	    ((and (<= ?0 translated) (< translated (+ ?0 (min 10 read-quoted-char-radix))))
1642	     (setq code (+ (* code read-quoted-char-radix) (- translated ?0)))
1643	     (and prompt (setq prompt (message "%s %c" prompt translated))))
1644	    ((and (<= ?a (downcase translated))
1645		  (< (downcase translated) (+ ?a -10 (min 36 read-quoted-char-radix))))
1646	     (setq code (+ (* code read-quoted-char-radix)
1647			   (+ 10 (- (downcase translated) ?a))))
1648	     (and prompt (setq prompt (message "%s %c" prompt translated))))
1649	    ((and (not first) (eq translated ?\C-m))
1650	     (setq done t))
1651	    ((not first)
1652	     (setq unread-command-events (list char)
1653		   done t))
1654	    (t (setq code translated
1655		     done t)))
1656      (setq first nil))
1657    code))
1658
1659(defun read-passwd (prompt &optional confirm default)
1660  "Read a password, prompting with PROMPT, and return it.
1661If optional CONFIRM is non-nil, read the password twice to make sure.
1662Optional DEFAULT is a default password to use instead of empty input.
1663
1664This function echoes `.' for each character that the user types.
1665The user ends with RET, LFD, or ESC.  DEL or C-h rubs out.  C-u kills line.
1666C-g quits; if `inhibit-quit' was non-nil around this function,
1667then it returns nil if the user types C-g, but quit-flag remains set.
1668
1669Once the caller uses the password, it can erase the password
1670by doing (clear-string STRING)."
1671  (with-local-quit
1672    (if confirm
1673	(let (success)
1674	  (while (not success)
1675	    (let ((first (read-passwd prompt nil default))
1676		  (second (read-passwd "Confirm password: " nil default)))
1677	      (if (equal first second)
1678		  (progn
1679		    (and (arrayp second) (clear-string second))
1680		    (setq success first))
1681		(and (arrayp first) (clear-string first))
1682		(and (arrayp second) (clear-string second))
1683		(message "Password not repeated accurately; please start over")
1684		(sit-for 1))))
1685	  success)
1686      (let ((pass nil)
1687	    ;; Copy it so that add-text-properties won't modify
1688	    ;; the object that was passed in by the caller.
1689	    (prompt (copy-sequence prompt))
1690	    (c 0)
1691	    (echo-keystrokes 0)
1692	    (cursor-in-echo-area t)
1693	    (message-log-max nil))
1694	(add-text-properties 0 (length prompt)
1695			     minibuffer-prompt-properties prompt)
1696	(while (progn (message "%s%s"
1697			       prompt
1698			       (make-string (length pass) ?.))
1699		      (setq c (read-char-exclusive nil t))
1700		      (and (/= c ?\r) (/= c ?\n) (/= c ?\e)))
1701	  (clear-this-command-keys)
1702	  (if (= c ?\C-u)
1703	      (progn
1704		(and (arrayp pass) (clear-string pass))
1705		(setq pass ""))
1706	    (if (and (/= c ?\b) (/= c ?\177))
1707		(let* ((new-char (char-to-string c))
1708		       (new-pass (concat pass new-char)))
1709		  (and (arrayp pass) (clear-string pass))
1710		  (clear-string new-char)
1711		  (setq c ?\0)
1712		  (setq pass new-pass))
1713	      (if (> (length pass) 0)
1714		  (let ((new-pass (substring pass 0 -1)))
1715		    (and (arrayp pass) (clear-string pass))
1716		    (setq pass new-pass))))))
1717	(message nil)
1718	(or pass default "")))))
1719
1720;; This should be used by `call-interactively' for `n' specs.
1721(defun read-number (prompt &optional default)
1722  "Read a numeric value in the minibuffer, prompting with PROMPT.
1723DEFAULT specifies a default value to return if the user just types RET.
1724The value of DEFAULT is inserted into PROMPT."
1725  (let ((n nil))
1726    (when default
1727      (setq prompt
1728	    (if (string-match "\\(\\):[ \t]*\\'" prompt)
1729		(replace-match (format " (default %s)" default) t t prompt 1)
1730	      (replace-regexp-in-string "[ \t]*\\'"
1731					(format " (default %s) " default)
1732					prompt t t))))
1733    (while
1734	(progn
1735	  (let ((str (read-from-minibuffer prompt nil nil nil nil
1736					   (and default
1737						(number-to-string default)))))
1738	    (condition-case nil
1739		(setq n (cond
1740			 ((zerop (length str)) default)
1741			 ((stringp str) (read str))))
1742	      (error nil)))
1743	  (unless (numberp n)
1744	    (message "Please enter a number.")
1745	    (sit-for 1)
1746	    t)))
1747    n))
1748
1749(defun sit-for (seconds &optional nodisp obsolete)
1750  "Perform redisplay, then wait for SECONDS seconds or until input is available.
1751SECONDS may be a floating-point value.
1752\(On operating systems that do not support waiting for fractions of a
1753second, floating-point values are rounded down to the nearest integer.)
1754
1755If optional arg NODISP is t, don't redisplay, just wait for input.
1756Redisplay does not happen if input is available before it starts.
1757
1758Value is t if waited the full time with no input arriving, and nil otherwise.
1759
1760An obsolete, but still supported form is
1761\(sit-for SECONDS &optional MILLISECONDS NODISP)
1762where the optional arg MILLISECONDS specifies an additional wait period,
1763in milliseconds; this was useful when Emacs was built without
1764floating point support.
1765
1766\(fn SECONDS &optional NODISP)"
1767  (when (or obsolete (numberp nodisp))
1768    (setq seconds (+ seconds (* 1e-3 nodisp)))
1769    (setq nodisp obsolete))
1770  (cond
1771   (noninteractive
1772    (sleep-for seconds)
1773    t)
1774   ((input-pending-p)
1775    nil)
1776   ((<= seconds 0)
1777    (or nodisp (redisplay)))
1778   (t
1779    (or nodisp (redisplay))
1780    (let ((read (read-event nil nil seconds)))
1781      (or (null read)
1782	  (progn
1783	    ;; If last command was a prefix arg, e.g. C-u, push this event onto
1784	    ;; unread-command-events as (t . EVENT) so it will be added to
1785	    ;; this-command-keys by read-key-sequence.
1786	    (if (eq overriding-terminal-local-map universal-argument-map)
1787		(setq read (cons t read)))
1788	    (push read unread-command-events)
1789	    nil))))))
1790
1791;;; Atomic change groups.
1792
1793(defmacro atomic-change-group (&rest body)
1794  "Perform BODY as an atomic change group.
1795This means that if BODY exits abnormally,
1796all of its changes to the current buffer are undone.
1797This works regardless of whether undo is enabled in the buffer.
1798
1799This mechanism is transparent to ordinary use of undo;
1800if undo is enabled in the buffer and BODY succeeds, the
1801user can undo the change normally."
1802  (declare (indent 0) (debug t))
1803  (let ((handle (make-symbol "--change-group-handle--"))
1804	(success (make-symbol "--change-group-success--")))
1805    `(let ((,handle (prepare-change-group))
1806	   (,success nil))
1807       (unwind-protect
1808	   (progn
1809	     ;; This is inside the unwind-protect because
1810	     ;; it enables undo if that was disabled; we need
1811	     ;; to make sure that it gets disabled again.
1812	     (activate-change-group ,handle)
1813	     ,@body
1814	     (setq ,success t))
1815	 ;; Either of these functions will disable undo
1816	 ;; if it was disabled before.
1817	 (if ,success
1818	     (accept-change-group ,handle)
1819	   (cancel-change-group ,handle))))))
1820
1821(defun prepare-change-group (&optional buffer)
1822  "Return a handle for the current buffer's state, for a change group.
1823If you specify BUFFER, make a handle for BUFFER's state instead.
1824
1825Pass the handle to `activate-change-group' afterward to initiate
1826the actual changes of the change group.
1827
1828To finish the change group, call either `accept-change-group' or
1829`cancel-change-group' passing the same handle as argument.  Call
1830`accept-change-group' to accept the changes in the group as final;
1831call `cancel-change-group' to undo them all.  You should use
1832`unwind-protect' to make sure the group is always finished.  The call
1833to `activate-change-group' should be inside the `unwind-protect'.
1834Once you finish the group, don't use the handle again--don't try to
1835finish the same group twice.  For a simple example of correct use, see
1836the source code of `atomic-change-group'.
1837
1838The handle records only the specified buffer.  To make a multibuffer
1839change group, call this function once for each buffer you want to
1840cover, then use `nconc' to combine the returned values, like this:
1841
1842  (nconc (prepare-change-group buffer-1)
1843         (prepare-change-group buffer-2))
1844
1845You can then activate that multibuffer change group with a single
1846call to `activate-change-group' and finish it with a single call
1847to `accept-change-group' or `cancel-change-group'."
1848
1849  (if buffer
1850      (list (cons buffer (with-current-buffer buffer buffer-undo-list)))
1851    (list (cons (current-buffer) buffer-undo-list))))
1852
1853(defun activate-change-group (handle)
1854  "Activate a change group made with `prepare-change-group' (which see)."
1855  (dolist (elt handle)
1856    (with-current-buffer (car elt)
1857      (if (eq buffer-undo-list t)
1858	  (setq buffer-undo-list nil)))))
1859
1860(defun accept-change-group (handle)
1861  "Finish a change group made with `prepare-change-group' (which see).
1862This finishes the change group by accepting its changes as final."
1863  (dolist (elt handle)
1864    (with-current-buffer (car elt)
1865      (if (eq elt t)
1866	  (setq buffer-undo-list t)))))
1867
1868(defun cancel-change-group (handle)
1869  "Finish a change group made with `prepare-change-group' (which see).
1870This finishes the change group by reverting all of its changes."
1871  (dolist (elt handle)
1872    (with-current-buffer (car elt)
1873      (setq elt (cdr elt))
1874      (let ((old-car
1875	     (if (consp elt) (car elt)))
1876	    (old-cdr
1877	     (if (consp elt) (cdr elt))))
1878	;; Temporarily truncate the undo log at ELT.
1879	(when (consp elt)
1880	  (setcar elt nil) (setcdr elt nil))
1881	(unless (eq last-command 'undo) (undo-start))
1882	;; Make sure there's no confusion.
1883	(when (and (consp elt) (not (eq elt (last pending-undo-list))))
1884	  (error "Undoing to some unrelated state"))
1885	;; Undo it all.
1886	(while (listp pending-undo-list) (undo-more 1))
1887	;; Reset the modified cons cell ELT to its original content.
1888	(when (consp elt)
1889	  (setcar elt old-car)
1890	  (setcdr elt old-cdr))
1891	;; Revert the undo info to what it was when we grabbed the state.
1892	(setq buffer-undo-list elt)))))
1893
1894;;;; Display-related functions.
1895
1896;; For compatibility.
1897(defalias 'redraw-modeline 'force-mode-line-update)
1898
1899(defun force-mode-line-update (&optional all)
1900  "Force redisplay of the current buffer's mode line and header line.
1901With optional non-nil ALL, force redisplay of all mode lines and
1902header lines.  This function also forces recomputation of the
1903menu bar menus and the frame title."
1904  (if all (save-excursion (set-buffer (other-buffer))))
1905  (set-buffer-modified-p (buffer-modified-p)))
1906
1907(defun momentary-string-display (string pos &optional exit-char message)
1908  "Momentarily display STRING in the buffer at POS.
1909Display remains until next event is input.
1910If POS is a marker, only its position is used; its buffer is ignored.
1911Optional third arg EXIT-CHAR can be a character, event or event
1912description list.  EXIT-CHAR defaults to SPC.  If the input is
1913EXIT-CHAR it is swallowed; otherwise it is then available as
1914input (as a command if nothing else).
1915Display MESSAGE (optional fourth arg) in the echo area.
1916If MESSAGE is nil, instructions to type EXIT-CHAR are displayed there."
1917  (or exit-char (setq exit-char ?\s))
1918  (let ((inhibit-read-only t)
1919	;; Don't modify the undo list at all.
1920	(buffer-undo-list t)
1921	(modified (buffer-modified-p))
1922	(name buffer-file-name)
1923	insert-end)
1924    (unwind-protect
1925	(progn
1926	  (save-excursion
1927	    (goto-char pos)
1928	    ;; To avoid trouble with out-of-bounds position
1929	    (setq pos (point))
1930	    ;; defeat file locking... don't try this at home, kids!
1931	    (setq buffer-file-name nil)
1932	    (insert-before-markers string)
1933	    (setq insert-end (point))
1934	    ;; If the message end is off screen, recenter now.
1935	    (if (< (window-end nil t) insert-end)
1936		(recenter (/ (window-height) 2)))
1937	    ;; If that pushed message start off the screen,
1938	    ;; scroll to start it at the top of the screen.
1939	    (move-to-window-line 0)
1940	    (if (> (point) pos)
1941		(progn
1942		  (goto-char pos)
1943		  (recenter 0))))
1944	  (message (or message "Type %s to continue editing.")
1945		   (single-key-description exit-char))
1946	  (let (char)
1947	    (if (integerp exit-char)
1948		(condition-case nil
1949		    (progn
1950		      (setq char (read-char))
1951		      (or (eq char exit-char)
1952			  (setq unread-command-events (list char))))
1953		  (error
1954		   ;; `exit-char' is a character, hence it differs
1955		   ;; from char, which is an event.
1956		   (setq unread-command-events (list char))))
1957	      ;; `exit-char' can be an event, or an event description
1958	      ;; list.
1959	      (setq char (read-event))
1960	      (or (eq char exit-char)
1961		  (eq char (event-convert-list exit-char))
1962		  (setq unread-command-events (list char))))))
1963      (if insert-end
1964	  (save-excursion
1965	    (delete-region pos insert-end)))
1966      (setq buffer-file-name name)
1967      (set-buffer-modified-p modified))))
1968
1969
1970;;;; Overlay operations
1971
1972(defun copy-overlay (o)
1973  "Return a copy of overlay O."
1974  (let ((o1 (make-overlay (overlay-start o) (overlay-end o)
1975			  ;; FIXME: there's no easy way to find the
1976			  ;; insertion-type of the two markers.
1977			  (overlay-buffer o)))
1978	(props (overlay-properties o)))
1979    (while props
1980      (overlay-put o1 (pop props) (pop props)))
1981    o1))
1982
1983(defun remove-overlays (&optional beg end name val)
1984  "Clear BEG and END of overlays whose property NAME has value VAL.
1985Overlays might be moved and/or split.
1986BEG and END default respectively to the beginning and end of buffer."
1987  ;; This speeds up the loops over overlays.
1988  (unless beg (setq beg (point-min)))
1989  (unless end (setq end (point-max)))
1990  (overlay-recenter end)
1991  (if (< end beg)
1992      (setq beg (prog1 end (setq end beg))))
1993  (save-excursion
1994    (dolist (o (overlays-in beg end))
1995      (when (eq (overlay-get o name) val)
1996	;; Either push this overlay outside beg...end
1997	;; or split it to exclude beg...end
1998	;; or delete it entirely (if it is contained in beg...end).
1999	(if (< (overlay-start o) beg)
2000	    (if (> (overlay-end o) end)
2001		(progn
2002		  (move-overlay (copy-overlay o)
2003				(overlay-start o) beg)
2004		  (move-overlay o end (overlay-end o)))
2005	      (move-overlay o (overlay-start o) beg))
2006	  (if (> (overlay-end o) end)
2007	      (move-overlay o end (overlay-end o))
2008	    (delete-overlay o)))))))
2009
2010;;;; Miscellanea.
2011
2012(defvar suspend-hook nil
2013  "Normal hook run by `suspend-emacs', before suspending.")
2014
2015(defvar suspend-resume-hook nil
2016  "Normal hook run by `suspend-emacs', after Emacs is continued.")
2017
2018(defvar temp-buffer-show-hook nil
2019  "Normal hook run by `with-output-to-temp-buffer' after displaying the buffer.
2020When the hook runs, the temporary buffer is current, and the window it
2021was displayed in is selected.  This hook is normally set up with a
2022function to make the buffer read only, and find function names and
2023variable names in it, provided the major mode is still Help mode.")
2024
2025(defvar temp-buffer-setup-hook nil
2026  "Normal hook run by `with-output-to-temp-buffer' at the start.
2027When the hook runs, the temporary buffer is current.
2028This hook is normally set up with a function to put the buffer in Help
2029mode.")
2030
2031;; Avoid compiler warnings about this variable,
2032;; which has a special meaning on certain system types.
2033(defvar buffer-file-type nil
2034  "Non-nil if the visited file is a binary file.
2035This variable is meaningful on MS-DOG and Windows NT.
2036On those systems, it is automatically local in every buffer.
2037On other systems, this variable is normally always nil.")
2038
2039;; The `assert' macro from the cl package signals
2040;; `cl-assertion-failed' at runtime so always define it.
2041(put 'cl-assertion-failed 'error-conditions '(error))
2042(put 'cl-assertion-failed 'error-message "Assertion failed")
2043
2044
2045;;;; Misc. useful functions.
2046
2047(defun find-tag-default ()
2048  "Determine default tag to search for, based on text at point.
2049If there is no plausible default, return nil."
2050  (save-excursion
2051    (while (looking-at "\\sw\\|\\s_")
2052      (forward-char 1))
2053    (if (or (re-search-backward "\\sw\\|\\s_"
2054				(save-excursion (beginning-of-line) (point))
2055				t)
2056	    (re-search-forward "\\(\\sw\\|\\s_\\)+"
2057			       (save-excursion (end-of-line) (point))
2058			       t))
2059	(progn
2060	  (goto-char (match-end 0))
2061	  (condition-case nil
2062	      (buffer-substring-no-properties
2063	       (point)
2064	       (progn (forward-sexp -1)
2065		      (while (looking-at "\\s'")
2066			(forward-char 1))
2067		      (point)))
2068	    (error nil)))
2069      nil)))
2070
2071(defun play-sound (sound)
2072  "SOUND is a list of the form `(sound KEYWORD VALUE...)'.
2073The following keywords are recognized:
2074
2075  :file FILE - read sound data from FILE.  If FILE isn't an
2076absolute file name, it is searched in `data-directory'.
2077
2078  :data DATA - read sound data from string DATA.
2079
2080Exactly one of :file or :data must be present.
2081
2082  :volume VOL - set volume to VOL.  VOL must an integer in the
2083range 0..100 or a float in the range 0..1.0.  If not specified,
2084don't change the volume setting of the sound device.
2085
2086  :device DEVICE - play sound on DEVICE.  If not specified,
2087a system-dependent default device name is used."
2088  (if (fboundp 'play-sound-internal)
2089      (play-sound-internal sound)
2090    (error "This Emacs binary lacks sound support")))
2091
2092(defun shell-quote-argument (argument)
2093  "Quote an argument for passing as argument to an inferior shell."
2094  (if (or (eq system-type 'ms-dos)
2095          (and (eq system-type 'windows-nt) (w32-shell-dos-semantics)))
2096      ;; Quote using double quotes, but escape any existing quotes in
2097      ;; the argument with backslashes.
2098      (let ((result "")
2099	    (start 0)
2100	    end)
2101	(if (or (null (string-match "[^\"]" argument))
2102		(< (match-end 0) (length argument)))
2103	    (while (string-match "[\"]" argument start)
2104	      (setq end (match-beginning 0)
2105		    result (concat result (substring argument start end)
2106				   "\\" (substring argument end (1+ end)))
2107		    start (1+ end))))
2108	(concat "\"" result (substring argument start) "\""))
2109    (if (equal argument "")
2110        "''"
2111      ;; Quote everything except POSIX filename characters.
2112      ;; This should be safe enough even for really weird shells.
2113      (let ((result "") (start 0) end)
2114        (while (string-match "[^-0-9a-zA-Z_./]" argument start)
2115          (setq end (match-beginning 0)
2116                result (concat result (substring argument start end)
2117                               "\\" (substring argument end (1+ end)))
2118                start (1+ end)))
2119        (concat result (substring argument start))))))
2120
2121(defun string-or-null-p (object)
2122  "Return t if OBJECT is a string or nil.
2123Otherwise, return nil."
2124  (or (stringp object) (null object)))
2125
2126(defun booleanp (object)
2127  "Return non-nil if OBJECT is one of the two canonical boolean values: t or nil."
2128  (memq object '(nil t)))
2129
2130(defun field-at-pos (pos)
2131  "Return the field at position POS, taking stickiness etc into account"
2132  (let ((raw-field (get-char-property (field-beginning pos) 'field)))
2133    (if (eq raw-field 'boundary)
2134	(get-char-property (1- (field-end pos)) 'field)
2135      raw-field)))
2136
2137
2138;;;; Support for yanking and text properties.
2139
2140(defvar yank-excluded-properties)
2141
2142(defun remove-yank-excluded-properties (start end)
2143  "Remove `yank-excluded-properties' between START and END positions.
2144Replaces `category' properties with their defined properties."
2145  (let ((inhibit-read-only t))
2146    ;; Replace any `category' property with the properties it stands for.
2147    (unless (memq yank-excluded-properties '(t nil))
2148      (save-excursion
2149	(goto-char start)
2150	(while (< (point) end)
2151	  (let ((cat (get-text-property (point) 'category))
2152		run-end)
2153	    (setq run-end
2154		  (next-single-property-change (point) 'category nil end))
2155	    (when cat
2156	      (let (run-end2 original)
2157		(remove-list-of-text-properties (point) run-end '(category))
2158		(while (< (point) run-end)
2159		  (setq run-end2 (next-property-change (point) nil run-end))
2160		  (setq original (text-properties-at (point)))
2161		  (set-text-properties (point) run-end2 (symbol-plist cat))
2162		  (add-text-properties (point) run-end2 original)
2163		  (goto-char run-end2))))
2164	    (goto-char run-end)))))
2165    (if (eq yank-excluded-properties t)
2166	(set-text-properties start end nil)
2167      (remove-list-of-text-properties start end yank-excluded-properties))))
2168
2169(defvar yank-undo-function)
2170
2171(defun insert-for-yank (string)
2172  "Calls `insert-for-yank-1' repetitively for each `yank-handler' segment.
2173
2174See `insert-for-yank-1' for more details."
2175  (let (to)
2176    (while (setq to (next-single-property-change 0 'yank-handler string))
2177      (insert-for-yank-1 (substring string 0 to))
2178      (setq string (substring string to))))
2179  (insert-for-yank-1 string))
2180
2181(defun insert-for-yank-1 (string)
2182  "Insert STRING at point, stripping some text properties.
2183
2184Strip text properties from the inserted text according to
2185`yank-excluded-properties'.  Otherwise just like (insert STRING).
2186
2187If STRING has a non-nil `yank-handler' property on the first character,
2188the normal insert behavior is modified in various ways.  The value of
2189the yank-handler property must be a list with one to four elements
2190with the following format:  (FUNCTION PARAM NOEXCLUDE UNDO).
2191When FUNCTION is present and non-nil, it is called instead of `insert'
2192 to insert the string.  FUNCTION takes one argument--the object to insert.
2193If PARAM is present and non-nil, it replaces STRING as the object
2194 passed to FUNCTION (or `insert'); for example, if FUNCTION is
2195 `yank-rectangle', PARAM may be a list of strings to insert as a
2196 rectangle.
2197If NOEXCLUDE is present and non-nil, the normal removal of the
2198 yank-excluded-properties is not performed; instead FUNCTION is
2199 responsible for removing those properties.  This may be necessary
2200 if FUNCTION adjusts point before or after inserting the object.
2201If UNDO is present and non-nil, it is a function that will be called
2202 by `yank-pop' to undo the insertion of the current object.  It is
2203 called with two arguments, the start and end of the current region.
2204 FUNCTION may set `yank-undo-function' to override the UNDO value."
2205  (let* ((handler (and (stringp string)
2206		       (get-text-property 0 'yank-handler string)))
2207	 (param (or (nth 1 handler) string))
2208	 (opoint (point))
2209	 (inhibit-read-only inhibit-read-only)
2210	 end)
2211
2212    (setq yank-undo-function t)
2213    (if (nth 0 handler) ;; FUNCTION
2214	(funcall (car handler) param)
2215      (insert param))
2216    (setq end (point))
2217
2218    ;; Prevent read-only properties from interfering with the
2219    ;; following text property changes.
2220    (setq inhibit-read-only t)
2221
2222    ;; What should we do with `font-lock-face' properties?
2223    (if font-lock-defaults
2224	;; No, just wipe them.
2225	(remove-list-of-text-properties opoint end '(font-lock-face))
2226      ;; Convert them to `face'.
2227      (save-excursion
2228	(goto-char opoint)
2229	(while (< (point) end)
2230	  (let ((face (get-text-property (point) 'font-lock-face))
2231		run-end)
2232	    (setq run-end
2233		  (next-single-property-change (point) 'font-lock-face nil end))
2234	    (when face
2235	      (remove-text-properties (point) run-end '(font-lock-face nil))
2236	      (put-text-property (point) run-end 'face face))
2237	    (goto-char run-end)))))
2238
2239    (unless (nth 2 handler) ;; NOEXCLUDE
2240      (remove-yank-excluded-properties opoint (point)))
2241
2242    ;; If last inserted char has properties, mark them as rear-nonsticky.
2243    (if (and (> end opoint)
2244	     (text-properties-at (1- end)))
2245	(put-text-property (1- end) end 'rear-nonsticky t))
2246
2247    (if (eq yank-undo-function t)		   ;; not set by FUNCTION
2248	(setq yank-undo-function (nth 3 handler))) ;; UNDO
2249    (if (nth 4 handler)				   ;; COMMAND
2250	(setq this-command (nth 4 handler)))))
2251
2252(defun insert-buffer-substring-no-properties (buffer &optional start end)
2253  "Insert before point a substring of BUFFER, without text properties.
2254BUFFER may be a buffer or a buffer name.
2255Arguments START and END are character positions specifying the substring.
2256They default to the values of (point-min) and (point-max) in BUFFER."
2257  (let ((opoint (point)))
2258    (insert-buffer-substring buffer start end)
2259    (let ((inhibit-read-only t))
2260      (set-text-properties opoint (point) nil))))
2261
2262(defun insert-buffer-substring-as-yank (buffer &optional start end)
2263  "Insert before point a part of BUFFER, stripping some text properties.
2264BUFFER may be a buffer or a buffer name.
2265Arguments START and END are character positions specifying the substring.
2266They default to the values of (point-min) and (point-max) in BUFFER.
2267Strip text properties from the inserted text according to
2268`yank-excluded-properties'."
2269  ;; Since the buffer text should not normally have yank-handler properties,
2270  ;; there is no need to handle them here.
2271  (let ((opoint (point)))
2272    (insert-buffer-substring buffer start end)
2273    (remove-yank-excluded-properties opoint (point))))
2274
2275
2276;;;; Synchronous shell commands.
2277
2278(defun start-process-shell-command (name buffer &rest args)
2279  "Start a program in a subprocess.  Return the process object for it.
2280NAME is name for process.  It is modified if necessary to make it unique.
2281BUFFER is the buffer (or buffer name) to associate with the process.
2282 Process output goes at end of that buffer, unless you specify
2283 an output stream or filter function to handle the output.
2284 BUFFER may be also nil, meaning that this process is not associated
2285 with any buffer
2286COMMAND is the name of a shell command.
2287Remaining arguments are the arguments for the command; they are all
2288spliced together with blanks separating between each two of them, before
2289passing the command to the shell.
2290Wildcards and redirection are handled as usual in the shell.
2291
2292\(fn NAME BUFFER COMMAND &rest COMMAND-ARGS)"
2293  (cond
2294   ((eq system-type 'vax-vms)
2295    (apply 'start-process name buffer args))
2296   ;; We used to use `exec' to replace the shell with the command,
2297   ;; but that failed to handle (...) and semicolon, etc.
2298   (t
2299    (start-process name buffer shell-file-name shell-command-switch
2300		   (mapconcat 'identity args " ")))))
2301
2302(defun call-process-shell-command (command &optional infile buffer display
2303					   &rest args)
2304  "Execute the shell command COMMAND synchronously in separate process.
2305The remaining arguments are optional.
2306The program's input comes from file INFILE (nil means `/dev/null').
2307Insert output in BUFFER before point; t means current buffer;
2308 nil for BUFFER means discard it; 0 means discard and don't wait.
2309BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,
2310REAL-BUFFER says what to do with standard output, as above,
2311while STDERR-FILE says what to do with standard error in the child.
2312STDERR-FILE may be nil (discard standard error output),
2313t (mix it with ordinary output), or a file name string.
2314
2315Fourth arg DISPLAY non-nil means redisplay buffer as output is inserted.
2316Remaining arguments are strings passed as additional arguments for COMMAND.
2317Wildcards and redirection are handled as usual in the shell.
2318
2319If BUFFER is 0, `call-process-shell-command' returns immediately with value nil.
2320Otherwise it waits for COMMAND to terminate and returns a numeric exit
2321status or a signal description string.
2322If you quit, the process is killed with SIGINT, or SIGKILL if you quit again."
2323  (cond
2324   ((eq system-type 'vax-vms)
2325    (apply 'call-process command infile buffer display args))
2326   ;; We used to use `exec' to replace the shell with the command,
2327   ;; but that failed to handle (...) and semicolon, etc.
2328   (t
2329    (call-process shell-file-name
2330		  infile buffer display
2331		  shell-command-switch
2332		  (mapconcat 'identity (cons command args) " ")))))
2333
2334;;;; Lisp macros to do various things temporarily.
2335
2336(defmacro with-current-buffer (buffer &rest body)
2337  "Execute the forms in BODY with BUFFER temporarily current.
2338BUFFER can be a buffer or a buffer name.
2339The value returned is the value of the last form in BODY.
2340See also `with-temp-buffer'."
2341  (declare (indent 1) (debug t))
2342  `(save-current-buffer
2343     (set-buffer ,buffer)
2344     ,@body))
2345
2346(defmacro with-selected-window (window &rest body)
2347  "Execute the forms in BODY with WINDOW as the selected window.
2348The value returned is the value of the last form in BODY.
2349
2350This macro saves and restores the current buffer, since otherwise
2351its normal operation could potentially make a different
2352buffer current.  It does not alter the buffer list ordering.
2353
2354This macro saves and restores the selected window, as well as
2355the selected window in each frame.  If the previously selected
2356window of some frame is no longer live at the end of BODY, that
2357frame's selected window is left alone.  If the selected window is
2358no longer live, then whatever window is selected at the end of
2359BODY remains selected.
2360See also `with-temp-buffer'."
2361  (declare (indent 1) (debug t))
2362  ;; Most of this code is a copy of save-selected-window.
2363  `(let ((save-selected-window-window (selected-window))
2364	 ;; It is necessary to save all of these, because calling
2365	 ;; select-window changes frame-selected-window for whatever
2366	 ;; frame that window is in.
2367	 (save-selected-window-alist
2368	  (mapcar (lambda (frame) (list frame (frame-selected-window frame)))
2369		  (frame-list))))
2370     (save-current-buffer
2371       (unwind-protect
2372	   (progn (select-window ,window 'norecord)
2373		  ,@body)
2374	 (dolist (elt save-selected-window-alist)
2375	   (and (frame-live-p (car elt))
2376		(window-live-p (cadr elt))
2377		(set-frame-selected-window (car elt) (cadr elt))))
2378	 (if (window-live-p save-selected-window-window)
2379	     (select-window save-selected-window-window 'norecord))))))
2380
2381(defmacro with-temp-file (file &rest body)
2382  "Create a new buffer, evaluate BODY there, and write the buffer to FILE.
2383The value returned is the value of the last form in BODY.
2384See also `with-temp-buffer'."
2385  (declare (debug t))
2386  (let ((temp-file (make-symbol "temp-file"))
2387	(temp-buffer (make-symbol "temp-buffer")))
2388    `(let ((,temp-file ,file)
2389	   (,temp-buffer
2390	    (get-buffer-create (generate-new-buffer-name " *temp file*"))))
2391       (unwind-protect
2392	   (prog1
2393	       (with-current-buffer ,temp-buffer
2394		 ,@body)
2395	     (with-current-buffer ,temp-buffer
2396	       (widen)
2397	       (write-region (point-min) (point-max) ,temp-file nil 0)))
2398	 (and (buffer-name ,temp-buffer)
2399	      (kill-buffer ,temp-buffer))))))
2400
2401(defmacro with-temp-message (message &rest body)
2402  "Display MESSAGE temporarily if non-nil while BODY is evaluated.
2403The original message is restored to the echo area after BODY has finished.
2404The value returned is the value of the last form in BODY.
2405MESSAGE is written to the message log buffer if `message-log-max' is non-nil.
2406If MESSAGE is nil, the echo area and message log buffer are unchanged.
2407Use a MESSAGE of \"\" to temporarily clear the echo area."
2408  (declare (debug t))
2409  (let ((current-message (make-symbol "current-message"))
2410	(temp-message (make-symbol "with-temp-message")))
2411    `(let ((,temp-message ,message)
2412	   (,current-message))
2413       (unwind-protect
2414	   (progn
2415	     (when ,temp-message
2416	       (setq ,current-message (current-message))
2417	       (message "%s" ,temp-message))
2418	     ,@body)
2419	 (and ,temp-message
2420	      (if ,current-message
2421		  (message "%s" ,current-message)
2422		(message nil)))))))
2423
2424(defmacro with-temp-buffer (&rest body)
2425  "Create a temporary buffer, and evaluate BODY there like `progn'.
2426See also `with-temp-file' and `with-output-to-string'."
2427  (declare (indent 0) (debug t))
2428  (let ((temp-buffer (make-symbol "temp-buffer")))
2429    `(let ((,temp-buffer (generate-new-buffer " *temp*")))
2430       (unwind-protect
2431	   (with-current-buffer ,temp-buffer
2432	     ,@body)
2433	 (and (buffer-name ,temp-buffer)
2434	      (kill-buffer ,temp-buffer))))))
2435
2436(defmacro with-output-to-string (&rest body)
2437  "Execute BODY, return the text it sent to `standard-output', as a string."
2438  (declare (indent 0) (debug t))
2439  `(let ((standard-output
2440	  (get-buffer-create (generate-new-buffer-name " *string-output*"))))
2441     (let ((standard-output standard-output))
2442       ,@body)
2443     (with-current-buffer standard-output
2444       (prog1
2445	   (buffer-string)
2446	 (kill-buffer nil)))))
2447
2448(defmacro with-local-quit (&rest body)
2449  "Execute BODY, allowing quits to terminate BODY but not escape further.
2450When a quit terminates BODY, `with-local-quit' returns nil but
2451requests another quit.  That quit will be processed as soon as quitting
2452is allowed once again.  (Immediately, if `inhibit-quit' is nil.)"
2453  (declare (debug t) (indent 0))
2454  `(condition-case nil
2455       (let ((inhibit-quit nil))
2456	 ,@body)
2457     (quit (setq quit-flag t)
2458	   ;; This call is to give a chance to handle quit-flag
2459	   ;; in case inhibit-quit is nil.
2460	   ;; Without this, it will not be handled until the next function
2461	   ;; call, and that might allow it to exit thru a condition-case
2462	   ;; that intends to handle the quit signal next time.
2463	   (eval '(ignore nil)))))
2464
2465(defmacro while-no-input (&rest body)
2466  "Execute BODY only as long as there's no pending input.
2467If input arrives, that ends the execution of BODY,
2468and `while-no-input' returns t.  Quitting makes it return nil.
2469If BODY finishes, `while-no-input' returns whatever value BODY produced."
2470  (declare (debug t) (indent 0))
2471  (let ((catch-sym (make-symbol "input")))
2472    `(with-local-quit
2473       (catch ',catch-sym
2474	 (let ((throw-on-input ',catch-sym))
2475	   (or (input-pending-p)
2476	       ,@body))))))
2477
2478(defmacro combine-after-change-calls (&rest body)
2479  "Execute BODY, but don't call the after-change functions till the end.
2480If BODY makes changes in the buffer, they are recorded
2481and the functions on `after-change-functions' are called several times
2482when BODY is finished.
2483The return value is the value of the last form in BODY.
2484
2485If `before-change-functions' is non-nil, then calls to the after-change
2486functions can't be deferred, so in that case this macro has no effect.
2487
2488Do not alter `after-change-functions' or `before-change-functions'
2489in BODY."
2490  (declare (indent 0) (debug t))
2491  `(unwind-protect
2492       (let ((combine-after-change-calls t))
2493	 . ,body)
2494     (combine-after-change-execute)))
2495
2496(defmacro with-case-table (table &rest body)
2497  "Execute the forms in BODY with TABLE as the current case table.
2498The value returned is the value of the last form in BODY."
2499  (declare (indent 1) (debug t))
2500  (let ((old-case-table (make-symbol "table"))
2501	(old-buffer (make-symbol "buffer")))
2502    `(let ((,old-case-table (current-case-table))
2503	   (,old-buffer (current-buffer)))
2504       (unwind-protect
2505	   (progn (set-case-table ,table)
2506		  ,@body)
2507	 (with-current-buffer ,old-buffer
2508	   (set-case-table ,old-case-table))))))
2509
2510;;;; Constructing completion tables.
2511
2512(defmacro dynamic-completion-table (fun)
2513  "Use function FUN as a dynamic completion table.
2514FUN is called with one argument, the string for which completion is required,
2515and it should return an alist containing all the intended possible
2516completions.  This alist may be a full list of possible completions so that FUN
2517can ignore the value of its argument.  If completion is performed in the
2518minibuffer, FUN will be called in the buffer from which the minibuffer was
2519entered.
2520
2521The result of the `dynamic-completion-table' form is a function
2522that can be used as the ALIST argument to `try-completion' and
2523`all-completion'.  See Info node `(elisp)Programmed Completion'."
2524  (declare (debug (lambda-expr)))
2525  (let ((win (make-symbol "window"))
2526        (string (make-symbol "string"))
2527        (predicate (make-symbol "predicate"))
2528        (mode (make-symbol "mode")))
2529    `(lambda (,string ,predicate ,mode)
2530       (with-current-buffer (let ((,win (minibuffer-selected-window)))
2531                              (if (window-live-p ,win) (window-buffer ,win)
2532                                (current-buffer)))
2533         (cond
2534          ((eq ,mode t) (all-completions ,string (,fun ,string) ,predicate))
2535          ((not ,mode) (try-completion ,string (,fun ,string) ,predicate))
2536          (t (test-completion ,string (,fun ,string) ,predicate)))))))
2537
2538(defmacro lazy-completion-table (var fun)
2539  ;; We used to have `&rest args' where `args' were evaluated late (at the
2540  ;; time of the call to `fun'), which was counter intuitive.  But to get
2541  ;; them to be evaluated early, we have to either use lexical-let (which is
2542  ;; not available in subr.el) or use `(lambda (,str) ...) which prevents the use
2543  ;; of lexical-let in the callers.
2544  ;; So we just removed the argument.  Callers can then simply use either of:
2545  ;;   (lazy-completion-table var (lambda () (fun x y)))
2546  ;; or
2547  ;;   (lazy-completion-table var `(lambda () (fun ',x ',y)))
2548  ;; or
2549  ;;   (lexical-let ((x x)) ((y y))
2550  ;;     (lazy-completion-table var (lambda () (fun x y))))
2551  ;; depending on the behavior they want.
2552  "Initialize variable VAR as a lazy completion table.
2553If the completion table VAR is used for the first time (e.g., by passing VAR
2554as an argument to `try-completion'), the function FUN is called with no
2555arguments.  FUN must return the completion table that will be stored in VAR.
2556If completion is requested in the minibuffer, FUN will be called in the buffer
2557from which the minibuffer was entered.  The return value of
2558`lazy-completion-table' must be used to initialize the value of VAR.
2559
2560You should give VAR a non-nil `risky-local-variable' property."
2561  (declare (debug (symbol lambda-expr)))
2562  (let ((str (make-symbol "string")))
2563    `(dynamic-completion-table
2564      (lambda (,str)
2565        (when (functionp ,var)
2566          (setq ,var (,fun)))
2567        ,var))))
2568
2569(defmacro complete-in-turn (a b)
2570  "Create a completion table that first tries completion in A and then in B.
2571A and B should not be costly (or side-effecting) expressions."
2572  (declare (debug (def-form def-form)))
2573  `(lambda (string predicate mode)
2574     (cond
2575      ((eq mode t)
2576       (or (all-completions string ,a predicate)
2577	   (all-completions string ,b predicate)))
2578      ((eq mode nil)
2579       (or (try-completion string ,a predicate)
2580	   (try-completion string ,b predicate)))
2581      (t
2582       (or (test-completion string ,a predicate)
2583	   (test-completion string ,b predicate))))))
2584
2585;;; Matching and match data.
2586
2587(defvar save-match-data-internal)
2588
2589;; We use save-match-data-internal as the local variable because
2590;; that works ok in practice (people should not use that variable elsewhere).
2591;; We used to use an uninterned symbol; the compiler handles that properly
2592;; now, but it generates slower code.
2593(defmacro save-match-data (&rest body)
2594  "Execute the BODY forms, restoring the global value of the match data.
2595The value returned is the value of the last form in BODY."
2596  ;; It is better not to use backquote here,
2597  ;; because that makes a bootstrapping problem
2598  ;; if you need to recompile all the Lisp files using interpreted code.
2599  (declare (indent 0) (debug t))
2600  (list 'let
2601	'((save-match-data-internal (match-data)))
2602	(list 'unwind-protect
2603	      (cons 'progn body)
2604	      ;; It is safe to free (evaporate) markers immediately here,
2605	      ;; as Lisp programs should not copy from save-match-data-internal.
2606	      '(set-match-data save-match-data-internal 'evaporate))))
2607
2608(defun match-string (num &optional string)
2609  "Return string of text matched by last search.
2610NUM specifies which parenthesized expression in the last regexp.
2611 Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
2612Zero means the entire text matched by the whole regexp or whole string.
2613STRING should be given if the last search was by `string-match' on STRING."
2614  (if (match-beginning num)
2615      (if string
2616	  (substring string (match-beginning num) (match-end num))
2617	(buffer-substring (match-beginning num) (match-end num)))))
2618
2619(defun match-string-no-properties (num &optional string)
2620  "Return string of text matched by last search, without text properties.
2621NUM specifies which parenthesized expression in the last regexp.
2622 Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
2623Zero means the entire text matched by the whole regexp or whole string.
2624STRING should be given if the last search was by `string-match' on STRING."
2625  (if (match-beginning num)
2626      (if string
2627	  (substring-no-properties string (match-beginning num)
2628				   (match-end num))
2629	(buffer-substring-no-properties (match-beginning num)
2630					(match-end num)))))
2631
2632(defun looking-back (regexp &optional limit greedy)
2633  "Return non-nil if text before point matches regular expression REGEXP.
2634Like `looking-at' except matches before point, and is slower.
2635LIMIT if non-nil speeds up the search by specifying a minimum
2636starting position, to avoid checking matches that would start
2637before LIMIT.
2638
2639If GREEDY is non-nil, extend the match backwards as far as possible,
2640stopping when a single additional previous character cannot be part
2641of a match for REGEXP."
2642  (let ((start (point))
2643	(pos
2644	 (save-excursion
2645	   (and (re-search-backward (concat "\\(?:" regexp "\\)\\=") limit t)
2646		(point)))))
2647    (if (and greedy pos)
2648	(save-restriction
2649	  (narrow-to-region (point-min) start)
2650	  (while (and (> pos (point-min))
2651		      (save-excursion
2652			(goto-char pos)
2653			(backward-char 1)
2654			(looking-at (concat "\\(?:"  regexp "\\)\\'"))))
2655	    (setq pos (1- pos)))
2656	  (save-excursion
2657	    (goto-char pos)
2658	    (looking-at (concat "\\(?:"  regexp "\\)\\'")))))
2659    (not (null pos))))
2660
2661(defun subregexp-context-p (regexp pos &optional start)
2662  "Return non-nil if POS is in a normal subregexp context in REGEXP.
2663A subregexp context is one where a sub-regexp can appear.
2664A non-subregexp context is for example within brackets, or within a
2665repetition bounds operator `\\=\\{...\\}', or right after a `\\'.
2666If START is non-nil, it should be a position in REGEXP, smaller
2667than POS, and known to be in a subregexp context."
2668  ;; Here's one possible implementation, with the great benefit that it
2669  ;; reuses the regexp-matcher's own parser, so it understands all the
2670  ;; details of the syntax.  A disadvantage is that it needs to match the
2671  ;; error string.
2672  (condition-case err
2673      (progn
2674        (string-match (substring regexp (or start 0) pos) "")
2675        t)
2676    (invalid-regexp
2677     (not (member (cadr err) '("Unmatched [ or [^"
2678                               "Unmatched \\{"
2679                               "Trailing backslash")))))
2680  ;; An alternative implementation:
2681  ;; (defconst re-context-re
2682  ;;   (let* ((harmless-ch "[^\\[]")
2683  ;;          (harmless-esc "\\\\[^{]")
2684  ;;          (class-harmless-ch "[^][]")
2685  ;;          (class-lb-harmless "[^]:]")
2686  ;;          (class-lb-colon-maybe-charclass ":\\([a-z]+:]\\)?")
2687  ;;          (class-lb (concat "\\[\\(" class-lb-harmless
2688  ;;                            "\\|" class-lb-colon-maybe-charclass "\\)"))
2689  ;;          (class
2690  ;;           (concat "\\[^?]?"
2691  ;;                   "\\(" class-harmless-ch
2692  ;;                   "\\|" class-lb "\\)*"
2693  ;;                   "\\[?]"))     ; special handling for bare [ at end of re
2694  ;;          (braces "\\\\{[0-9,]+\\\\}"))
2695  ;;     (concat "\\`\\(" harmless-ch "\\|" harmless-esc
2696  ;;             "\\|" class "\\|" braces "\\)*\\'"))
2697  ;;   "Matches any prefix that corresponds to a normal subregexp context.")
2698  ;; (string-match re-context-re (substring regexp (or start 0) pos))
2699  )
2700
2701;;;; split-string
2702
2703(defconst split-string-default-separators "[ \f\t\n\r\v]+"
2704  "The default value of separators for `split-string'.
2705
2706A regexp matching strings of whitespace.  May be locale-dependent
2707\(as yet unimplemented).  Should not match non-breaking spaces.
2708
2709Warning: binding this to a different value and using it as default is
2710likely to have undesired semantics.")
2711
2712;; The specification says that if both SEPARATORS and OMIT-NULLS are
2713;; defaulted, OMIT-NULLS should be treated as t.  Simplifying the logical
2714;; expression leads to the equivalent implementation that if SEPARATORS
2715;; is defaulted, OMIT-NULLS is treated as t.
2716(defun split-string (string &optional separators omit-nulls)
2717  "Split STRING into substrings bounded by matches for SEPARATORS.
2718
2719The beginning and end of STRING, and each match for SEPARATORS, are
2720splitting points.  The substrings matching SEPARATORS are removed, and
2721the substrings between the splitting points are collected as a list,
2722which is returned.
2723
2724If SEPARATORS is non-nil, it should be a regular expression matching text
2725which separates, but is not part of, the substrings.  If nil it defaults to
2726`split-string-default-separators', normally \"[ \\f\\t\\n\\r\\v]+\", and
2727OMIT-NULLS is forced to t.
2728
2729If OMIT-NULLS is t, zero-length substrings are omitted from the list \(so
2730that for the default value of SEPARATORS leading and trailing whitespace
2731are effectively trimmed).  If nil, all zero-length substrings are retained,
2732which correctly parses CSV format, for example.
2733
2734Note that the effect of `(split-string STRING)' is the same as
2735`(split-string STRING split-string-default-separators t)'.  In the rare
2736case that you wish to retain zero-length substrings when splitting on
2737whitespace, use `(split-string STRING split-string-default-separators)'.
2738
2739Modifies the match data; use `save-match-data' if necessary."
2740  (let ((keep-nulls (not (if separators omit-nulls t)))
2741	(rexp (or separators split-string-default-separators))
2742	(start 0)
2743	notfirst
2744	(list nil))
2745    (while (and (string-match rexp string
2746			      (if (and notfirst
2747				       (= start (match-beginning 0))
2748				       (< start (length string)))
2749				  (1+ start) start))
2750		(< start (length string)))
2751      (setq notfirst t)
2752      (if (or keep-nulls (< start (match-beginning 0)))
2753	  (setq list
2754		(cons (substring string start (match-beginning 0))
2755		      list)))
2756      (setq start (match-end 0)))
2757    (if (or keep-nulls (< start (length string)))
2758	(setq list
2759	      (cons (substring string start)
2760		    list)))
2761    (nreverse list)))
2762
2763;;;; Replacement in strings.
2764
2765(defun subst-char-in-string (fromchar tochar string &optional inplace)
2766  "Replace FROMCHAR with TOCHAR in STRING each time it occurs.
2767Unless optional argument INPLACE is non-nil, return a new string."
2768  (let ((i (length string))
2769	(newstr (if inplace string (copy-sequence string))))
2770    (while (> i 0)
2771      (setq i (1- i))
2772      (if (eq (aref newstr i) fromchar)
2773	  (aset newstr i tochar)))
2774    newstr))
2775
2776(defun replace-regexp-in-string (regexp rep string &optional
2777					fixedcase literal subexp start)
2778  "Replace all matches for REGEXP with REP in STRING.
2779
2780Return a new string containing the replacements.
2781
2782Optional arguments FIXEDCASE, LITERAL and SUBEXP are like the
2783arguments with the same names of function `replace-match'.  If START
2784is non-nil, start replacements at that index in STRING.
2785
2786REP is either a string used as the NEWTEXT arg of `replace-match' or a
2787function.  If it is a function, it is called with the actual text of each
2788match, and its value is used as the replacement text.  When REP is called,
2789the match-data are the result of matching REGEXP against a substring
2790of STRING.
2791
2792To replace only the first match (if any), make REGEXP match up to \\'
2793and replace a sub-expression, e.g.
2794  (replace-regexp-in-string \"\\\\(foo\\\\).*\\\\'\" \"bar\" \" foo foo\" nil nil 1)
2795    => \" bar foo\"
2796"
2797
2798  ;; To avoid excessive consing from multiple matches in long strings,
2799  ;; don't just call `replace-match' continually.  Walk down the
2800  ;; string looking for matches of REGEXP and building up a (reversed)
2801  ;; list MATCHES.  This comprises segments of STRING which weren't
2802  ;; matched interspersed with replacements for segments that were.
2803  ;; [For a `large' number of replacements it's more efficient to
2804  ;; operate in a temporary buffer; we can't tell from the function's
2805  ;; args whether to choose the buffer-based implementation, though it
2806  ;; might be reasonable to do so for long enough STRING.]
2807  (let ((l (length string))
2808	(start (or start 0))
2809	matches str mb me)
2810    (save-match-data
2811      (while (and (< start l) (string-match regexp string start))
2812	(setq mb (match-beginning 0)
2813	      me (match-end 0))
2814	;; If we matched the empty string, make sure we advance by one char
2815	(when (= me mb) (setq me (min l (1+ mb))))
2816	;; Generate a replacement for the matched substring.
2817	;; Operate only on the substring to minimize string consing.
2818	;; Set up match data for the substring for replacement;
2819	;; presumably this is likely to be faster than munging the
2820	;; match data directly in Lisp.
2821	(string-match regexp (setq str (substring string mb me)))
2822	(setq matches
2823	      (cons (replace-match (if (stringp rep)
2824				       rep
2825				     (funcall rep (match-string 0 str)))
2826				   fixedcase literal str subexp)
2827		    (cons (substring string start mb) ; unmatched prefix
2828			  matches)))
2829	(setq start me))
2830      ;; Reconstruct a string from the pieces.
2831      (setq matches (cons (substring string start l) matches)) ; leftover
2832      (apply #'concat (nreverse matches)))))
2833
2834;;;; invisibility specs
2835
2836(defun add-to-invisibility-spec (element)
2837  "Add ELEMENT to `buffer-invisibility-spec'.
2838See documentation for `buffer-invisibility-spec' for the kind of elements
2839that can be added."
2840  (if (eq buffer-invisibility-spec t)
2841      (setq buffer-invisibility-spec (list t)))
2842  (setq buffer-invisibility-spec
2843	(cons element buffer-invisibility-spec)))
2844
2845(defun remove-from-invisibility-spec (element)
2846  "Remove ELEMENT from `buffer-invisibility-spec'."
2847  (if (consp buffer-invisibility-spec)
2848      (setq buffer-invisibility-spec
2849	    (delete element buffer-invisibility-spec))))
2850
2851;;;; Syntax tables.
2852
2853(defmacro with-syntax-table (table &rest body)
2854  "Evaluate BODY with syntax table of current buffer set to TABLE.
2855The syntax table of the current buffer is saved, BODY is evaluated, and the
2856saved table is restored, even in case of an abnormal exit.
2857Value is what BODY returns."
2858  (declare (debug t))
2859  (let ((old-table (make-symbol "table"))
2860	(old-buffer (make-symbol "buffer")))
2861    `(let ((,old-table (syntax-table))
2862	   (,old-buffer (current-buffer)))
2863       (unwind-protect
2864	   (progn
2865	     (set-syntax-table ,table)
2866	     ,@body)
2867	 (save-current-buffer
2868	   (set-buffer ,old-buffer)
2869	   (set-syntax-table ,old-table))))))
2870
2871(defun make-syntax-table (&optional oldtable)
2872  "Return a new syntax table.
2873Create a syntax table which inherits from OLDTABLE (if non-nil) or
2874from `standard-syntax-table' otherwise."
2875  (let ((table (make-char-table 'syntax-table nil)))
2876    (set-char-table-parent table (or oldtable (standard-syntax-table)))
2877    table))
2878
2879(defun syntax-after (pos)
2880  "Return the raw syntax of the char after POS.
2881If POS is outside the buffer's accessible portion, return nil."
2882  (unless (or (< pos (point-min)) (>= pos (point-max)))
2883    (let ((st (if parse-sexp-lookup-properties
2884		  (get-char-property pos 'syntax-table))))
2885      (if (consp st) st
2886	(aref (or st (syntax-table)) (char-after pos))))))
2887
2888(defun syntax-class (syntax)
2889  "Return the syntax class part of the syntax descriptor SYNTAX.
2890If SYNTAX is nil, return nil."
2891  (and syntax (logand (car syntax) 65535)))
2892
2893;;;; Text clones
2894
2895(defun text-clone-maintain (ol1 after beg end &optional len)
2896  "Propagate the changes made under the overlay OL1 to the other clones.
2897This is used on the `modification-hooks' property of text clones."
2898  (when (and after (not undo-in-progress) (overlay-start ol1))
2899    (let ((margin (if (overlay-get ol1 'text-clone-spreadp) 1 0)))
2900      (setq beg (max beg (+ (overlay-start ol1) margin)))
2901      (setq end (min end (- (overlay-end ol1) margin)))
2902      (when (<= beg end)
2903	(save-excursion
2904	  (when (overlay-get ol1 'text-clone-syntax)
2905	    ;; Check content of the clone's text.
2906	    (let ((cbeg (+ (overlay-start ol1) margin))
2907		  (cend (- (overlay-end ol1) margin)))
2908	      (goto-char cbeg)
2909	      (save-match-data
2910		(if (not (re-search-forward
2911			  (overlay-get ol1 'text-clone-syntax) cend t))
2912		    ;; Mark the overlay for deletion.
2913		    (overlay-put ol1 'text-clones nil)
2914		  (when (< (match-end 0) cend)
2915		    ;; Shrink the clone at its end.
2916		    (setq end (min end (match-end 0)))
2917		    (move-overlay ol1 (overlay-start ol1)
2918				  (+ (match-end 0) margin)))
2919		  (when (> (match-beginning 0) cbeg)
2920		    ;; Shrink the clone at its beginning.
2921		    (setq beg (max (match-beginning 0) beg))
2922		    (move-overlay ol1 (- (match-beginning 0) margin)
2923				  (overlay-end ol1)))))))
2924	  ;; Now go ahead and update the clones.
2925	  (let ((head (- beg (overlay-start ol1)))
2926		(tail (- (overlay-end ol1) end))
2927		(str (buffer-substring beg end))
2928		(nothing-left t)
2929		(inhibit-modification-hooks t))
2930	    (dolist (ol2 (overlay-get ol1 'text-clones))
2931	      (let ((oe (overlay-end ol2)))
2932		(unless (or (eq ol1 ol2) (null oe))
2933		  (setq nothing-left nil)
2934		  (let ((mod-beg (+ (overlay-start ol2) head)))
2935		    ;;(overlay-put ol2 'modification-hooks nil)
2936		    (goto-char (- (overlay-end ol2) tail))
2937		    (unless (> mod-beg (point))
2938		      (save-excursion (insert str))
2939		      (delete-region mod-beg (point)))
2940		    ;;(overlay-put ol2 'modification-hooks '(text-clone-maintain))
2941		    ))))
2942	    (if nothing-left (delete-overlay ol1))))))))
2943
2944(defun text-clone-create (start end &optional spreadp syntax)
2945  "Create a text clone of START...END at point.
2946Text clones are chunks of text that are automatically kept identical:
2947changes done to one of the clones will be immediately propagated to the other.
2948
2949The buffer's content at point is assumed to be already identical to
2950the one between START and END.
2951If SYNTAX is provided it's a regexp that describes the possible text of
2952the clones; the clone will be shrunk or killed if necessary to ensure that
2953its text matches the regexp.
2954If SPREADP is non-nil it indicates that text inserted before/after the
2955clone should be incorporated in the clone."
2956  ;; To deal with SPREADP we can either use an overlay with `nil t' along
2957  ;; with insert-(behind|in-front-of)-hooks or use a slightly larger overlay
2958  ;; (with a one-char margin at each end) with `t nil'.
2959  ;; We opted for a larger overlay because it behaves better in the case
2960  ;; where the clone is reduced to the empty string (we want the overlay to
2961  ;; stay when the clone's content is the empty string and we want to use
2962  ;; `evaporate' to make sure those overlays get deleted when needed).
2963  ;;
2964  (let* ((pt-end (+ (point) (- end start)))
2965  	 (start-margin (if (or (not spreadp) (bobp) (<= start (point-min)))
2966			   0 1))
2967  	 (end-margin (if (or (not spreadp)
2968			     (>= pt-end (point-max))
2969  			     (>= start (point-max)))
2970  			 0 1))
2971  	 (ol1 (make-overlay (- start start-margin) (+ end end-margin) nil t))
2972  	 (ol2 (make-overlay (- (point) start-margin) (+ pt-end end-margin) nil t))
2973	 (dups (list ol1 ol2)))
2974    (overlay-put ol1 'modification-hooks '(text-clone-maintain))
2975    (when spreadp (overlay-put ol1 'text-clone-spreadp t))
2976    (when syntax (overlay-put ol1 'text-clone-syntax syntax))
2977    ;;(overlay-put ol1 'face 'underline)
2978    (overlay-put ol1 'evaporate t)
2979    (overlay-put ol1 'text-clones dups)
2980    ;;
2981    (overlay-put ol2 'modification-hooks '(text-clone-maintain))
2982    (when spreadp (overlay-put ol2 'text-clone-spreadp t))
2983    (when syntax (overlay-put ol2 'text-clone-syntax syntax))
2984    ;;(overlay-put ol2 'face 'underline)
2985    (overlay-put ol2 'evaporate t)
2986    (overlay-put ol2 'text-clones dups)))
2987
2988;;;; Mail user agents.
2989
2990;; Here we include just enough for other packages to be able
2991;; to define them.
2992
2993(defun define-mail-user-agent (symbol composefunc sendfunc
2994				      &optional abortfunc hookvar)
2995  "Define a symbol to identify a mail-sending package for `mail-user-agent'.
2996
2997SYMBOL can be any Lisp symbol.  Its function definition and/or
2998value as a variable do not matter for this usage; we use only certain
2999properties on its property list, to encode the rest of the arguments.
3000
3001COMPOSEFUNC is program callable function that composes an outgoing
3002mail message buffer.  This function should set up the basics of the
3003buffer without requiring user interaction.  It should populate the
3004standard mail headers, leaving the `to:' and `subject:' headers blank
3005by default.
3006
3007COMPOSEFUNC should accept several optional arguments--the same
3008arguments that `compose-mail' takes.  See that function's documentation.
3009
3010SENDFUNC is the command a user would run to send the message.
3011
3012Optional ABORTFUNC is the command a user would run to abort the
3013message.  For mail packages that don't have a separate abort function,
3014this can be `kill-buffer' (the equivalent of omitting this argument).
3015
3016Optional HOOKVAR is a hook variable that gets run before the message
3017is actually sent.  Callers that use the `mail-user-agent' may
3018install a hook function temporarily on this hook variable.
3019If HOOKVAR is nil, `mail-send-hook' is used.
3020
3021The properties used on SYMBOL are `composefunc', `sendfunc',
3022`abortfunc', and `hookvar'."
3023  (put symbol 'composefunc composefunc)
3024  (put symbol 'sendfunc sendfunc)
3025  (put symbol 'abortfunc (or abortfunc 'kill-buffer))
3026  (put symbol 'hookvar (or hookvar 'mail-send-hook)))
3027
3028;;;; Progress reporters.
3029
3030;; Progress reporter has the following structure:
3031;;
3032;;	(NEXT-UPDATE-VALUE . [NEXT-UPDATE-TIME
3033;;			      MIN-VALUE
3034;;			      MAX-VALUE
3035;;			      MESSAGE
3036;;			      MIN-CHANGE
3037;;			      MIN-TIME])
3038;;
3039;; This weirdeness is for optimization reasons: we want
3040;; `progress-reporter-update' to be as fast as possible, so
3041;; `(car reporter)' is better than `(aref reporter 0)'.
3042;;
3043;; NEXT-UPDATE-TIME is a float.  While `float-time' loses a couple
3044;; digits of precision, it doesn't really matter here.  On the other
3045;; hand, it greatly simplifies the code.
3046
3047(defsubst progress-reporter-update (reporter value)
3048  "Report progress of an operation in the echo area.
3049However, if the change since last echo area update is too small
3050or not enough time has passed, then do nothing (see
3051`make-progress-reporter' for details).
3052
3053First parameter, REPORTER, should be the result of a call to
3054`make-progress-reporter'.  Second, VALUE, determines the actual
3055progress of operation; it must be between MIN-VALUE and MAX-VALUE
3056as passed to `make-progress-reporter'.
3057
3058This function is very inexpensive, you may not bother how often
3059you call it."
3060  (when (>= value (car reporter))
3061    (progress-reporter-do-update reporter value)))
3062
3063(defun make-progress-reporter (message min-value max-value
3064				       &optional current-value
3065				       min-change min-time)
3066  "Return progress reporter object to be used with `progress-reporter-update'.
3067
3068MESSAGE is shown in the echo area.  When at least 1% of operation
3069is complete, the exact percentage will be appended to the
3070MESSAGE.  When you call `progress-reporter-done', word \"done\"
3071is printed after the MESSAGE.  You can change MESSAGE of an
3072existing progress reporter with `progress-reporter-force-update'.
3073
3074MIN-VALUE and MAX-VALUE designate starting (0% complete) and
3075final (100% complete) states of operation.  The latter should be
3076larger; if this is not the case, then simply negate all values.
3077Optional CURRENT-VALUE specifies the progress by the moment you
3078call this function.  You should omit it or set it to nil in most
3079cases since it defaults to MIN-VALUE.
3080
3081Optional MIN-CHANGE determines the minimal change in percents to
3082report (default is 1%.)  Optional MIN-TIME specifies the minimal
3083time before echo area updates (default is 0.2 seconds.)  If
3084`float-time' function is not present, then time is not tracked
3085at all.  If OS is not capable of measuring fractions of seconds,
3086then this parameter is effectively rounded up."
3087
3088  (unless min-time
3089    (setq min-time 0.2))
3090  (let ((reporter
3091	 (cons min-value ;; Force a call to `message' now
3092	       (vector (if (and (fboundp 'float-time)
3093				(>= min-time 0.02))
3094			   (float-time) nil)
3095		       min-value
3096		       max-value
3097		       message
3098		       (if min-change (max (min min-change 50) 1) 1)
3099		       min-time))))
3100    (progress-reporter-update reporter (or current-value min-value))
3101    reporter))
3102
3103(defun progress-reporter-force-update (reporter value &optional new-message)
3104  "Report progress of an operation in the echo area unconditionally.
3105
3106First two parameters are the same as for
3107`progress-reporter-update'.  Optional NEW-MESSAGE allows you to
3108change the displayed message."
3109  (let ((parameters (cdr reporter)))
3110    (when new-message
3111      (aset parameters 3 new-message))
3112    (when (aref parameters 0)
3113      (aset parameters 0 (float-time)))
3114    (progress-reporter-do-update reporter value)))
3115
3116(defun progress-reporter-do-update (reporter value)
3117  (let* ((parameters   (cdr reporter))
3118	 (min-value    (aref parameters 1))
3119	 (max-value    (aref parameters 2))
3120	 (one-percent  (/ (- max-value min-value) 100.0))
3121	 (percentage   (if (= max-value min-value)
3122			   0
3123			 (truncate (/ (- value min-value) one-percent))))
3124	 (update-time  (aref parameters 0))
3125	 (current-time (float-time))
3126	 (enough-time-passed
3127	  ;; See if enough time has passed since the last update.
3128	  (or (not update-time)
3129	      (when (>= current-time update-time)
3130		;; Calculate time for the next update
3131		(aset parameters 0 (+ update-time (aref parameters 5)))))))
3132    ;;
3133    ;; Calculate NEXT-UPDATE-VALUE.  If we are not going to print
3134    ;; message this time because not enough time has passed, then use
3135    ;; 1 instead of MIN-CHANGE.  This makes delays between echo area
3136    ;; updates closer to MIN-TIME.
3137    (setcar reporter
3138	    (min (+ min-value (* (+ percentage
3139				    (if enough-time-passed
3140					(aref parameters 4) ;; MIN-CHANGE
3141				      1))
3142				 one-percent))
3143		 max-value))
3144    (when (integerp value)
3145      (setcar reporter (ceiling (car reporter))))
3146    ;;
3147    ;; Only print message if enough time has passed
3148    (when enough-time-passed
3149      (if (> percentage 0)
3150	  (message "%s%d%%" (aref parameters 3) percentage)
3151	(message "%s" (aref parameters 3))))))
3152
3153(defun progress-reporter-done (reporter)
3154  "Print reporter's message followed by word \"done\" in echo area."
3155  (message "%sdone" (aref (cdr reporter) 3)))
3156
3157(defmacro dotimes-with-progress-reporter (spec message &rest body)
3158  "Loop a certain number of times and report progress in the echo area.
3159Evaluate BODY with VAR bound to successive integers running from
31600, inclusive, to COUNT, exclusive.  Then evaluate RESULT to get
3161the return value (nil if RESULT is omitted).
3162
3163At each iteration MESSAGE followed by progress percentage is
3164printed in the echo area.  After the loop is finished, MESSAGE
3165followed by word \"done\" is printed.  This macro is a
3166convenience wrapper around `make-progress-reporter' and friends.
3167
3168\(fn (VAR COUNT [RESULT]) MESSAGE BODY...)"
3169  (declare (indent 2) (debug ((symbolp form &optional form) form body)))
3170  (let ((temp (make-symbol "--dotimes-temp--"))
3171	(temp2 (make-symbol "--dotimes-temp2--"))
3172	(start 0)
3173	(end (nth 1 spec)))
3174    `(let ((,temp ,end)
3175	   (,(car spec) ,start)
3176	   (,temp2 (make-progress-reporter ,message ,start ,end)))
3177       (while (< ,(car spec) ,temp)
3178	 ,@body
3179	 (progress-reporter-update ,temp2
3180				   (setq ,(car spec) (1+ ,(car spec)))))
3181       (progress-reporter-done ,temp2)
3182       nil ,@(cdr (cdr spec)))))
3183
3184
3185;;;; Comparing version strings.
3186
3187(defvar version-separator "."
3188  "*Specify the string used to separate the version elements.
3189
3190Usually the separator is \".\", but it can be any other string.")
3191
3192
3193(defvar version-regexp-alist
3194  '(("^[-_+ ]?a\\(lpha\\)?$"   . -3)
3195    ("^[-_+]$"                 . -3) ; treat "1.2.3-20050920" and "1.2-3" as alpha releases
3196    ("^[-_+ ]cvs$"             . -3)	; treat "1.2.3-CVS" as alpha release
3197    ("^[-_+ ]?b\\(eta\\)?$"    . -2)
3198    ("^[-_+ ]?\\(pre\\|rc\\)$" . -1))
3199  "*Specify association between non-numeric version part and a priority.
3200
3201This association is used to handle version string like \"1.0pre2\",
3202\"0.9alpha1\", etc.  It's used by `version-to-list' (which see) to convert the
3203non-numeric part to an integer.  For example:
3204
3205   String Version    Integer List Version
3206   \"1.0pre2\"         (1  0 -1 2)
3207   \"1.0PRE2\"         (1  0 -1 2)
3208   \"22.8beta3\"       (22 8 -2 3)
3209   \"22.8 Beta3\"      (22 8 -2 3)
3210   \"0.9alpha1\"       (0  9 -3 1)
3211   \"0.9AlphA1\"       (0  9 -3 1)
3212   \"0.9 alpha\"       (0  9 -3)
3213
3214Each element has the following form:
3215
3216   (REGEXP . PRIORITY)
3217
3218Where:
3219
3220REGEXP		regexp used to match non-numeric part of a version string.
3221		It should begin with a `^' anchor and end with a `$' to
3222		prevent false hits.  Letter-case is ignored while matching
3223		REGEXP.
3224
3225PRIORITY	negative integer which indicate the non-numeric priority.")
3226
3227
3228(defun version-to-list (ver)
3229  "Convert version string VER into an integer list.
3230
3231The version syntax is given by the following EBNF:
3232
3233   VERSION ::= NUMBER ( SEPARATOR NUMBER )*.
3234
3235   NUMBER ::= (0|1|2|3|4|5|6|7|8|9)+.
3236
3237   SEPARATOR ::= `version-separator' (which see)
3238	       | `version-regexp-alist' (which see).
3239
3240The NUMBER part is optional if SEPARATOR is a match for an element
3241in `version-regexp-alist'.
3242
3243As an example of valid version syntax:
3244
3245   1.0pre2   1.0.7.5   22.8beta3   0.9alpha1   6.9.30Beta
3246
3247As an example of invalid version syntax:
3248
3249   1.0prepre2   1.0..7.5   22.8X3   alpha3.2   .5
3250
3251As an example of version convertion:
3252
3253   String Version    Integer List Version
3254   \"1.0.7.5\"         (1  0  7 5)
3255   \"1.0pre2\"         (1  0 -1 2)
3256   \"1.0PRE2\"         (1  0 -1 2)
3257   \"22.8beta3\"       (22 8 -2 3)
3258   \"22.8Beta3\"       (22 8 -2 3)
3259   \"0.9alpha1\"       (0  9 -3 1)
3260   \"0.9AlphA1\"       (0  9 -3 1)
3261   \"0.9alpha\"        (0  9 -3)
3262
3263See documentation for `version-separator' and `version-regexp-alist'."
3264  (or (and (stringp ver) (> (length ver) 0))
3265      (error "Invalid version string: '%s'" ver))
3266  ;; Change .x.y to 0.x.y
3267  (if (and (>= (length ver) (length version-separator))
3268	   (string-equal (substring ver 0 (length version-separator))
3269			 version-separator))
3270      (setq ver (concat "0" ver)))
3271  (save-match-data
3272    (let ((i 0)
3273	  (case-fold-search t)		; ignore case in matching
3274	  lst s al)
3275      (while (and (setq s (string-match "[0-9]+" ver i))
3276		  (= s i))
3277	;; handle numeric part
3278	(setq lst (cons (string-to-number (substring ver i (match-end 0)))
3279			lst)
3280	      i   (match-end 0))
3281	;; handle non-numeric part
3282	(when (and (setq s (string-match "[^0-9]+" ver i))
3283		   (= s i))
3284	  (setq s (substring ver i (match-end 0))
3285		i (match-end 0))
3286	  ;; handle alpha, beta, pre, etc. separator
3287	  (unless (string= s version-separator)
3288	    (setq al version-regexp-alist)
3289	    (while (and al (not (string-match (caar al) s)))
3290	      (setq al (cdr al)))
3291	    (or al (error "Invalid version syntax: '%s'" ver))
3292	    (setq lst (cons (cdar al) lst)))))
3293      (if (null lst)
3294	  (error "Invalid version syntax: '%s'" ver)
3295	(nreverse lst)))))
3296
3297
3298(defun version-list-< (l1 l2)
3299  "Return t if integer list L1 is lesser than L2.
3300
3301Note that integer list (1) is equal to (1 0), (1 0 0), (1 0 0 0),
3302etc.  That is, the trailing zeroes are irrelevant.  Also, integer
3303list (1) is greater than (1 -1) which is greater than (1 -2)
3304which is greater than (1 -3)."
3305  (while (and l1 l2 (= (car l1) (car l2)))
3306    (setq l1 (cdr l1)
3307	  l2 (cdr l2)))
3308  (cond
3309   ;; l1 not null and l2 not null
3310   ((and l1 l2) (< (car l1) (car l2)))
3311   ;; l1 null and l2 null         ==> l1 length = l2 length
3312   ((and (null l1) (null l2)) nil)
3313   ;; l1 not null and l2 null     ==> l1 length > l2 length
3314   (l1 (< (version-list-not-zero l1) 0))
3315   ;; l1 null and l2 not null     ==> l2 length > l1 length
3316   (t  (< 0 (version-list-not-zero l2)))))
3317
3318
3319(defun version-list-= (l1 l2)
3320  "Return t if integer list L1 is equal to L2.
3321
3322Note that integer list (1) is equal to (1 0), (1 0 0), (1 0 0 0),
3323etc.  That is, the trailing zeroes are irrelevant.  Also, integer
3324list (1) is greater than (1 -1) which is greater than (1 -2)
3325which is greater than (1 -3)."
3326  (while (and l1 l2 (= (car l1) (car l2)))
3327    (setq l1 (cdr l1)
3328	  l2 (cdr l2)))
3329  (cond
3330   ;; l1 not null and l2 not null
3331   ((and l1 l2) nil)
3332   ;; l1 null and l2 null     ==> l1 length = l2 length
3333   ((and (null l1) (null l2)))
3334   ;; l1 not null and l2 null ==> l1 length > l2 length
3335   (l1 (zerop (version-list-not-zero l1)))
3336   ;; l1 null and l2 not null ==> l2 length > l1 length
3337   (t  (zerop (version-list-not-zero l2)))))
3338
3339
3340(defun version-list-<= (l1 l2)
3341  "Return t if integer list L1 is lesser than or equal to L2.
3342
3343Note that integer list (1) is equal to (1 0), (1 0 0), (1 0 0 0),
3344etc.  That is, the trailing zeroes are irrelevant.  Also, integer
3345list (1) is greater than (1 -1) which is greater than (1 -2)
3346which is greater than (1 -3)."
3347  (while (and l1 l2 (= (car l1) (car l2)))
3348    (setq l1 (cdr l1)
3349	  l2 (cdr l2)))
3350  (cond
3351   ;; l1 not null and l2 not null
3352   ((and l1 l2) (< (car l1) (car l2)))
3353   ;; l1 null and l2 null     ==> l1 length = l2 length
3354   ((and (null l1) (null l2)))
3355   ;; l1 not null and l2 null ==> l1 length > l2 length
3356   (l1 (<= (version-list-not-zero l1) 0))
3357   ;; l1 null and l2 not null ==> l2 length > l1 length
3358   (t  (<= 0 (version-list-not-zero l2)))))
3359
3360(defun version-list-not-zero (lst)
3361  "Return the first non-zero element of integer list LST.
3362
3363If all LST elements are zeroes or LST is nil, return zero."
3364  (while (and lst (zerop (car lst)))
3365    (setq lst (cdr lst)))
3366  (if lst
3367      (car lst)
3368    ;; there is no element different of zero
3369    0))
3370
3371
3372(defun version< (v1 v2)
3373  "Return t if version V1 is lesser than V2.
3374
3375Note that version string \"1\" is equal to \"1.0\", \"1.0.0\", \"1.0.0.0\",
3376etc.  That is, the trailing \".0\"s are irrelevant.  Also, version string \"1\"
3377is greater than \"1pre\" which is greater than \"1beta\" which is greater than
3378\"1alpha\"."
3379  (version-list-< (version-to-list v1) (version-to-list v2)))
3380
3381
3382(defun version<= (v1 v2)
3383  "Return t if version V1 is lesser than or equal to V2.
3384
3385Note that version string \"1\" is equal to \"1.0\", \"1.0.0\", \"1.0.0.0\",
3386etc.  That is, the trailing \".0\"s are irrelevant.  Also, version string \"1\"
3387is greater than \"1pre\" which is greater than \"1beta\" which is greater than
3388\"1alpha\"."
3389  (version-list-<= (version-to-list v1) (version-to-list v2)))
3390
3391(defun version= (v1 v2)
3392  "Return t if version V1 is equal to V2.
3393
3394Note that version string \"1\" is equal to \"1.0\", \"1.0.0\", \"1.0.0.0\",
3395etc.  That is, the trailing \".0\"s are irrelevant.  Also, version string \"1\"
3396is greater than \"1pre\" which is greater than \"1beta\" which is greater than
3397\"1alpha\"."
3398  (version-list-= (version-to-list v1) (version-to-list v2)))
3399
3400
3401
3402;; arch-tag: f7e0e6e5-70aa-4897-ae72-7a3511ec40bc
3403;;; subr.el ends here
3404