Symbol prettify in prog-mode; added to perl-mode, cfengine3-mode, and emacs-lisp...
[bpt/emacs.git] / lisp / subr.el
CommitLineData
bfa3acd6 1;;; subr.el --- basic lisp subroutines for Emacs -*- coding: utf-8; lexical-binding:t -*-
630cc463 2
ab422c4d
PE
3;; Copyright (C) 1985-1986, 1992, 1994-1995, 1999-2013 Free Software
4;; Foundation, Inc.
be9b65ac 5
30764597
PJ
6;; Maintainer: FSF
7;; Keywords: internal
bd78fa1d 8;; Package: emacs
30764597 9
be9b65ac
DL
10;; This file is part of GNU Emacs.
11
eb3fa2cf 12;; GNU Emacs is free software: you can redistribute it and/or modify
be9b65ac 13;; it under the terms of the GNU General Public License as published by
eb3fa2cf
GM
14;; the Free Software Foundation, either version 3 of the License, or
15;; (at your option) any later version.
be9b65ac
DL
16
17;; GNU Emacs is distributed in the hope that it will be useful,
18;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20;; GNU General Public License for more details.
21
22;; You should have received a copy of the GNU General Public License
eb3fa2cf 23;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
be9b65ac 24
60370d40
PJ
25;;; Commentary:
26
630cc463 27;;; Code:
d0fc47ed 28
2ee3d7f0
SM
29;; Beware: while this file has tag `utf-8', before it's compiled, it gets
30;; loaded as "raw-text", so non-ASCII chars won't work right during bootstrap.
31
77a5664f
RS
32(defvar custom-declare-variable-list nil
33 "Record `defcustom' calls made before `custom.el' is loaded to handle them.
34Each element of this list holds the arguments to one call to `defcustom'.")
35
68e3e5f5 36;; Use this, rather than defcustom, in subr.el and other files loaded
77a5664f
RS
37;; before custom.el.
38(defun custom-declare-variable-early (&rest arguments)
39 (setq custom-declare-variable-list
40 (cons arguments custom-declare-variable-list)))
2c642c03 41
bfa3acd6 42(defmacro declare-function (_fn _file &optional _arglist _fileonly)
708bb6f8
RS
43 "Tell the byte-compiler that function FN is defined, in FILE.
44Optional ARGLIST is the argument list used by the function. The
45FILE argument is not used by the byte-compiler, but by the
46`check-declare' package, which checks that FILE contains a
47definition for FN. ARGLIST is used by both the byte-compiler and
48`check-declare' to check for consistency.
49
50FILE can be either a Lisp file (in which case the \".el\"
51extension is optional), or a C file. C files are expanded
52relative to the Emacs \"src/\" directory. Lisp files are
53searched for using `locate-library', and if that fails they are
54expanded relative to the location of the file containing the
55declaration. A FILE with an \"ext:\" prefix is an external file.
56`check-declare' will check such files if they are found, and skip
57them without error if they are not.
58
59FILEONLY non-nil means that `check-declare' will only check that
60FILE exists, not that it defines FN. This is intended for
61function-definitions that `check-declare' does not recognize, e.g.
62`defstruct'.
63
64To specify a value for FILEONLY without passing an argument list,
3fa173b4 65set ARGLIST to t. This is necessary because nil means an
708bb6f8
RS
66empty argument list, rather than an unspecified one.
67
68Note that for the purposes of `check-declare', this statement
a4d2c321 69must be the first non-whitespace on a line.
708bb6f8 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."
2de39f08 83 (declare (debug t))
6b61353c
KH
84 `(prog1 ,form
85 (error "Form marked with `noreturn' did return")))
86
87(defmacro 1value (form)
70c6db6c
LT
88 "Evaluate FORM, expecting a constant return value.
89This is the global do-nothing version. There is also `testcover-1value'
90that complains if FORM ever does return differing values."
2de39f08 91 (declare (debug t))
6b61353c
KH
92 form)
93
8285ccd2
RS
94(defmacro def-edebug-spec (symbol spec)
95 "Set the `edebug-form-spec' property of SYMBOL according to SPEC.
e32721f5
GM
96Both SYMBOL and SPEC are unevaluated. The SPEC can be:
970 (instrument no arguments); t (instrument all arguments);
98a symbol (naming a function with an Edebug specification); or a list.
99The elements of the list describe the argument types; see
2b1e1a22 100Info node `(elisp)Specification List' for details."
8285ccd2
RS
101 `(put (quote ,symbol) 'edebug-form-spec (quote ,spec)))
102
9a5336ae
JB
103(defmacro lambda (&rest cdr)
104 "Return a lambda expression.
105A call of the form (lambda ARGS DOCSTRING INTERACTIVE BODY) is
106self-quoting; the result of evaluating the lambda expression is the
107expression itself. The lambda expression may then be treated as a
bec0d7f9 108function, i.e., stored as the function value of a symbol, passed to
265b3f2a 109`funcall' or `mapcar', etc.
bec0d7f9 110
9a5336ae 111ARGS should take the same form as an argument list for a `defun'.
8fd68088
RS
112DOCSTRING is an optional documentation string.
113 If present, it should describe how to call the function.
114 But documentation strings are usually not useful in nameless functions.
9a5336ae
JB
115INTERACTIVE should be a call to the function `interactive', which see.
116It may also be omitted.
a478f3e1
JB
117BODY should be a list of Lisp expressions.
118
119\(fn ARGS [DOCSTRING] [INTERACTIVE] BODY)"
a179e3f7
SM
120 (declare (doc-string 2) (indent defun)
121 (debug (&define lambda-list
122 [&optional stringp]
123 [&optional ("interactive" interactive)]
124 def-body)))
9a5336ae
JB
125 ;; Note that this definition should not use backquotes; subr.el should not
126 ;; depend on backquote.el.
127 (list 'function (cons 'lambda cdr)))
128
f95e9344
SM
129(defmacro setq-local (var val)
130 "Set variable VAR to value VAL in current buffer."
131 ;; Can't use backquote here, it's too early in the bootstrap.
132 (list 'set (list 'make-local-variable (list 'quote var)) val))
133
134(defmacro defvar-local (var val &optional docstring)
135 "Define VAR as a buffer-local variable with default value VAL.
136Like `defvar' but additionally marks the variable as being automatically
137buffer-local wherever it is set."
8bba5a75 138 (declare (debug defvar) (doc-string 3))
f95e9344
SM
139 ;; Can't use backquote here, it's too early in the bootstrap.
140 (list 'progn (list 'defvar var val docstring)
141 (list 'make-variable-buffer-local (list 'quote var))))
142
2ec42da9
SM
143(defun apply-partially (fun &rest args)
144 "Return a function that is a partial application of FUN to ARGS.
145ARGS is a list of the first N arguments to pass to FUN.
146The result is a new function which does the same as FUN, except that
147the first N arguments are fixed at the values with which this function
148was called."
f488fb65 149 `(closure (t) (&rest args)
2ec42da9
SM
150 (apply ',fun ,@(mapcar (lambda (arg) `',arg) args) args)))
151
2ee3d7f0
SM
152(defmacro push (newelt place)
153 "Add NEWELT to the list stored in the generalized variable PLACE.
154This is morally equivalent to (setf PLACE (cons NEWELT PLACE)),
155except that PLACE is only evaluated once (after NEWELT)."
156 (declare (debug (form gv-place)))
157 (if (symbolp place)
158 ;; Important special case, to avoid triggering GV too early in
159 ;; the bootstrap.
160 (list 'setq place
161 (list 'cons newelt place))
162 (require 'macroexp)
163 (macroexp-let2 macroexp-copyable-p v newelt
164 (gv-letplace (getter setter) place
165 (funcall setter `(cons ,v ,getter))))))
166
167(defmacro pop (place)
168 "Return the first element of PLACE's value, and remove it from the list.
169PLACE must be a generalized variable whose value is a list.
d270117a
RS
170If the value is nil, `pop' returns nil but does not actually
171change the list."
2ee3d7f0 172 (declare (debug (gv-place)))
54993fa4 173 (list 'car
2ee3d7f0
SM
174 (if (symbolp place)
175 ;; So we can use `pop' in the bootstrap before `gv' can be used.
176 (list 'prog1 place (list 'setq place (list 'cdr place)))
177 (gv-letplace (getter setter) place
178 `(prog1 ,getter ,(funcall setter `(cdr ,getter)))))))
d270117a 179
debff3c3 180(defmacro when (cond &rest body)
7f67eea0
KS
181 "If COND yields non-nil, do BODY, else return nil.
182When COND yields non-nil, eval BODY forms sequentially and return
183value of last one, or nil if there are none.
184
ebc3ae14 185\(fn COND BODY...)"
d47f7515 186 (declare (indent 1) (debug t))
debff3c3 187 (list 'if cond (cons 'progn body)))
9a5336ae 188
debff3c3 189(defmacro unless (cond &rest body)
7f67eea0
KS
190 "If COND yields nil, do BODY, else return nil.
191When COND yields nil, eval BODY forms sequentially and return
192value of last one, or nil if there are none.
193
ebc3ae14 194\(fn COND BODY...)"
d47f7515 195 (declare (indent 1) (debug t))
debff3c3 196 (cons 'if (cons cond (cons nil body))))
d370591d 197
a0b0756a 198(defmacro dolist (spec &rest body)
d47f7515 199 "Loop over a list.
a0b0756a 200Evaluate BODY with VAR bound to each car from LIST, in turn.
d47f7515
SM
201Then evaluate RESULT to get return value, default nil.
202
d775d486 203\(fn (VAR LIST [RESULT]) BODY...)"
d47f7515 204 (declare (indent 1) (debug ((symbolp form &optional form) body)))
01d16e16
RS
205 ;; It would be cleaner to create an uninterned symbol,
206 ;; but that uses a lot more space when many functions in many files
207 ;; use dolist.
ca105506 208 ;; FIXME: This cost disappears in byte-compiled lexical-binding files.
01d16e16 209 (let ((temp '--dolist-tail--))
f488fb65
SM
210 ;; This is not a reliable test, but it does not matter because both
211 ;; semantics are acceptable, tho one is slightly faster with dynamic
212 ;; scoping and the other is slightly faster (and has cleaner semantics)
213 ;; with lexical scoping.
214 (if lexical-binding
215 `(let ((,temp ,(nth 1 spec)))
216 (while ,temp
217 (let ((,(car spec) (car ,temp)))
218 ,@body
219 (setq ,temp (cdr ,temp))))
da03ef8a 220 ,@(cdr (cdr spec)))
f488fb65
SM
221 `(let ((,temp ,(nth 1 spec))
222 ,(car spec))
223 (while ,temp
224 (setq ,(car spec) (car ,temp))
225 ,@body
226 (setq ,temp (cdr ,temp)))
227 ,@(if (cdr (cdr spec))
228 `((setq ,(car spec) nil) ,@(cdr (cdr spec))))))))
01d16e16 229
a0b0756a 230(defmacro dotimes (spec &rest body)
d47f7515 231 "Loop a certain number of times.
a0b0756a
RS
232Evaluate BODY with VAR bound to successive integers running from 0,
233inclusive, to COUNT, exclusive. Then evaluate RESULT to get
d47f7515
SM
234the return value (nil if RESULT is omitted).
235
d775d486 236\(fn (VAR COUNT [RESULT]) BODY...)"
d47f7515 237 (declare (indent 1) (debug dolist))
01d16e16
RS
238 ;; It would be cleaner to create an uninterned symbol,
239 ;; but that uses a lot more space when many functions in many files
240 ;; use dotimes.
f488fb65 241 ;; FIXME: This cost disappears in byte-compiled lexical-binding files.
01d16e16 242 (let ((temp '--dotimes-limit--)
d47f7515
SM
243 (start 0)
244 (end (nth 1 spec)))
f488fb65
SM
245 ;; This is not a reliable test, but it does not matter because both
246 ;; semantics are acceptable, tho one is slightly faster with dynamic
247 ;; scoping and the other has cleaner semantics.
248 (if lexical-binding
249 (let ((counter '--dotimes-counter--))
250 `(let ((,temp ,end)
251 (,counter ,start))
252 (while (< ,counter ,temp)
253 (let ((,(car spec) ,counter))
254 ,@body)
255 (setq ,counter (1+ ,counter)))
256 ,@(if (cddr spec)
257 ;; FIXME: This let often leads to "unused var" warnings.
258 `((let ((,(car spec) ,counter)) ,@(cddr spec))))))
259 `(let ((,temp ,end)
260 (,(car spec) ,start))
261 (while (< ,(car spec) ,temp)
262 ,@body
263 (setq ,(car spec) (1+ ,(car spec))))
264 ,@(cdr (cdr spec))))))
a0b0756a 265
06b60517 266(defmacro declare (&rest _specs)
863666eb
CY
267 "Do not evaluate any arguments, and return nil.
268If a `declare' form appears as the first form in the body of a
269`defun' or `defmacro' form, SPECS specifies various additional
270information about the function or macro; these go into effect
271during the evaluation of the `defun' or `defmacro' form.
272
273The possible values of SPECS are specified by
274`defun-declarations-alist' and `macro-declarations-alist'."
36cec983 275 ;; FIXME: edebug spec should pay attention to defun-declarations-alist.
a69c67e8 276 nil)
6b5de136
GM
277
278(defmacro ignore-errors (&rest body)
279 "Execute BODY; if an error occurs, return nil.
d02e58f8
LL
280Otherwise, return result of last form in BODY.
281See also `with-demoted-errors' that does something similar
282without silencing all errors."
7467d0a8 283 (declare (debug t) (indent 0))
6b5de136 284 `(condition-case nil (progn ,@body) (error nil)))
c4f484f2
RS
285\f
286;;;; Basic Lisp functions.
287
06b60517 288(defun ignore (&rest _ignore)
c4f484f2
RS
289 "Do nothing and return nil.
290This function accepts any number of arguments, but ignores them."
291 (interactive)
292 nil)
293
fd6c5134 294;; Signal a compile-error if the first arg is missing.
c4f484f2
RS
295(defun error (&rest args)
296 "Signal an error, making error message by passing all args to `format'.
297In Emacs, the convention is that error messages start with a capital
298letter but *do not* end with a period. Please follow this convention
fd6c5134 299for the sake of consistency."
c4f484f2
RS
300 (while t
301 (signal 'error (list (apply 'format args)))))
f3a30a50 302(set-advertised-calling-convention 'error '(string &rest args) "23.1")
c4f484f2 303
71873e2b
SM
304(defun user-error (format &rest args)
305 "Signal a pilot error, making error message by passing all args to `format'.
306In Emacs, the convention is that error messages start with a capital
307letter but *do not* end with a period. Please follow this convention
308for the sake of consistency.
309This is just like `error' except that `user-error's are expected to be the
310result of an incorrect manipulation on the part of the user, rather than the
311result of an actual problem."
312 (while t
313 (signal 'user-error (list (apply #'format format args)))))
314
c4f484f2
RS
315;; We put this here instead of in frame.el so that it's defined even on
316;; systems where frame.el isn't loaded.
317(defun frame-configuration-p (object)
318 "Return non-nil if OBJECT seems to be a frame configuration.
319Any list whose car is `frame-configuration' is assumed to be a frame
320configuration."
321 (and (consp object)
322 (eq (car object) 'frame-configuration)))
c4f484f2
RS
323\f
324;;;; List functions.
6b61353c 325
d370591d
RS
326(defsubst caar (x)
327 "Return the car of the car of X."
328 (car (car x)))
329
330(defsubst cadr (x)
331 "Return the car of the cdr of X."
332 (car (cdr x)))
333
334(defsubst cdar (x)
335 "Return the cdr of the car of X."
336 (cdr (car x)))
337
338(defsubst cddr (x)
339 "Return the cdr of the cdr of X."
340 (cdr (cdr x)))
e8c32c99 341
a478f3e1
JB
342(defun last (list &optional n)
343 "Return the last link of LIST. Its car is the last element.
344If LIST is nil, return nil.
345If N is non-nil, return the Nth-to-last link of LIST.
346If N is bigger than the length of LIST, return LIST."
369fba5f 347 (if n
10e4702a 348 (and (>= n 0)
88f427d5 349 (let ((m (safe-length list)))
35744400
IS
350 (if (< n m) (nthcdr (- m n) list) list)))
351 (and list
88f427d5 352 (nthcdr (1- (safe-length list)) list))))
526d204e 353
a478f3e1 354(defun butlast (list &optional n)
a3111ae4 355 "Return a copy of LIST with the last N elements removed."
a478f3e1
JB
356 (if (and n (<= n 0)) list
357 (nbutlast (copy-sequence list) n)))
1c1c65de 358
a478f3e1 359(defun nbutlast (list &optional n)
1c1c65de 360 "Modifies LIST to remove the last N elements."
a478f3e1 361 (let ((m (length list)))
1c1c65de
KH
362 (or n (setq n 1))
363 (and (< n m)
364 (progn
a478f3e1
JB
365 (if (> n 0) (setcdr (nthcdr (- (1- m) n) list) nil))
366 list))))
1c1c65de 367
6b61353c
KH
368(defun delete-dups (list)
369 "Destructively remove `equal' duplicates from LIST.
370Store the result in LIST and return it. LIST must be a proper list.
371Of several `equal' occurrences of an element in LIST, the first
372one is kept."
373 (let ((tail list))
374 (while tail
375 (setcdr tail (delete (car tail) (cdr tail)))
376 (setq tail (cdr tail))))
377 list)
378
c7a8fcac
LL
379;; See http://lists.gnu.org/archive/html/emacs-devel/2013-05/msg00204.html
380(defun delete-consecutive-dups (list &optional circular)
381 "Destructively remove `equal' consecutive duplicates from LIST.
382First and last elements are considered consecutive if CIRCULAR is
383non-nil."
384 (let ((tail list) last)
385 (while (consp tail)
386 (if (equal (car tail) (cadr tail))
387 (setcdr tail (cddr tail))
388 (setq last (car tail)
389 tail (cdr tail))))
390 (if (and circular
391 (cdr list)
392 (equal last (car list)))
393 (nbutlast list)
394 list)))
395
0ed2c9b6 396(defun number-sequence (from &optional to inc)
abd9177a 397 "Return a sequence of numbers from FROM to TO (both inclusive) as a list.
6b61353c
KH
398INC is the increment used between numbers in the sequence and defaults to 1.
399So, the Nth element of the list is \(+ FROM \(* N INC)) where N counts from
400zero. TO is only included if there is an N for which TO = FROM + N * INC.
401If TO is nil or numerically equal to FROM, return \(FROM).
402If INC is positive and TO is less than FROM, or INC is negative
403and TO is larger than FROM, return nil.
404If INC is zero and TO is neither nil nor numerically equal to
405FROM, signal an error.
406
407This function is primarily designed for integer arguments.
408Nevertheless, FROM, TO and INC can be integer or float. However,
409floating point arithmetic is inexact. For instance, depending on
410the machine, it may quite well happen that
411\(number-sequence 0.4 0.6 0.2) returns the one element list \(0.4),
412whereas \(number-sequence 0.4 0.8 0.2) returns a list with three
413elements. Thus, if some of the arguments are floats and one wants
414to make sure that TO is included, one may have to explicitly write
415TO as \(+ FROM \(* N INC)) or use a variable whose value was
416computed with this exact expression. Alternatively, you can,
417of course, also replace TO with a slightly larger value
418\(or a slightly more negative value if INC is negative)."
419 (if (or (not to) (= from to))
0ed2c9b6
VJL
420 (list from)
421 (or inc (setq inc 1))
6b61353c
KH
422 (when (zerop inc) (error "The increment can not be zero"))
423 (let (seq (n 0) (next from))
424 (if (> inc 0)
425 (while (<= next to)
426 (setq seq (cons next seq)
427 n (1+ n)
428 next (+ from (* n inc))))
429 (while (>= next to)
430 (setq seq (cons next seq)
431 n (1+ n)
432 next (+ from (* n inc)))))
0ed2c9b6 433 (nreverse seq))))
abd9177a 434
a176c9eb
CW
435(defun copy-tree (tree &optional vecp)
436 "Make a copy of TREE.
437If TREE is a cons cell, this recursively copies both its car and its cdr.
cfebd4db 438Contrast to `copy-sequence', which copies only along the cdrs. With second
a176c9eb
CW
439argument VECP, this copies vectors as well as conses."
440 (if (consp tree)
cfebd4db
RS
441 (let (result)
442 (while (consp tree)
443 (let ((newcar (car tree)))
444 (if (or (consp (car tree)) (and vecp (vectorp (car tree))))
445 (setq newcar (copy-tree (car tree) vecp)))
446 (push newcar result))
447 (setq tree (cdr tree)))
68b08950 448 (nconc (nreverse result) tree))
a176c9eb
CW
449 (if (and vecp (vectorp tree))
450 (let ((i (length (setq tree (copy-sequence tree)))))
451 (while (>= (setq i (1- i)) 0)
cfebd4db
RS
452 (aset tree i (copy-tree (aref tree i) vecp)))
453 tree)
454 tree)))
c4f484f2
RS
455\f
456;;;; Various list-search functions.
a176c9eb 457
8a288450
RS
458(defun assoc-default (key alist &optional test default)
459 "Find object KEY in a pseudo-alist ALIST.
753bc4f6
CY
460ALIST is a list of conses or objects. Each element
461 (or the element's car, if it is a cons) is compared with KEY by
462 calling TEST, with two arguments: (i) the element or its car,
463 and (ii) KEY.
464If that is non-nil, the element matches; then `assoc-default'
465 returns the element's cdr, if it is a cons, or DEFAULT if the
466 element is not a cons.
8a288450
RS
467
468If no element matches, the value is nil.
469If TEST is omitted or nil, `equal' is used."
470 (let (found (tail alist) value)
471 (while (and tail (not found))
472 (let ((elt (car tail)))
473 (when (funcall (or test 'equal) (if (consp elt) (car elt) elt) key)
474 (setq found t value (if (consp elt) (cdr elt) default))))
475 (setq tail (cdr tail)))
476 value))
98aae5f6
KH
477
478(defun assoc-ignore-case (key alist)
479 "Like `assoc', but ignores differences in case and text representation.
480KEY must be a string. Upper-case and lower-case letters are treated as equal.
481Unibyte strings are converted to multibyte for comparison."
59f7af81 482 (declare (obsolete assoc-string "22.1"))
6b61353c 483 (assoc-string key alist t))
98aae5f6
KH
484
485(defun assoc-ignore-representation (key alist)
486 "Like `assoc', but ignores differences in text representation.
264ef586 487KEY must be a string.
98aae5f6 488Unibyte strings are converted to multibyte for comparison."
59f7af81 489 (declare (obsolete assoc-string "22.1"))
6b61353c 490 (assoc-string key alist nil))
cbbc3205
GM
491
492(defun member-ignore-case (elt list)
5612fd08 493 "Like `member', but ignore differences in case and text representation.
cbbc3205 494ELT must be a string. Upper-case and lower-case letters are treated as equal.
d86a3084
RS
495Unibyte strings are converted to multibyte for comparison.
496Non-strings in LIST are ignored."
497 (while (and list
498 (not (and (stringp (car list))
499 (eq t (compare-strings elt 0 nil (car list) 0 nil t)))))
242c13e8
MB
500 (setq list (cdr list)))
501 list)
cbbc3205 502
c4f484f2
RS
503(defun assq-delete-all (key alist)
504 "Delete from ALIST all elements whose car is `eq' to KEY.
505Return the modified alist.
506Elements of ALIST that are not conses are ignored."
507 (while (and (consp (car alist))
508 (eq (car (car alist)) key))
509 (setq alist (cdr alist)))
510 (let ((tail alist) tail-cdr)
511 (while (setq tail-cdr (cdr tail))
512 (if (and (consp (car tail-cdr))
513 (eq (car (car tail-cdr)) key))
514 (setcdr tail (cdr tail-cdr))
515 (setq tail tail-cdr))))
516 alist)
517
518(defun rassq-delete-all (value alist)
519 "Delete from ALIST all elements whose cdr is `eq' to VALUE.
520Return the modified alist.
521Elements of ALIST that are not conses are ignored."
522 (while (and (consp (car alist))
523 (eq (cdr (car alist)) value))
524 (setq alist (cdr alist)))
525 (let ((tail alist) tail-cdr)
526 (while (setq tail-cdr (cdr tail))
527 (if (and (consp (car tail-cdr))
528 (eq (cdr (car tail-cdr)) value))
529 (setcdr tail (cdr tail-cdr))
530 (setq tail tail-cdr))))
531 alist)
532
533(defun remove (elt seq)
534 "Return a copy of SEQ with all occurrences of ELT removed.
535SEQ must be a list, vector, or string. The comparison is done with `equal'."
536 (if (nlistp seq)
537 ;; If SEQ isn't a list, there's no need to copy SEQ because
538 ;; `delete' will return a new object.
539 (delete elt seq)
540 (delete elt (copy-sequence seq))))
541
542(defun remq (elt list)
543 "Return LIST with all occurrences of ELT removed.
544The comparison is done with `eq'. Contrary to `delq', this does not use
545side-effects, and the argument LIST is not modified."
7f9b7c53 546 (while (and (eq elt (car list)) (setq list (cdr list))))
c4f484f2
RS
547 (if (memq elt list)
548 (delq elt (copy-sequence list))
549 list))
9a5336ae 550\f
9a5336ae 551;;;; Keymap support.
be9b65ac 552
ed8bd4d7
SM
553(defun kbd (keys)
554 "Convert KEYS to the internal Emacs key representation.
555KEYS should be a string constant in the format used for
556saving keyboard macros (see `edmacro-mode')."
557 ;; Don't use a defalias, since the `pure' property is only true for
558 ;; the calling convention of `kbd'.
559 (read-kbd-macro keys))
f95e9344 560(put 'kbd 'pure t)
c4f484f2 561
be9b65ac 562(defun undefined ()
3fa173b4 563 "Beep to tell the user this binding is undefined."
be9b65ac
DL
564 (interactive)
565 (ding))
566
c4f484f2
RS
567;; Prevent the \{...} documentation construct
568;; from mentioning keys that run this command.
be9b65ac
DL
569(put 'undefined 'suppress-keymap t)
570
571(defun suppress-keymap (map &optional nodigits)
572 "Make MAP override all normally self-inserting keys to be undefined.
573Normally, as an exception, digits and minus-sign are set to make prefix args,
574but optional second arg NODIGITS non-nil treats them like other chars."
098ba983 575 (define-key map [remap self-insert-command] 'undefined)
be9b65ac
DL
576 (or nodigits
577 (let (loop)
578 (define-key map "-" 'negative-argument)
579 ;; Make plain numbers do numeric args.
580 (setq loop ?0)
581 (while (<= loop ?9)
582 (define-key map (char-to-string loop) 'digit-argument)
583 (setq loop (1+ loop))))))
584
640c8776
SM
585(defun make-composed-keymap (maps &optional parent)
586 "Construct a new keymap composed of MAPS and inheriting from PARENT.
587When looking up a key in the returned map, the key is looked in each
588keymap of MAPS in turn until a binding is found.
589If no binding is found in MAPS, the lookup continues in PARENT, if non-nil.
590As always with keymap inheritance, a nil binding in MAPS overrides
591any corresponding binding in PARENT, but it does not override corresponding
592bindings in other keymaps of MAPS.
593MAPS can be a list of keymaps or a single keymap.
594PARENT if non-nil should be a keymap."
595 `(keymap
596 ,@(if (keymapp maps) (list maps) maps)
597 ,@parent))
598
4ced66fd 599(defun define-key-after (keymap key definition &optional after)
4434d61b
RS
600 "Add binding in KEYMAP for KEY => DEFINITION, right after AFTER's binding.
601This is like `define-key' except that the binding for KEY is placed
602just after the binding for the event AFTER, instead of at the beginning
c34a9d34
RS
603of the map. Note that AFTER must be an event type (like KEY), NOT a command
604\(like DEFINITION).
605
4ced66fd 606If AFTER is t or omitted, the new binding goes at the end of the keymap.
08b1f8a1 607AFTER should be a single event type--a symbol or a character, not a sequence.
c34a9d34 608
4ced66fd 609Bindings are always added before any inherited map.
c34a9d34 610
0181e193
LMI
611The order of bindings in a keymap only matters when it is used as
612a menu, so this function is not useful for non-menu keymaps."
4ced66fd 613 (unless after (setq after t))
4434d61b
RS
614 (or (keymapp keymap)
615 (signal 'wrong-type-argument (list 'keymapp keymap)))
08b1f8a1
GM
616 (setq key
617 (if (<= (length key) 1) (aref key 0)
618 (setq keymap (lookup-key keymap
619 (apply 'vector
620 (butlast (mapcar 'identity key)))))
621 (aref key (1- (length key)))))
622 (let ((tail keymap) done inserted)
4434d61b
RS
623 (while (and (not done) tail)
624 ;; Delete any earlier bindings for the same key.
08b1f8a1 625 (if (eq (car-safe (car (cdr tail))) key)
4434d61b 626 (setcdr tail (cdr (cdr tail))))
08b1f8a1
GM
627 ;; If we hit an included map, go down that one.
628 (if (keymapp (car tail)) (setq tail (car tail)))
4434d61b
RS
629 ;; When we reach AFTER's binding, insert the new binding after.
630 ;; If we reach an inherited keymap, insert just before that.
113d28a8 631 ;; If we reach the end of this keymap, insert at the end.
c34a9d34
RS
632 (if (or (and (eq (car-safe (car tail)) after)
633 (not (eq after t)))
113d28a8
RS
634 (eq (car (cdr tail)) 'keymap)
635 (null (cdr tail)))
4434d61b 636 (progn
113d28a8
RS
637 ;; Stop the scan only if we find a parent keymap.
638 ;; Keep going past the inserted element
639 ;; so we can delete any duplications that come later.
640 (if (eq (car (cdr tail)) 'keymap)
641 (setq done t))
642 ;; Don't insert more than once.
643 (or inserted
08b1f8a1 644 (setcdr tail (cons (cons key definition) (cdr tail))))
113d28a8 645 (setq inserted t)))
4434d61b
RS
646 (setq tail (cdr tail)))))
647
a10cca6c 648(defun map-keymap-sorted (function keymap)
14694a59
RS
649 "Implement `map-keymap' with sorting.
650Don't call this function; it is for internal use only."
a10cca6c
SM
651 (let (list)
652 (map-keymap (lambda (a b) (push (cons a b) list))
653 keymap)
654 (setq list (sort list
655 (lambda (a b)
656 (setq a (car a) b (car b))
657 (if (integerp a)
658 (if (integerp b) (< a b)
659 t)
660 (if (integerp b) t
661 ;; string< also accepts symbols.
662 (string< a b))))))
663 (dolist (p list)
664 (funcall function (car p) (cdr p)))))
51fa3961 665
3349e122
SM
666(defun keymap--menu-item-binding (val)
667 "Return the binding part of a menu-item."
668 (cond
669 ((not (consp val)) val) ;Not a menu-item.
670 ((eq 'menu-item (car val))
671 (let* ((binding (nth 2 val))
672 (plist (nthcdr 3 val))
673 (filter (plist-get plist :filter)))
674 (if filter (funcall filter binding)
675 binding)))
676 ((and (consp (cdr val)) (stringp (cadr val)))
677 (cddr val))
678 ((stringp (car val))
679 (cdr val))
680 (t val))) ;Not a menu-item either.
681
682(defun keymap--menu-item-with-binding (item binding)
683 "Build a menu-item like ITEM but with its binding changed to BINDING."
684 (cond
08e1d82c 685 ((not (consp item)) binding) ;Not a menu-item.
3349e122
SM
686 ((eq 'menu-item (car item))
687 (setq item (copy-sequence item))
688 (let ((tail (nthcdr 2 item)))
689 (setcar tail binding)
690 ;; Remove any potential filter.
691 (if (plist-get (cdr tail) :filter)
692 (setcdr tail (plist-put (cdr tail) :filter nil))))
693 item)
694 ((and (consp (cdr item)) (stringp (cadr item)))
695 (cons (car item) (cons (cadr item) binding)))
696 (t (cons (car item) binding))))
697
698(defun keymap--merge-bindings (val1 val2)
699 "Merge bindings VAL1 and VAL2."
700 (let ((map1 (keymap--menu-item-binding val1))
701 (map2 (keymap--menu-item-binding val2)))
702 (if (not (and (keymapp map1) (keymapp map2)))
703 ;; There's nothing to merge: val1 takes precedence.
704 val1
705 (let ((map (list 'keymap map1 map2))
706 (item (if (keymapp val1) (if (keymapp val2) nil val2) val1)))
707 (keymap--menu-item-with-binding item map)))))
708
00f7c5ed 709(defun keymap-canonicalize (map)
3349e122
SM
710 "Return a simpler equivalent keymap.
711This resolves inheritance and redefinitions. The returned keymap
712should behave identically to a copy of KEYMAP w.r.t `lookup-key'
713and use in active keymaps and menus.
714Subkeymaps may be modified but are not canonicalized."
715 ;; FIXME: Problem with the difference between a nil binding
716 ;; that hides a binding in an inherited map and a nil binding that's ignored
717 ;; to let some further binding visible. Currently a nil binding hides all.
718 ;; FIXME: we may want to carefully (re)order elements in case they're
719 ;; menu-entries.
00f7c5ed 720 (let ((bindings ())
c099a588
AS
721 (ranges ())
722 (prompt (keymap-prompt map)))
00f7c5ed 723 (while (keymapp map)
3349e122 724 (setq map (map-keymap ;; -internal
00f7c5ed
SM
725 (lambda (key item)
726 (if (consp key)
727 ;; Treat char-ranges specially.
728 (push (cons key item) ranges)
729 (push (cons key item) bindings)))
730 map)))
3349e122 731 ;; Create the new map.
c099a588 732 (setq map (funcall (if ranges 'make-keymap 'make-sparse-keymap) prompt))
00f7c5ed 733 (dolist (binding ranges)
3349e122 734 ;; Treat char-ranges specially. FIXME: need to merge as well.
64981d1a 735 (define-key map (vector (car binding)) (cdr binding)))
3349e122 736 ;; Process the bindings starting from the end.
00f7c5ed
SM
737 (dolist (binding (prog1 bindings (setq bindings ())))
738 (let* ((key (car binding))
00f7c5ed 739 (oldbind (assq key bindings)))
3349e122
SM
740 (push (if (not oldbind)
741 ;; The normal case: no duplicate bindings.
742 binding
743 ;; This is the second binding for this key.
744 (setq bindings (delq oldbind bindings))
745 (cons key (keymap--merge-bindings (cdr binding)
746 (cdr oldbind))))
747 bindings)))
00f7c5ed
SM
748 (nconc map bindings)))
749
8bed5e3d
RS
750(put 'keyboard-translate-table 'char-table-extra-slots 0)
751
9a5336ae 752(defun keyboard-translate (from to)
9aeb25a6 753 "Translate character FROM to TO on the current terminal.
9a5336ae
JB
754This function creates a `keyboard-translate-table' if necessary
755and then modifies one entry in it."
8bed5e3d
RS
756 (or (char-table-p keyboard-translate-table)
757 (setq keyboard-translate-table
758 (make-char-table 'keyboard-translate-table nil)))
9a5336ae 759 (aset keyboard-translate-table from to))
9a5336ae 760\f
c4f484f2 761;;;; Key binding commands.
9a5336ae 762
c4f484f2
RS
763(defun global-set-key (key command)
764 "Give KEY a global binding as COMMAND.
765COMMAND is the command definition to use; usually it is
766a symbol naming an interactively-callable function.
767KEY is a key sequence; noninteractively, it is a string or vector
768of characters or event types, and non-ASCII characters with codes
769above 127 (such as ISO Latin-1) can be included if you use a vector.
9a5336ae 770
c4f484f2
RS
771Note that if KEY has a local binding in the current buffer,
772that local binding will continue to shadow any global binding
773that you make with this function."
774 (interactive "KSet key globally: \nCSet key %s to command: ")
775 (or (vectorp key) (stringp key)
776 (signal 'wrong-type-argument (list 'arrayp key)))
777 (define-key (current-global-map) key command))
9a5336ae 778
c4f484f2
RS
779(defun local-set-key (key command)
780 "Give KEY a local binding as COMMAND.
781COMMAND is the command definition to use; usually it is
782a symbol naming an interactively-callable function.
783KEY is a key sequence; noninteractively, it is a string or vector
784of characters or event types, and non-ASCII characters with codes
785above 127 (such as ISO Latin-1) can be included if you use a vector.
9a5336ae 786
c4f484f2
RS
787The binding goes in the current buffer's local map,
788which in most cases is shared with all other buffers in the same major mode."
789 (interactive "KSet key locally: \nCSet key %s locally to command: ")
790 (let ((map (current-local-map)))
791 (or map
792 (use-local-map (setq map (make-sparse-keymap))))
793 (or (vectorp key) (stringp key)
794 (signal 'wrong-type-argument (list 'arrayp key)))
795 (define-key map key command)))
9a5336ae 796
c4f484f2
RS
797(defun global-unset-key (key)
798 "Remove global binding of KEY.
799KEY is a string or vector representing a sequence of keystrokes."
800 (interactive "kUnset key globally: ")
801 (global-set-key key nil))
9a5336ae 802
c4f484f2
RS
803(defun local-unset-key (key)
804 "Remove local binding of KEY.
805KEY is a string or vector representing a sequence of keystrokes."
806 (interactive "kUnset key locally: ")
807 (if (current-local-map)
808 (local-set-key key nil))
809 nil)
810\f
811;;;; substitute-key-definition and its subroutines.
812
813(defvar key-substitution-in-progress nil
c8227332 814 "Used internally by `substitute-key-definition'.")
c4f484f2
RS
815
816(defun substitute-key-definition (olddef newdef keymap &optional oldmap prefix)
817 "Replace OLDDEF with NEWDEF for any keys in KEYMAP now defined as OLDDEF.
818In other words, OLDDEF is replaced with NEWDEF where ever it appears.
819Alternatively, if optional fourth argument OLDMAP is specified, we redefine
820in KEYMAP as NEWDEF those keys which are defined as OLDDEF in OLDMAP.
821
fda11e85
RS
822If you don't specify OLDMAP, you can usually get the same results
823in a cleaner way with command remapping, like this:
50d16788
JB
824 \(define-key KEYMAP [remap OLDDEF] NEWDEF)
825\n(fn OLDDEF NEWDEF KEYMAP &optional OLDMAP)"
c4f484f2
RS
826 ;; Don't document PREFIX in the doc string because we don't want to
827 ;; advertise it. It's meant for recursive calls only. Here's its
828 ;; meaning
829
830 ;; If optional argument PREFIX is specified, it should be a key
831 ;; prefix, a string. Redefined bindings will then be bound to the
832 ;; original key, with PREFIX added at the front.
833 (or prefix (setq prefix ""))
834 (let* ((scan (or oldmap keymap))
835 (prefix1 (vconcat prefix [nil]))
836 (key-substitution-in-progress
837 (cons scan key-substitution-in-progress)))
838 ;; Scan OLDMAP, finding each char or event-symbol that
839 ;; has any definition, and act on it with hack-key.
840 (map-keymap
841 (lambda (char defn)
842 (aset prefix1 (length prefix) char)
843 (substitute-key-definition-key defn olddef newdef prefix1 keymap))
844 scan)))
845
846(defun substitute-key-definition-key (defn olddef newdef prefix keymap)
847 (let (inner-def skipped menu-item)
848 ;; Find the actual command name within the binding.
849 (if (eq (car-safe defn) 'menu-item)
850 (setq menu-item defn defn (nth 2 defn))
851 ;; Skip past menu-prompt.
852 (while (stringp (car-safe defn))
853 (push (pop defn) skipped))
854 ;; Skip past cached key-equivalence data for menu items.
855 (if (consp (car-safe defn))
856 (setq defn (cdr defn))))
857 (if (or (eq defn olddef)
858 ;; Compare with equal if definition is a key sequence.
859 ;; That is useful for operating on function-key-map.
860 (and (or (stringp defn) (vectorp defn))
861 (equal defn olddef)))
862 (define-key keymap prefix
863 (if menu-item
864 (let ((copy (copy-sequence menu-item)))
865 (setcar (nthcdr 2 copy) newdef)
866 copy)
867 (nconc (nreverse skipped) newdef)))
868 ;; Look past a symbol that names a keymap.
869 (setq inner-def
cf25c647 870 (or (indirect-function defn t) defn))
c4f484f2
RS
871 ;; For nested keymaps, we use `inner-def' rather than `defn' so as to
872 ;; avoid autoloading a keymap. This is mostly done to preserve the
873 ;; original non-autoloading behavior of pre-map-keymap times.
874 (if (and (keymapp inner-def)
875 ;; Avoid recursively scanning
876 ;; where KEYMAP does not have a submap.
877 (let ((elt (lookup-key keymap prefix)))
878 (or (null elt) (natnump elt) (keymapp elt)))
879 ;; Avoid recursively rescanning keymap being scanned.
880 (not (memq inner-def key-substitution-in-progress)))
881 ;; If this one isn't being scanned already, scan it now.
882 (substitute-key-definition olddef newdef keymap inner-def prefix)))))
9a5336ae
JB
883
884\f
264ef586 885;;;; The global keymap tree.
9a5336ae 886
354f0faf
SM
887;; global-map, esc-map, and ctl-x-map have their values set up in
888;; keymap.c; we just give them docstrings here.
9a5336ae
JB
889
890(defvar global-map nil
891 "Default global keymap mapping Emacs keyboard input into commands.
892The value is a keymap which is usually (but not necessarily) Emacs's
893global map.")
894
895(defvar esc-map nil
896 "Default keymap for ESC (meta) commands.
897The normal global definition of the character ESC indirects to this keymap.")
898
899(defvar ctl-x-map nil
900 "Default keymap for C-x commands.
901The normal global definition of the character C-x indirects to this keymap.")
902
903(defvar ctl-x-4-map (make-sparse-keymap)
03eeb110 904 "Keymap for subcommands of C-x 4.")
059184dd 905(defalias 'ctl-x-4-prefix ctl-x-4-map)
9a5336ae
JB
906(define-key ctl-x-map "4" 'ctl-x-4-prefix)
907
908(defvar ctl-x-5-map (make-sparse-keymap)
909 "Keymap for frame commands.")
059184dd 910(defalias 'ctl-x-5-prefix ctl-x-5-map)
9a5336ae
JB
911(define-key ctl-x-map "5" 'ctl-x-5-prefix)
912
0f03054a 913\f
9a5336ae
JB
914;;;; Event manipulation functions.
915
03a74b84 916(defconst listify-key-sequence-1 (logior 128 ?\M-\C-@))
114137b8 917
cde6d7e3
RS
918(defun listify-key-sequence (key)
919 "Convert a key sequence to a list of events."
920 (if (vectorp key)
921 (append key nil)
922 (mapcar (function (lambda (c)
923 (if (> c 127)
114137b8 924 (logxor c listify-key-sequence-1)
cde6d7e3 925 c)))
d47f7515 926 key)))
cde6d7e3 927
e1894109 928(defun eventp (obj)
53e5a4e8 929 "True if the argument is an event object."
e1894109
SM
930 (when obj
931 (or (integerp obj)
932 (and (symbolp obj) obj (not (keywordp obj)))
933 (and (consp obj) (symbolp (car obj))))))
53e5a4e8
RS
934
935(defun event-modifiers (event)
a3111ae4 936 "Return a list of symbols representing the modifier keys in event EVENT.
53e5a4e8 937The elements of the list may include `meta', `control',
32295976 938`shift', `hyper', `super', `alt', `click', `double', `triple', `drag',
0e91dc92
LT
939and `down'.
940EVENT may be an event or an event type. If EVENT is a symbol
941that has never been used in an event that has been read as input
b1a4f8e1
SM
942in the current Emacs session, then this function may fail to include
943the `click' modifier."
53e5a4e8
RS
944 (let ((type event))
945 (if (listp type)
946 (setq type (car type)))
947 (if (symbolp type)
58da34c7
SM
948 ;; Don't read event-symbol-elements directly since we're not
949 ;; sure the symbol has already been parsed.
950 (cdr (internal-event-symbol-parse-modifiers type))
5572c97f
RS
951 (let ((list nil)
952 (char (logand type (lognot (logior ?\M-\^@ ?\C-\^@ ?\S-\^@
953 ?\H-\^@ ?\s-\^@ ?\A-\^@)))))
954 (if (not (zerop (logand type ?\M-\^@)))
9166dbf6 955 (push 'meta list))
5572c97f
RS
956 (if (or (not (zerop (logand type ?\C-\^@)))
957 (< char 32))
9166dbf6 958 (push 'control list))
5572c97f
RS
959 (if (or (not (zerop (logand type ?\S-\^@)))
960 (/= char (downcase char)))
9166dbf6 961 (push 'shift list))
da16e648 962 (or (zerop (logand type ?\H-\^@))
9166dbf6 963 (push 'hyper list))
da16e648 964 (or (zerop (logand type ?\s-\^@))
9166dbf6 965 (push 'super list))
da16e648 966 (or (zerop (logand type ?\A-\^@))
9166dbf6 967 (push 'alt list))
53e5a4e8
RS
968 list))))
969
d63de416 970(defun event-basic-type (event)
a3111ae4 971 "Return the basic type of the given event (all modifiers removed).
0e91dc92
LT
972The value is a printing character (not upper case) or a symbol.
973EVENT may be an event or an event type. If EVENT is a symbol
974that has never been used in an event that has been read as input
975in the current Emacs session, then this function may return nil."
2b0f4ba5
JB
976 (if (consp event)
977 (setq event (car event)))
d63de416
RS
978 (if (symbolp event)
979 (car (get event 'event-symbol-elements))
9aca2476
RS
980 (let* ((base (logand event (1- ?\A-\^@)))
981 (uncontrolled (if (< base 32) (logior base 64) base)))
982 ;; There are some numbers that are invalid characters and
983 ;; cause `downcase' to get an error.
984 (condition-case ()
985 (downcase uncontrolled)
986 (error uncontrolled)))))
d63de416 987
0f03054a
RS
988(defsubst mouse-movement-p (object)
989 "Return non-nil if OBJECT is a mouse movement event."
9166dbf6 990 (eq (car-safe object) 'mouse-movement))
0f03054a 991
5ad4f91c
SS
992(defun mouse-event-p (object)
993 "Return non-nil if OBJECT is a mouse click event."
994 ;; is this really correct? maybe remove mouse-movement?
995 (memq (event-basic-type object) '(mouse-1 mouse-2 mouse-3 mouse-movement)))
996
e1894109 997(defun event-start (event)
0f03054a 998 "Return the starting position of EVENT.
c88aaf48
CY
999EVENT should be a click, drag, or key press event.
1000If it is a key press event, the return value has the form
1001 (WINDOW POS (0 . 0) 0)
1002If it is a click or drag event, it has the form
6b61353c
KH
1003 (WINDOW AREA-OR-POS (X . Y) TIMESTAMP OBJECT POS (COL . ROW)
1004 IMAGE (DX . DY) (WIDTH . HEIGHT))
c88aaf48
CY
1005The `posn-' functions access elements of such lists.
1006For more information, see Info node `(elisp)Click Events'.
1007
1008If EVENT is a mouse or key press or a mouse click, this is the
1009position of the event. If EVENT is a drag, this is the starting
1010position of the drag."
5ef6a86d 1011 (if (consp event) (nth 1 event)
e1894109
SM
1012 (or (posn-at-point)
1013 (list (selected-window) (point) '(0 . 0) 0))))
0f03054a 1014
e1894109 1015(defun event-end (event)
6b61353c
KH
1016 "Return the ending location of EVENT.
1017EVENT should be a click, drag, or key press event.
c88aaf48
CY
1018If EVENT is a key press event, the return value has the form
1019 (WINDOW POS (0 . 0) 0)
1020If EVENT is a click event, this function is the same as
1021`event-start'. For click and drag events, the return value has
1022the form
6b61353c
KH
1023 (WINDOW AREA-OR-POS (X . Y) TIMESTAMP OBJECT POS (COL . ROW)
1024 IMAGE (DX . DY) (WIDTH . HEIGHT))
c88aaf48
CY
1025The `posn-' functions access elements of such lists.
1026For more information, see Info node `(elisp)Click Events'.
1027
1028If EVENT is a mouse or key press or a mouse click, this is the
1029position of the event. If EVENT is a drag, this is the starting
1030position of the drag."
5ef6a86d 1031 (if (consp event) (nth (if (consp (nth 2 event)) 2 1) event)
e1894109
SM
1032 (or (posn-at-point)
1033 (list (selected-window) (point) '(0 . 0) 0))))
0f03054a 1034
32295976
RS
1035(defsubst event-click-count (event)
1036 "Return the multi-click count of EVENT, a click or drag event.
1037The return value is a positive integer."
5ef6a86d 1038 (if (and (consp event) (integerp (nth 2 event))) (nth 2 event) 1))
c4f484f2
RS
1039\f
1040;;;; Extracting fields of the positions in an event.
32295976 1041
e1894109
SM
1042(defun posnp (obj)
1043 "Return non-nil if OBJ appears to be a valid `posn' object."
1044 (and (windowp (car-safe obj))
1045 (atom (car-safe (setq obj (cdr obj)))) ;AREA-OR-POS.
1046 (integerp (car-safe (car-safe (setq obj (cdr obj))))) ;XOFFSET.
1047 (integerp (car-safe (cdr obj))))) ;TIMESTAMP.
1048
0f03054a
RS
1049(defsubst posn-window (position)
1050 "Return the window in POSITION.
6b61353c
KH
1051POSITION should be a list of the form returned by the `event-start'
1052and `event-end' functions."
0f03054a
RS
1053 (nth 0 position))
1054
6b61353c
KH
1055(defsubst posn-area (position)
1056 "Return the window area recorded in POSITION, or nil for the text area.
1057POSITION should be a list of the form returned by the `event-start'
1058and `event-end' functions."
1059 (let ((area (if (consp (nth 1 position))
1060 (car (nth 1 position))
1061 (nth 1 position))))
1062 (and (symbolp area) area)))
1063
9a1ff164 1064(defun posn-point (position)
0f03054a 1065 "Return the buffer location in POSITION.
6b61353c 1066POSITION should be a list of the form returned by the `event-start'
9a1ff164
SM
1067and `event-end' functions.
1068Returns nil if POSITION does not correspond to any buffer location (e.g.
1069a click on a scroll bar)."
6b61353c 1070 (or (nth 5 position)
9a1ff164
SM
1071 (let ((pt (nth 1 position)))
1072 (or (car-safe pt)
1073 ;; Apparently this can also be `vertical-scroll-bar' (bug#13979).
1074 (if (integerp pt) pt)))))
6b61353c
KH
1075
1076(defun posn-set-point (position)
1077 "Move point to POSITION.
1078Select the corresponding window as well."
c8227332
VJL
1079 (if (not (windowp (posn-window position)))
1080 (error "Position not in text area of window"))
1081 (select-window (posn-window position))
1082 (if (numberp (posn-point position))
1083 (goto-char (posn-point position))))
0f03054a 1084
e55c21be
RS
1085(defsubst posn-x-y (position)
1086 "Return the x and y coordinates in POSITION.
74194465
CY
1087The return value has the form (X . Y), where X and Y are given in
1088pixels. POSITION should be a list of the form returned by
1089`event-start' and `event-end'."
0f03054a
RS
1090 (nth 2 position))
1091
aa360da1
GM
1092(declare-function scroll-bar-scale "scroll-bar" (num-denom whole))
1093
ed627e08 1094(defun posn-col-row (position)
6b61353c
KH
1095 "Return the nominal column and row in POSITION, measured in characters.
1096The column and row values are approximations calculated from the x
1097and y coordinates in POSITION and the frame's default character width
1098and height.
ed627e08 1099For a scroll-bar event, the result column is 0, and the row
6b61353c
KH
1100corresponds to the vertical position of the click in the scroll bar.
1101POSITION should be a list of the form returned by the `event-start'
1102and `event-end' functions."
1103 (let* ((pair (posn-x-y position))
1104 (window (posn-window position))
1105 (area (posn-area position)))
1106 (cond
1107 ((null window)
1108 '(0 . 0))
1109 ((eq area 'vertical-scroll-bar)
1110 (cons 0 (scroll-bar-scale pair (1- (window-height window)))))
1111 ((eq area 'horizontal-scroll-bar)
1112 (cons (scroll-bar-scale pair (window-width window)) 0))
1113 (t
1114 (let* ((frame (if (framep window) window (window-frame window)))
7beba943
CY
1115 ;; FIXME: This should take line-spacing properties on
1116 ;; newlines into account.
1117 (spacing (when (display-graphic-p frame)
1118 (or (with-current-buffer (window-buffer window)
1119 line-spacing)
1120 (frame-parameter frame 'line-spacing)))))
1121 (cond ((floatp spacing)
1122 (setq spacing (truncate (* spacing
1123 (frame-char-height frame)))))
1124 ((null spacing)
1125 (setq spacing 0)))
1126 (cons (/ (car pair) (frame-char-width frame))
e68afd74 1127 (- (/ (cdr pair) (+ (frame-char-height frame) spacing))
11aad4e9
EZ
1128 (if (null (with-current-buffer (window-buffer window)
1129 header-line-format))
1130 0 1))))))))
6b61353c
KH
1131
1132(defun posn-actual-col-row (position)
1133 "Return the actual column and row in POSITION, measured in characters.
1134These are the actual row number in the window and character number in that row.
1135Return nil if POSITION does not contain the actual position; in that case
1136`posn-col-row' can be used to get approximate values.
1137POSITION should be a list of the form returned by the `event-start'
1138and `event-end' functions."
1139 (nth 6 position))
e55c21be 1140
0f03054a
RS
1141(defsubst posn-timestamp (position)
1142 "Return the timestamp of POSITION.
6b61353c
KH
1143POSITION should be a list of the form returned by the `event-start'
1144and `event-end' functions."
0f03054a 1145 (nth 3 position))
9a5336ae 1146
9a1ff164 1147(defun posn-string (position)
79a09c9c
KS
1148 "Return the string object of POSITION.
1149Value is a cons (STRING . STRING-POS), or nil if not a string.
6b61353c
KH
1150POSITION should be a list of the form returned by the `event-start'
1151and `event-end' functions."
9a1ff164
SM
1152 (let ((x (nth 4 position)))
1153 ;; Apparently this can also be `handle' or `below-handle' (bug#13979).
1154 (when (consp x) x)))
6b61353c
KH
1155
1156(defsubst posn-image (position)
79a09c9c 1157 "Return the image object of POSITION.
0c3f75f6 1158Value is a list (image ...), or nil if not an image.
6b61353c
KH
1159POSITION should be a list of the form returned by the `event-start'
1160and `event-end' functions."
1161 (nth 7 position))
1162
1163(defsubst posn-object (position)
1164 "Return the object (image or string) of POSITION.
79a09c9c
KS
1165Value is a list (image ...) for an image object, a cons cell
1166\(STRING . STRING-POS) for a string object, and nil for a buffer position.
6b61353c
KH
1167POSITION should be a list of the form returned by the `event-start'
1168and `event-end' functions."
1169 (or (posn-image position) (posn-string position)))
1170
1171(defsubst posn-object-x-y (position)
1172 "Return the x and y coordinates relative to the object of POSITION.
74194465
CY
1173The return value has the form (DX . DY), where DX and DY are
1174given in pixels. POSITION should be a list of the form returned
1175by `event-start' and `event-end'."
6b61353c
KH
1176 (nth 8 position))
1177
1178(defsubst posn-object-width-height (position)
1179 "Return the pixel width and height of the object of POSITION.
74194465
CY
1180The return value has the form (WIDTH . HEIGHT). POSITION should
1181be a list of the form returned by `event-start' and `event-end'."
6b61353c
KH
1182 (nth 9 position))
1183
0f03054a 1184\f
9a5336ae
JB
1185;;;; Obsolescent names for functions.
1186
9d28c33e
SM
1187(define-obsolete-function-alias 'window-dot 'window-point "22.1")
1188(define-obsolete-function-alias 'set-window-dot 'set-window-point "22.1")
1189(define-obsolete-function-alias 'read-input 'read-string "22.1")
1190(define-obsolete-function-alias 'show-buffer 'set-window-buffer "22.1")
1191(define-obsolete-function-alias 'eval-current-buffer 'eval-buffer "22.1")
1192(define-obsolete-function-alias 'string-to-int 'string-to-number "22.1")
1193
9d28c33e 1194(make-obsolete 'forward-point "use (+ (point) N) instead." "23.1")
2a1e2476 1195(make-obsolete 'buffer-has-markers-at nil "24.3")
9d28c33e
SM
1196
1197(defun insert-string (&rest args)
1198 "Mocklisp-compatibility insert function.
1199Like the function `insert' except that any argument that is a number
1200is converted into a string by expressing it in decimal."
59f7af81 1201 (declare (obsolete insert "22.1"))
9d28c33e
SM
1202 (dolist (el args)
1203 (insert (if (integerp el) (number-to-string el) el))))
9d28c33e 1204
59f7af81
CY
1205(defun makehash (&optional test)
1206 (declare (obsolete make-hash-table "22.1"))
1207 (make-hash-table :test (or test 'eql)))
9d28c33e
SM
1208
1209;; These are used by VM and some old programs
1210(defalias 'focus-frame 'ignore "")
1211(make-obsolete 'focus-frame "it does nothing." "22.1")
1212(defalias 'unfocus-frame 'ignore "")
1213(make-obsolete 'unfocus-frame "it does nothing." "22.1")
1214(make-obsolete 'make-variable-frame-local
1215 "explicitly check for a frame-parameter instead." "22.2")
4fcc3d32 1216(set-advertised-calling-convention
f3a30a50
SM
1217 'all-completions '(string collection &optional predicate) "23.1")
1218(set-advertised-calling-convention 'unintern '(name obarray) "23.3")
2a1e2476 1219(set-advertised-calling-convention 'redirect-frame-focus '(frame focus-frame) "24.3")
9d28c33e
SM
1220\f
1221;;;; Obsolescence declarations for variables, and aliases.
1222
4e3b4528
SM
1223;; Special "default-FOO" variables which contain the default value of
1224;; the "FOO" variable are nasty. Their implementation is brittle, and
1225;; slows down several unrelated variable operations; furthermore, they
1226;; can lead to really odd behavior if you decide to make them
1227;; buffer-local.
1228
1229;; Not used at all in Emacs, last time I checked:
1230(make-obsolete-variable 'default-mode-line-format 'mode-line-format "23.2")
1231(make-obsolete-variable 'default-header-line-format 'header-line-format "23.2")
1232(make-obsolete-variable 'default-line-spacing 'line-spacing "23.2")
1233(make-obsolete-variable 'default-abbrev-mode 'abbrev-mode "23.2")
1234(make-obsolete-variable 'default-ctl-arrow 'ctl-arrow "23.2")
4e3b4528
SM
1235(make-obsolete-variable 'default-truncate-lines 'truncate-lines "23.2")
1236(make-obsolete-variable 'default-left-margin 'left-margin "23.2")
1237(make-obsolete-variable 'default-tab-width 'tab-width "23.2")
1238(make-obsolete-variable 'default-case-fold-search 'case-fold-search "23.2")
1239(make-obsolete-variable 'default-left-margin-width 'left-margin-width "23.2")
1240(make-obsolete-variable 'default-right-margin-width 'right-margin-width "23.2")
1241(make-obsolete-variable 'default-left-fringe-width 'left-fringe-width "23.2")
1242(make-obsolete-variable 'default-right-fringe-width 'right-fringe-width "23.2")
1243(make-obsolete-variable 'default-fringes-outside-margins 'fringes-outside-margins "23.2")
1244(make-obsolete-variable 'default-scroll-bar-width 'scroll-bar-width "23.2")
1245(make-obsolete-variable 'default-vertical-scroll-bar 'vertical-scroll-bar "23.2")
1246(make-obsolete-variable 'default-indicate-empty-lines 'indicate-empty-lines "23.2")
1247(make-obsolete-variable 'default-indicate-buffer-boundaries 'indicate-buffer-boundaries "23.2")
1248(make-obsolete-variable 'default-fringe-indicator-alist 'fringe-indicator-alist "23.2")
1249(make-obsolete-variable 'default-fringe-cursor-alist 'fringe-cursor-alist "23.2")
1250(make-obsolete-variable 'default-scroll-up-aggressively 'scroll-up-aggressively "23.2")
1251(make-obsolete-variable 'default-scroll-down-aggressively 'scroll-down-aggressively "23.2")
1252(make-obsolete-variable 'default-fill-column 'fill-column "23.2")
1253(make-obsolete-variable 'default-cursor-type 'cursor-type "23.2")
4e3b4528
SM
1254(make-obsolete-variable 'default-cursor-in-non-selected-windows 'cursor-in-non-selected-windows "23.2")
1255(make-obsolete-variable 'default-buffer-file-coding-system 'buffer-file-coding-system "23.2")
1256(make-obsolete-variable 'default-major-mode 'major-mode "23.2")
1257(make-obsolete-variable 'default-enable-multibyte-characters
1258 "use enable-multibyte-characters or set-buffer-multibyte instead" "23.2")
1259
50d4ba39 1260(make-obsolete-variable 'define-key-rebound-commands nil "23.2")
379ec02c 1261(make-obsolete-variable 'redisplay-end-trigger-functions 'jit-lock-register "23.1")
78f64af0
SM
1262(make-obsolete-variable 'deferred-action-list 'post-command-hook "24.1")
1263(make-obsolete-variable 'deferred-action-function 'post-command-hook "24.1")
bfa3acd6
SM
1264(make-obsolete-variable 'overriding-local-map
1265 'overriding-terminal-local-map "24.4" 'set)
379ec02c
SM
1266(make-obsolete 'window-redisplay-end-trigger nil "23.1")
1267(make-obsolete 'set-window-redisplay-end-trigger nil "23.1")
1268
1269(make-obsolete 'process-filter-multibyte-p nil "23.1")
1270(make-obsolete 'set-process-filter-multibyte nil "23.1")
1271
8ee7e9db
LT
1272;; Lisp manual only updated in 22.1.
1273(define-obsolete-variable-alias 'executing-macro 'executing-kbd-macro
c8227332 1274 "before 19.34")
8ee7e9db 1275
d1069532
SM
1276(define-obsolete-variable-alias 'x-lost-selection-hooks
1277 'x-lost-selection-functions "22.1")
1278(define-obsolete-variable-alias 'x-sent-selection-hooks
1279 'x-sent-selection-functions "22.1")
9e247d24 1280
b46957e2
EZ
1281;; This was introduced in 21.4 for pre-unicode unification. That
1282;; usage was rendered obsolete in 23.1 which uses Unicode internally.
1283;; Other uses are possible, so this variable is not _really_ obsolete,
1284;; but Stefan insists to mark it so.
1285(make-obsolete-variable 'translation-table-for-input nil "23.1")
1286
9e247d24 1287(defvaralias 'messages-buffer-max-lines 'message-log-max)
9a5336ae
JB
1288\f
1289;;;; Alternate names for functions - these are not being phased out.
1290
a18ff988
JB
1291(defalias 'send-string 'process-send-string)
1292(defalias 'send-region 'process-send-region)
059184dd
ER
1293(defalias 'string= 'string-equal)
1294(defalias 'string< 'string-lessp)
1295(defalias 'move-marker 'set-marker)
059184dd
ER
1296(defalias 'rplaca 'setcar)
1297(defalias 'rplacd 'setcdr)
eb8c3be9 1298(defalias 'beep 'ding) ;preserve lingual purity
059184dd
ER
1299(defalias 'indent-to-column 'indent-to)
1300(defalias 'backward-delete-char 'delete-backward-char)
1301(defalias 'search-forward-regexp (symbol-function 're-search-forward))
1302(defalias 'search-backward-regexp (symbol-function 're-search-backward))
1303(defalias 'int-to-string 'number-to-string)
024ae2c6 1304(defalias 'store-match-data 'set-match-data)
e6979067 1305(defalias 'chmod 'set-file-modes)
53374291 1306(defalias 'mkdir 'make-directory)
d6c22d46 1307;; These are the XEmacs names:
475fb2fb
KH
1308(defalias 'point-at-eol 'line-end-position)
1309(defalias 'point-at-bol 'line-beginning-position)
37f6661a 1310
c4f484f2
RS
1311(defalias 'user-original-login-name 'user-login-name)
1312
be9b65ac 1313\f
9a5336ae 1314;;;; Hook manipulation functions.
be9b65ac 1315
0e4d378b 1316(defun add-hook (hook function &optional append local)
32295976
RS
1317 "Add to the value of HOOK the function FUNCTION.
1318FUNCTION is not added if already present.
1319FUNCTION is added (if necessary) at the beginning of the hook list
1320unless the optional argument APPEND is non-nil, in which case
1321FUNCTION is added at the end.
1322
0e4d378b 1323The optional fourth argument, LOCAL, if non-nil, says to modify
465c5fc8
LMI
1324the hook's buffer-local value rather than its global value.
1325This makes the hook buffer-local, and it makes t a member of the
1326buffer-local value. That acts as a flag to run the hook
1327functions of the global value as well as in the local value.
0e4d378b 1328
32295976
RS
1329HOOK should be a symbol, and FUNCTION may be any valid function. If
1330HOOK is void, it is first set to nil. If HOOK's value is a single
aa09b5ca 1331function, it is changed to a list of functions."
be9b65ac 1332 (or (boundp hook) (set hook nil))
0e4d378b 1333 (or (default-boundp hook) (set-default hook nil))
08b1f8a1
GM
1334 (if local (unless (local-variable-if-set-p hook)
1335 (set (make-local-variable hook) (list t)))
8947a5e2
SM
1336 ;; Detect the case where make-local-variable was used on a hook
1337 ;; and do what we used to do.
1338 (unless (and (consp (symbol-value hook)) (memq t (symbol-value hook)))
1339 (setq local t)))
1340 (let ((hook-value (if local (symbol-value hook) (default-value hook))))
1341 ;; If the hook value is a single function, turn it into a list.
1342 (when (or (not (listp hook-value)) (eq (car hook-value) 'lambda))
2248c40d 1343 (setq hook-value (list hook-value)))
8947a5e2
SM
1344 ;; Do the actual addition if necessary
1345 (unless (member function hook-value)
ff917d63
DN
1346 (when (stringp function)
1347 (setq function (purecopy function)))
8947a5e2
SM
1348 (setq hook-value
1349 (if append
1350 (append hook-value (list function))
1351 (cons function hook-value))))
1352 ;; Set the actual variable
35310461
RS
1353 (if local
1354 (progn
1355 ;; If HOOK isn't a permanent local,
1356 ;; but FUNCTION wants to survive a change of modes,
1357 ;; mark HOOK as partially permanent.
1358 (and (symbolp function)
1359 (get function 'permanent-local-hook)
1360 (not (get hook 'permanent-local))
1361 (put hook 'permanent-local 'permanent-local-hook))
1362 (set hook hook-value))
1363 (set-default hook hook-value))))
0e4d378b
RS
1364
1365(defun remove-hook (hook function &optional local)
24980d16
RS
1366 "Remove from the value of HOOK the function FUNCTION.
1367HOOK should be a symbol, and FUNCTION may be any valid function. If
1368FUNCTION isn't the value of HOOK, or, if FUNCTION doesn't appear in the
0e4d378b
RS
1369list of hooks to run in HOOK, then nothing is done. See `add-hook'.
1370
1371The optional third argument, LOCAL, if non-nil, says to modify
6b61353c 1372the hook's buffer-local value rather than its default value."
8947a5e2
SM
1373 (or (boundp hook) (set hook nil))
1374 (or (default-boundp hook) (set-default hook nil))
6b61353c
KH
1375 ;; Do nothing if LOCAL is t but this hook has no local binding.
1376 (unless (and local (not (local-variable-p hook)))
8947a5e2
SM
1377 ;; Detect the case where make-local-variable was used on a hook
1378 ;; and do what we used to do.
6b61353c
KH
1379 (when (and (local-variable-p hook)
1380 (not (and (consp (symbol-value hook))
1381 (memq t (symbol-value hook)))))
1382 (setq local t))
1383 (let ((hook-value (if local (symbol-value hook) (default-value hook))))
1384 ;; Remove the function, for both the list and the non-list cases.
1385 (if (or (not (listp hook-value)) (eq (car hook-value) 'lambda))
1386 (if (equal hook-value function) (setq hook-value nil))
1387 (setq hook-value (delete function (copy-sequence hook-value))))
1388 ;; If the function is on the global hook, we need to shadow it locally
1389 ;;(when (and local (member function (default-value hook))
1390 ;; (not (member (cons 'not function) hook-value)))
1391 ;; (push (cons 'not function) hook-value))
1392 ;; Set the actual variable
1393 (if (not local)
1394 (set-default hook hook-value)
1395 (if (equal hook-value '(t))
1396 (kill-local-variable hook)
1397 (set hook hook-value))))))
6e3af630 1398
ba83908c
SM
1399(defmacro letrec (binders &rest body)
1400 "Bind variables according to BINDERS then eval BODY.
1401The value of the last form in BODY is returned.
1402Each element of BINDERS is a list (SYMBOL VALUEFORM) which binds
1403SYMBOL to the value of VALUEFORM.
1404All symbols are bound before the VALUEFORMs are evalled."
1405 ;; Only useful in lexical-binding mode.
1406 ;; As a special-form, we could implement it more efficiently (and cleanly,
1407 ;; making the vars actually unbound during evaluation of the binders).
1408 (declare (debug let) (indent 1))
1409 `(let ,(mapcar #'car binders)
1410 ,@(mapcar (lambda (binder) `(setq ,@binder)) binders)
1411 ,@body))
1412
b1f6fa26
CY
1413(defmacro with-wrapper-hook (hook args &rest body)
1414 "Run BODY, using wrapper functions from HOOK with additional ARGS.
1415HOOK is an abnormal hook. Each hook function in HOOK \"wraps\"
1416around the preceding ones, like a set of nested `around' advices.
1417
1418Each hook function should accept an argument list consisting of a
1419function FUN, followed by the additional arguments in ARGS.
1420
c7291ad9
GM
1421The first hook function in HOOK is passed a FUN that, if it is called
1422with arguments ARGS, performs BODY (i.e., the default operation).
1423The FUN passed to each successive hook function is defined based
1424on the preceding hook functions; if called with arguments ARGS,
1425it does what the `with-wrapper-hook' call would do if the
1426preceding hook functions were the only ones present in HOOK.
1427
1428Each hook function may call its FUN argument as many times as it wishes,
1429including never. In that case, such a hook function acts to replace
1430the default definition altogether, and any preceding hook functions.
1431Of course, a subsequent hook function may do the same thing.
1432
1433Each hook function definition is used to construct the FUN passed
b1f6fa26
CY
1434to the next hook function, if any. The last (or \"outermost\")
1435FUN is then called once."
d36ed1c8
SM
1436 (declare (indent 2) (debug (form sexp body))
1437 (obsolete "use a <foo>-function variable modified by add-function."
1438 "24.4"))
ba83908c
SM
1439 ;; We need those two gensyms because CL's lexical scoping is not available
1440 ;; for function arguments :-(
1441 (let ((funs (make-symbol "funs"))
1442 (global (make-symbol "global"))
1443 (argssym (make-symbol "args"))
1444 (runrestofhook (make-symbol "runrestofhook")))
1445 ;; Since the hook is a wrapper, the loop has to be done via
1446 ;; recursion: a given hook function will call its parameter in order to
1447 ;; continue looping.
1448 `(letrec ((,runrestofhook
1449 (lambda (,funs ,global ,argssym)
1450 ;; `funs' holds the functions left on the hook and `global'
1451 ;; holds the functions left on the global part of the hook
1452 ;; (in case the hook is local).
1453 (if (consp ,funs)
1454 (if (eq t (car ,funs))
1455 (funcall ,runrestofhook
1456 (append ,global (cdr ,funs)) nil ,argssym)
1457 (apply (car ,funs)
1458 (apply-partially
1459 (lambda (,funs ,global &rest ,argssym)
1460 (funcall ,runrestofhook ,funs ,global ,argssym))
1461 (cdr ,funs) ,global)
1462 ,argssym))
1463 ;; Once there are no more functions on the hook, run
1464 ;; the original body.
1465 (apply (lambda ,args ,@body) ,argssym)))))
b1f6fa26 1466 (funcall ,runrestofhook ,hook
ba83908c 1467 ;; The global part of the hook, if any.
b1f6fa26
CY
1468 ,(if (symbolp hook)
1469 `(if (local-variable-p ',hook)
1470 (default-value ',hook)))
ba83908c
SM
1471 (list ,@args)))))
1472
62e197b1 1473(defun add-to-list (list-var element &optional append compare-fn)
4072ef25 1474 "Add ELEMENT to the value of LIST-VAR if it isn't there yet.
62e197b1
RS
1475The test for presence of ELEMENT is done with `equal',
1476or with COMPARE-FN if that's non-nil.
c8bfa689
MB
1477If ELEMENT is added, it is added at the beginning of the list,
1478unless the optional argument APPEND is non-nil, in which case
1479ELEMENT is added at the end.
508bcbca 1480
daebae3d
PJ
1481The return value is the new value of LIST-VAR.
1482
bfa3acd6
SM
1483This is handy to add some elements to configuration variables,
1484but please do not abuse it in Elisp code, where you are usually better off
1485using `push' or `cl-pushnew'.
1486
8851c1f0
RS
1487If you want to use `add-to-list' on a variable that is not defined
1488until a certain package is loaded, you should put the call to `add-to-list'
1489into a hook function that will be run only after loading the package.
1490`eval-after-load' provides one way to do this. In some cases
1491other hooks, such as major mode hooks, can do the job."
bfa3acd6
SM
1492 (declare
1493 (compiler-macro
1494 (lambda (exp)
1495 ;; FIXME: Something like this could be used for `set' as well.
1496 (if (or (not (eq 'quote (car-safe list-var)))
1497 (special-variable-p (cadr list-var))
1498 (and append compare-fn))
1499 exp
1500 (let* ((sym (cadr list-var))
1501 (msg (format "`add-to-list' can't use lexical var `%s'; use `push' or `cl-pushnew'"
1502 sym))
1503 ;; Big ugly hack so we only output a warning during
1504 ;; byte-compilation, and so we can use
1505 ;; byte-compile-not-lexical-var-p to silence the warning
1506 ;; when a defvar has been seen but not yet executed.
1507 (warnfun (lambda ()
1508 ;; FIXME: We should also emit a warning for let-bound
1509 ;; variables with dynamic binding.
1510 (when (assq sym byte-compile--lexical-environment)
1511 (byte-compile-log-warning msg t :error))))
1512 (code
1513 (if append
1514 (macroexp-let2 macroexp-copyable-p x element
1515 `(unless (member ,x ,sym)
1516 (setq ,sym (append ,sym (list ,x)))))
1517 (require 'cl-lib)
1518 `(cl-pushnew ,element ,sym
1519 :test ,(or compare-fn '#'equal)))))
1520 (if (not (macroexp--compiling-p))
1521 code
1522 `(progn
1523 (macroexp--funcall-if-compiled ',warnfun)
1524 ,code)))))))
fb1a5d8a 1525 (if (cond
78bdfbf3 1526 ((null compare-fn)
62e197b1 1527 (member element (symbol-value list-var)))
fb1a5d8a
KS
1528 ((eq compare-fn 'eq)
1529 (memq element (symbol-value list-var)))
1530 ((eq compare-fn 'eql)
1531 (memql element (symbol-value list-var)))
78bdfbf3 1532 (t
2d1dd54d
DK
1533 (let ((lst (symbol-value list-var)))
1534 (while (and lst
1535 (not (funcall compare-fn element (car lst))))
1536 (setq lst (cdr lst)))
1537 lst)))
15171a06 1538 (symbol-value list-var)
c8bfa689
MB
1539 (set list-var
1540 (if append
1541 (append (symbol-value list-var) (list element))
1542 (cons element (symbol-value list-var))))))
448a0170 1543
cbbd0b5a
KS
1544
1545(defun add-to-ordered-list (list-var element &optional order)
4072ef25 1546 "Add ELEMENT to the value of LIST-VAR if it isn't there yet.
ef1eef06 1547The test for presence of ELEMENT is done with `eq'.
cbbd0b5a
KS
1548
1549The resulting list is reordered so that the elements are in the
ef1eef06
KS
1550order given by each element's numeric list order. Elements
1551without a numeric list order are placed at the end of the list.
cbbd0b5a 1552
4072ef25
LT
1553If the third optional argument ORDER is a number (integer or
1554float), set the element's list order to the given value. If
1555ORDER is nil or omitted, do not change the numeric order of
1556ELEMENT. If ORDER has any other value, remove the numeric order
1557of ELEMENT if it has one.
8da6c2f8 1558
219fd6cf 1559The list order for each element is stored in LIST-VAR's
8da6c2f8 1560`list-order' property.
cbbd0b5a
KS
1561
1562The return value is the new value of LIST-VAR."
219fd6cf
SM
1563 (let ((ordering (get list-var 'list-order)))
1564 (unless ordering
1565 (put list-var 'list-order
1566 (setq ordering (make-hash-table :weakness 'key :test 'eq))))
8da6c2f8 1567 (when order
ef1eef06
KS
1568 (puthash element (and (numberp order) order) ordering))
1569 (unless (memq element (symbol-value list-var))
1570 (set list-var (cons element (symbol-value list-var))))
8da6c2f8
KS
1571 (set list-var (sort (symbol-value list-var)
1572 (lambda (a b)
219fd6cf
SM
1573 (let ((oa (gethash a ordering))
1574 (ob (gethash b ordering)))
ef1eef06
KS
1575 (if (and oa ob)
1576 (< oa ob)
1577 oa)))))))
6b04bd6e 1578
d7494911 1579(defun add-to-history (history-var newelt &optional maxelt keep-all)
6b04bd6e
KS
1580 "Add NEWELT to the history list stored in the variable HISTORY-VAR.
1581Return the new history list.
1582If MAXELT is non-nil, it specifies the maximum length of the history.
1583Otherwise, the maximum history length is the value of the `history-length'
1584property on symbol HISTORY-VAR, if set, or the value of the `history-length'
1585variable.
d7494911
KS
1586Remove duplicates of NEWELT if `history-delete-duplicates' is non-nil.
1587If optional fourth arg KEEP-ALL is non-nil, add NEWELT to history even
1588if it is empty or a duplicate."
6b04bd6e
KS
1589 (unless maxelt
1590 (setq maxelt (or (get history-var 'history-length)
1591 history-length)))
1592 (let ((history (symbol-value history-var))
1593 tail)
d7494911
KS
1594 (when (and (listp history)
1595 (or keep-all
1596 (not (stringp newelt))
1597 (> (length newelt) 0))
1598 (or keep-all
1599 (not (equal (car history) newelt))))
1600 (if history-delete-duplicates
1715f2db 1601 (setq history (delete newelt history)))
d7494911
KS
1602 (setq history (cons newelt history))
1603 (when (integerp maxelt)
1604 (if (= 0 maxelt)
1605 (setq history nil)
1606 (setq tail (nthcdr (1- maxelt) history))
1607 (when (consp tail)
1608 (setcdr tail nil)))))
6b04bd6e
KS
1609 (set history-var history)))
1610
c4f484f2
RS
1611\f
1612;;;; Mode hooks.
1613
1614(defvar delay-mode-hooks nil
1615 "If non-nil, `run-mode-hooks' should delay running the hooks.")
1616(defvar delayed-mode-hooks nil
1617 "List of delayed mode hooks waiting to be run.")
1618(make-variable-buffer-local 'delayed-mode-hooks)
1619(put 'delay-mode-hooks 'permanent-local t)
cbbd0b5a 1620
15de15c6
CY
1621(defvar change-major-mode-after-body-hook nil
1622 "Normal hook run in major mode functions, before the mode hooks.")
1623
c4f484f2
RS
1624(defvar after-change-major-mode-hook nil
1625 "Normal hook run at the very end of major mode functions.")
1626
1627(defun run-mode-hooks (&rest hooks)
1628 "Run mode hooks `delayed-mode-hooks' and HOOKS, or delay HOOKS.
12f381b7
GM
1629If the variable `delay-mode-hooks' is non-nil, does not run any hooks,
1630just adds the HOOKS to the list `delayed-mode-hooks'.
1631Otherwise, runs hooks in the sequence: `change-major-mode-after-body-hook',
1632`delayed-mode-hooks' (in reverse order), HOOKS, and finally
1633`after-change-major-mode-hook'. Major mode functions should use
1634this instead of `run-hooks' when running their FOO-mode-hook."
c4f484f2
RS
1635 (if delay-mode-hooks
1636 ;; Delaying case.
1637 (dolist (hook hooks)
1638 (push hook delayed-mode-hooks))
1639 ;; Normal case, just run the hook as before plus any delayed hooks.
1640 (setq hooks (nconc (nreverse delayed-mode-hooks) hooks))
1641 (setq delayed-mode-hooks nil)
15de15c6 1642 (apply 'run-hooks (cons 'change-major-mode-after-body-hook hooks))
c4f484f2
RS
1643 (run-hooks 'after-change-major-mode-hook)))
1644
1645(defmacro delay-mode-hooks (&rest body)
1646 "Execute BODY, but delay any `run-mode-hooks'.
1647These hooks will be executed by the first following call to
1648`run-mode-hooks' that occurs outside any `delayed-mode-hooks' form.
1649Only affects hooks run in the current buffer."
1650 (declare (debug t) (indent 0))
1651 `(progn
1652 (make-local-variable 'delay-mode-hooks)
1653 (let ((delay-mode-hooks t))
1654 ,@body)))
1655
1656;; PUBLIC: find if the current mode derives from another.
1657
1658(defun derived-mode-p (&rest modes)
1659 "Non-nil if the current major mode is derived from one of MODES.
1660Uses the `derived-mode-parent' property of the symbol to trace backwards."
1661 (let ((parent major-mode))
1662 (while (and (not (memq parent modes))
1663 (setq parent (get parent 'derived-mode-parent))))
1664 parent))
1665\f
1666;;;; Minor modes.
1667
1668;; If a minor mode is not defined with define-minor-mode,
1669;; add it here explicitly.
1670;; isearch-mode is deliberately excluded, since you should
1671;; not call it yourself.
1672(defvar minor-mode-list '(auto-save-mode auto-fill-mode abbrev-mode
1673 overwrite-mode view-mode
1674 hs-minor-mode)
1675 "List of all minor mode functions.")
1676
1677(defun add-minor-mode (toggle name &optional keymap after toggle-fun)
1678 "Register a new minor mode.
1679
1680This is an XEmacs-compatibility function. Use `define-minor-mode' instead.
1681
1682TOGGLE is a symbol which is the name of a buffer-local variable that
1683is toggled on or off to say whether the minor mode is active or not.
1684
1685NAME specifies what will appear in the mode line when the minor mode
1686is active. NAME should be either a string starting with a space, or a
1687symbol whose value is such a string.
1688
1689Optional KEYMAP is the keymap for the minor mode that will be added
1690to `minor-mode-map-alist'.
1691
1692Optional AFTER specifies that TOGGLE should be added after AFTER
1693in `minor-mode-alist'.
1694
1695Optional TOGGLE-FUN is an interactive function to toggle the mode.
1696It defaults to (and should by convention be) TOGGLE.
1697
1698If TOGGLE has a non-nil `:included' property, an entry for the mode is
1699included in the mode-line minor mode menu.
1700If TOGGLE has a `:menu-tag', that is used for the menu item's label."
1701 (unless (memq toggle minor-mode-list)
1702 (push toggle minor-mode-list))
1703
1704 (unless toggle-fun (setq toggle-fun toggle))
1705 (unless (eq toggle-fun toggle)
1706 (put toggle :minor-mode-function toggle-fun))
1707 ;; Add the name to the minor-mode-alist.
1708 (when name
1709 (let ((existing (assq toggle minor-mode-alist)))
1710 (if existing
1711 (setcdr existing (list name))
1712 (let ((tail minor-mode-alist) found)
1713 (while (and tail (not found))
1714 (if (eq after (caar tail))
1715 (setq found tail)
1716 (setq tail (cdr tail))))
1717 (if found
1718 (let ((rest (cdr found)))
1719 (setcdr found nil)
1720 (nconc found (list (list toggle name)) rest))
365f8d85 1721 (push (list toggle name) minor-mode-alist))))))
c4f484f2
RS
1722 ;; Add the toggle to the minor-modes menu if requested.
1723 (when (get toggle :included)
1724 (define-key mode-line-mode-menu
1725 (vector toggle)
1726 (list 'menu-item
1727 (concat
1728 (or (get toggle :menu-tag)
1729 (if (stringp name) name (symbol-name toggle)))
1730 (let ((mode-name (if (symbolp name) (symbol-value name))))
1731 (if (and (stringp mode-name) (string-match "[^ ]+" mode-name))
1732 (concat " (" (match-string 0 mode-name) ")"))))
1733 toggle-fun
1734 :button (cons :toggle toggle))))
cbbd0b5a 1735
c4f484f2
RS
1736 ;; Add the map to the minor-mode-map-alist.
1737 (when keymap
1738 (let ((existing (assq toggle minor-mode-map-alist)))
1739 (if existing
1740 (setcdr existing keymap)
1741 (let ((tail minor-mode-map-alist) found)
1742 (while (and tail (not found))
1743 (if (eq after (caar tail))
1744 (setq found tail)
1745 (setq tail (cdr tail))))
1746 (if found
1747 (let ((rest (cdr found)))
1748 (setcdr found nil)
1749 (nconc found (list (cons toggle keymap)) rest))
365f8d85 1750 (push (cons toggle keymap) minor-mode-map-alist)))))))
448a0170
MB
1751\f
1752;;; Load history
1753
7abaf5cc
SM
1754(defsubst autoloadp (object)
1755 "Non-nil if OBJECT is an autoload."
1756 (eq 'autoload (car-safe object)))
1757
1758;; (defun autoload-type (object)
1759;; "Returns the type of OBJECT or `function' or `command' if the type is nil.
1760;; OBJECT should be an autoload object."
1761;; (when (autoloadp object)
1762;; (let ((type (nth 3 object)))
1763;; (cond ((null type) (if (nth 2 object) 'command 'function))
1764;; ((eq 'keymap t) 'macro)
1765;; (type)))))
1766
1767;; (defalias 'autoload-file #'cadr
1768;; "Return the name of the file from which AUTOLOAD will be loaded.
1769;; \n\(fn AUTOLOAD)")
1770
9e247d24 1771(defun symbol-file (symbol &optional type)
37fda77e
MR
1772 "Return the name of the file that defined SYMBOL.
1773The value is normally an absolute file name. It can also be nil,
1774if the definition is not associated with any file. If SYMBOL
1775specifies an autoloaded function, the value can be a relative
1776file name without extension.
1777
1778If TYPE is nil, then any kind of definition is acceptable. If
1779TYPE is `defun', `defvar', or `defface', that specifies function
1780definition, variable definition, or face definition only."
9e247d24
RS
1781 (if (and (or (null type) (eq type 'defun))
1782 (symbolp symbol) (fboundp symbol)
7abaf5cc 1783 (autoloadp (symbol-function symbol)))
9e247d24 1784 (nth 1 (symbol-function symbol))
e9f13a95 1785 (let ((files load-history)
cb21744e 1786 file)
e9f13a95 1787 (while files
9e247d24
RS
1788 (if (if type
1789 (if (eq type 'defvar)
1790 ;; Variables are present just as their names.
1791 (member symbol (cdr (car files)))
1792 ;; Other types are represented as (TYPE . NAME).
1793 (member (cons type symbol) (cdr (car files))))
1794 ;; We accept all types, so look for variable def
1795 ;; and then for any other kind.
1796 (or (member symbol (cdr (car files)))
1797 (rassq symbol (cdr (car files)))))
e9f13a95
SM
1798 (setq file (car (car files)) files nil))
1799 (setq files (cdr files)))
1800 file)))
448a0170 1801
059a552c
RF
1802(defun locate-library (library &optional nosuffix path interactive-call)
1803 "Show the precise file name of Emacs library LIBRARY.
c9ae6ddd
EZ
1804LIBRARY should be a relative file name of the library, a string.
1805It can omit the suffix (a.k.a. file-name extension) if NOSUFFIX is
1806nil (which is the default, see below).
059a552c
RF
1807This command searches the directories in `load-path' like `\\[load-library]'
1808to find the file that `\\[load-library] RET LIBRARY RET' would load.
1809Optional second arg NOSUFFIX non-nil means don't add suffixes `load-suffixes'
1810to the specified name LIBRARY.
1811
1812If the optional third arg PATH is specified, that list of directories
1813is used instead of `load-path'.
1814
3ac9d254 1815When called from a program, the file name is normally returned as a
059a552c
RF
1816string. When run interactively, the argument INTERACTIVE-CALL is t,
1817and the file name is displayed in the echo area."
1818 (interactive (list (completing-read "Locate library: "
6a021917
SM
1819 (apply-partially
1820 'locate-file-completion-table
1821 load-path (get-load-suffixes)))
059a552c
RF
1822 nil nil
1823 t))
1824 (let ((file (locate-file library
1825 (or path load-path)
667b73dc
LT
1826 (append (unless nosuffix (get-load-suffixes))
1827 load-file-rep-suffixes))))
059a552c
RF
1828 (if interactive-call
1829 (if file
1830 (message "Library is file %s" (abbreviate-file-name file))
1831 (message "No library %s in search path" library)))
1832 file))
1833
be9b65ac 1834\f
adbe2d11
RS
1835;;;; Specifying things to do later.
1836
33d74677 1837(defun load-history-regexp (file)
0988217a
RS
1838 "Form a regexp to find FILE in `load-history'.
1839FILE, a string, is described in the function `eval-after-load'."
33d74677
AM
1840 (if (file-name-absolute-p file)
1841 (setq file (file-truename file)))
0988217a 1842 (concat (if (file-name-absolute-p file) "\\`" "\\(\\`\\|/\\)")
33d74677
AM
1843 (regexp-quote file)
1844 (if (file-name-extension file)
1845 ""
1846 ;; Note: regexp-opt can't be used here, since we need to call
1847 ;; this before Emacs has been fully started. 2006-05-21
1848 (concat "\\(" (mapconcat 'regexp-quote load-suffixes "\\|") "\\)?"))
1849 "\\(" (mapconcat 'regexp-quote jka-compr-load-suffixes "\\|")
1850 "\\)?\\'"))
1851
1852(defun load-history-filename-element (file-regexp)
0988217a 1853 "Get the first elt of `load-history' whose car matches FILE-REGEXP.
33d74677
AM
1854Return nil if there isn't one."
1855 (let* ((loads load-history)
1856 (load-elt (and loads (car loads))))
1857 (save-match-data
1858 (while (and loads
1859 (or (null (car load-elt))
1860 (not (string-match file-regexp (car load-elt)))))
1861 (setq loads (cdr loads)
1862 load-elt (and loads (car loads)))))
1863 load-elt))
1864
f291fe60 1865(put 'eval-after-load 'lisp-indent-function 1)
9a5336ae 1866(defun eval-after-load (file form)
0b1c89c1 1867 "Arrange that if FILE is loaded, FORM will be run immediately afterwards.
90914938 1868If FILE is already loaded, evaluate FORM right now.
33d74677
AM
1869
1870If a matching file is loaded again, FORM will be evaluated again.
1871
1872If FILE is a string, it may be either an absolute or a relative file
1873name, and may have an extension \(e.g. \".el\") or may lack one, and
1874additionally may or may not have an extension denoting a compressed
1875format \(e.g. \".gz\").
1876
0988217a
RS
1877When FILE is absolute, this first converts it to a true name by chasing
1878symbolic links. Only a file of this name \(see next paragraph regarding
33d74677
AM
1879extensions) will trigger the evaluation of FORM. When FILE is relative,
1880a file whose absolute true name ends in FILE will trigger evaluation.
1881
1882When FILE lacks an extension, a file name with any extension will trigger
1883evaluation. Otherwise, its extension must match FILE's. A further
1884extension for a compressed format \(e.g. \".gz\") on FILE will not affect
1885this name matching.
1886
1887Alternatively, FILE can be a feature (i.e. a symbol), in which case FORM
3fa173b4 1888is evaluated at the end of any file that `provide's this feature.
0835f01e
GM
1889If the feature is provided when evaluating code not associated with a
1890file, FORM is evaluated immediately after the provide statement.
33d74677
AM
1891
1892Usually FILE is just a library name like \"font-lock\" or a feature name
1893like 'font-lock.
1894
1895This function makes or adds to an entry on `after-load-alist'."
1896 ;; Add this FORM into after-load-alist (regardless of whether we'll be
1897 ;; evaluating it now).
1898 (let* ((regexp-or-feature
3fa173b4
SM
1899 (if (stringp file)
1900 (setq file (purecopy (load-history-regexp file)))
1901 file))
33d74677
AM
1902 (elt (assoc regexp-or-feature after-load-alist)))
1903 (unless elt
1904 (setq elt (list regexp-or-feature))
1905 (push elt after-load-alist))
2ec42da9
SM
1906 ;; Make sure `form' is evalled in the current lexical/dynamic code.
1907 (setq form `(funcall ',(eval `(lambda () ,form) lexical-binding)))
33d74677
AM
1908 ;; Is there an already loaded file whose name (or `provide' name)
1909 ;; matches FILE?
68cbc58b
GM
1910 (prog1 (if (if (stringp file)
1911 (load-history-filename-element regexp-or-feature)
1912 (featurep file))
1913 (eval form))
1914 (when (symbolp regexp-or-feature)
1915 ;; For features, the after-load-alist elements get run when `provide' is
1916 ;; called rather than at the end of the file. So add an indirection to
1917 ;; make sure that `form' is really run "after-load" in case the provide
1918 ;; call happens early.
1919 (setq form
0835f01e
GM
1920 `(if load-file-name
1921 (let ((fun (make-symbol "eval-after-load-helper")))
1922 (fset fun `(lambda (file)
1923 (if (not (equal file ',load-file-name))
1924 nil
1925 (remove-hook 'after-load-functions ',fun)
1926 ,',form)))
1927 (add-hook 'after-load-functions fun))
1928 ;; Not being provided from a file, run form right now.
1929 ,form)))
68cbc58b
GM
1930 ;; Add FORM to the element unless it's already there.
1931 (unless (member form (cdr elt))
ed5bdeb9 1932 (nconc elt (list form))))))
33d74677 1933
838ff458
SM
1934(defvar after-load-functions nil
1935 "Special hook run after loading a file.
1936Each function there is called with a single argument, the absolute
1937name of the file just loaded.")
1938
33d74677
AM
1939(defun do-after-load-evaluation (abs-file)
1940 "Evaluate all `eval-after-load' forms, if any, for ABS-FILE.
5766c380
SM
1941ABS-FILE, a string, should be the absolute true name of a file just loaded.
1942This function is called directly from the C code."
1943 ;; Run the relevant eval-after-load forms.
060c08b5
JB
1944 (mapc #'(lambda (a-l-element)
1945 (when (and (stringp (car a-l-element))
1946 (string-match-p (car a-l-element) abs-file))
1947 ;; discard the file name regexp
1948 (mapc #'eval (cdr a-l-element))))
5766c380
SM
1949 after-load-alist)
1950 ;; Complain when the user uses obsolete files.
838ff458 1951 (when (string-match-p "/obsolete/[^/]*\\'" abs-file)
5766c380
SM
1952 (run-with-timer 0 nil
1953 (lambda (file)
1954 (message "Package %s is obsolete!"
1955 (substring file 0
1956 (string-match "\\.elc?\\>" file))))
838ff458
SM
1957 (file-name-nondirectory abs-file)))
1958 ;; Finally, run any other hook.
1959 (run-hook-with-args 'after-load-functions abs-file))
9a5336ae
JB
1960
1961(defun eval-next-after-load (file)
1962 "Read the following input sexp, and run it whenever FILE is loaded.
1963This makes or adds to an entry on `after-load-alist'.
1964FILE should be the name of a library, with no directory name."
59f7af81 1965 (declare (obsolete eval-after-load "23.2"))
9a5336ae 1966 (eval-after-load file (read)))
638f053a
JB
1967
1968(defun display-delayed-warnings ()
1969 "Display delayed warnings from `delayed-warnings-list'.
2724d9c7
JB
1970Used from `delayed-warnings-hook' (which see)."
1971 (dolist (warning (nreverse delayed-warnings-list))
1972 (apply 'display-warning warning))
1973 (setq delayed-warnings-list nil))
1974
1975(defun collapse-delayed-warnings ()
1976 "Remove duplicates from `delayed-warnings-list'.
1977Collapse identical adjacent warnings into one (plus count).
1978Used from `delayed-warnings-hook' (which see)."
d1a5c3b4 1979 (let ((count 1)
2724d9c7
JB
1980 collapsed warning)
1981 (while delayed-warnings-list
1982 (setq warning (pop delayed-warnings-list))
1983 (if (equal warning (car delayed-warnings-list))
d1a5c3b4
JB
1984 (setq count (1+ count))
1985 (when (> count 1)
1986 (setcdr warning (cons (format "%s [%d times]" (cadr warning) count)
1987 (cddr warning)))
1988 (setq count 1))
2724d9c7
JB
1989 (push warning collapsed)))
1990 (setq delayed-warnings-list (nreverse collapsed))))
638f053a 1991
8eae3a58 1992;; At present this is only used for Emacs internals.
001bf877 1993;; Ref http://lists.gnu.org/archive/html/emacs-devel/2012-02/msg00085.html
2724d9c7
JB
1994(defvar delayed-warnings-hook '(collapse-delayed-warnings
1995 display-delayed-warnings)
3d439cd1
CY
1996 "Normal hook run to process and display delayed warnings.
1997By default, this hook contains functions to consolidate the
1998warnings listed in `delayed-warnings-list', display them, and set
1999`delayed-warnings-list' back to nil.")
638f053a 2000
7aaacaff 2001\f
c4f484f2
RS
2002;;;; Process stuff.
2003
d43c8d03
GM
2004(defun process-lines (program &rest args)
2005 "Execute PROGRAM with ARGS, returning its output as a list of lines.
2006Signal an error if the program returns with a non-zero exit status."
2007 (with-temp-buffer
2008 (let ((status (apply 'call-process program nil (current-buffer) nil args)))
2009 (unless (eq status 0)
2010 (error "%s exited with status %s" program status))
2011 (goto-char (point-min))
2012 (let (lines)
2013 (while (not (eobp))
2014 (setq lines (cons (buffer-substring-no-properties
2015 (line-beginning-position)
2016 (line-end-position))
2017 lines))
2018 (forward-line 1))
2019 (nreverse lines)))))
2020
b96e6cde 2021(defun process-live-p (process)
bcd54f83
LMI
2022 "Returns non-nil if PROCESS is alive.
2023A process is considered alive if its status is `run', `open',
2024`listen', `connect' or `stop'."
2025 (memq (process-status process)
2026 '(run open listen connect stop)))
2027
7aaacaff
RS
2028;; compatibility
2029
c8227332
VJL
2030(make-obsolete
2031 'process-kill-without-query
2032 "use `process-query-on-exit-flag' or `set-process-query-on-exit-flag'."
2033 "22.1")
06b60517 2034(defun process-kill-without-query (process &optional _flag)
7aaacaff
RS
2035 "Say no query needed if PROCESS is running when Emacs is exited.
2036Optional second argument if non-nil says to require a query.
a478f3e1 2037Value is t if a query was formerly required."
7aaacaff
RS
2038 (let ((old (process-query-on-exit-flag process)))
2039 (set-process-query-on-exit-flag process nil)
2040 old))
9a5336ae 2041
d842b103
JL
2042(defun process-kill-buffer-query-function ()
2043 "Ask before killing a buffer that has a running process."
2044 (let ((process (get-buffer-process (current-buffer))))
2045 (or (not process)
2046 (not (memq (process-status process) '(run stop open listen)))
2047 (not (process-query-on-exit-flag process))
da9fcb93
LMI
2048 (yes-or-no-p
2049 (format "Buffer %S has a running process; kill it? "
2050 (buffer-name (current-buffer)))))))
d842b103
JL
2051
2052(add-hook 'kill-buffer-query-functions 'process-kill-buffer-query-function)
2053
34368d12
KS
2054;; process plist management
2055
2056(defun process-get (process propname)
2057 "Return the value of PROCESS' PROPNAME property.
2058This is the last value stored with `(process-put PROCESS PROPNAME VALUE)'."
2059 (plist-get (process-plist process) propname))
2060
2061(defun process-put (process propname value)
2062 "Change PROCESS' PROPNAME property to VALUE.
2063It can be retrieved with `(process-get PROCESS PROPNAME)'."
f1180544 2064 (set-process-plist process
34368d12
KS
2065 (plist-put (process-plist process) propname value)))
2066
9a5336ae
JB
2067\f
2068;;;; Input and display facilities.
2069
77a5664f 2070(defvar read-quoted-char-radix 8
fb7ada5f 2071 "Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
77a5664f
RS
2072Legitimate radix values are 8, 10 and 16.")
2073
2074(custom-declare-variable-early
264ef586 2075 'read-quoted-char-radix 8
77a5664f 2076 "*Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
1ba764de 2077Legitimate radix values are 8, 10 and 16."
c8227332
VJL
2078 :type '(choice (const 8) (const 10) (const 16))
2079 :group 'editing-basics)
1ba764de 2080
03a74b84
SM
2081(defconst read-key-empty-map (make-sparse-keymap))
2082
79bd5ba1 2083(defvar read-key-delay 0.01) ;Fast enough for 100Hz repeat rate, hopefully.
03a74b84
SM
2084
2085(defun read-key (&optional prompt)
2086 "Read a key from the keyboard.
2087Contrary to `read-event' this will not return a raw event but instead will
2088obey the input decoding and translations usually done by `read-key-sequence'.
2089So escape sequences and keyboard encoding are taken into account.
2090When there's an ambiguity because the key looks like the prefix of
2091some sort of escape sequence, the ambiguity is resolved via `read-key-delay'."
088be6fb
SM
2092 ;; This overriding-terminal-local-map binding also happens to
2093 ;; disable quail's input methods, so although read-key-sequence
2094 ;; always inherits the input method, in practice read-key does not
2095 ;; inherit the input method (at least not if it's based on quail).
bfa3acd6
SM
2096 (let ((overriding-terminal-local-map nil)
2097 (overriding-local-map read-key-empty-map)
3ff78624 2098 (echo-keystrokes 0)
03a74b84
SM
2099 (old-global-map (current-global-map))
2100 (timer (run-with-idle-timer
2101 ;; Wait long enough that Emacs has the time to receive and
2102 ;; process all the raw events associated with the single-key.
2103 ;; But don't wait too long, or the user may find the delay
2104 ;; annoying (or keep hitting more keys which may then get
2105 ;; lost or misinterpreted).
2106 ;; This is only relevant for keys which Emacs perceives as
2107 ;; "prefixes", such as C-x (because of the C-x 8 map in
2108 ;; key-translate-table and the C-x @ map in function-key-map)
2109 ;; or ESC (because of terminal escape sequences in
2110 ;; input-decode-map).
2111 read-key-delay t
2112 (lambda ()
2113 (let ((keys (this-command-keys-vector)))
2114 (unless (zerop (length keys))
2115 ;; `keys' is non-empty, so the user has hit at least
2116 ;; one key; there's no point waiting any longer, even
2117 ;; though read-key-sequence thinks we should wait
2118 ;; for more input to decide how to interpret the
2119 ;; current input.
2120 (throw 'read-key keys)))))))
2121 (unwind-protect
2122 (progn
186e86db
SM
2123 (use-global-map
2124 (let ((map (make-sparse-keymap)))
2125 ;; Don't hide the menu-bar and tool-bar entries.
2126 (define-key map [menu-bar] (lookup-key global-map [menu-bar]))
c5bb7569
CY
2127 (define-key map [tool-bar]
2128 ;; This hack avoids evaluating the :filter (Bug#9922).
2129 (or (cdr (assq 'tool-bar global-map))
2130 (lookup-key global-map [tool-bar])))
186e86db 2131 map))
79bd5ba1 2132 (aref (catch 'read-key (read-key-sequence-vector prompt nil t)) 0))
03a74b84
SM
2133 (cancel-timer timer)
2134 (use-global-map old-global-map))))
2135
9a5336ae 2136(defun read-quoted-char (&optional prompt)
2444730b
RS
2137 "Like `read-char', but do not allow quitting.
2138Also, if the first character read is an octal digit,
2139we read any number of octal digits and return the
569b03f2 2140specified character code. Any nondigit terminates the sequence.
1ba764de 2141If the terminator is RET, it is discarded;
2444730b
RS
2142any other terminator is used itself as input.
2143
569b03f2
RS
2144The optional argument PROMPT specifies a string to use to prompt the user.
2145The variable `read-quoted-char-radix' controls which radix to use
2146for numeric input."
c83256a0 2147 (let ((message-log-max nil) done (first t) (code 0) char translated)
2444730b
RS
2148 (while (not done)
2149 (let ((inhibit-quit first)
42e636f0
KH
2150 ;; Don't let C-h get the help message--only help function keys.
2151 (help-char nil)
2152 (help-form
2153 "Type the special character you want to use,
2444730b 2154or the octal character code.
1ba764de 2155RET terminates the character code and is discarded;
2444730b 2156any other non-digit terminates the character code and is then used as input."))
3f0161d0 2157 (setq char (read-event (and prompt (format "%s-" prompt)) t))
9a5336ae 2158 (if inhibit-quit (setq quit-flag nil)))
3f0161d0
SM
2159 ;; Translate TAB key into control-I ASCII character, and so on.
2160 ;; Note: `read-char' does it using the `ascii-character' property.
278847cd
SM
2161 ;; We should try and use read-key instead.
2162 (let ((translation (lookup-key local-function-key-map (vector char))))
b8add347
SM
2163 (setq translated (if (arrayp translation)
2164 (aref translation 0)
2165 char)))
2166 (if (integerp translated)
2167 (setq translated (char-resolve-modifiers translated)))
c83256a0
RS
2168 (cond ((null translated))
2169 ((not (integerp translated))
2170 (setq unread-command-events (list char)
1ba764de 2171 done t))
c83256a0 2172 ((/= (logand translated ?\M-\^@) 0)
bf896a1b 2173 ;; Turn a meta-character into a character with the 0200 bit set.
c83256a0 2174 (setq code (logior (logand translated (lognot ?\M-\^@)) 128)
bf896a1b 2175 done t))
4fcc3d32
SM
2176 ((and (<= ?0 translated)
2177 (< translated (+ ?0 (min 10 read-quoted-char-radix))))
c83256a0
RS
2178 (setq code (+ (* code read-quoted-char-radix) (- translated ?0)))
2179 (and prompt (setq prompt (message "%s %c" prompt translated))))
2180 ((and (<= ?a (downcase translated))
4fcc3d32
SM
2181 (< (downcase translated)
2182 (+ ?a -10 (min 36 read-quoted-char-radix))))
92304bc8 2183 (setq code (+ (* code read-quoted-char-radix)
c83256a0
RS
2184 (+ 10 (- (downcase translated) ?a))))
2185 (and prompt (setq prompt (message "%s %c" prompt translated))))
2186 ((and (not first) (eq translated ?\C-m))
2444730b
RS
2187 (setq done t))
2188 ((not first)
c83256a0 2189 (setq unread-command-events (list char)
2444730b 2190 done t))
c83256a0 2191 (t (setq code translated
2444730b
RS
2192 done t)))
2193 (setq first nil))
bf896a1b 2194 code))
9a5336ae 2195
795b1482
SM
2196(defvar read-passwd-map
2197 ;; BEWARE: `defconst' would purecopy it, breaking the sharing with
2198 ;; minibuffer-local-map along the way!
d39109c3
SM
2199 (let ((map (make-sparse-keymap)))
2200 (set-keymap-parent map minibuffer-local-map)
2201 (define-key map "\C-u" #'delete-minibuffer-contents) ;bug#12570
2202 map)
2203 "Keymap used while reading passwords.")
2204
266725f1
SJ
2205(defun read-passwd (prompt &optional confirm default)
2206 "Read a password, prompting with PROMPT, and return it.
2207If optional CONFIRM is non-nil, read the password twice to make sure.
2208Optional DEFAULT is a default password to use instead of empty input.
2209
2210This function echoes `.' for each character that the user types.
08640de5 2211
266725f1
SJ
2212Once the caller uses the password, it can erase the password
2213by doing (clear-string STRING)."
088be6fb
SM
2214 (if confirm
2215 (let (success)
2216 (while (not success)
2217 (let ((first (read-passwd prompt nil default))
2218 (second (read-passwd "Confirm password: " nil default)))
2219 (if (equal first second)
2220 (progn
2221 (and (arrayp second) (clear-string second))
2222 (setq success first))
2223 (and (arrayp first) (clear-string first))
2224 (and (arrayp second) (clear-string second))
2225 (message "Password not repeated accurately; please start over")
2226 (sit-for 1))))
2227 success)
99d27583
SM
2228 (let ((hide-chars-fun
2229 (lambda (beg end _len)
2230 (clear-this-command-keys)
2231 (setq beg (min end (max (minibuffer-prompt-end)
2232 beg)))
2233 (dotimes (i (- end beg))
2234 (put-text-property (+ i beg) (+ 1 i beg)
2235 'display (string ?.)))))
2236 minibuf)
088be6fb
SM
2237 (minibuffer-with-setup-hook
2238 (lambda ()
2239 (setq minibuf (current-buffer))
2240 ;; Turn off electricity.
795b1482
SM
2241 (setq-local post-self-insert-hook nil)
2242 (setq-local buffer-undo-list t)
2243 (setq-local select-active-regions nil)
d39109c3 2244 (use-local-map read-passwd-map)
99d27583 2245 (add-hook 'after-change-functions hide-chars-fun nil 'local))
088be6fb 2246 (unwind-protect
d39109c3
SM
2247 (let ((enable-recursive-minibuffers t))
2248 (read-string prompt nil t default)) ; t = "no history"
088be6fb 2249 (when (buffer-live-p minibuf)
99d27583
SM
2250 (with-current-buffer minibuf
2251 ;; Not sure why but it seems that there might be cases where the
2252 ;; minibuffer is not always properly reset later on, so undo
2253 ;; whatever we've done here (bug#11392).
2254 (remove-hook 'after-change-functions hide-chars-fun 'local)
2255 (kill-local-variable 'post-self-insert-hook)
2256 ;; And of course, don't keep the sensitive data around.
2257 (erase-buffer))))))))
266725f1 2258
6b61353c 2259(defun read-number (prompt &optional default)
3238cde3
RS
2260 "Read a numeric value in the minibuffer, prompting with PROMPT.
2261DEFAULT specifies a default value to return if the user just types RET.
0208ede7
JL
2262The value of DEFAULT is inserted into PROMPT.
2263This function is used by the `interactive' code letter `n'."
a5dcc929
JL
2264 (let ((n nil)
2265 (default1 (if (consp default) (car default) default)))
2266 (when default1
6b61353c 2267 (setq prompt
2d14d61e 2268 (if (string-match "\\(\\):[ \t]*\\'" prompt)
a5dcc929 2269 (replace-match (format " (default %s)" default1) t t prompt 1)
2d14d61e 2270 (replace-regexp-in-string "[ \t]*\\'"
a5dcc929 2271 (format " (default %s) " default1)
f8cf33b1 2272 prompt t t))))
6b61353c
KH
2273 (while
2274 (progn
a5dcc929
JL
2275 (let ((str (read-from-minibuffer
2276 prompt nil nil nil nil
2277 (when default
2278 (if (consp default)
2279 (mapcar 'number-to-string (delq nil default))
2280 (number-to-string default))))))
219f06f7
RS
2281 (condition-case nil
2282 (setq n (cond
a5dcc929 2283 ((zerop (length str)) default1)
e5271cf2 2284 ((stringp str) (read str))))
219f06f7 2285 (error nil)))
6b61353c
KH
2286 (unless (numberp n)
2287 (message "Please enter a number.")
2288 (sit-for 1)
2289 t)))
2290 n))
0369eb85 2291
3ef01959
CY
2292(defun read-char-choice (prompt chars &optional inhibit-keyboard-quit)
2293 "Read and return one of CHARS, prompting for PROMPT.
2294Any input that is not one of CHARS is ignored.
2295
2296If optional argument INHIBIT-KEYBOARD-QUIT is non-nil, ignore
2297keyboard-quit events while waiting for a valid input."
2298 (unless (consp chars)
2299 (error "Called `read-char-choice' without valid char choices"))
03ea5b87 2300 (let (char done show-help (helpbuf " *Char Help*"))
49c5410a 2301 (let ((cursor-in-echo-area t)
145823ec
CY
2302 (executing-kbd-macro executing-kbd-macro)
2303 (esc-flag nil))
03ea5b87
GM
2304 (save-window-excursion ; in case we call help-form-show
2305 (while (not done)
2306 (unless (get-text-property 0 'face prompt)
2307 (setq prompt (propertize prompt 'face 'minibuffer-prompt)))
2308 (setq char (let ((inhibit-quit inhibit-keyboard-quit))
2309 (read-key prompt)))
647ab967 2310 (and show-help (buffer-live-p (get-buffer helpbuf))
03ea5b87
GM
2311 (kill-buffer helpbuf))
2312 (cond
2313 ((not (numberp char)))
2314 ;; If caller has set help-form, that's enough.
2315 ;; They don't explicitly have to add help-char to chars.
2316 ((and help-form
2317 (eq char help-char)
2318 (setq show-help t)
2319 (help-form-show)))
2320 ((memq char chars)
2321 (setq done t))
2322 ((and executing-kbd-macro (= char -1))
2323 ;; read-event returns -1 if we are in a kbd macro and
2324 ;; there are no more events in the macro. Attempt to
2325 ;; get an event interactively.
2326 (setq executing-kbd-macro nil))
145823ec
CY
2327 ((not inhibit-keyboard-quit)
2328 (cond
2329 ((and (null esc-flag) (eq char ?\e))
2330 (setq esc-flag t))
2331 ((memq char '(?\C-g ?\e))
2332 (keyboard-quit))))))))
49c5410a 2333 ;; Display the question with the answer. But without cursor-in-echo-area.
3ef01959
CY
2334 (message "%s%s" prompt (char-to-string char))
2335 char))
2336
0369eb85
CY
2337(defun sit-for (seconds &optional nodisp obsolete)
2338 "Perform redisplay, then wait for SECONDS seconds or until input is available.
2339SECONDS may be a floating-point value.
2340\(On operating systems that do not support waiting for fractions of a
2341second, floating-point values are rounded down to the nearest integer.)
2342
2343If optional arg NODISP is t, don't redisplay, just wait for input.
2344Redisplay does not happen if input is available before it starts.
0369eb85
CY
2345
2346Value is t if waited the full time with no input arriving, and nil otherwise.
2347
d8120806 2348An obsolete, but still supported form is
0369eb85 2349\(sit-for SECONDS &optional MILLISECONDS NODISP)
d8120806 2350where the optional arg MILLISECONDS specifies an additional wait period,
0369eb85 2351in milliseconds; this was useful when Emacs was built without
fd6c5134 2352floating point support."
000b06df
GM
2353 (if (numberp nodisp)
2354 (setq seconds (+ seconds (* 1e-3 nodisp))
2355 nodisp obsolete)
2356 (if obsolete (setq nodisp obsolete)))
790e0ef7
KS
2357 (cond
2358 (noninteractive
2359 (sleep-for seconds)
2360 t)
2361 ((input-pending-p)
2362 nil)
2363 ((<= seconds 0)
2364 (or nodisp (redisplay)))
2365 (t
2366 (or nodisp (redisplay))
2367 (let ((read (read-event nil nil seconds)))
2368 (or (null read)
fb1a5d8a
KS
2369 (progn
2370 ;; If last command was a prefix arg, e.g. C-u, push this event onto
2371 ;; unread-command-events as (t . EVENT) so it will be added to
2372 ;; this-command-keys by read-key-sequence.
2373 (if (eq overriding-terminal-local-map universal-argument-map)
2374 (setq read (cons t read)))
2375 (push read unread-command-events)
2376 nil))))))
f3a30a50 2377(set-advertised-calling-convention 'sit-for '(seconds &optional nodisp) "22.1")
8c51d2a2 2378
9aea757b 2379(defun y-or-n-p (prompt)
8c51d2a2 2380 "Ask user a \"y or n\" question. Return t if answer is \"y\".
9aea757b
CY
2381PROMPT is the string to display to ask the question. It should
2382end in a space; `y-or-n-p' adds \"(y or n) \" to it.
3d91e302 2383
011474aa
CY
2384No confirmation of the answer is requested; a single character is
2385enough. SPC also means yes, and DEL means no.
2386
2387To be precise, this function translates user input into responses
2388by consulting the bindings in `query-replace-map'; see the
2389documentation of that variable for more information. In this
2390case, the useful bindings are `act', `skip', `recenter',
2391`scroll-up', `scroll-down', and `quit'.
2392An `act' response means yes, and a `skip' response means no.
2393A `quit' response means to invoke `keyboard-quit'.
2394If the user enters `recenter', `scroll-up', or `scroll-down'
2395responses, perform the requested window recentering or scrolling
2396and ask again.
8c51d2a2
CY
2397
2398Under a windowing system a dialog box will be used if `last-nonmenu-event'
2399is nil and `use-dialog-box' is non-nil."
2400 ;; ¡Beware! when I tried to edebug this code, Emacs got into a weird state
2401 ;; where all the keys were unbound (i.e. it somehow got triggered
2402 ;; within read-key, apparently). I had to kill it.
2403 (let ((answer 'recenter))
aa4de341
CY
2404 (cond
2405 (noninteractive
2406 (setq prompt (concat prompt
2407 (if (eq ?\s (aref prompt (1- (length prompt))))
2408 "" " ")
2409 "(y or n) "))
2410 (let ((temp-prompt prompt))
2411 (while (not (memq answer '(act skip)))
2412 (let ((str (read-string temp-prompt)))
2413 (cond ((member str '("y" "Y")) (setq answer 'act))
2414 ((member str '("n" "N")) (setq answer 'skip))
2415 (t (setq temp-prompt (concat "Please answer y or n. "
2416 prompt))))))))
2417 ((and (display-popup-menus-p)
2418 (listp last-nonmenu-event)
2419 use-dialog-box)
2420 (setq answer
2421 (x-popup-dialog t `(,prompt ("Yes" . act) ("No" . skip)))))
2422 (t
9aea757b 2423 (setq prompt (concat prompt
8c51d2a2
CY
2424 (if (eq ?\s (aref prompt (1- (length prompt))))
2425 "" " ")
2426 "(y or n) "))
2427 (while
011474aa
CY
2428 (let* ((scroll-actions '(recenter scroll-up scroll-down
2429 scroll-other-window scroll-other-window-down))
2430 (key
8c51d2a2
CY
2431 (let ((cursor-in-echo-area t))
2432 (when minibuffer-auto-raise
2433 (raise-frame (window-frame (minibuffer-window))))
011474aa 2434 (read-key (propertize (if (memq answer scroll-actions)
8c51d2a2
CY
2435 prompt
2436 (concat "Please answer y or n. "
2437 prompt))
2438 'face 'minibuffer-prompt)))))
2439 (setq answer (lookup-key query-replace-map (vector key) t))
2440 (cond
011474aa
CY
2441 ((memq answer '(skip act)) nil)
2442 ((eq answer 'recenter)
2443 (recenter) t)
2444 ((eq answer 'scroll-up)
2445 (ignore-errors (scroll-up-command)) t)
2446 ((eq answer 'scroll-down)
2447 (ignore-errors (scroll-down-command)) t)
2448 ((eq answer 'scroll-other-window)
2449 (ignore-errors (scroll-other-window)) t)
2450 ((eq answer 'scroll-other-window-down)
2451 (ignore-errors (scroll-other-window-down)) t)
2452 ((or (memq answer '(exit-prefix quit)) (eq key ?\e))
2453 (signal 'quit nil) t)
2454 (t t)))
8c51d2a2 2455 (ding)
aa4de341 2456 (discard-input))))
8c51d2a2
CY
2457 (let ((ret (eq answer 'act)))
2458 (unless noninteractive
c0ea08d2
GM
2459 ;; FIXME this prints one too many spaces, since prompt
2460 ;; already ends in a space. Eg "... (y or n) y".
8c51d2a2
CY
2461 (message "%s %s" prompt (if ret "y" "n")))
2462 ret)))
2463
e0e4cb7a 2464\f
2493767e
RS
2465;;; Atomic change groups.
2466
69cae2d4
RS
2467(defmacro atomic-change-group (&rest body)
2468 "Perform BODY as an atomic change group.
2469This means that if BODY exits abnormally,
2470all of its changes to the current buffer are undone.
b9ab4064 2471This works regardless of whether undo is enabled in the buffer.
69cae2d4
RS
2472
2473This mechanism is transparent to ordinary use of undo;
2474if undo is enabled in the buffer and BODY succeeds, the
2475user can undo the change normally."
6273dc68 2476 (declare (indent 0) (debug t))
69cae2d4
RS
2477 (let ((handle (make-symbol "--change-group-handle--"))
2478 (success (make-symbol "--change-group-success--")))
2479 `(let ((,handle (prepare-change-group))
cf191706
RS
2480 ;; Don't truncate any undo data in the middle of this.
2481 (undo-outer-limit nil)
2482 (undo-limit most-positive-fixnum)
2483 (undo-strong-limit most-positive-fixnum)
69cae2d4
RS
2484 (,success nil))
2485 (unwind-protect
2486 (progn
2487 ;; This is inside the unwind-protect because
2488 ;; it enables undo if that was disabled; we need
2489 ;; to make sure that it gets disabled again.
2490 (activate-change-group ,handle)
2491 ,@body
2492 (setq ,success t))
2493 ;; Either of these functions will disable undo
2494 ;; if it was disabled before.
2495 (if ,success
2496 (accept-change-group ,handle)
2497 (cancel-change-group ,handle))))))
2498
62ea1306 2499(defun prepare-change-group (&optional buffer)
69cae2d4 2500 "Return a handle for the current buffer's state, for a change group.
62ea1306 2501If you specify BUFFER, make a handle for BUFFER's state instead.
69cae2d4
RS
2502
2503Pass the handle to `activate-change-group' afterward to initiate
2504the actual changes of the change group.
2505
2506To finish the change group, call either `accept-change-group' or
2507`cancel-change-group' passing the same handle as argument. Call
2508`accept-change-group' to accept the changes in the group as final;
2509call `cancel-change-group' to undo them all. You should use
2510`unwind-protect' to make sure the group is always finished. The call
2511to `activate-change-group' should be inside the `unwind-protect'.
2512Once you finish the group, don't use the handle again--don't try to
2513finish the same group twice. For a simple example of correct use, see
2514the source code of `atomic-change-group'.
2515
2516The handle records only the specified buffer. To make a multibuffer
2517change group, call this function once for each buffer you want to
2518cover, then use `nconc' to combine the returned values, like this:
2519
2520 (nconc (prepare-change-group buffer-1)
2521 (prepare-change-group buffer-2))
2522
2523You can then activate that multibuffer change group with a single
2524call to `activate-change-group' and finish it with a single call
2525to `accept-change-group' or `cancel-change-group'."
2526
62ea1306
RS
2527 (if buffer
2528 (list (cons buffer (with-current-buffer buffer buffer-undo-list)))
2529 (list (cons (current-buffer) buffer-undo-list))))
69cae2d4
RS
2530
2531(defun activate-change-group (handle)
2532 "Activate a change group made with `prepare-change-group' (which see)."
2533 (dolist (elt handle)
2534 (with-current-buffer (car elt)
2535 (if (eq buffer-undo-list t)
2536 (setq buffer-undo-list nil)))))
2537
2538(defun accept-change-group (handle)
2539 "Finish a change group made with `prepare-change-group' (which see).
2540This finishes the change group by accepting its changes as final."
2541 (dolist (elt handle)
2542 (with-current-buffer (car elt)
7511ded8 2543 (if (eq (cdr elt) t)
69cae2d4
RS
2544 (setq buffer-undo-list t)))))
2545
2546(defun cancel-change-group (handle)
2547 "Finish a change group made with `prepare-change-group' (which see).
2548This finishes the change group by reverting all of its changes."
2549 (dolist (elt handle)
2550 (with-current-buffer (car elt)
2551 (setq elt (cdr elt))
d21cba62
MR
2552 (save-restriction
2553 ;; Widen buffer temporarily so if the buffer was narrowed within
2554 ;; the body of `atomic-change-group' all changes can be undone.
2555 (widen)
2556 (let ((old-car
2557 (if (consp elt) (car elt)))
2558 (old-cdr
2559 (if (consp elt) (cdr elt))))
2560 ;; Temporarily truncate the undo log at ELT.
2561 (when (consp elt)
2562 (setcar elt nil) (setcdr elt nil))
2563 (unless (eq last-command 'undo) (undo-start))
2564 ;; Make sure there's no confusion.
2565 (when (and (consp elt) (not (eq elt (last pending-undo-list))))
2566 (error "Undoing to some unrelated state"))
2567 ;; Undo it all.
2568 (save-excursion
2569 (while (listp pending-undo-list) (undo-more 1)))
2570 ;; Reset the modified cons cell ELT to its original content.
2571 (when (consp elt)
2572 (setcar elt old-car)
2573 (setcdr elt old-cdr))
2574 ;; Revert the undo info to what it was when we grabbed the state.
2575 (setq buffer-undo-list elt))))))
69cae2d4 2576\f
c4f484f2
RS
2577;;;; Display-related functions.
2578
a9d956be 2579;; For compatibility.
37269466 2580(define-obsolete-function-alias 'redraw-modeline
2a1e2476 2581 'force-mode-line-update "24.3")
a9d956be 2582
9a5336ae 2583(defun force-mode-line-update (&optional all)
6b61353c
KH
2584 "Force redisplay of the current buffer's mode line and header line.
2585With optional non-nil ALL, force redisplay of all mode lines and
2586header lines. This function also forces recomputation of the
2587menu bar menus and the frame title."
03a74b84 2588 (if all (with-current-buffer (other-buffer)))
9a5336ae
JB
2589 (set-buffer-modified-p (buffer-modified-p)))
2590
aa3b4ded 2591(defun momentary-string-display (string pos &optional exit-char message)
be9b65ac 2592 "Momentarily display STRING in the buffer at POS.
12092fb3 2593Display remains until next event is input.
dbf284be 2594If POS is a marker, only its position is used; its buffer is ignored.
12092fb3
EZ
2595Optional third arg EXIT-CHAR can be a character, event or event
2596description list. EXIT-CHAR defaults to SPC. If the input is
2597EXIT-CHAR it is swallowed; otherwise it is then available as
2598input (as a command if nothing else).
be9b65ac
DL
2599Display MESSAGE (optional fourth arg) in the echo area.
2600If MESSAGE is nil, instructions to type EXIT-CHAR are displayed there."
b754307b 2601 (or exit-char (setq exit-char ?\s))
f70c4736 2602 (let ((ol (make-overlay pos pos))
bc91aee9 2603 (str (copy-sequence string)))
be9b65ac 2604 (unwind-protect
f70c4736
SM
2605 (progn
2606 (save-excursion
bc91aee9 2607 (overlay-put ol 'after-string str)
f70c4736
SM
2608 (goto-char pos)
2609 ;; To avoid trouble with out-of-bounds position
2610 (setq pos (point))
bc91aee9 2611 ;; If the string end is off screen, recenter now.
f70c4736
SM
2612 (if (<= (window-end nil t) pos)
2613 (recenter (/ (window-height) 2))))
2614 (message (or message "Type %s to continue editing.")
2615 (single-key-description exit-char))
fe40dc63
JB
2616 (let ((event (read-event)))
2617 ;; `exit-char' can be an event, or an event description list.
2618 (or (eq event exit-char)
2619 (eq event (event-convert-list exit-char))
2620 (setq unread-command-events (list event)))))
f70c4736 2621 (delete-overlay ol))))
be9b65ac 2622
9a5336ae 2623\f
aa3b4ded
SM
2624;;;; Overlay operations
2625
2626(defun copy-overlay (o)
2627 "Return a copy of overlay O."
48b1e7cf
SM
2628 (let ((o1 (if (overlay-buffer o)
2629 (make-overlay (overlay-start o) (overlay-end o)
2630 ;; FIXME: there's no easy way to find the
2631 ;; insertion-type of the two markers.
2632 (overlay-buffer o))
2633 (let ((o1 (make-overlay (point-min) (point-min))))
2634 (delete-overlay o1)
28f0b072 2635 o1)))
aa3b4ded
SM
2636 (props (overlay-properties o)))
2637 (while props
2638 (overlay-put o1 (pop props) (pop props)))
2639 o1))
2640
f24485f1 2641(defun remove-overlays (&optional beg end name val)
aa3b4ded 2642 "Clear BEG and END of overlays whose property NAME has value VAL.
cba61075
JB
2643Overlays might be moved and/or split.
2644BEG and END default respectively to the beginning and end of buffer."
d6f5ac10 2645 ;; This speeds up the loops over overlays.
f24485f1
MY
2646 (unless beg (setq beg (point-min)))
2647 (unless end (setq end (point-max)))
ee6bb693 2648 (overlay-recenter end)
aa3b4ded
SM
2649 (if (< end beg)
2650 (setq beg (prog1 end (setq end beg))))
2651 (save-excursion
2652 (dolist (o (overlays-in beg end))
2653 (when (eq (overlay-get o name) val)
2654 ;; Either push this overlay outside beg...end
2655 ;; or split it to exclude beg...end
2656 ;; or delete it entirely (if it is contained in beg...end).
2657 (if (< (overlay-start o) beg)
2658 (if (> (overlay-end o) end)
2659 (progn
2660 (move-overlay (copy-overlay o)
2661 (overlay-start o) beg)
2662 (move-overlay o end (overlay-end o)))
2663 (move-overlay o (overlay-start o) beg))
2664 (if (> (overlay-end o) end)
2665 (move-overlay o end (overlay-end o))
2666 (delete-overlay o)))))))
c5802acf 2667\f
9a5336ae
JB
2668;;;; Miscellanea.
2669
4fb17037
RS
2670(defvar suspend-hook nil
2671 "Normal hook run by `suspend-emacs', before suspending.")
2672
2673(defvar suspend-resume-hook nil
2674 "Normal hook run by `suspend-emacs', after Emacs is continued.")
2675
784bc7cd
RS
2676(defvar temp-buffer-show-hook nil
2677 "Normal hook run by `with-output-to-temp-buffer' after displaying the buffer.
2678When the hook runs, the temporary buffer is current, and the window it
5247a8e6 2679was displayed in is selected.")
784bc7cd
RS
2680
2681(defvar temp-buffer-setup-hook nil
2682 "Normal hook run by `with-output-to-temp-buffer' at the start.
2683When the hook runs, the temporary buffer is current.
2684This hook is normally set up with a function to put the buffer in Help
2685mode.")
2686
28ac46f8
JPW
2687;; The `assert' macro from the cl package signals
2688;; `cl-assertion-failed' at runtime so always define it.
2689(put 'cl-assertion-failed 'error-conditions '(error))
6bdad9ae 2690(put 'cl-assertion-failed 'error-message (purecopy "Assertion failed"))
28ac46f8 2691
d8869c65
CY
2692(defconst user-emacs-directory
2693 (if (eq system-type 'ms-dos)
2694 ;; MS-DOS cannot have initial dot.
2695 "~/_emacs.d/"
2696 "~/.emacs.d/")
2697 "Directory beneath which additional per-user Emacs-specific files are placed.
2698Various programs in Emacs store information in this directory.
d6c180c4
JB
2699Note that this should end with a directory separator.
2700See also `locate-user-emacs-file'.")
2701
0114073a
GM
2702(custom-declare-variable-early 'user-emacs-directory-warning t
2703 "Non-nil means warn if cannot access `user-emacs-directory'.
2704Set this to nil at your own risk..."
2705 :type 'boolean
2706 :group 'initialization
2707 :version "24.4")
2708
d6c180c4
JB
2709(defun locate-user-emacs-file (new-name &optional old-name)
2710 "Return an absolute per-user Emacs-specific file name.
85e55412
SM
2711If NEW-NAME exists in `user-emacs-directory', return it.
2712Else If OLD-NAME is non-nil and ~/OLD-NAME exists, return ~/OLD-NAME.
d6c180c4
JB
2713Else return NEW-NAME in `user-emacs-directory', creating the
2714directory if it does not exist."
2715 (convert-standard-filename
2716 (let* ((home (concat "~" (or init-file-user "")))
85e55412
SM
2717 (at-home (and old-name (expand-file-name old-name home)))
2718 (bestname (abbreviate-file-name
2719 (expand-file-name new-name user-emacs-directory))))
2720 (if (and at-home (not (file-readable-p bestname))
2721 (file-readable-p at-home))
d6c180c4 2722 at-home
2bea2795 2723 ;; Make sure `user-emacs-directory' exists,
0114073a 2724 ;; unless we're in batch mode or dumping Emacs.
2bea2795
JB
2725 (or noninteractive
2726 purify-flag
0114073a
GM
2727 (let (errtype)
2728 (if (file-directory-p user-emacs-directory)
2729 (or (file-accessible-directory-p user-emacs-directory)
2730 (setq errtype "access"))
2731 (let ((umask (default-file-modes)))
2732 (unwind-protect
2733 (progn
2734 (set-default-file-modes ?\700)
2735 (condition-case nil
2736 (make-directory user-emacs-directory)
2737 (error (setq errtype "create"))))
2738 (set-default-file-modes umask))))
2739 (when (and errtype
2740 user-emacs-directory-warning
2741 (not (get 'user-emacs-directory-warning 'this-session)))
2742 ;; Only warn once per Emacs session.
2743 (put 'user-emacs-directory-warning 'this-session t)
2744 (display-warning 'initialization
2745 (format "\
2746Unable to %s `user-emacs-directory' (%s).
2747Any data that would normally be written there may be lost!
2748If you never want to see this message again,
2749customize the variable `user-emacs-directory-warning'."
2750 errtype user-emacs-directory)))))
85e55412 2751 bestname))))
c4f484f2
RS
2752\f
2753;;;; Misc. useful functions.
448b61c9 2754
e5c2edf7
CY
2755(defsubst buffer-narrowed-p ()
2756 "Return non-nil if the current buffer is narrowed."
2757 (/= (- (point-max) (point-min)) (buffer-size)))
2758
e5e4a942
JL
2759(defun find-tag-default-bounds ()
2760 "Determine the boundaries of the default tag, based on text at point.
2761Return a cons cell with the beginning and end of the found tag.
c4f484f2 2762If there is no plausible default, return nil."
9db3bfae
MR
2763 (let (from to bound)
2764 (when (or (progn
2765 ;; Look at text around `point'.
2766 (save-excursion
2767 (skip-syntax-backward "w_") (setq from (point)))
2768 (save-excursion
2769 (skip-syntax-forward "w_") (setq to (point)))
2770 (> to from))
2771 ;; Look between `line-beginning-position' and `point'.
2772 (save-excursion
2773 (and (setq bound (line-beginning-position))
2774 (skip-syntax-backward "^w_" bound)
2775 (> (setq to (point)) bound)
2776 (skip-syntax-backward "w_")
2777 (setq from (point))))
2778 ;; Look between `point' and `line-end-position'.
2779 (save-excursion
2780 (and (setq bound (line-end-position))
2781 (skip-syntax-forward "^w_" bound)
2782 (< (setq from (point)) bound)
2783 (skip-syntax-forward "w_")
2784 (setq to (point)))))
e5e4a942
JL
2785 (cons from to))))
2786
2787(defun find-tag-default ()
2788 "Determine default tag to search for, based on text at point.
2789If there is no plausible default, return nil."
2790 (let ((bounds (find-tag-default-bounds)))
2791 (when bounds
2792 (buffer-substring-no-properties (car bounds) (cdr bounds)))))
a860d25f 2793
eb1a6e15
J
2794(defun find-tag-default-as-regexp ()
2795 "Return regexp that matches the default tag at point.
2796If there is no tag at point, return nil.
2797
48c6afa6 2798When in a major mode that does not provide its own
eb1a6e15
J
2799`find-tag-default-function', return a regexp that matches the
2800symbol at point exactly."
2801 (let* ((tagf (or find-tag-default-function
2802 (get major-mode 'find-tag-default-function)
2803 'find-tag-default))
2804 (tag (funcall tagf)))
180ed218 2805 (cond ((null tag) nil)
eb1a6e15
J
2806 ((eq tagf 'find-tag-default)
2807 (format "\\_<%s\\_>" (regexp-quote tag)))
2808 (t (regexp-quote tag)))))
2809
c4f484f2
RS
2810(defun play-sound (sound)
2811 "SOUND is a list of the form `(sound KEYWORD VALUE...)'.
2812The following keywords are recognized:
9a5336ae 2813
c4f484f2
RS
2814 :file FILE - read sound data from FILE. If FILE isn't an
2815absolute file name, it is searched in `data-directory'.
9a5336ae 2816
c4f484f2
RS
2817 :data DATA - read sound data from string DATA.
2818
2819Exactly one of :file or :data must be present.
2820
2821 :volume VOL - set volume to VOL. VOL must an integer in the
2822range 0..100 or a float in the range 0..1.0. If not specified,
2823don't change the volume setting of the sound device.
9a5336ae 2824
c4f484f2 2825 :device DEVICE - play sound on DEVICE. If not specified,
d7f90d6c
JB
2826a system-dependent default device name is used.
2827
2828Note: :data and :device are currently not supported on Windows."
c4f484f2
RS
2829 (if (fboundp 'play-sound-internal)
2830 (play-sound-internal sound)
2831 (error "This Emacs binary lacks sound support")))
9a5336ae 2832
0ef97535
GM
2833(declare-function w32-shell-dos-semantics "w32-fns" nil)
2834
c4f484f2 2835(defun shell-quote-argument (argument)
d7f90d6c 2836 "Quote ARGUMENT for passing as argument to an inferior shell."
8f91bf93
DC
2837 (cond
2838 ((eq system-type 'ms-dos)
2839 ;; Quote using double quotes, but escape any existing quotes in
2840 ;; the argument with backslashes.
2841 (let ((result "")
2842 (start 0)
2843 end)
2844 (if (or (null (string-match "[^\"]" argument))
2845 (< (match-end 0) (length argument)))
2846 (while (string-match "[\"]" argument start)
2847 (setq end (match-beginning 0)
2848 result (concat result (substring argument start end)
2849 "\\" (substring argument end (1+ end)))
2850 start (1+ end))))
2851 (concat "\"" result (substring argument start) "\"")))
2852
2853 ((and (eq system-type 'windows-nt) (w32-shell-dos-semantics))
638f053a 2854
8f91bf93
DC
2855 ;; First, quote argument so that CommandLineToArgvW will
2856 ;; understand it. See
2857 ;; http://msdn.microsoft.com/en-us/library/17w5ykft%28v=vs.85%29.aspx
2858 ;; After we perform that level of quoting, escape shell
2859 ;; metacharacters so that cmd won't mangle our argument. If the
2860 ;; argument contains no double quote characters, we can just
2861 ;; surround it with double quotes. Otherwise, we need to prefix
2862 ;; each shell metacharacter with a caret.
2863
2864 (setq argument
2865 ;; escape backslashes at end of string
2866 (replace-regexp-in-string
2867 "\\(\\\\*\\)$"
2868 "\\1\\1"
2869 ;; escape backslashes and quotes in string body
2870 (replace-regexp-in-string
2871 "\\(\\\\*\\)\""
2872 "\\1\\1\\\\\""
2873 argument)))
2874
2a782793 2875 (if (string-match "[%!\"]" argument)
8f91bf93
DC
2876 (concat
2877 "^\""
2878 (replace-regexp-in-string
2879 "\\([%!()\"<>&|^]\\)"
2880 "^\\1"
2881 argument)
2882 "^\"")
2883 (concat "\"" argument "\"")))
2884
2885 (t
4bbf6b41
JR
2886 (if (equal argument "")
2887 "''"
2888 ;; Quote everything except POSIX filename characters.
2889 ;; This should be safe enough even for really weird shells.
8f91bf93
DC
2890 (replace-regexp-in-string
2891 "\n" "'\n'"
2892 (replace-regexp-in-string "[^-0-9a-zA-Z_./\n]" "\\\\\\&" argument))))
2893 ))
3e457225
RS
2894
2895(defun string-or-null-p (object)
2896 "Return t if OBJECT is a string or nil.
2897Otherwise, return nil."
2898 (or (stringp object) (null object)))
2899
26715e1b 2900(defun booleanp (object)
ac6ca7ba
KR
2901 "Return t if OBJECT is one of the two canonical boolean values: t or nil.
2902Otherwise, return nil."
2903 (and (memq object '(nil t)) t))
26715e1b 2904
231d8498
SM
2905(defun special-form-p (object)
2906 "Non-nil if and only if OBJECT is a special form."
2907 (if (and (symbolp object) (fboundp object))
96c052a5 2908 (setq object (indirect-function object t)))
231d8498
SM
2909 (and (subrp object) (eq (cdr (subr-arity object)) 'unevalled)))
2910
1627b55f 2911(defun field-at-pos (pos)
d7f90d6c 2912 "Return the field at position POS, taking stickiness etc into account."
1ecaae6c
NR
2913 (let ((raw-field (get-char-property (field-beginning pos) 'field)))
2914 (if (eq raw-field 'boundary)
2915 (get-char-property (1- (field-end pos)) 'field)
2916 raw-field)))
2917
7f3f739f
LL
2918(defun sha1 (object &optional start end binary)
2919 "Return the SHA1 (Secure Hash Algorithm) of an OBJECT.
2920OBJECT is either a string or a buffer. Optional arguments START and
2921END are character positions specifying which portion of OBJECT for
2922computing the hash. If BINARY is non-nil, return a string in binary
2923form."
2924 (secure-hash 'sha1 object start end binary))
2925
7abaf5cc
SM
2926(defun function-get (f prop &optional autoload)
2927 "Return the value of property PROP of function F.
3c98c962
SM
2928If AUTOLOAD is non-nil and F is autoloaded, try to autoload it
2929in the hope that it will set PROP. If AUTOLOAD is `macro', only do it
2930if it's an autoloaded macro."
7abaf5cc
SM
2931 (let ((val nil))
2932 (while (and (symbolp f)
2933 (null (setq val (get f prop)))
2934 (fboundp f))
2935 (let ((fundef (symbol-function f)))
2936 (if (and autoload (autoloadp fundef)
3c98c962
SM
2937 (not (equal fundef
2938 (autoload-do-load fundef f
2939 (if (eq autoload 'macro)
2940 'macro)))))
7abaf5cc
SM
2941 nil ;Re-try `get' on the same `f'.
2942 (setq f fundef))))
2943 val))
c4f484f2
RS
2944\f
2945;;;; Support for yanking and text properties.
9a5336ae 2946
2170b1bd 2947(defvar yank-handled-properties)
2493767e
RS
2948(defvar yank-excluded-properties)
2949
8ed59ad5 2950(defun remove-yank-excluded-properties (start end)
2170b1bd
CY
2951 "Process text properties between START and END, inserted for a `yank'.
2952Perform the handling specified by `yank-handled-properties', then
2953remove properties specified by `yank-excluded-properties'."
8ed59ad5 2954 (let ((inhibit-read-only t))
2170b1bd
CY
2955 (dolist (handler yank-handled-properties)
2956 (let ((prop (car handler))
2957 (fun (cdr handler))
2958 (run-start start))
2959 (while (< run-start end)
2960 (let ((value (get-text-property run-start prop))
2961 (run-end (next-single-property-change
2962 run-start prop nil end)))
2963 (funcall fun value run-start run-end)
2964 (setq run-start run-end)))))
8ed59ad5
KS
2965 (if (eq yank-excluded-properties t)
2966 (set-text-properties start end nil)
ebaa3349 2967 (remove-list-of-text-properties start end yank-excluded-properties))))
8ed59ad5 2968
e0e80ec9
KS
2969(defvar yank-undo-function)
2970
2971(defun insert-for-yank (string)
3fa173b4 2972 "Call `insert-for-yank-1' repetitively for each `yank-handler' segment.
6b61353c
KH
2973
2974See `insert-for-yank-1' for more details."
2975 (let (to)
2976 (while (setq to (next-single-property-change 0 'yank-handler string))
2977 (insert-for-yank-1 (substring string 0 to))
2978 (setq string (substring string to))))
2979 (insert-for-yank-1 string))
2980
2981(defun insert-for-yank-1 (string)
2170b1bd
CY
2982 "Insert STRING at point for the `yank' command.
2983This function is like `insert', except it honors the variables
2984`yank-handled-properties' and `yank-excluded-properties', and the
2985`yank-handler' text property.
2986
2987Properties listed in `yank-handled-properties' are processed,
2988then those listed in `yank-excluded-properties' are discarded.
2989
2990If STRING has a non-nil `yank-handler' property on its first
2991character, the normal insert behavior is altered. The value of
2992the `yank-handler' property must be a list of one to four
2993elements, of the form (FUNCTION PARAM NOEXCLUDE UNDO).
2994FUNCTION, if non-nil, should be a function of one argument, an
2995 object to insert; it is called instead of `insert'.
2996PARAM, if present and non-nil, replaces STRING as the argument to
2997 FUNCTION or `insert'; e.g. if FUNCTION is `yank-rectangle', PARAM
2998 may be a list of strings to insert as a rectangle.
2999If NOEXCLUDE is present and non-nil, the normal removal of
5612fd08 3000 `yank-excluded-properties' is not performed; instead FUNCTION is
2170b1bd
CY
3001 responsible for the removal. This may be necessary if FUNCTION
3002 adjusts point before or after inserting the object.
3003UNDO, if present and non-nil, should be a function to be called
e0e80ec9 3004 by `yank-pop' to undo the insertion of the current object. It is
2170b1bd
CY
3005 given two arguments, the start and end of the region. FUNCTION
3006 may set `yank-undo-function' to override UNDO."
57596fb6
KS
3007 (let* ((handler (and (stringp string)
3008 (get-text-property 0 'yank-handler string)))
3009 (param (or (nth 1 handler) string))
4f0f29aa 3010 (opoint (point))
029fd82c 3011 (inhibit-read-only inhibit-read-only)
4f0f29aa
RS
3012 end)
3013
57596fb6 3014 (setq yank-undo-function t)
2170b1bd 3015 (if (nth 0 handler) ; FUNCTION
57596fb6 3016 (funcall (car handler) param)
e0e80ec9 3017 (insert param))
4f0f29aa
RS
3018 (setq end (point))
3019
029fd82c
CY
3020 ;; Prevent read-only properties from interfering with the
3021 ;; following text property changes.
3022 (setq inhibit-read-only t)
3023
2170b1bd
CY
3024 (unless (nth 2 handler) ; NOEXCLUDE
3025 (remove-yank-excluded-properties opoint end))
631890d8
RS
3026
3027 ;; If last inserted char has properties, mark them as rear-nonsticky.
3028 (if (and (> end opoint)
3029 (text-properties-at (1- end)))
3030 (put-text-property (1- end) end 'rear-nonsticky t))
3031
2170b1bd
CY
3032 (if (eq yank-undo-function t) ; not set by FUNCTION
3033 (setq yank-undo-function (nth 3 handler))) ; UNDO
3034 (if (nth 4 handler) ; COMMAND
57596fb6 3035 (setq this-command (nth 4 handler)))))
f1180544 3036
a478f3e1
JB
3037(defun insert-buffer-substring-no-properties (buffer &optional start end)
3038 "Insert before point a substring of BUFFER, without text properties.
3b8690f6 3039BUFFER may be a buffer or a buffer name.
f8cf33b1
JB
3040Arguments START and END are character positions specifying the substring.
3041They default to the values of (point-min) and (point-max) in BUFFER."
3b8690f6 3042 (let ((opoint (point)))
a478f3e1 3043 (insert-buffer-substring buffer start end)
3b8690f6
KS
3044 (let ((inhibit-read-only t))
3045 (set-text-properties opoint (point) nil))))
3046
a478f3e1
JB
3047(defun insert-buffer-substring-as-yank (buffer &optional start end)
3048 "Insert before point a part of BUFFER, stripping some text properties.
3049BUFFER may be a buffer or a buffer name.
f8cf33b1
JB
3050Arguments START and END are character positions specifying the substring.
3051They default to the values of (point-min) and (point-max) in BUFFER.
05b621a6
CY
3052Before insertion, process text properties according to
3053`yank-handled-properties' and `yank-excluded-properties'."
6b61353c
KH
3054 ;; Since the buffer text should not normally have yank-handler properties,
3055 ;; there is no need to handle them here.
3b8690f6 3056 (let ((opoint (point)))
a478f3e1 3057 (insert-buffer-substring buffer start end)
8ed59ad5 3058 (remove-yank-excluded-properties opoint (point))))
3b8690f6 3059
2170b1bd
CY
3060(defun yank-handle-font-lock-face-property (face start end)
3061 "If `font-lock-defaults' is nil, apply FACE as a `face' property.
3062START and END denote the start and end of the text to act on.
3063Do nothing if FACE is nil."
3064 (and face
3065 (null font-lock-defaults)
3066 (put-text-property start end 'face face)))
3067
3068;; This removes `mouse-face' properties in *Help* buffer buttons:
3069;; http://lists.gnu.org/archive/html/emacs-devel/2002-04/msg00648.html
3070(defun yank-handle-category-property (category start end)
3071 "Apply property category CATEGORY's properties between START and END."
3072 (when category
3073 (let ((start2 start))
3074 (while (< start2 end)
3075 (let ((end2 (next-property-change start2 nil end))
3076 (original (text-properties-at start2)))
3077 (set-text-properties start2 end2 (symbol-plist category))
3078 (add-text-properties start2 end2 original)
3079 (setq start2 end2))))))
3080
2493767e 3081\f
c4f484f2 3082;;;; Synchronous shell commands.
2493767e 3083
be9b65ac
DL
3084(defun start-process-shell-command (name buffer &rest args)
3085 "Start a program in a subprocess. Return the process object for it.
be9b65ac 3086NAME is name for process. It is modified if necessary to make it unique.
54ce7cbf 3087BUFFER is the buffer (or buffer name) to associate with the process.
be9b65ac
DL
3088 Process output goes at end of that buffer, unless you specify
3089 an output stream or filter function to handle the output.
3090 BUFFER may be also nil, meaning that this process is not associated
3091 with any buffer
03a74b84
SM
3092COMMAND is the shell command to run.
3093
3094An old calling convention accepted any number of arguments after COMMAND,
3095which were just concatenated to COMMAND. This is still supported but strongly
fd6c5134 3096discouraged."
b59f6d7a
RS
3097 ;; We used to use `exec' to replace the shell with the command,
3098 ;; but that failed to handle (...) and semicolon, etc.
7c2fb837
DN
3099 (start-process name buffer shell-file-name shell-command-switch
3100 (mapconcat 'identity args " ")))
f3ed9aca 3101(set-advertised-calling-convention 'start-process-shell-command
f3a30a50 3102 '(name buffer command) "23.1")
f3ed9aca 3103
a9e11582
MA
3104(defun start-file-process-shell-command (name buffer &rest args)
3105 "Start a program in a subprocess. Return the process object for it.
fd6c5134 3106Similar to `start-process-shell-command', but calls `start-file-process'."
a9e11582
MA
3107 (start-file-process
3108 name buffer
3109 (if (file-remote-p default-directory) "/bin/sh" shell-file-name)
3110 (if (file-remote-p default-directory) "-c" shell-command-switch)
3111 (mapconcat 'identity args " ")))
f3ed9aca 3112(set-advertised-calling-convention 'start-file-process-shell-command
f3a30a50 3113 '(name buffer command) "23.1")
a9e11582 3114
93aca633
MB
3115(defun call-process-shell-command (command &optional infile buffer display
3116 &rest args)
3117 "Execute the shell command COMMAND synchronously in separate process.
3118The remaining arguments are optional.
3119The program's input comes from file INFILE (nil means `/dev/null').
3120Insert output in BUFFER before point; t means current buffer;
3121 nil for BUFFER means discard it; 0 means discard and don't wait.
3122BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,
3123REAL-BUFFER says what to do with standard output, as above,
3124while STDERR-FILE says what to do with standard error in the child.
3125STDERR-FILE may be nil (discard standard error output),
3126t (mix it with ordinary output), or a file name string.
3127
3128Fourth arg DISPLAY non-nil means redisplay buffer as output is inserted.
3129Remaining arguments are strings passed as additional arguments for COMMAND.
3130Wildcards and redirection are handled as usual in the shell.
3131
3132If BUFFER is 0, `call-process-shell-command' returns immediately with value nil.
3133Otherwise it waits for COMMAND to terminate and returns a numeric exit
3134status or a signal description string.
3135If you quit, the process is killed with SIGINT, or SIGKILL if you quit again."
7c2fb837
DN
3136 ;; We used to use `exec' to replace the shell with the command,
3137 ;; but that failed to handle (...) and semicolon, etc.
3138 (call-process shell-file-name
3139 infile buffer display
3140 shell-command-switch
3141 (mapconcat 'identity (cons command args) " ")))
a9e11582
MA
3142
3143(defun process-file-shell-command (command &optional infile buffer display
3144 &rest args)
3145 "Process files synchronously in a separate process.
3146Similar to `call-process-shell-command', but calls `process-file'."
3147 (process-file
3148 (if (file-remote-p default-directory) "/bin/sh" shell-file-name)
3149 infile buffer display
3150 (if (file-remote-p default-directory) "-c" shell-command-switch)
3151 (mapconcat 'identity (cons command args) " ")))
a7ed4c2a 3152\f
c4f484f2
RS
3153;;;; Lisp macros to do various things temporarily.
3154
83f57f49
MR
3155(defmacro with-current-buffer (buffer-or-name &rest body)
3156 "Execute the forms in BODY with BUFFER-OR-NAME temporarily current.
3157BUFFER-OR-NAME must be a buffer or the name of an existing buffer.
3158The value returned is the value of the last form in BODY. See
3159also `with-temp-buffer'."
d47f7515
SM
3160 (declare (indent 1) (debug t))
3161 `(save-current-buffer
83f57f49 3162 (set-buffer ,buffer-or-name)
d47f7515
SM
3163 ,@body))
3164
89660017 3165(defun internal--before-with-selected-window (window)
1439443b
SM
3166 (let ((other-frame (window-frame window)))
3167 (list window (selected-window)
3168 ;; Selecting a window on another frame also changes that
3169 ;; frame's frame-selected-window. We must save&restore it.
3170 (unless (eq (selected-frame) other-frame)
3171 (frame-selected-window other-frame))
3172 ;; Also remember the top-frame if on ttys.
3173 (unless (eq (selected-frame) other-frame)
3174 (tty-top-frame other-frame)))))
3175
89660017 3176(defun internal--after-with-selected-window (state)
1439443b
SM
3177 ;; First reset frame-selected-window.
3178 (when (window-live-p (nth 2 state))
3179 ;; We don't use set-frame-selected-window because it does not
3180 ;; pass the `norecord' argument to Fselect_window.
3181 (select-window (nth 2 state) 'norecord)
3182 (and (frame-live-p (nth 3 state))
3183 (not (eq (tty-top-frame) (nth 3 state)))
3184 (select-frame (nth 3 state) 'norecord)))
3185 ;; Then reset the actual selected-window.
7d806b1e
DU
3186 (when (window-live-p (nth 1 state))
3187 (select-window (nth 1 state) 'norecord)))
1439443b 3188
d47f7515
SM
3189(defmacro with-selected-window (window &rest body)
3190 "Execute the forms in BODY with WINDOW as the selected window.
3191The value returned is the value of the last form in BODY.
4c6d1e16 3192
a5094f72
MR
3193This macro saves and restores the selected window, as well as the
3194selected window of each frame. It does not change the order of
3195recently selected windows. If the previously selected window of
3196some frame is no longer live at the end of BODY, that frame's
3197selected window is left alone. If the selected window is no
3198longer live, then whatever window is selected at the end of BODY
3199remains selected.
3200
3201This macro uses `save-current-buffer' to save and restore the
3202current buffer, since otherwise its normal operation could
3203potentially make a different buffer current. It does not alter
3204the buffer list ordering."
d47f7515 3205 (declare (indent 1) (debug t))
1439443b 3206 `(let ((save-selected-window--state
89660017 3207 (internal--before-with-selected-window ,window)))
4c6d1e16
RS
3208 (save-current-buffer
3209 (unwind-protect
1439443b 3210 (progn (select-window (car save-selected-window--state) 'norecord)
4c6d1e16 3211 ,@body)
89660017 3212 (internal--after-with-selected-window save-selected-window--state)))))
a7f284ec 3213
c3e242d3
KL
3214(defmacro with-selected-frame (frame &rest body)
3215 "Execute the forms in BODY with FRAME as the selected frame.
3216The value returned is the value of the last form in BODY.
a5094f72 3217
4e5d086d
LMI
3218This macro saves and restores the selected frame, and changes the
3219order of neither the recently selected windows nor the buffers in
3220the buffer list."
c3e242d3 3221 (declare (indent 1) (debug t))
632210dd
KL
3222 (let ((old-frame (make-symbol "old-frame"))
3223 (old-buffer (make-symbol "old-buffer")))
3224 `(let ((,old-frame (selected-frame))
3225 (,old-buffer (current-buffer)))
3226 (unwind-protect
a5094f72 3227 (progn (select-frame ,frame 'norecord)
632210dd 3228 ,@body)
a5094f72
MR
3229 (when (frame-live-p ,old-frame)
3230 (select-frame ,old-frame 'norecord))
3231 (when (buffer-live-p ,old-buffer)
3232 (set-buffer ,old-buffer))))))
c3e242d3 3233
e0f57e65 3234(defmacro save-window-excursion (&rest body)
2cc775f9 3235 "Execute BODY, then restore previous window configuration.
d3760c4b
CY
3236This macro saves the window configuration on the selected frame,
3237executes BODY, then calls `set-window-configuration' to restore
3238the saved window configuration. The return value is the last
3239form in BODY. The window configuration is also restored if BODY
3240exits nonlocally.
e0f57e65
SM
3241
3242BEWARE: Most uses of this macro introduce bugs.
3243E.g. it should not be used to try and prevent some code from opening
3244a new window, since that window may sometimes appear in another frame,
3245in which case `save-window-excursion' cannot help."
3246 (declare (indent 0) (debug t))
3247 (let ((c (make-symbol "wconfig")))
3248 `(let ((,c (current-window-configuration)))
3249 (unwind-protect (progn ,@body)
3250 (set-window-configuration ,c)))))
3251
4ff5b1b2 3252(defun internal-temp-output-buffer-show (buffer)
43bf5e8e
MR
3253 "Internal function for `with-output-to-temp-buffer'."
3254 (with-current-buffer buffer
3255 (set-buffer-modified-p nil)
3256 (goto-char (point-min)))
3257
3258 (if temp-buffer-show-function
3259 (funcall temp-buffer-show-function buffer)
3260 (with-current-buffer buffer
3261 (let* ((window
3262 (let ((window-combination-limit
3263 ;; When `window-combination-limit' equals
3264 ;; `temp-buffer' or `temp-buffer-resize' and
3265 ;; `temp-buffer-resize-mode' is enabled in this
3266 ;; buffer bind it to t so resizing steals space
3267 ;; preferably from the window that was split.
3268 (if (or (eq window-combination-limit 'temp-buffer)
3269 (and (eq window-combination-limit
3270 'temp-buffer-resize)
3271 temp-buffer-resize-mode))
3272 t
3273 window-combination-limit)))
3274 (display-buffer buffer)))
3275 (frame (and window (window-frame window))))
3276 (when window
3277 (unless (eq frame (selected-frame))
3278 (make-frame-visible frame))
3279 (setq minibuffer-scroll-window window)
3280 (set-window-hscroll window 0)
3281 ;; Don't try this with NOFORCE non-nil!
3282 (set-window-start window (point-min) t)
735135f9 3283 ;; This should not be necessary.
43bf5e8e
MR
3284 (set-window-point window (point-min))
3285 ;; Run `temp-buffer-show-hook', with the chosen window selected.
3286 (with-selected-window window
3287 (run-hooks 'temp-buffer-show-hook))))))
3288 ;; Return nil.
3289 nil)
3290
95f0501e 3291;; Doc is very similar to with-temp-buffer-window.
3e21b6a7
SM
3292(defmacro with-output-to-temp-buffer (bufname &rest body)
3293 "Bind `standard-output' to buffer BUFNAME, eval BODY, then show that buffer.
3294
3295This construct makes buffer BUFNAME empty before running BODY.
3296It does not make the buffer current for BODY.
3297Instead it binds `standard-output' to that buffer, so that output
3298generated with `prin1' and similar functions in BODY goes into
3299the buffer.
3300
a239d4e9 3301At the end of BODY, this marks buffer BUFNAME unmodified and displays
3e21b6a7
SM
3302it in a window, but does not select it. The normal way to do this is
3303by calling `display-buffer', then running `temp-buffer-show-hook'.
3304However, if `temp-buffer-show-function' is non-nil, it calls that
3305function instead (and does not run `temp-buffer-show-hook'). The
3306function gets one argument, the buffer to display.
3307
3308The return value of `with-output-to-temp-buffer' is the value of the
3309last form in BODY. If BODY does not finish normally, the buffer
3310BUFNAME is not displayed.
3311
3312This runs the hook `temp-buffer-setup-hook' before BODY,
3313with the buffer BUFNAME temporarily current. It runs the hook
3314`temp-buffer-show-hook' after displaying buffer BUFNAME, with that
3315buffer temporarily current, and the window that was used to display it
3316temporarily selected. But it doesn't run `temp-buffer-show-hook'
95f0501e
GM
3317if it uses `temp-buffer-show-function'.
3318
3319See the related form `with-temp-buffer-window'."
2462470b 3320 (declare (debug t))
3e21b6a7
SM
3321 (let ((old-dir (make-symbol "old-dir"))
3322 (buf (make-symbol "buf")))
9dba2c64
SM
3323 `(let* ((,old-dir default-directory)
3324 (,buf
3325 (with-current-buffer (get-buffer-create ,bufname)
3326 (prog1 (current-buffer)
3327 (kill-all-local-variables)
3328 ;; FIXME: delete_all_overlays
3329 (setq default-directory ,old-dir)
3330 (setq buffer-read-only nil)
3331 (setq buffer-file-name nil)
3332 (setq buffer-undo-list t)
3333 (let ((inhibit-read-only t)
3334 (inhibit-modification-hooks t))
3335 (erase-buffer)
3336 (run-hooks 'temp-buffer-setup-hook)))))
3337 (standard-output ,buf))
3338 (prog1 (progn ,@body)
4ff5b1b2 3339 (internal-temp-output-buffer-show ,buf)))))
3e21b6a7 3340
e5bb8a8c
SM
3341(defmacro with-temp-file (file &rest body)
3342 "Create a new buffer, evaluate BODY there, and write the buffer to FILE.
3343The value returned is the value of the last form in BODY.
a2fdb55c 3344See also `with-temp-buffer'."
f291fe60 3345 (declare (indent 1) (debug t))
a7ed4c2a 3346 (let ((temp-file (make-symbol "temp-file"))
a2fdb55c
EN
3347 (temp-buffer (make-symbol "temp-buffer")))
3348 `(let ((,temp-file ,file)
3349 (,temp-buffer
3350 (get-buffer-create (generate-new-buffer-name " *temp file*"))))
3351 (unwind-protect
3352 (prog1
3353 (with-current-buffer ,temp-buffer
e5bb8a8c 3354 ,@body)
a2fdb55c 3355 (with-current-buffer ,temp-buffer
ab1d3835 3356 (write-region nil nil ,temp-file nil 0)))
a2fdb55c
EN
3357 (and (buffer-name ,temp-buffer)
3358 (kill-buffer ,temp-buffer))))))
3359
e5bb8a8c 3360(defmacro with-temp-message (message &rest body)
a600effe 3361 "Display MESSAGE temporarily if non-nil while BODY is evaluated.
e5bb8a8c
SM
3362The original message is restored to the echo area after BODY has finished.
3363The value returned is the value of the last form in BODY.
a600effe
SM
3364MESSAGE is written to the message log buffer if `message-log-max' is non-nil.
3365If MESSAGE is nil, the echo area and message log buffer are unchanged.
3366Use a MESSAGE of \"\" to temporarily clear the echo area."
f291fe60 3367 (declare (debug t) (indent 1))
110201c8
SM
3368 (let ((current-message (make-symbol "current-message"))
3369 (temp-message (make-symbol "with-temp-message")))
3370 `(let ((,temp-message ,message)
3371 (,current-message))
e5bb8a8c
SM
3372 (unwind-protect
3373 (progn
110201c8
SM
3374 (when ,temp-message
3375 (setq ,current-message (current-message))
aadf7ff3 3376 (message "%s" ,temp-message))
e5bb8a8c 3377 ,@body)
cad84646
RS
3378 (and ,temp-message
3379 (if ,current-message
3380 (message "%s" ,current-message)
3381 (message nil)))))))
e5bb8a8c
SM
3382
3383(defmacro with-temp-buffer (&rest body)
3384 "Create a temporary buffer, and evaluate BODY there like `progn'.
a2fdb55c 3385See also `with-temp-file' and `with-output-to-string'."
d47f7515 3386 (declare (indent 0) (debug t))
a2fdb55c 3387 (let ((temp-buffer (make-symbol "temp-buffer")))
9166dbf6 3388 `(let ((,temp-buffer (generate-new-buffer " *temp*")))
4a5e1832
SM
3389 ;; FIXME: kill-buffer can change current-buffer in some odd cases.
3390 (with-current-buffer ,temp-buffer
3391 (unwind-protect
3392 (progn ,@body)
3393 (and (buffer-name ,temp-buffer)
3394 (kill-buffer ,temp-buffer)))))))
a2fdb55c 3395
83a5aac5 3396(defmacro with-silent-modifications (&rest body)
f291fe60 3397 "Execute BODY, pretending it does not modify the buffer.
83a5aac5
SM
3398If BODY performs real modifications to the buffer's text, other
3399than cosmetic ones, undo data may become corrupted.
a28e4607
LMI
3400
3401This macro will run BODY normally, but doesn't count its buffer
3402modifications as being buffer modifications. This affects things
3403like buffer-modified-p, checking whether the file is locked by
3404someone else, running buffer modification hooks, and other things
3405of that nature.
3406
3407Typically used around modifications of text-properties which do
3408not really affect the buffer's content."
83a5aac5
SM
3409 (declare (debug t) (indent 0))
3410 (let ((modified (make-symbol "modified")))
3411 `(let* ((,modified (buffer-modified-p))
3412 (buffer-undo-list t)
3413 (inhibit-read-only t)
3414 (inhibit-modification-hooks t)
3415 deactivate-mark
3416 ;; Avoid setting and removing file locks and checking
3417 ;; buffer's uptodate-ness w.r.t the underlying file.
3418 buffer-file-name
3419 buffer-file-truename)
3420 (unwind-protect
3421 (progn
3422 ,@body)
3423 (unless ,modified
3424 (restore-buffer-modified-p nil))))))
3425
5db7925d
RS
3426(defmacro with-output-to-string (&rest body)
3427 "Execute BODY, return the text it sent to `standard-output', as a string."
d47f7515 3428 (declare (indent 0) (debug t))
a2fdb55c
EN
3429 `(let ((standard-output
3430 (get-buffer-create (generate-new-buffer-name " *string-output*"))))
86ec740e
RF
3431 (unwind-protect
3432 (progn
3433 (let ((standard-output standard-output))
3434 ,@body)
3435 (with-current-buffer standard-output
3436 (buffer-string)))
3437 (kill-buffer standard-output))))
2ec9c94e 3438
0764e16f 3439(defmacro with-local-quit (&rest body)
53a7160c 3440 "Execute BODY, allowing quits to terminate BODY but not escape further.
b9308c61 3441When a quit terminates BODY, `with-local-quit' returns nil but
60f7e8b6
RS
3442requests another quit. That quit will be processed as soon as quitting
3443is allowed once again. (Immediately, if `inhibit-quit' is nil.)"
12320833 3444 (declare (debug t) (indent 0))
0764e16f
SM
3445 `(condition-case nil
3446 (let ((inhibit-quit nil))
3447 ,@body)
113fe928
RS
3448 (quit (setq quit-flag t)
3449 ;; This call is to give a chance to handle quit-flag
3450 ;; in case inhibit-quit is nil.
3451 ;; Without this, it will not be handled until the next function
3452 ;; call, and that might allow it to exit thru a condition-case
3453 ;; that intends to handle the quit signal next time.
3454 (eval '(ignore nil)))))
0764e16f 3455
c2b53d7b
RS
3456(defmacro while-no-input (&rest body)
3457 "Execute BODY only as long as there's no pending input.
3458If input arrives, that ends the execution of BODY,
83047ee3
RS
3459and `while-no-input' returns t. Quitting makes it return nil.
3460If BODY finishes, `while-no-input' returns whatever value BODY produced."
c2b53d7b
RS
3461 (declare (debug t) (indent 0))
3462 (let ((catch-sym (make-symbol "input")))
3463 `(with-local-quit
3464 (catch ',catch-sym
3465 (let ((throw-on-input ',catch-sym))
790e0ef7 3466 (or (input-pending-p)
ff7d73ac 3467 (progn ,@body)))))))
c2b53d7b 3468
1be3ca5a 3469(defmacro condition-case-unless-debug (var bodyform &rest handlers)
e5b5a34d
SM
3470 "Like `condition-case' except that it does not prevent debugging.
3471More specifically if `debug-on-error' is set then the debugger will be invoked
3472even if this catches the signal."
47ccb993 3473 (declare (debug condition-case) (indent 2))
e5b5a34d
SM
3474 `(condition-case ,var
3475 ,bodyform
3476 ,@(mapcar (lambda (handler)
3477 `((debug ,@(if (listp (car handler)) (car handler)
3478 (list (car handler))))
3479 ,@(cdr handler)))
3480 handlers)))
47ccb993 3481
1be3ca5a
LL
3482(define-obsolete-function-alias 'condition-case-no-debug
3483 'condition-case-unless-debug "24.1")
3484
47ccb993
SM
3485(defmacro with-demoted-errors (&rest body)
3486 "Run BODY and demote any errors to simple messages.
3487If `debug-on-error' is non-nil, run BODY without catching its errors.
3488This is to be used around code which is not expected to signal an error
04bf5b65 3489but which should be robust in the unexpected case that an error is signaled."
47ccb993
SM
3490 (declare (debug t) (indent 0))
3491 (let ((err (make-symbol "err")))
1be3ca5a 3492 `(condition-case-unless-debug ,err
47ccb993 3493 (progn ,@body)
7f0ea0ff 3494 (error (message "Error: %S" ,err) nil))))
47ccb993 3495
2ec9c94e
RS
3496(defmacro combine-after-change-calls (&rest body)
3497 "Execute BODY, but don't call the after-change functions till the end.
3498If BODY makes changes in the buffer, they are recorded
3499and the functions on `after-change-functions' are called several times
3500when BODY is finished.
31aa282e 3501The return value is the value of the last form in BODY.
2ec9c94e
RS
3502
3503If `before-change-functions' is non-nil, then calls to the after-change
3504functions can't be deferred, so in that case this macro has no effect.
3505
3506Do not alter `after-change-functions' or `before-change-functions'
3507in BODY."
d47f7515 3508 (declare (indent 0) (debug t))
2ec9c94e
RS
3509 `(unwind-protect
3510 (let ((combine-after-change-calls t))
3511 . ,body)
3512 (combine-after-change-execute)))
6a978be3
CY
3513
3514(defmacro with-case-table (table &rest body)
3515 "Execute the forms in BODY with TABLE as the current case table.
3516The value returned is the value of the last form in BODY."
3517 (declare (indent 1) (debug t))
8d6fd8d4
JPW
3518 (let ((old-case-table (make-symbol "table"))
3519 (old-buffer (make-symbol "buffer")))
3520 `(let ((,old-case-table (current-case-table))
3521 (,old-buffer (current-buffer)))
3522 (unwind-protect
3523 (progn (set-case-table ,table)
3524 ,@body)
3525 (with-current-buffer ,old-buffer
3526 (set-case-table ,old-case-table))))))
c4f484f2 3527\f
c4f484f2 3528;;; Matching and match data.
2493767e 3529
c7ca41e6
RS
3530(defvar save-match-data-internal)
3531
3532;; We use save-match-data-internal as the local variable because
3533;; that works ok in practice (people should not use that variable elsewhere).
3534;; We used to use an uninterned symbol; the compiler handles that properly
3535;; now, but it generates slower code.
9a5336ae 3536(defmacro save-match-data (&rest body)
e4d03691
JB
3537 "Execute the BODY forms, restoring the global value of the match data.
3538The value returned is the value of the last form in BODY."
64ed733a
PE
3539 ;; It is better not to use backquote here,
3540 ;; because that makes a bootstrapping problem
3541 ;; if you need to recompile all the Lisp files using interpreted code.
d47f7515 3542 (declare (indent 0) (debug t))
64ed733a
PE
3543 (list 'let
3544 '((save-match-data-internal (match-data)))
3545 (list 'unwind-protect
3546 (cons 'progn body)
d1fab151
KS
3547 ;; It is safe to free (evaporate) markers immediately here,
3548 ;; as Lisp programs should not copy from save-match-data-internal.
a0ef72df 3549 '(set-match-data save-match-data-internal 'evaporate))))
993713ce 3550
cd323f89 3551(defun match-string (num &optional string)
993713ce
SM
3552 "Return string of text matched by last search.
3553NUM specifies which parenthesized expression in the last regexp.
3554 Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
3555Zero means the entire text matched by the whole regexp or whole string.
91054f8f
LMI
3556STRING should be given if the last search was by `string-match' on STRING.
3557If STRING is nil, the current buffer should be the same buffer
3558the search/match was performed in."
cd323f89
SM
3559 (if (match-beginning num)
3560 (if string
3561 (substring string (match-beginning num) (match-end num))
3562 (buffer-substring (match-beginning num) (match-end num)))))
58f950b4 3563
bb760c71
RS
3564(defun match-string-no-properties (num &optional string)
3565 "Return string of text matched by last search, without text properties.
3566NUM specifies which parenthesized expression in the last regexp.
3567 Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
3568Zero means the entire text matched by the whole regexp or whole string.
91054f8f
LMI
3569STRING should be given if the last search was by `string-match' on STRING.
3570If STRING is nil, the current buffer should be the same buffer
3571the search/match was performed in."
bb760c71
RS
3572 (if (match-beginning num)
3573 (if string
6b61353c
KH
3574 (substring-no-properties string (match-beginning num)
3575 (match-end num))
bb760c71
RS
3576 (buffer-substring-no-properties (match-beginning num)
3577 (match-end num)))))
3578
8c2e721a
JL
3579
3580(defun match-substitute-replacement (replacement
3581 &optional fixedcase literal string subexp)
3582 "Return REPLACEMENT as it will be inserted by `replace-match'.
3583In other words, all back-references in the form `\\&' and `\\N'
3584are substituted with actual strings matched by the last search.
3585Optional FIXEDCASE, LITERAL, STRING and SUBEXP have the same
3586meaning as for `replace-match'."
3587 (let ((match (match-string 0 string)))
3588 (save-match-data
3589 (set-match-data (mapcar (lambda (x)
3590 (if (numberp x)
3591 (- x (match-beginning 0))
3592 x))
3593 (match-data t)))
3594 (replace-match replacement fixedcase literal match subexp))))
3595
3596
46065dd4 3597(defun looking-back (regexp &optional limit greedy)
f30e0cd8 3598 "Return non-nil if text before point matches regular expression REGEXP.
991b32c3 3599Like `looking-at' except matches before point, and is slower.
01d16e16
RS
3600LIMIT if non-nil speeds up the search by specifying a minimum
3601starting position, to avoid checking matches that would start
3602before LIMIT.
46065dd4 3603
cde27dd2
CY
3604If GREEDY is non-nil, extend the match backwards as far as
3605possible, stopping when a single additional previous character
3606cannot be part of a match for REGEXP. When the match is
3dcde186 3607extended, its starting position is allowed to occur before
cde27dd2 3608LIMIT."
46065dd4
RS
3609 (let ((start (point))
3610 (pos
3611 (save-excursion
3612 (and (re-search-backward (concat "\\(?:" regexp "\\)\\=") limit t)
3613 (point)))))
3614 (if (and greedy pos)
3615 (save-restriction
3616 (narrow-to-region (point-min) start)
3617 (while (and (> pos (point-min))
3618 (save-excursion
3619 (goto-char pos)
3620 (backward-char 1)
3621 (looking-at (concat "\\(?:" regexp "\\)\\'"))))
3622 (setq pos (1- pos)))
3623 (save-excursion
3624 (goto-char pos)
3625 (looking-at (concat "\\(?:" regexp "\\)\\'")))))
3626 (not (null pos))))
3627
45595a4f
RS
3628(defsubst looking-at-p (regexp)
3629 "\
3630Same as `looking-at' except this function does not change the match data."
3631 (let ((inhibit-changing-match-data t))
3632 (looking-at regexp)))
3633
3634(defsubst string-match-p (regexp string &optional start)
3635 "\
3636Same as `string-match' except this function does not change the match data."
3637 (let ((inhibit-changing-match-data t))
3638 (string-match regexp string start)))
3639
c4f484f2
RS
3640(defun subregexp-context-p (regexp pos &optional start)
3641 "Return non-nil if POS is in a normal subregexp context in REGEXP.
3642A subregexp context is one where a sub-regexp can appear.
3643A non-subregexp context is for example within brackets, or within a
3644repetition bounds operator `\\=\\{...\\}', or right after a `\\'.
3645If START is non-nil, it should be a position in REGEXP, smaller
3646than POS, and known to be in a subregexp context."
3647 ;; Here's one possible implementation, with the great benefit that it
3648 ;; reuses the regexp-matcher's own parser, so it understands all the
3649 ;; details of the syntax. A disadvantage is that it needs to match the
3650 ;; error string.
3651 (condition-case err
3652 (progn
3653 (string-match (substring regexp (or start 0) pos) "")
3654 t)
3655 (invalid-regexp
3656 (not (member (cadr err) '("Unmatched [ or [^"
3657 "Unmatched \\{"
3658 "Trailing backslash")))))
3659 ;; An alternative implementation:
3660 ;; (defconst re-context-re
3661 ;; (let* ((harmless-ch "[^\\[]")
3662 ;; (harmless-esc "\\\\[^{]")
3663 ;; (class-harmless-ch "[^][]")
3664 ;; (class-lb-harmless "[^]:]")
3665 ;; (class-lb-colon-maybe-charclass ":\\([a-z]+:]\\)?")
3666 ;; (class-lb (concat "\\[\\(" class-lb-harmless
3667 ;; "\\|" class-lb-colon-maybe-charclass "\\)"))
3668 ;; (class
3669 ;; (concat "\\[^?]?"
3670 ;; "\\(" class-harmless-ch
3671 ;; "\\|" class-lb "\\)*"
3672 ;; "\\[?]")) ; special handling for bare [ at end of re
3673 ;; (braces "\\\\{[0-9,]+\\\\}"))
3674 ;; (concat "\\`\\(" harmless-ch "\\|" harmless-esc
3675 ;; "\\|" class "\\|" braces "\\)*\\'"))
3676 ;; "Matches any prefix that corresponds to a normal subregexp context.")
3677 ;; (string-match re-context-re (substring regexp (or start 0) pos))
3678 )
3679\f
3680;;;; split-string
498535fb 3681
6a646626
JB
3682(defconst split-string-default-separators "[ \f\t\n\r\v]+"
3683 "The default value of separators for `split-string'.
3684
3685A regexp matching strings of whitespace. May be locale-dependent
3686\(as yet unimplemented). Should not match non-breaking spaces.
3687
3688Warning: binding this to a different value and using it as default is
3689likely to have undesired semantics.")
3690
3691;; The specification says that if both SEPARATORS and OMIT-NULLS are
3692;; defaulted, OMIT-NULLS should be treated as t. Simplifying the logical
3693;; expression leads to the equivalent implementation that if SEPARATORS
3694;; is defaulted, OMIT-NULLS is treated as t.
3695(defun split-string (string &optional separators omit-nulls)
203998e5 3696 "Split STRING into substrings bounded by matches for SEPARATORS.
6a646626
JB
3697
3698The beginning and end of STRING, and each match for SEPARATORS, are
3699splitting points. The substrings matching SEPARATORS are removed, and
3700the substrings between the splitting points are collected as a list,
edce3654 3701which is returned.
b222b786 3702
6a646626
JB
3703If SEPARATORS is non-nil, it should be a regular expression matching text
3704which separates, but is not part of, the substrings. If nil it defaults to
3705`split-string-default-separators', normally \"[ \\f\\t\\n\\r\\v]+\", and
3706OMIT-NULLS is forced to t.
3707
a478f3e1 3708If OMIT-NULLS is t, zero-length substrings are omitted from the list \(so
6a646626
JB
3709that for the default value of SEPARATORS leading and trailing whitespace
3710are effectively trimmed). If nil, all zero-length substrings are retained,
3711which correctly parses CSV format, for example.
3712
3713Note that the effect of `(split-string STRING)' is the same as
55e45419 3714`(split-string STRING split-string-default-separators t)'. In the rare
6a646626
JB
3715case that you wish to retain zero-length substrings when splitting on
3716whitespace, use `(split-string STRING split-string-default-separators)'.
b021ef18
DL
3717
3718Modifies the match data; use `save-match-data' if necessary."
6a646626
JB
3719 (let ((keep-nulls (not (if separators omit-nulls t)))
3720 (rexp (or separators split-string-default-separators))
edce3654 3721 (start 0)
b222b786 3722 notfirst
edce3654 3723 (list nil))
b222b786
RS
3724 (while (and (string-match rexp string
3725 (if (and notfirst
3726 (= start (match-beginning 0))
3727 (< start (length string)))
3728 (1+ start) start))
6a646626 3729 (< start (length string)))
b222b786 3730 (setq notfirst t)
6a646626 3731 (if (or keep-nulls (< start (match-beginning 0)))
edce3654
RS
3732 (setq list
3733 (cons (substring string start (match-beginning 0))
3734 list)))
3735 (setq start (match-end 0)))
6a646626 3736 (if (or keep-nulls (< start (length string)))
edce3654
RS
3737 (setq list
3738 (cons (substring string start)
3739 list)))
3740 (nreverse list)))
0b93ff3a 3741
e80b3849 3742(defun combine-and-quote-strings (strings &optional separator)
0b93ff3a
NR
3743 "Concatenate the STRINGS, adding the SEPARATOR (default \" \").
3744This tries to quote the strings to avoid ambiguity such that
e80b3849 3745 (split-string-and-unquote (combine-and-quote-strings strs)) == strs
0b93ff3a 3746Only some SEPARATORs will work properly."
9f2bd2e7
SM
3747 (let* ((sep (or separator " "))
3748 (re (concat "[\\\"]" "\\|" (regexp-quote sep))))
0b93ff3a
NR
3749 (mapconcat
3750 (lambda (str)
9f2bd2e7 3751 (if (string-match re str)
0b93ff3a
NR
3752 (concat "\"" (replace-regexp-in-string "[\\\"]" "\\\\\\&" str) "\"")
3753 str))
3754 strings sep)))
3755
e80b3849 3756(defun split-string-and-unquote (string &optional separator)
0b93ff3a 3757 "Split the STRING into a list of strings.
e80b3849
RS
3758It understands Emacs Lisp quoting within STRING, such that
3759 (split-string-and-unquote (combine-and-quote-strings strs)) == strs
0b93ff3a
NR
3760The SEPARATOR regexp defaults to \"\\s-+\"."
3761 (let ((sep (or separator "\\s-+"))
d551d20d 3762 (i (string-match "\"" string)))
e80b3849
RS
3763 (if (null i)
3764 (split-string string sep t) ; no quoting: easy
0b93ff3a
NR
3765 (append (unless (eq i 0) (split-string (substring string 0 i) sep t))
3766 (let ((rfs (read-from-string string i)))
3767 (cons (car rfs)
e80b3849
RS
3768 (split-string-and-unquote (substring string (cdr rfs))
3769 sep)))))))
0b93ff3a 3770
c4f484f2
RS
3771\f
3772;;;; Replacement in strings.
1ccaea52
AI
3773
3774(defun subst-char-in-string (fromchar tochar string &optional inplace)
3775 "Replace FROMCHAR with TOCHAR in STRING each time it occurs.
3776Unless optional argument INPLACE is non-nil, return a new string."
e6e71807
SM
3777 (let ((i (length string))
3778 (newstr (if inplace string (copy-sequence string))))
3779 (while (> i 0)
3780 (setq i (1- i))
3781 (if (eq (aref newstr i) fromchar)
3782 (aset newstr i tochar)))
3783 newstr))
b021ef18 3784
1697159c 3785(defun replace-regexp-in-string (regexp rep string &optional
c8227332 3786 fixedcase literal subexp start)
b021ef18
DL
3787 "Replace all matches for REGEXP with REP in STRING.
3788
3789Return a new string containing the replacements.
3790
3791Optional arguments FIXEDCASE, LITERAL and SUBEXP are like the
3792arguments with the same names of function `replace-match'. If START
3793is non-nil, start replacements at that index in STRING.
3794
3795REP is either a string used as the NEWTEXT arg of `replace-match' or a
23bb94bb
RS
3796function. If it is a function, it is called with the actual text of each
3797match, and its value is used as the replacement text. When REP is called,
3fa173b4 3798the match data are the result of matching REGEXP against a substring
23bb94bb 3799of STRING.
b021ef18 3800
1697159c
DL
3801To replace only the first match (if any), make REGEXP match up to \\'
3802and replace a sub-expression, e.g.
c9bcb507 3803 (replace-regexp-in-string \"\\\\(foo\\\\).*\\\\'\" \"bar\" \" foo foo\" nil nil 1)
088be6fb 3804 => \" bar foo\""
b021ef18
DL
3805
3806 ;; To avoid excessive consing from multiple matches in long strings,
3807 ;; don't just call `replace-match' continually. Walk down the
3808 ;; string looking for matches of REGEXP and building up a (reversed)
3809 ;; list MATCHES. This comprises segments of STRING which weren't
3810 ;; matched interspersed with replacements for segments that were.
08b1f8a1 3811 ;; [For a `large' number of replacements it's more efficient to
b021ef18
DL
3812 ;; operate in a temporary buffer; we can't tell from the function's
3813 ;; args whether to choose the buffer-based implementation, though it
3814 ;; might be reasonable to do so for long enough STRING.]
3815 (let ((l (length string))
3816 (start (or start 0))
3817 matches str mb me)
3818 (save-match-data
3819 (while (and (< start l) (string-match regexp string start))
3820 (setq mb (match-beginning 0)
3821 me (match-end 0))
a9853251
SM
3822 ;; If we matched the empty string, make sure we advance by one char
3823 (when (= me mb) (setq me (min l (1+ mb))))
3824 ;; Generate a replacement for the matched substring.
3825 ;; Operate only on the substring to minimize string consing.
3826 ;; Set up match data for the substring for replacement;
3827 ;; presumably this is likely to be faster than munging the
3828 ;; match data directly in Lisp.
3829 (string-match regexp (setq str (substring string mb me)))
3830 (setq matches
3831 (cons (replace-match (if (stringp rep)
3832 rep
3833 (funcall rep (match-string 0 str)))
3834 fixedcase literal str subexp)
c8227332 3835 (cons (substring string start mb) ; unmatched prefix
a9853251
SM
3836 matches)))
3837 (setq start me))
b021ef18
DL
3838 ;; Reconstruct a string from the pieces.
3839 (setq matches (cons (substring string start l) matches)) ; leftover
3840 (apply #'concat (nreverse matches)))))
a7ed4c2a 3841\f
cb190d7d
SM
3842(defun string-prefix-p (str1 str2 &optional ignore-case)
3843 "Return non-nil if STR1 is a prefix of STR2.
3844If IGNORE-CASE is non-nil, the comparison is done without paying attention
3845to case differences."
3846 (eq t (compare-strings str1 nil nil
3847 str2 0 (length str1) ignore-case)))
3e26a4a2 3848
f635daa1 3849(defun bidi-string-mark-left-to-right (str)
9ccaaa4b 3850 "Return a string that can be safely inserted in left-to-right text.
9ccaaa4b 3851
f635daa1
CY
3852Normally, inserting a string with right-to-left (RTL) script into
3853a buffer may cause some subsequent text to be displayed as part
3854of the RTL segment (usually this affects punctuation characters).
3855This function returns a string which displays as STR but forces
3856subsequent text to be displayed as left-to-right.
9ccaaa4b 3857
f635daa1
CY
3858If STR contains any RTL character, this function returns a string
3859consisting of STR followed by an invisible left-to-right mark
3860\(LRM) character. Otherwise, it returns STR."
3e26a4a2
CY
3861 (unless (stringp str)
3862 (signal 'wrong-type-argument (list 'stringp str)))
f635daa1
CY
3863 (if (string-match "\\cR" str)
3864 (concat str (propertize (string ?\x200e) 'invisible t))
3865 str))
cb190d7d 3866\f
c4f484f2 3867;;;; invisibility specs
df8e73e1 3868
c4f484f2
RS
3869(defun add-to-invisibility-spec (element)
3870 "Add ELEMENT to `buffer-invisibility-spec'.
3871See documentation for `buffer-invisibility-spec' for the kind of elements
3872that can be added."
3873 (if (eq buffer-invisibility-spec t)
3874 (setq buffer-invisibility-spec (list t)))
3875 (setq buffer-invisibility-spec
3876 (cons element buffer-invisibility-spec)))
3877
3878(defun remove-from-invisibility-spec (element)
3879 "Remove ELEMENT from `buffer-invisibility-spec'."
3880 (if (consp buffer-invisibility-spec)
c8227332
VJL
3881 (setq buffer-invisibility-spec
3882 (delete element buffer-invisibility-spec))))
a7ed4c2a 3883\f
c4f484f2
RS
3884;;;; Syntax tables.
3885
3886(defmacro with-syntax-table (table &rest body)
3887 "Evaluate BODY with syntax table of current buffer set to TABLE.
3888The syntax table of the current buffer is saved, BODY is evaluated, and the
3889saved table is restored, even in case of an abnormal exit.
3890Value is what BODY returns."
f291fe60 3891 (declare (debug t) (indent 1))
c4f484f2
RS
3892 (let ((old-table (make-symbol "table"))
3893 (old-buffer (make-symbol "buffer")))
3894 `(let ((,old-table (syntax-table))
3895 (,old-buffer (current-buffer)))
3896 (unwind-protect
3897 (progn
3898 (set-syntax-table ,table)
3899 ,@body)
3900 (save-current-buffer
3901 (set-buffer ,old-buffer)
3902 (set-syntax-table ,old-table))))))
8af7df60 3903
297d863b 3904(defun make-syntax-table (&optional oldtable)
984f718a 3905 "Return a new syntax table.
0764e16f
SM
3906Create a syntax table which inherits from OLDTABLE (if non-nil) or
3907from `standard-syntax-table' otherwise."
3908 (let ((table (make-char-table 'syntax-table nil)))
3909 (set-char-table-parent table (or oldtable (standard-syntax-table)))
3910 table))
31aa282e 3911
e9f13a95 3912(defun syntax-after (pos)
6dcef6ec 3913 "Return the raw syntax descriptor for the char after POS.
9d1ffd5a 3914If POS is outside the buffer's accessible portion, return nil."
e9f13a95 3915 (unless (or (< pos (point-min)) (>= pos (point-max)))
d8ac3d27
SM
3916 (let ((st (if parse-sexp-lookup-properties
3917 (get-char-property pos 'syntax-table))))
3918 (if (consp st) st
3919 (aref (or st (syntax-table)) (char-after pos))))))
e9f13a95 3920
cdd8dc28 3921(defun syntax-class (syntax)
6dcef6ec
CY
3922 "Return the code for the syntax class described by SYNTAX.
3923
3924SYNTAX should be a raw syntax descriptor; the return value is a
3925integer which encodes the corresponding syntax class. See Info
3926node `(elisp)Syntax Table Internals' for a list of codes.
3927
9d1ffd5a
EZ
3928If SYNTAX is nil, return nil."
3929 (and syntax (logand (car syntax) 65535)))
2493767e 3930\f
0b938190
TZ
3931;; Utility motion commands
3932
3933;; Whitespace
3934
3935(defun forward-whitespace (arg)
3936 "Move point to the end of the next sequence of whitespace chars.
3937Each such sequence may be a single newline, or a sequence of
3938consecutive space and/or tab characters.
3939With prefix argument ARG, do it ARG times if positive, or move
3940backwards ARG times if negative."
3941 (interactive "^p")
3942 (if (natnump arg)
3943 (re-search-forward "[ \t]+\\|\n" nil 'move arg)
3944 (while (< arg 0)
3945 (if (re-search-backward "[ \t]+\\|\n" nil 'move)
3946 (or (eq (char-after (match-beginning 0)) ?\n)
3947 (skip-chars-backward " \t")))
3948 (setq arg (1+ arg)))))
3949
3950;; Symbols
3951
3952(defun forward-symbol (arg)
3953 "Move point to the next position that is the end of a symbol.
3954A symbol is any sequence of characters that are in either the
3955word constituent or symbol constituent syntax class.
3956With prefix argument ARG, do it ARG times if positive, or move
3957backwards ARG times if negative."
3958 (interactive "^p")
3959 (if (natnump arg)
3960 (re-search-forward "\\(\\sw\\|\\s_\\)+" nil 'move arg)
3961 (while (< arg 0)
3962 (if (re-search-backward "\\(\\sw\\|\\s_\\)+" nil 'move)
3963 (skip-syntax-backward "w_"))
3964 (setq arg (1+ arg)))))
3965
3966;; Syntax blocks
3967
3968(defun forward-same-syntax (&optional arg)
3969 "Move point past all characters with the same syntax class.
3970With prefix argument ARG, do it ARG times if positive, or move
3971backwards ARG times if negative."
3972 (interactive "^p")
3973 (or arg (setq arg 1))
3974 (while (< arg 0)
3975 (skip-syntax-backward
3976 (char-to-string (char-syntax (char-before))))
3977 (setq arg (1+ arg)))
3978 (while (> arg 0)
3979 (skip-syntax-forward (char-to-string (char-syntax (char-after))))
3980 (setq arg (1- arg))))
3981
3982\f
c4f484f2 3983;;;; Text clones
a13fe4c5 3984
06b60517 3985(defun text-clone-maintain (ol1 after beg end &optional _len)
a13fe4c5
SM
3986 "Propagate the changes made under the overlay OL1 to the other clones.
3987This is used on the `modification-hooks' property of text clones."
3988 (when (and after (not undo-in-progress) (overlay-start ol1))
3989 (let ((margin (if (overlay-get ol1 'text-clone-spreadp) 1 0)))
3990 (setq beg (max beg (+ (overlay-start ol1) margin)))
3991 (setq end (min end (- (overlay-end ol1) margin)))
3992 (when (<= beg end)
3993 (save-excursion
3994 (when (overlay-get ol1 'text-clone-syntax)
3995 ;; Check content of the clone's text.
3996 (let ((cbeg (+ (overlay-start ol1) margin))
3997 (cend (- (overlay-end ol1) margin)))
3998 (goto-char cbeg)
3999 (save-match-data
4000 (if (not (re-search-forward
4001 (overlay-get ol1 'text-clone-syntax) cend t))
4002 ;; Mark the overlay for deletion.
454eb095 4003 (setq end cbeg)
a13fe4c5
SM
4004 (when (< (match-end 0) cend)
4005 ;; Shrink the clone at its end.
4006 (setq end (min end (match-end 0)))
4007 (move-overlay ol1 (overlay-start ol1)
4008 (+ (match-end 0) margin)))
4009 (when (> (match-beginning 0) cbeg)
4010 ;; Shrink the clone at its beginning.
4011 (setq beg (max (match-beginning 0) beg))
4012 (move-overlay ol1 (- (match-beginning 0) margin)
4013 (overlay-end ol1)))))))
4014 ;; Now go ahead and update the clones.
4015 (let ((head (- beg (overlay-start ol1)))
4016 (tail (- (overlay-end ol1) end))
4017 (str (buffer-substring beg end))
4018 (nothing-left t)
4019 (inhibit-modification-hooks t))
4020 (dolist (ol2 (overlay-get ol1 'text-clones))
4021 (let ((oe (overlay-end ol2)))
4022 (unless (or (eq ol1 ol2) (null oe))
4023 (setq nothing-left nil)
4024 (let ((mod-beg (+ (overlay-start ol2) head)))
4025 ;;(overlay-put ol2 'modification-hooks nil)
4026 (goto-char (- (overlay-end ol2) tail))
4027 (unless (> mod-beg (point))
4028 (save-excursion (insert str))
4029 (delete-region mod-beg (point)))
4030 ;;(overlay-put ol2 'modification-hooks '(text-clone-maintain))
4031 ))))
4032 (if nothing-left (delete-overlay ol1))))))))
4033
4034(defun text-clone-create (start end &optional spreadp syntax)
4035 "Create a text clone of START...END at point.
4036Text clones are chunks of text that are automatically kept identical:
4037changes done to one of the clones will be immediately propagated to the other.
4038
4039The buffer's content at point is assumed to be already identical to
4040the one between START and END.
4041If SYNTAX is provided it's a regexp that describes the possible text of
4042the clones; the clone will be shrunk or killed if necessary to ensure that
4043its text matches the regexp.
4044If SPREADP is non-nil it indicates that text inserted before/after the
4045clone should be incorporated in the clone."
4046 ;; To deal with SPREADP we can either use an overlay with `nil t' along
4047 ;; with insert-(behind|in-front-of)-hooks or use a slightly larger overlay
4048 ;; (with a one-char margin at each end) with `t nil'.
4049 ;; We opted for a larger overlay because it behaves better in the case
4050 ;; where the clone is reduced to the empty string (we want the overlay to
4051 ;; stay when the clone's content is the empty string and we want to use
4052 ;; `evaporate' to make sure those overlays get deleted when needed).
264ef586 4053 ;;
a13fe4c5
SM
4054 (let* ((pt-end (+ (point) (- end start)))
4055 (start-margin (if (or (not spreadp) (bobp) (<= start (point-min)))
4056 0 1))
4057 (end-margin (if (or (not spreadp)
4058 (>= pt-end (point-max))
4059 (>= start (point-max)))
4060 0 1))
4061 (ol1 (make-overlay (- start start-margin) (+ end end-margin) nil t))
4062 (ol2 (make-overlay (- (point) start-margin) (+ pt-end end-margin) nil t))
4063 (dups (list ol1 ol2)))
4064 (overlay-put ol1 'modification-hooks '(text-clone-maintain))
4065 (when spreadp (overlay-put ol1 'text-clone-spreadp t))
4066 (when syntax (overlay-put ol1 'text-clone-syntax syntax))
4067 ;;(overlay-put ol1 'face 'underline)
4068 (overlay-put ol1 'evaporate t)
4069 (overlay-put ol1 'text-clones dups)
264ef586 4070 ;;
a13fe4c5
SM
4071 (overlay-put ol2 'modification-hooks '(text-clone-maintain))
4072 (when spreadp (overlay-put ol2 'text-clone-spreadp t))
4073 (when syntax (overlay-put ol2 'text-clone-syntax syntax))
4074 ;;(overlay-put ol2 'face 'underline)
4075 (overlay-put ol2 'evaporate t)
4076 (overlay-put ol2 'text-clones dups)))
c4f484f2
RS
4077\f
4078;;;; Mail user agents.
27c079eb 4079
c4f484f2
RS
4080;; Here we include just enough for other packages to be able
4081;; to define them.
324cd947 4082
27c079eb
SM
4083(defun define-mail-user-agent (symbol composefunc sendfunc
4084 &optional abortfunc hookvar)
4085 "Define a symbol to identify a mail-sending package for `mail-user-agent'.
4086
4087SYMBOL can be any Lisp symbol. Its function definition and/or
4088value as a variable do not matter for this usage; we use only certain
4089properties on its property list, to encode the rest of the arguments.
4090
4091COMPOSEFUNC is program callable function that composes an outgoing
4092mail message buffer. This function should set up the basics of the
4093buffer without requiring user interaction. It should populate the
4094standard mail headers, leaving the `to:' and `subject:' headers blank
4095by default.
4096
4097COMPOSEFUNC should accept several optional arguments--the same
4098arguments that `compose-mail' takes. See that function's documentation.
4099
4100SENDFUNC is the command a user would run to send the message.
4101
4102Optional ABORTFUNC is the command a user would run to abort the
4103message. For mail packages that don't have a separate abort function,
4104this can be `kill-buffer' (the equivalent of omitting this argument).
4105
4106Optional HOOKVAR is a hook variable that gets run before the message
4107is actually sent. Callers that use the `mail-user-agent' may
4108install a hook function temporarily on this hook variable.
4109If HOOKVAR is nil, `mail-send-hook' is used.
4110
4111The properties used on SYMBOL are `composefunc', `sendfunc',
4112`abortfunc', and `hookvar'."
4113 (put symbol 'composefunc composefunc)
4114 (put symbol 'sendfunc sendfunc)
4115 (put symbol 'abortfunc (or abortfunc 'kill-buffer))
4116 (put symbol 'hookvar (or hookvar 'mail-send-hook)))
c4f484f2 4117\f
23ba2705
SM
4118(defvar called-interactively-p-functions nil
4119 "Special hook called to skip special frames in `called-interactively-p'.
4120The functions are called with 3 arguments: (I FRAME1 FRAME2),
4121where FRAME1 is a \"current frame\", FRAME2 is the next frame,
4122I is the index of the frame after FRAME2. It should return nil
4123if those frames don't seem special and otherwise, it should return
4124the number of frames to skip (minus 1).")
4125
4126(defmacro internal--called-interactively-p--get-frame (n)
4127 ;; `sym' will hold a global variable, which will be used kind of like C's
4128 ;; "static" variables.
4129 (let ((sym (make-symbol "base-index")))
4130 `(progn
659a9010
SM
4131 (defvar ,sym)
4132 (unless (boundp ',sym)
23ba2705 4133 (let ((i 1))
c0bd248c
SM
4134 (while (not (eq (indirect-function (nth 1 (backtrace-frame i)) t)
4135 (indirect-function 'called-interactively-p)))
23ba2705 4136 (setq i (1+ i)))
659a9010 4137 (setq ,sym i)))
23ba2705
SM
4138 ;; (unless (eq (nth 1 (backtrace-frame ,sym)) 'called-interactively-p)
4139 ;; (error "called-interactively-p: %s is out-of-sync!" ,sym))
4140 (backtrace-frame (+ ,sym ,n)))))
4141
4142(defun called-interactively-p (&optional kind)
4143 "Return t if the containing function was called by `call-interactively'.
4144If KIND is `interactive', then only return t if the call was made
4145interactively by the user, i.e. not in `noninteractive' mode nor
4146when `executing-kbd-macro'.
4147If KIND is `any', on the other hand, it will return t for any kind of
4148interactive call, including being called as the binding of a key or
4149from a keyboard macro, even in `noninteractive' mode.
4150
4151This function is very brittle, it may fail to return the intended result when
4152the code is debugged, advised, or instrumented in some form. Some macros and
4153special forms (such as `condition-case') may also sometimes wrap their bodies
4154in a `lambda', so any call to `called-interactively-p' from those bodies will
4155indicate whether that lambda (rather than the surrounding function) was called
4156interactively.
4157
4158Instead of using this function, it is cleaner and more reliable to give your
4159function an extra optional argument whose `interactive' spec specifies
4160non-nil unconditionally (\"p\" is a good way to do this), or via
4161\(not (or executing-kbd-macro noninteractive)).
4162
4163The only known proper use of `interactive' for KIND is in deciding
4164whether to display a helpful message, or how to display it. If you're
4165thinking of using it for any other purpose, it is quite likely that
4166you're making a mistake. Think: what do you want to do when the
4167command is called from a keyboard macro?"
4168 (declare (advertised-calling-convention (kind) "23.1"))
4169 (when (not (and (eq kind 'interactive)
4170 (or executing-kbd-macro noninteractive)))
4171 (let* ((i 1) ;; 0 is the called-interactively-p frame.
4172 frame nextframe
4173 (get-next-frame
4174 (lambda ()
4175 (setq frame nextframe)
4176 (setq nextframe (internal--called-interactively-p--get-frame i))
4177 ;; (message "Frame %d = %S" i nextframe)
4178 (setq i (1+ i)))))
4179 (funcall get-next-frame) ;; Get the first frame.
4180 (while
4181 ;; FIXME: The edebug and advice handling should be made modular and
4182 ;; provided directly by edebug.el and nadvice.el.
4183 (progn
4184 ;; frame =(backtrace-frame i-2)
4185 ;; nextframe=(backtrace-frame i-1)
4186 (funcall get-next-frame)
4187 ;; `pcase' would be a fairly good fit here, but it sometimes moves
4188 ;; branches within local functions, which then messes up the
4189 ;; `backtrace-frame' data we get,
4190 (or
4191 ;; Skip special forms (from non-compiled code).
4192 (and frame (null (car frame)))
4193 ;; Skip also `interactive-p' (because we don't want to know if
4194 ;; interactive-p was called interactively but if it's caller was)
4195 ;; and `byte-code' (idem; this appears in subexpressions of things
4196 ;; like condition-case, which are wrapped in a separate bytecode
4197 ;; chunk).
4198 ;; FIXME: For lexical-binding code, this is much worse,
4199 ;; because the frames look like "byte-code -> funcall -> #[...]",
4200 ;; which is not a reliable signature.
4201 (memq (nth 1 frame) '(interactive-p 'byte-code))
4202 ;; Skip package-specific stack-frames.
4203 (let ((skip (run-hook-with-args-until-success
4204 'called-interactively-p-functions
4205 i frame nextframe)))
4206 (pcase skip
4207 (`nil nil)
4208 (`0 t)
4209 (_ (setq i (+ i skip -1)) (funcall get-next-frame)))))))
4210 ;; Now `frame' should be "the function from which we were called".
4211 (pcase (cons frame nextframe)
4212 ;; No subr calls `interactive-p', so we can rule that out.
4213 (`((,_ ,(pred (lambda (f) (subrp (indirect-function f)))) . ,_) . ,_) nil)
4214 ;; Somehow, I sometimes got `command-execute' rather than
4215 ;; `call-interactively' on my stacktrace !?
4216 ;;(`(,_ . (t command-execute . ,_)) t)
4217 (`(,_ . (t call-interactively . ,_)) t)))))
4218
4219(defun interactive-p ()
4220 "Return t if the containing function was run directly by user input.
4221This means that the function was called with `call-interactively'
4222\(which includes being called as the binding of a key)
4223and input is currently coming from the keyboard (not a keyboard macro),
4224and Emacs is not running in batch mode (`noninteractive' is nil).
4225
4226The only known proper use of `interactive-p' is in deciding whether to
4227display a helpful message, or how to display it. If you're thinking
4228of using it for any other purpose, it is quite likely that you're
4229making a mistake. Think: what do you want to do when the command is
4230called from a keyboard macro or in batch mode?
4231
4232To test whether your function was called with `call-interactively',
4233either (i) add an extra optional argument and give it an `interactive'
4234spec that specifies non-nil unconditionally (such as \"p\"); or (ii)
4235use `called-interactively-p'."
4236 (declare (obsolete called-interactively-p "23.2"))
4237 (called-interactively-p 'interactive))
4238
4239(defun function-arity (f &optional num)
4240 "Return the (MIN . MAX) arity of F.
4241If the maximum arity is infinite, MAX is `many'.
4242F can be a function or a macro.
4243If NUM is non-nil, return non-nil iff F can be called with NUM args."
4244 (if (symbolp f) (setq f (indirect-function f)))
4245 (if (eq (car-safe f) 'macro) (setq f (cdr f)))
4246 (let ((res
4247 (if (subrp f)
4248 (let ((x (subr-arity f)))
4249 (if (eq (cdr x) 'unevalled) (cons (car x) 'many)))
4250 (let* ((args (if (consp f) (cadr f) (aref f 0)))
4251 (max (length args))
4252 (opt (memq '&optional args))
4253 (rest (memq '&rest args))
4254 (min (- max (length opt))))
4255 (if opt
4256 (cons min (if rest 'many (1- max)))
4257 (if rest
4258 (cons (- max (length rest)) 'many)
4259 (cons min max)))))))
4260 (if (not num)
4261 res
4262 (and (>= num (car res))
4263 (or (eq 'many (cdr res)) (<= num (cdr res)))))))
4264
f95e9344 4265(defun set-temporary-overlay-map (map &optional keep-pred)
e0ea8060
GM
4266 "Set MAP as a temporary keymap taking precedence over most other keymaps.
4267Note that this does NOT take precedence over the \"overriding\" maps
4268`overriding-terminal-local-map' and `overriding-local-map' (or the
4269`keymap' text property). Unlike those maps, if no match for a key is
4270found in MAP, the normal key lookup sequence then continues.
4271
4272Normally, MAP is used only once. If the optional argument
dc26b310 4273KEEP-PRED is t, MAP stays active if a key from MAP is used.
e0ea8060
GM
4274KEEP-PRED can also be a function of no arguments: if it returns
4275non-nil then MAP stays active."
f95e9344
SM
4276 (let* ((clearfunsym (make-symbol "clear-temporary-overlay-map"))
4277 (overlaysym (make-symbol "t"))
4278 (alist (list (cons overlaysym map)))
4279 (clearfun
4280 ;; FIXME: Use lexical-binding.
4281 `(lambda ()
4282 (unless ,(cond ((null keep-pred) nil)
4283 ((eq t keep-pred)
4284 `(eq this-command
4285 (lookup-key ',map
4286 (this-command-keys-vector))))
4287 (t `(funcall ',keep-pred)))
bfeae2cf 4288 (set ',overlaysym nil) ;Just in case.
f95e9344
SM
4289 (remove-hook 'pre-command-hook ',clearfunsym)
4290 (setq emulation-mode-map-alists
4291 (delq ',alist emulation-mode-map-alists))))))
4292 (set overlaysym overlaysym)
4293 (fset clearfunsym clearfun)
4294 (add-hook 'pre-command-hook clearfunsym)
4295 ;; FIXME: That's the keymaps with highest precedence, except for
4296 ;; the `keymap' text-property ;-(
4297 (push alist emulation-mode-map-alists)))
4298
c4f484f2 4299;;;; Progress reporters.
b4329caa
EZ
4300
4301;; Progress reporter has the following structure:
4302;;
4303;; (NEXT-UPDATE-VALUE . [NEXT-UPDATE-TIME
4304;; MIN-VALUE
4305;; MAX-VALUE
4306;; MESSAGE
4307;; MIN-CHANGE
4308;; MIN-TIME])
4309;;
ee7683eb 4310;; This weirdness is for optimization reasons: we want
b4329caa
EZ
4311;; `progress-reporter-update' to be as fast as possible, so
4312;; `(car reporter)' is better than `(aref reporter 0)'.
4313;;
4314;; NEXT-UPDATE-TIME is a float. While `float-time' loses a couple
4315;; digits of precision, it doesn't really matter here. On the other
4316;; hand, it greatly simplifies the code.
4317
9326ba26 4318(defsubst progress-reporter-update (reporter &optional value)
c85152fc 4319 "Report progress of an operation in the echo area.
9326ba26
CY
4320REPORTER should be the result of a call to `make-progress-reporter'.
4321
4322If REPORTER is a numerical progress reporter---i.e. if it was
4323 made using non-nil MIN-VALUE and MAX-VALUE arguments to
4324 `make-progress-reporter'---then VALUE should be a number between
4325 MIN-VALUE and MAX-VALUE.
c85152fc 4326
9326ba26 4327If REPORTER is a non-numerical reporter, VALUE should be nil.
b4329caa 4328
9326ba26
CY
4329This function is relatively inexpensive. If the change since
4330last update is too small or insufficient time has passed, it does
4331nothing."
4332 (when (or (not (numberp value)) ; For pulsing reporter
4333 (>= value (car reporter))) ; For numerical reporter
4334 (progress-reporter-do-update reporter value)))
4335
4336(defun make-progress-reporter (message &optional min-value max-value
4337 current-value min-change min-time)
4338 "Return progress reporter object for use with `progress-reporter-update'.
4339
4340MESSAGE is shown in the echo area, with a status indicator
4341appended to the end. When you call `progress-reporter-done', the
4342word \"done\" is printed after the MESSAGE. You can change the
4343MESSAGE of an existing progress reporter by calling
4344`progress-reporter-force-update'.
4345
4346MIN-VALUE and MAX-VALUE, if non-nil, are starting (0% complete)
4347and final (100% complete) states of operation; the latter should
4348be larger. In this case, the status message shows the percentage
4349progress.
4350
4351If MIN-VALUE and/or MAX-VALUE is omitted or nil, the status
4352message shows a \"spinning\", non-numeric indicator.
4353
4354Optional CURRENT-VALUE is the initial progress; the default is
4355MIN-VALUE.
4356Optional MIN-CHANGE is the minimal change in percents to report;
4357the default is 1%.
4358CURRENT-VALUE and MIN-CHANGE do not have any effect if MIN-VALUE
4359and/or MAX-VALUE are nil.
4360
4361Optional MIN-TIME specifies the minimum interval time between
4362echo area updates (default is 0.2 seconds.) If the function
4363`float-time' is not present, time is not tracked at all. If the
4364OS is not capable of measuring fractions of seconds, this
4365parameter is effectively rounded up."
ea9fafe0
SM
4366 (when (string-match "[[:alnum:]]\\'" message)
4367 (setq message (concat message "...")))
b4329caa
EZ
4368 (unless min-time
4369 (setq min-time 0.2))
4370 (let ((reporter
9326ba26
CY
4371 ;; Force a call to `message' now
4372 (cons (or min-value 0)
b4329caa
EZ
4373 (vector (if (and (fboundp 'float-time)
4374 (>= min-time 0.02))
4375 (float-time) nil)
4376 min-value
4377 max-value
4378 message
4379 (if min-change (max (min min-change 50) 1) 1)
4380 min-time))))
4381 (progress-reporter-update reporter (or current-value min-value))
4382 reporter))
4383
9326ba26 4384(defun progress-reporter-force-update (reporter &optional value new-message)
b4329caa
EZ
4385 "Report progress of an operation in the echo area unconditionally.
4386
9326ba26
CY
4387The first two arguments are the same as in `progress-reporter-update'.
4388NEW-MESSAGE, if non-nil, sets a new message for the reporter."
b4329caa
EZ
4389 (let ((parameters (cdr reporter)))
4390 (when new-message
4391 (aset parameters 3 new-message))
4392 (when (aref parameters 0)
4393 (aset parameters 0 (float-time)))
4394 (progress-reporter-do-update reporter value)))
4395
9326ba26
CY
4396(defvar progress-reporter--pulse-characters ["-" "\\" "|" "/"]
4397 "Characters to use for pulsing progress reporters.")
4398
b4329caa
EZ
4399(defun progress-reporter-do-update (reporter value)
4400 (let* ((parameters (cdr reporter))
9326ba26 4401 (update-time (aref parameters 0))
b4329caa
EZ
4402 (min-value (aref parameters 1))
4403 (max-value (aref parameters 2))
9326ba26 4404 (text (aref parameters 3))
b4329caa
EZ
4405 (current-time (float-time))
4406 (enough-time-passed
4407 ;; See if enough time has passed since the last update.
4408 (or (not update-time)
4409 (when (>= current-time update-time)
4410 ;; Calculate time for the next update
4411 (aset parameters 0 (+ update-time (aref parameters 5)))))))
9326ba26
CY
4412 (cond ((and min-value max-value)
4413 ;; Numerical indicator
4414 (let* ((one-percent (/ (- max-value min-value) 100.0))
4415 (percentage (if (= max-value min-value)
4416 0
4417 (truncate (/ (- value min-value)
4418 one-percent)))))
4419 ;; Calculate NEXT-UPDATE-VALUE. If we are not printing
4420 ;; message because not enough time has passed, use 1
4421 ;; instead of MIN-CHANGE. This makes delays between echo
4422 ;; area updates closer to MIN-TIME.
4423 (setcar reporter
4424 (min (+ min-value (* (+ percentage
4425 (if enough-time-passed
4426 ;; MIN-CHANGE
4427 (aref parameters 4)
4428 1))
4429 one-percent))
4430 max-value))
4431 (when (integerp value)
4432 (setcar reporter (ceiling (car reporter))))
4433 ;; Only print message if enough time has passed
4434 (when enough-time-passed
4435 (if (> percentage 0)
4436 (message "%s%d%%" text percentage)
4437 (message "%s" text)))))
4438 ;; Pulsing indicator
4439 (enough-time-passed
4440 (let ((index (mod (1+ (car reporter)) 4))
4441 (message-log-max nil))
4442 (setcar reporter index)
4443 (message "%s %s"
4444 text
4445 (aref progress-reporter--pulse-characters
4446 index)))))))
b4329caa
EZ
4447
4448(defun progress-reporter-done (reporter)
4449 "Print reporter's message followed by word \"done\" in echo area."
4450 (message "%sdone" (aref (cdr reporter) 3)))
4451
aa56124a
SM
4452(defmacro dotimes-with-progress-reporter (spec message &rest body)
4453 "Loop a certain number of times and report progress in the echo area.
4454Evaluate BODY with VAR bound to successive integers running from
44550, inclusive, to COUNT, exclusive. Then evaluate RESULT to get
4456the return value (nil if RESULT is omitted).
4457
4458At each iteration MESSAGE followed by progress percentage is
4459printed in the echo area. After the loop is finished, MESSAGE
4460followed by word \"done\" is printed. This macro is a
4461convenience wrapper around `make-progress-reporter' and friends.
4462
4463\(fn (VAR COUNT [RESULT]) MESSAGE BODY...)"
4464 (declare (indent 2) (debug ((symbolp form &optional form) form body)))
4465 (let ((temp (make-symbol "--dotimes-temp--"))
4466 (temp2 (make-symbol "--dotimes-temp2--"))
4467 (start 0)
4468 (end (nth 1 spec)))
4469 `(let ((,temp ,end)
4470 (,(car spec) ,start)
4471 (,temp2 (make-progress-reporter ,message ,start ,end)))
4472 (while (< ,(car spec) ,temp)
4473 ,@body
4474 (progress-reporter-update ,temp2
4475 (setq ,(car spec) (1+ ,(car spec)))))
4476 (progress-reporter-done ,temp2)
4477 nil ,@(cdr (cdr spec)))))
ca548b00 4478
e9454757 4479\f
81606b10
RS
4480;;;; Support for watching filesystem events.
4481
c9628c79
MA
4482(defun file-notify-handle-event (event)
4483 "Handle file system monitoring event.
4484If EVENT is a filewatch event, call its callback.
3907e630 4485Otherwise, signal a `filewatch-error'."
81606b10 4486 (interactive "e")
c9628c79
MA
4487 (if (and (eq (car event) 'file-notify)
4488 (>= (length event) 3))
3907e630
EZ
4489 (funcall (nth 2 event) (nth 1 event))
4490 (signal 'filewatch-error
c9628c79 4491 (cons "Not a valid file-notify event" event))))
3907e630 4492
81606b10 4493\f
c4f484f2 4494;;;; Comparing version strings.
e9454757 4495
2f7f4bee 4496(defconst version-separator "."
b29f5b7b 4497 "Specify the string used to separate the version elements.
e9454757
VJL
4498
4499Usually the separator is \".\", but it can be any other string.")
4500
4501
2f7f4bee 4502(defconst version-regexp-alist
b29f5b7b
VJL
4503 '(("^[-_+ ]?alpha$" . -3)
4504 ("^[-_+]$" . -3) ; treat "1.2.3-20050920" and "1.2-3" as alpha releases
4505 ("^[-_+ ]cvs$" . -3) ; treat "1.2.3-CVS" as alpha release
4506 ("^[-_+ ]?beta$" . -2)
e2046ecf 4507 ("^[-_+ ]?\\(pre\\|rcc\\)$" . -1))
b29f5b7b 4508 "Specify association between non-numeric version and its priority.
e9454757
VJL
4509
4510This association is used to handle version string like \"1.0pre2\",
4511\"0.9alpha1\", etc. It's used by `version-to-list' (which see) to convert the
94785022 4512non-numeric part of a version string to an integer. For example:
e9454757
VJL
4513
4514 String Version Integer List Version
4515 \"1.0pre2\" (1 0 -1 2)
4516 \"1.0PRE2\" (1 0 -1 2)
4517 \"22.8beta3\" (22 8 -2 3)
c71abb54 4518 \"22.8 Beta3\" (22 8 -2 3)
e9454757
VJL
4519 \"0.9alpha1\" (0 9 -3 1)
4520 \"0.9AlphA1\" (0 9 -3 1)
c71abb54 4521 \"0.9 alpha\" (0 9 -3)
e9454757
VJL
4522
4523Each element has the following form:
4524
4525 (REGEXP . PRIORITY)
4526
4527Where:
4528
4529REGEXP regexp used to match non-numeric part of a version string.
94785022 4530 It should begin with the `^' anchor and end with a `$' to
d74a5c91
EZ
4531 prevent false hits. Letter-case is ignored while matching
4532 REGEXP.
e9454757 4533
94785022 4534PRIORITY a negative integer specifying non-numeric priority of REGEXP.")
e9454757
VJL
4535
4536
4537(defun version-to-list (ver)
94785022 4538 "Convert version string VER into a list of integers.
e9454757
VJL
4539
4540The version syntax is given by the following EBNF:
4541
4542 VERSION ::= NUMBER ( SEPARATOR NUMBER )*.
4543
4544 NUMBER ::= (0|1|2|3|4|5|6|7|8|9)+.
4545
4546 SEPARATOR ::= `version-separator' (which see)
4547 | `version-regexp-alist' (which see).
4548
d74a5c91
EZ
4549The NUMBER part is optional if SEPARATOR is a match for an element
4550in `version-regexp-alist'.
4551
94785022 4552Examples of valid version syntax:
e9454757 4553
d74a5c91 4554 1.0pre2 1.0.7.5 22.8beta3 0.9alpha1 6.9.30Beta
e9454757 4555
94785022 4556Examples of invalid version syntax:
e9454757
VJL
4557
4558 1.0prepre2 1.0..7.5 22.8X3 alpha3.2 .5
4559
94785022 4560Examples of version conversion:
e9454757 4561
94785022 4562 Version String Version as a List of Integers
e9454757
VJL
4563 \"1.0.7.5\" (1 0 7 5)
4564 \"1.0pre2\" (1 0 -1 2)
4565 \"1.0PRE2\" (1 0 -1 2)
4566 \"22.8beta3\" (22 8 -2 3)
4567 \"22.8Beta3\" (22 8 -2 3)
4568 \"0.9alpha1\" (0 9 -3 1)
4569 \"0.9AlphA1\" (0 9 -3 1)
4570 \"0.9alpha\" (0 9 -3)
4571
4572See documentation for `version-separator' and `version-regexp-alist'."
c71abb54 4573 (or (and (stringp ver) (> (length ver) 0))
e9454757 4574 (error "Invalid version string: '%s'" ver))
c71abb54
KS
4575 ;; Change .x.y to 0.x.y
4576 (if (and (>= (length ver) (length version-separator))
4577 (string-equal (substring ver 0 (length version-separator))
c8227332 4578 version-separator))
c71abb54 4579 (setq ver (concat "0" ver)))
e9454757
VJL
4580 (save-match-data
4581 (let ((i 0)
d74a5c91 4582 (case-fold-search t) ; ignore case in matching
e9454757
VJL
4583 lst s al)
4584 (while (and (setq s (string-match "[0-9]+" ver i))
4585 (= s i))
4586 ;; handle numeric part
4587 (setq lst (cons (string-to-number (substring ver i (match-end 0)))
4588 lst)
4589 i (match-end 0))
4590 ;; handle non-numeric part
4591 (when (and (setq s (string-match "[^0-9]+" ver i))
4592 (= s i))
4593 (setq s (substring ver i (match-end 0))
4594 i (match-end 0))
4595 ;; handle alpha, beta, pre, etc. separator
4596 (unless (string= s version-separator)
4597 (setq al version-regexp-alist)
4598 (while (and al (not (string-match (caar al) s)))
4599 (setq al (cdr al)))
e2046ecf
CY
4600 (cond (al
4601 (push (cdar al) lst))
b29f5b7b 4602 ;; Convert 22.3a to 22.3.1, 22.3b to 22.3.2, etc.
e2046ecf
CY
4603 ((string-match "^[-_+ ]?\\([a-zA-Z]\\)$" s)
4604 (push (- (aref (downcase (match-string 1 s)) 0) ?a -1)
4605 lst))
4606 (t (error "Invalid version syntax: '%s'" ver))))))
e9454757
VJL
4607 (if (null lst)
4608 (error "Invalid version syntax: '%s'" ver)
4609 (nreverse lst)))))
4610
4611
ca548b00 4612(defun version-list-< (l1 l2)
94785022 4613 "Return t if L1, a list specification of a version, is lower than L2.
e9454757 4614
94785022
EZ
4615Note that a version specified by the list (1) is equal to (1 0),
4616\(1 0 0), (1 0 0 0), etc. That is, the trailing zeros are insignificant.
4617Also, a version given by the list (1) is higher than (1 -1), which in
4618turn is higher than (1 -2), which is higher than (1 -3)."
e9454757
VJL
4619 (while (and l1 l2 (= (car l1) (car l2)))
4620 (setq l1 (cdr l1)
4621 l2 (cdr l2)))
4622 (cond
4623 ;; l1 not null and l2 not null
4624 ((and l1 l2) (< (car l1) (car l2)))
4625 ;; l1 null and l2 null ==> l1 length = l2 length
4626 ((and (null l1) (null l2)) nil)
4627 ;; l1 not null and l2 null ==> l1 length > l2 length
ca548b00 4628 (l1 (< (version-list-not-zero l1) 0))
e9454757 4629 ;; l1 null and l2 not null ==> l2 length > l1 length
ca548b00 4630 (t (< 0 (version-list-not-zero l2)))))
e9454757
VJL
4631
4632
ca548b00 4633(defun version-list-= (l1 l2)
94785022 4634 "Return t if L1, a list specification of a version, is equal to L2.
e9454757 4635
94785022
EZ
4636Note that a version specified by the list (1) is equal to (1 0),
4637\(1 0 0), (1 0 0 0), etc. That is, the trailing zeros are insignificant.
4638Also, a version given by the list (1) is higher than (1 -1), which in
4639turn is higher than (1 -2), which is higher than (1 -3)."
e9454757
VJL
4640 (while (and l1 l2 (= (car l1) (car l2)))
4641 (setq l1 (cdr l1)
4642 l2 (cdr l2)))
4643 (cond
4644 ;; l1 not null and l2 not null
4645 ((and l1 l2) nil)
4646 ;; l1 null and l2 null ==> l1 length = l2 length
4647 ((and (null l1) (null l2)))
4648 ;; l1 not null and l2 null ==> l1 length > l2 length
ca548b00 4649 (l1 (zerop (version-list-not-zero l1)))
e9454757 4650 ;; l1 null and l2 not null ==> l2 length > l1 length
ca548b00 4651 (t (zerop (version-list-not-zero l2)))))
e9454757
VJL
4652
4653
ca548b00 4654(defun version-list-<= (l1 l2)
94785022 4655 "Return t if L1, a list specification of a version, is lower or equal to L2.
e9454757
VJL
4656
4657Note that integer list (1) is equal to (1 0), (1 0 0), (1 0 0 0),
b29f5b7b 4658etc. That is, the trailing zeroes are insignificant. Also, integer
e9454757
VJL
4659list (1) is greater than (1 -1) which is greater than (1 -2)
4660which is greater than (1 -3)."
4661 (while (and l1 l2 (= (car l1) (car l2)))
4662 (setq l1 (cdr l1)
4663 l2 (cdr l2)))
4664 (cond
4665 ;; l1 not null and l2 not null
4666 ((and l1 l2) (< (car l1) (car l2)))
4667 ;; l1 null and l2 null ==> l1 length = l2 length
4668 ((and (null l1) (null l2)))
4669 ;; l1 not null and l2 null ==> l1 length > l2 length
ca548b00 4670 (l1 (<= (version-list-not-zero l1) 0))
e9454757 4671 ;; l1 null and l2 not null ==> l2 length > l1 length
ca548b00 4672 (t (<= 0 (version-list-not-zero l2)))))
e9454757 4673
ca548b00 4674(defun version-list-not-zero (lst)
94785022 4675 "Return the first non-zero element of LST, which is a list of integers.
e9454757 4676
94785022 4677If all LST elements are zeros or LST is nil, return zero."
ca548b00
KS
4678 (while (and lst (zerop (car lst)))
4679 (setq lst (cdr lst)))
4680 (if lst
4681 (car lst)
4682 ;; there is no element different of zero
4683 0))
e9454757
VJL
4684
4685
4686(defun version< (v1 v2)
94785022 4687 "Return t if version V1 is lower (older) than V2.
e9454757
VJL
4688
4689Note that version string \"1\" is equal to \"1.0\", \"1.0.0\", \"1.0.0.0\",
94785022
EZ
4690etc. That is, the trailing \".0\"s are insignificant. Also, version
4691string \"1\" is higher (newer) than \"1pre\", which is higher than \"1beta\",
7e5bfb8f
EZ
4692which is higher than \"1alpha\". Also, \"-CVS\" and \"-NNN\" are treated
4693as alpha versions."
ca548b00 4694 (version-list-< (version-to-list v1) (version-to-list v2)))
e9454757
VJL
4695
4696
4697(defun version<= (v1 v2)
94785022 4698 "Return t if version V1 is lower (older) than or equal to V2.
e9454757
VJL
4699
4700Note that version string \"1\" is equal to \"1.0\", \"1.0.0\", \"1.0.0.0\",
b29f5b7b 4701etc. That is, the trailing \".0\"s are insignificant. Also, version
94785022 4702string \"1\" is higher (newer) than \"1pre\", which is higher than \"1beta\",
7e5bfb8f
EZ
4703which is higher than \"1alpha\". Also, \"-CVS\" and \"-NNN\" are treated
4704as alpha versions."
ca548b00 4705 (version-list-<= (version-to-list v1) (version-to-list v2)))
e9454757 4706
ca548b00
KS
4707(defun version= (v1 v2)
4708 "Return t if version V1 is equal to V2.
e9454757 4709
ca548b00 4710Note that version string \"1\" is equal to \"1.0\", \"1.0.0\", \"1.0.0.0\",
b29f5b7b 4711etc. That is, the trailing \".0\"s are insignificant. Also, version
94785022 4712string \"1\" is higher (newer) than \"1pre\", which is higher than \"1beta\",
7e5bfb8f
EZ
4713which is higher than \"1alpha\". Also, \"-CVS\" and \"-NNN\" are treated
4714as alpha versions."
ca548b00 4715 (version-list-= (version-to-list v1) (version-to-list v2)))
e9454757 4716
18d433a7
CY
4717\f
4718;;; Misc.
a3c20c83
DN
4719(defconst menu-bar-separator '("--")
4720 "Separator for menus.")
18d433a7
CY
4721
4722;; The following statement ought to be in print.c, but `provide' can't
4723;; be used there.
5612fd08 4724;; http://lists.gnu.org/archive/html/emacs-devel/2009-08/msg00236.html
18d433a7
CY
4725(when (hash-table-p (car (read-from-string
4726 (prin1-to-string (make-hash-table)))))
4727 (provide 'hashtable-print-readable))
4728
629ecae3
EZ
4729;; This is used in lisp/Makefile.in and in leim/Makefile.in to
4730;; generate file names for autoloads, custom-deps, and finder-data.
bc1dd793 4731(defun unmsys--file-name (file)
a052ef3b 4732 "Produce the canonical file name for FILE from its MSYS form.
1c0977a9
EZ
4733
4734On systems other than MS-Windows, just returns FILE.
4735On MS-Windows, converts /d/foo/bar form of file names
4736passed by MSYS Make into d:/foo/bar that Emacs can grok.
4737
a052ef3b 4738This function is called from lisp/Makefile and leim/Makefile."
1c0977a9
EZ
4739 (when (and (eq system-type 'windows-nt)
4740 (string-match "\\`/[a-zA-Z]/" file))
4741 (setq file (concat (substring file 1 2) ":" (substring file 2))))
4742 file)
4743
4744
630cc463 4745;;; subr.el ends here