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