1 ;;; subr.el --- basic lisp subroutines for Emacs -*- lexical-binding:t -*-
3 ;; Copyright (C) 1985-1986, 1992, 1994-1995, 1999-2018 Free Software
6 ;; Maintainer: emacs-devel@gnu.org
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
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.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
25 ;; Beware: while this file has tag `utf-8', before it's compiled, it gets
26 ;; loaded as "raw-text", so non-ASCII chars won't work right during bootstrap.
29 ;; declare-function's args use &rest, not &optional, for compatibility
30 ;; with byte-compile-macroexpand-declare-function.
32 (defmacro declare-function
(_fn _file
&rest _args
)
33 "Tell the byte-compiler that function FN is defined, in FILE.
34 The FILE argument is not used by the byte-compiler, but by the
35 `check-declare' package, which checks that FILE contains a
38 FILE can be either a Lisp file (in which case the \".el\"
39 extension is optional), or a C file. C files are expanded
40 relative to the Emacs \"src/\" directory. Lisp files are
41 searched for using `locate-library', and if that fails they are
42 expanded relative to the location of the file containing the
43 declaration. A FILE with an \"ext:\" prefix is an external file.
44 `check-declare' will check such files if they are found, and skip
45 them without error if they are not.
47 Optional ARGLIST specifies FN's arguments, or is t to not specify
48 FN's arguments. An omitted ARGLIST defaults to t, not nil: a nil
49 ARGLIST specifies an empty argument list, and an explicit t
50 ARGLIST is a placeholder that allows supplying a later arg.
52 Optional FILEONLY non-nil means that `check-declare' will check
53 only that FILE exists, not that it defines FN. This is intended
54 for function definitions that `check-declare' does not recognize,
57 Note that for the purposes of `check-declare', this statement
58 must be the first non-whitespace on a line.
60 For more information, see Info node `(elisp)Declaring Functions'."
61 (declare (advertised-calling-convention
62 (fn file
&optional arglist fileonly
) nil
))
63 ;; Does nothing - byte-compile-declare-function does the work.
67 ;;;; Basic Lisp macros.
70 (defalias 'sxhash
'sxhash-equal
)
72 (defmacro noreturn
(form)
73 "Evaluate FORM, expecting it not to return.
74 If FORM does return, signal an error."
77 (error "Form marked with `noreturn' did return")))
79 (defmacro 1value
(form)
80 "Evaluate FORM, expecting a constant return value.
81 If FORM returns differing values when running under Testcover,
82 Testcover will raise an error."
86 (defmacro def-edebug-spec
(symbol spec
)
87 "Set the `edebug-form-spec' property of SYMBOL according to SPEC.
88 Both SYMBOL and SPEC are unevaluated. The SPEC can be:
89 0 (instrument no arguments); t (instrument all arguments);
90 a symbol (naming a function with an Edebug specification); or a list.
91 The elements of the list describe the argument types; see
92 Info node `(elisp)Specification List' for details."
93 `(put (quote ,symbol
) 'edebug-form-spec
(quote ,spec
)))
95 (defmacro lambda
(&rest cdr
)
96 "Return a lambda expression.
97 A call of the form (lambda ARGS DOCSTRING INTERACTIVE BODY) is
98 self-quoting; the result of evaluating the lambda expression is the
99 expression itself. The lambda expression may then be treated as a
100 function, i.e., stored as the function value of a symbol, passed to
101 `funcall' or `mapcar', etc.
103 ARGS should take the same form as an argument list for a `defun'.
104 DOCSTRING is an optional documentation string.
105 If present, it should describe how to call the function.
106 But documentation strings are usually not useful in nameless functions.
107 INTERACTIVE should be a call to the function `interactive', which see.
108 It may also be omitted.
109 BODY should be a list of Lisp expressions.
111 \(fn ARGS [DOCSTRING] [INTERACTIVE] BODY)"
112 (declare (doc-string 2) (indent defun
)
113 (debug (&define lambda-list lambda-doc
114 [&optional
("interactive" interactive
)]
116 ;; Note that this definition should not use backquotes; subr.el should not
117 ;; depend on backquote.el.
118 (list 'function
(cons 'lambda cdr
)))
120 (defmacro setq-local
(var val
)
121 "Set variable VAR to value VAL in current buffer."
122 ;; Can't use backquote here, it's too early in the bootstrap.
123 (declare (debug (symbolp form
)))
124 (list 'set
(list 'make-local-variable
(list 'quote var
)) val
))
126 (defmacro defvar-local
(var val
&optional docstring
)
127 "Define VAR as a buffer-local variable with default value VAL.
128 Like `defvar' but additionally marks the variable as being automatically
129 buffer-local wherever it is set."
130 (declare (debug defvar
) (doc-string 3))
131 ;; Can't use backquote here, it's too early in the bootstrap.
132 (list 'progn
(list 'defvar var val docstring
)
133 (list 'make-variable-buffer-local
(list 'quote var
))))
135 (defmacro push
(newelt place
)
136 "Add NEWELT to the list stored in the generalized variable PLACE.
137 This is morally equivalent to (setf PLACE (cons NEWELT PLACE)),
138 except that PLACE is only evaluated once (after NEWELT)."
139 (declare (debug (form gv-place
)))
141 ;; Important special case, to avoid triggering GV too early in
144 (list 'cons newelt place
))
146 (macroexp-let2 macroexp-copyable-p v newelt
147 (gv-letplace (getter setter
) place
148 (funcall setter
`(cons ,v
,getter
))))))
150 (defmacro pop
(place)
151 "Return the first element of PLACE's value, and remove it from the list.
152 PLACE must be a generalized variable whose value is a list.
153 If the value is nil, `pop' returns nil but does not actually
155 (declare (debug (gv-place)))
156 ;; We use `car-safe' here instead of `car' because the behavior is the same
157 ;; (if it's not a cons cell, the `cdr' would have signaled an error already),
158 ;; but `car-safe' is total, so the byte-compiler can safely remove it if the
159 ;; result is not used.
162 ;; So we can use `pop' in the bootstrap before `gv' can be used.
163 (list 'prog1 place
(list 'setq place
(list 'cdr place
)))
164 (gv-letplace (getter setter
) place
165 (macroexp-let2 macroexp-copyable-p x getter
166 `(prog1 ,x
,(funcall setter
`(cdr ,x
))))))))
168 (defmacro when
(cond &rest body
)
169 "If COND yields non-nil, do BODY, else return nil.
170 When COND yields non-nil, eval BODY forms sequentially and return
171 value of last one, or nil if there are none.
174 (declare (indent 1) (debug t
))
175 (list 'if cond
(cons 'progn body
)))
177 (defmacro unless
(cond &rest body
)
178 "If COND yields nil, do BODY, else return nil.
179 When COND yields nil, eval BODY forms sequentially and return
180 value of last one, or nil if there are none.
183 (declare (indent 1) (debug t
))
184 (cons 'if
(cons cond
(cons nil body
))))
186 (defmacro dolist
(spec &rest body
)
188 Evaluate BODY with VAR bound to each car from LIST, in turn.
189 Then evaluate RESULT to get return value, default nil.
191 \(fn (VAR LIST [RESULT]) BODY...)"
192 (declare (indent 1) (debug ((symbolp form
&optional form
) body
)))
194 (signal 'wrong-type-argument
(list 'consp spec
)))
195 (unless (<= 2 (length spec
) 3)
196 (signal 'wrong-number-of-arguments
(list '(2 .
3) (length spec
))))
197 ;; It would be cleaner to create an uninterned symbol,
198 ;; but that uses a lot more space when many functions in many files
200 ;; FIXME: This cost disappears in byte-compiled lexical-binding files.
201 (let ((temp '--dolist-tail--
))
202 ;; This is not a reliable test, but it does not matter because both
203 ;; semantics are acceptable, tho one is slightly faster with dynamic
204 ;; scoping and the other is slightly faster (and has cleaner semantics)
205 ;; with lexical scoping.
207 `(let ((,temp
,(nth 1 spec
)))
209 (let ((,(car spec
) (car ,temp
)))
211 (setq ,temp
(cdr ,temp
))))
213 `(let ((,temp
,(nth 1 spec
))
216 (setq ,(car spec
) (car ,temp
))
218 (setq ,temp
(cdr ,temp
)))
219 ,@(if (cdr (cdr spec
))
220 `((setq ,(car spec
) nil
) ,@(cdr (cdr spec
))))))))
222 (defmacro dotimes
(spec &rest body
)
223 "Loop a certain number of times.
224 Evaluate BODY with VAR bound to successive integers running from 0,
225 inclusive, to COUNT, exclusive. Then evaluate RESULT to get
226 the return value (nil if RESULT is omitted).
228 \(fn (VAR COUNT [RESULT]) BODY...)"
229 (declare (indent 1) (debug dolist
))
230 ;; It would be cleaner to create an uninterned symbol,
231 ;; but that uses a lot more space when many functions in many files
233 ;; FIXME: This cost disappears in byte-compiled lexical-binding files.
234 (let ((temp '--dotimes-limit--
)
237 ;; This is not a reliable test, but it does not matter because both
238 ;; semantics are acceptable, tho one is slightly faster with dynamic
239 ;; scoping and the other has cleaner semantics.
241 (let ((counter '--dotimes-counter--
))
244 (while (< ,counter
,temp
)
245 (let ((,(car spec
) ,counter
))
247 (setq ,counter
(1+ ,counter
)))
249 ;; FIXME: This let often leads to "unused var" warnings.
250 `((let ((,(car spec
) ,counter
)) ,@(cddr spec
))))))
252 (,(car spec
) ,start
))
253 (while (< ,(car spec
) ,temp
)
255 (setq ,(car spec
) (1+ ,(car spec
))))
256 ,@(cdr (cdr spec
))))))
258 (defmacro declare
(&rest _specs
)
259 "Do not evaluate any arguments, and return nil.
260 If a `declare' form appears as the first form in the body of a
261 `defun' or `defmacro' form, SPECS specifies various additional
262 information about the function or macro; these go into effect
263 during the evaluation of the `defun' or `defmacro' form.
265 The possible values of SPECS are specified by
266 `defun-declarations-alist' and `macro-declarations-alist'.
268 For more information, see info node `(elisp)Declare Form'."
269 ;; FIXME: edebug spec should pay attention to defun-declarations-alist.
272 (defmacro ignore-errors
(&rest body
)
273 "Execute BODY; if an error occurs, return nil.
274 Otherwise, return result of last form in BODY.
275 See also `with-demoted-errors' that does something similar
276 without silencing all errors."
277 (declare (debug t
) (indent 0))
278 `(condition-case nil
(progn ,@body
) (error nil
)))
280 ;;;; Basic Lisp functions.
282 (defvar gensym-counter
0
283 "Number used to construct the name of the next symbol created by `gensym'.")
285 (defun gensym (&optional prefix
)
286 "Return a new uninterned symbol.
287 The name is made by appending `gensym-counter' to PREFIX.
288 PREFIX is a string, and defaults to \"g\"."
289 (let ((num (prog1 gensym-counter
290 (setq gensym-counter
(1+ gensym-counter
)))))
291 (make-symbol (format "%s%d" (or prefix
"g") num
))))
293 (defun ignore (&rest _ignore
)
294 "Do nothing and return nil.
295 This function accepts any number of arguments, but ignores them."
299 ;; Signal a compile-error if the first arg is missing.
300 (defun error (&rest args
)
301 "Signal an error, making a message by passing args to `format-message'.
302 In Emacs, the convention is that error messages start with a capital
303 letter but *do not* end with a period. Please follow this convention
304 for the sake of consistency.
306 Note: (error \"%s\" VALUE) makes the message VALUE without
307 interpreting format characters like `%', `\\=`', and `\\=''."
308 (declare (advertised-calling-convention (string &rest args
) "23.1"))
309 (signal 'error
(list (apply #'format-message args
))))
311 (defun user-error (format &rest args
)
312 "Signal a pilot error, making a message by passing args to `format-message'.
313 In Emacs, the convention is that error messages start with a capital
314 letter but *do not* end with a period. Please follow this convention
315 for the sake of consistency.
316 This is just like `error' except that `user-error's are expected to be the
317 result of an incorrect manipulation on the part of the user, rather than the
318 result of an actual problem.
320 Note: (user-error \"%s\" VALUE) makes the message VALUE without
321 interpreting format characters like `%', `\\=`', and `\\=''."
322 (signal 'user-error
(list (apply #'format-message format args
))))
324 (defun define-error (name message
&optional parent
)
325 "Define NAME as a new error signal.
326 MESSAGE is a string that will be output to the echo area if such an error
327 is signaled without being caught by a `condition-case'.
328 PARENT is either a signal or a list of signals from which it inherits.
329 Defaults to `error'."
330 (unless parent
(setq parent
'error
))
334 (mapcar (lambda (parent)
336 (or (get parent
'error-conditions
)
337 (error "Unknown signal `%s'" parent
))))
339 (cons parent
(get parent
'error-conditions
)))))
340 (put name
'error-conditions
341 (delete-dups (copy-sequence (cons name conditions
))))
342 (when message
(put name
'error-message message
))))
344 ;; We put this here instead of in frame.el so that it's defined even on
345 ;; systems where frame.el isn't loaded.
346 (defun frame-configuration-p (object)
347 "Return non-nil if OBJECT seems to be a frame configuration.
348 Any list whose car is `frame-configuration' is assumed to be a frame
351 (eq (car object
) 'frame-configuration
)))
353 (defun apply-partially (fun &rest args
)
354 "Return a function that is a partial application of FUN to ARGS.
355 ARGS is a list of the first N arguments to pass to FUN.
356 The result is a new function which does the same as FUN, except that
357 the first N arguments are fixed at the values with which this function
359 (lambda (&rest args2
)
360 (apply fun
(append args args2
))))
365 ;; Note: `internal--compiler-macro-cXXr' was copied from
366 ;; `cl--compiler-macro-cXXr' in cl-macs.el. If you amend either one,
367 ;; you may want to amend the other, too.
368 (defun internal--compiler-macro-cXXr (form x
)
369 (let* ((head (car form
))
370 (n (symbol-name (car form
)))
371 (i (- (length n
) 2)))
372 (if (not (string-match "c[ad]+r\\'" n
))
373 (if (and (fboundp head
) (symbolp (symbol-function head
)))
374 (internal--compiler-macro-cXXr (cons (symbol-function head
) (cdr form
))
376 (error "Compiler macro for cXXr applied to non-cXXr form"))
377 (while (> i
(match-beginning 0))
378 (setq x
(list (if (eq (aref n i
) ?a
) 'car
'cdr
) x
))
383 "Return the car of the car of X."
384 (declare (compiler-macro internal--compiler-macro-cXXr
))
388 "Return the car of the cdr of X."
389 (declare (compiler-macro internal--compiler-macro-cXXr
))
393 "Return the cdr of the car of X."
394 (declare (compiler-macro internal--compiler-macro-cXXr
))
398 "Return the cdr of the cdr of X."
399 (declare (compiler-macro internal--compiler-macro-cXXr
))
403 "Return the `car' of the `car' of the `car' of X."
404 (declare (compiler-macro internal--compiler-macro-cXXr
))
408 "Return the `car' of the `car' of the `cdr' of X."
409 (declare (compiler-macro internal--compiler-macro-cXXr
))
413 "Return the `car' of the `cdr' of the `car' of X."
414 (declare (compiler-macro internal--compiler-macro-cXXr
))
418 "Return the `car' of the `cdr' of the `cdr' of X."
419 (declare (compiler-macro internal--compiler-macro-cXXr
))
423 "Return the `cdr' of the `car' of the `car' of X."
424 (declare (compiler-macro internal--compiler-macro-cXXr
))
428 "Return the `cdr' of the `car' of the `cdr' of X."
429 (declare (compiler-macro internal--compiler-macro-cXXr
))
433 "Return the `cdr' of the `cdr' of the `car' of X."
434 (declare (compiler-macro internal--compiler-macro-cXXr
))
438 "Return the `cdr' of the `cdr' of the `cdr' of X."
439 (declare (compiler-macro internal--compiler-macro-cXXr
))
443 "Return the `car' of the `car' of the `car' of the `car' of X."
444 (declare (compiler-macro internal--compiler-macro-cXXr
))
445 (car (car (car (car x
)))))
448 "Return the `car' of the `car' of the `car' of the `cdr' of X."
449 (declare (compiler-macro internal--compiler-macro-cXXr
))
450 (car (car (car (cdr x
)))))
453 "Return the `car' of the `car' of the `cdr' of the `car' of X."
454 (declare (compiler-macro internal--compiler-macro-cXXr
))
455 (car (car (cdr (car x
)))))
458 "Return the `car' of the `car' of the `cdr' of the `cdr' of X."
459 (declare (compiler-macro internal--compiler-macro-cXXr
))
460 (car (car (cdr (cdr x
)))))
463 "Return the `car' of the `cdr' of the `car' of the `car' of X."
464 (declare (compiler-macro internal--compiler-macro-cXXr
))
465 (car (cdr (car (car x
)))))
468 "Return the `car' of the `cdr' of the `car' of the `cdr' of X."
469 (declare (compiler-macro internal--compiler-macro-cXXr
))
470 (car (cdr (car (cdr x
)))))
473 "Return the `car' of the `cdr' of the `cdr' of the `car' of X."
474 (declare (compiler-macro internal--compiler-macro-cXXr
))
475 (car (cdr (cdr (car x
)))))
478 "Return the `car' of the `cdr' of the `cdr' of the `cdr' of X."
479 (declare (compiler-macro internal--compiler-macro-cXXr
))
480 (car (cdr (cdr (cdr x
)))))
483 "Return the `cdr' of the `car' of the `car' of the `car' of X."
484 (declare (compiler-macro internal--compiler-macro-cXXr
))
485 (cdr (car (car (car x
)))))
488 "Return the `cdr' of the `car' of the `car' of the `cdr' of X."
489 (declare (compiler-macro internal--compiler-macro-cXXr
))
490 (cdr (car (car (cdr x
)))))
493 "Return the `cdr' of the `car' of the `cdr' of the `car' of X."
494 (declare (compiler-macro internal--compiler-macro-cXXr
))
495 (cdr (car (cdr (car x
)))))
498 "Return the `cdr' of the `car' of the `cdr' of the `cdr' of X."
499 (declare (compiler-macro internal--compiler-macro-cXXr
))
500 (cdr (car (cdr (cdr x
)))))
503 "Return the `cdr' of the `cdr' of the `car' of the `car' of X."
504 (declare (compiler-macro internal--compiler-macro-cXXr
))
505 (cdr (cdr (car (car x
)))))
508 "Return the `cdr' of the `cdr' of the `car' of the `cdr' of X."
509 (declare (compiler-macro internal--compiler-macro-cXXr
))
510 (cdr (cdr (car (cdr x
)))))
513 "Return the `cdr' of the `cdr' of the `cdr' of the `car' of X."
514 (declare (compiler-macro internal--compiler-macro-cXXr
))
515 (cdr (cdr (cdr (car x
)))))
518 "Return the `cdr' of the `cdr' of the `cdr' of the `cdr' of X."
519 (declare (compiler-macro internal--compiler-macro-cXXr
))
520 (cdr (cdr (cdr (cdr x
)))))
522 (defun last (list &optional n
)
523 "Return the last link of LIST. Its car is the last element.
524 If LIST is nil, return nil.
525 If N is non-nil, return the Nth-to-last link of LIST.
526 If N is bigger than the length of LIST, return LIST."
529 (let ((m (safe-length list
)))
530 (if (< n m
) (nthcdr (- m n
) list
) list
)))
532 (nthcdr (1- (safe-length list
)) list
))))
534 (defun butlast (list &optional n
)
535 "Return a copy of LIST with the last N elements removed.
536 If N is omitted or nil, the last element is removed from the
538 (if (and n
(<= n
0)) list
539 (nbutlast (copy-sequence list
) n
)))
541 (defun nbutlast (list &optional n
)
542 "Modifies LIST to remove the last N elements.
543 If N is omitted or nil, remove the last element."
544 (let ((m (length list
)))
548 (if (> n
0) (setcdr (nthcdr (- (1- m
) n
) list
) nil
))
551 (defun zerop (number)
552 "Return t if NUMBER is zero."
553 ;; Used to be in C, but it's pointless since (= 0 n) is faster anyway because
554 ;; = has a byte-code.
555 (declare (compiler-macro (lambda (_) `(= 0 ,number
))))
558 (defun delete-dups (list)
559 "Destructively remove `equal' duplicates from LIST.
560 Store the result in LIST and return it. LIST must be a proper list.
561 Of several `equal' occurrences of an element in LIST, the first
563 (let ((l (length list
)))
565 (let ((hash (make-hash-table :test
#'equal
:size l
))
567 (puthash (car list
) t hash
)
568 (while (setq retail
(cdr tail
))
569 (let ((elt (car retail
)))
570 (if (gethash elt hash
)
571 (setcdr tail
(cdr retail
))
573 (setq tail retail
)))))
576 (setcdr tail
(delete (car tail
) (cdr tail
)))
577 (setq tail
(cdr tail
))))))
580 ;; See https://lists.gnu.org/r/emacs-devel/2013-05/msg00204.html
581 (defun delete-consecutive-dups (list &optional circular
)
582 "Destructively remove `equal' consecutive duplicates from LIST.
583 First and last elements are considered consecutive if CIRCULAR is
585 (let ((tail list
) last
)
587 (if (equal (car tail
) (cadr tail
))
588 (setcdr tail
(cddr tail
))
593 (equal (car tail
) (car list
)))
597 (defun number-sequence (from &optional to inc
)
598 "Return a sequence of numbers from FROM to TO (both inclusive) as a list.
599 INC is the increment used between numbers in the sequence and defaults to 1.
600 So, the Nth element of the list is (+ FROM (* N INC)) where N counts from
601 zero. TO is only included if there is an N for which TO = FROM + N * INC.
602 If TO is nil or numerically equal to FROM, return (FROM).
603 If INC is positive and TO is less than FROM, or INC is negative
604 and TO is larger than FROM, return nil.
605 If INC is zero and TO is neither nil nor numerically equal to
606 FROM, signal an error.
608 This function is primarily designed for integer arguments.
609 Nevertheless, FROM, TO and INC can be integer or float. However,
610 floating point arithmetic is inexact. For instance, depending on
611 the machine, it may quite well happen that
612 \(number-sequence 0.4 0.6 0.2) returns the one element list (0.4),
613 whereas (number-sequence 0.4 0.8 0.2) returns a list with three
614 elements. Thus, if some of the arguments are floats and one wants
615 to make sure that TO is included, one may have to explicitly write
616 TO as (+ FROM (* N INC)) or use a variable whose value was
617 computed with this exact expression. Alternatively, you can,
618 of course, also replace TO with a slightly larger value
619 \(or a slightly more negative value if INC is negative)."
620 (if (or (not to
) (= from to
))
622 (or inc
(setq inc
1))
623 (when (zerop inc
) (error "The increment can not be zero"))
624 (let (seq (n 0) (next from
) (last from
))
626 ;; The (>= next last) condition protects against integer
627 ;; overflow in computing NEXT.
628 (while (and (>= next last
) (<= next to
))
629 (setq seq
(cons next seq
)
632 next
(+ from
(* n inc
))))
633 (while (and (<= next last
) (>= next to
))
634 (setq seq
(cons next seq
)
636 next
(+ from
(* n inc
)))))
639 (defun copy-tree (tree &optional vecp
)
640 "Make a copy of TREE.
641 If TREE is a cons cell, this recursively copies both its car and its cdr.
642 Contrast to `copy-sequence', which copies only along the cdrs. With second
643 argument VECP, this copies vectors as well as conses."
647 (let ((newcar (car tree
)))
648 (if (or (consp (car tree
)) (and vecp
(vectorp (car tree
))))
649 (setq newcar
(copy-tree (car tree
) vecp
)))
650 (push newcar result
))
651 (setq tree
(cdr tree
)))
652 (nconc (nreverse result
)
653 (if (and vecp
(vectorp tree
)) (copy-tree tree vecp
) tree
)))
654 (if (and vecp
(vectorp tree
))
655 (let ((i (length (setq tree
(copy-sequence tree
)))))
656 (while (>= (setq i
(1- i
)) 0)
657 (aset tree i
(copy-tree (aref tree i
) vecp
)))
661 ;;;; Various list-search functions.
663 (defun assoc-default (key alist
&optional test default
)
664 "Find object KEY in a pseudo-alist ALIST.
665 ALIST is a list of conses or objects. Each element
666 (or the element's car, if it is a cons) is compared with KEY by
667 calling TEST, with two arguments: (i) the element or its car,
669 If that is non-nil, the element matches; then `assoc-default'
670 returns the element's cdr, if it is a cons, or DEFAULT if the
671 element is not a cons.
673 If no element matches, the value is nil.
674 If TEST is omitted or nil, `equal' is used."
675 (let (found (tail alist
) value
)
676 (while (and tail
(not found
))
677 (let ((elt (car tail
)))
678 (when (funcall (or test
'equal
) (if (consp elt
) (car elt
) elt
) key
)
679 (setq found t value
(if (consp elt
) (cdr elt
) default
))))
680 (setq tail
(cdr tail
)))
683 (defun member-ignore-case (elt list
)
684 "Like `member', but ignore differences in case and text representation.
685 ELT must be a string. Upper-case and lower-case letters are treated as equal.
686 Unibyte strings are converted to multibyte for comparison.
687 Non-strings in LIST are ignored."
689 (not (and (stringp (car list
))
690 (eq t
(compare-strings elt
0 nil
(car list
) 0 nil t
)))))
691 (setq list
(cdr list
)))
694 (defun assoc-delete-all (key alist
&optional test
)
695 "Delete from ALIST all elements whose car is KEY.
696 Compare keys with TEST. Defaults to `equal'.
697 Return the modified alist.
698 Elements of ALIST that are not conses are ignored."
699 (unless test
(setq test
#'equal
))
700 (while (and (consp (car alist
))
701 (funcall test
(caar alist
) key
))
702 (setq alist
(cdr alist
)))
703 (let ((tail alist
) tail-cdr
)
704 (while (setq tail-cdr
(cdr tail
))
705 (if (and (consp (car tail-cdr
))
706 (funcall test
(caar tail-cdr
) key
))
707 (setcdr tail
(cdr tail-cdr
))
708 (setq tail tail-cdr
))))
711 (defun assq-delete-all (key alist
)
712 "Delete from ALIST all elements whose car is `eq' to KEY.
713 Return the modified alist.
714 Elements of ALIST that are not conses are ignored."
715 (assoc-delete-all key alist
#'eq
))
717 (defun rassq-delete-all (value alist
)
718 "Delete from ALIST all elements whose cdr is `eq' to VALUE.
719 Return the modified alist.
720 Elements of ALIST that are not conses are ignored."
721 (while (and (consp (car alist
))
722 (eq (cdr (car alist
)) value
))
723 (setq alist
(cdr alist
)))
724 (let ((tail alist
) tail-cdr
)
725 (while (setq tail-cdr
(cdr tail
))
726 (if (and (consp (car tail-cdr
))
727 (eq (cdr (car tail-cdr
)) value
))
728 (setcdr tail
(cdr tail-cdr
))
729 (setq tail tail-cdr
))))
732 (defun alist-get (key alist
&optional default remove testfn
)
733 "Return the value associated with KEY in ALIST.
734 If KEY is not found in ALIST, return DEFAULT.
735 Use TESTFN to lookup in the alist if non-nil. Otherwise, use `assq'.
737 This is a generalized variable suitable for use with `setf'.
738 When using it to set a value, optional argument REMOVE non-nil
739 means to remove KEY from ALIST if the new value is `eql' to DEFAULT."
740 (ignore remove
) ;;Silence byte-compiler.
741 (let ((x (if (not testfn
)
743 (assoc key alist testfn
))))
744 (if x
(cdr x
) default
)))
746 (defun remove (elt seq
)
747 "Return a copy of SEQ with all occurrences of ELT removed.
748 SEQ must be a list, vector, or string. The comparison is done with `equal'."
750 ;; If SEQ isn't a list, there's no need to copy SEQ because
751 ;; `delete' will return a new object.
753 (delete elt
(copy-sequence seq
))))
755 (defun remq (elt list
)
756 "Return LIST with all occurrences of ELT removed.
757 The comparison is done with `eq'. Contrary to `delq', this does not use
758 side-effects, and the argument LIST is not modified."
759 (while (and (eq elt
(car list
)) (setq list
(cdr list
))))
761 (delq elt
(copy-sequence list
))
767 "Convert KEYS to the internal Emacs key representation.
768 KEYS should be a string in the format returned by commands such
769 as `C-h k' (`describe-key').
770 This is the same format used for saving keyboard macros (see
773 For an approximate inverse of this, see `key-description'."
774 ;; Don't use a defalias, since the `pure' property is only true for
775 ;; the calling convention of `kbd'.
776 (read-kbd-macro keys
))
780 "Beep to tell the user this binding is undefined."
783 (if defining-kbd-macro
784 (error "%s is undefined" (key-description (this-single-command-keys)))
785 (message "%s is undefined" (key-description (this-single-command-keys))))
786 (force-mode-line-update)
787 ;; If this is a down-mouse event, don't reset prefix-arg;
788 ;; pass it to the command run by the up event.
790 (when (memq 'down
(event-modifiers last-command-event
))
791 current-prefix-arg
)))
793 ;; Prevent the \{...} documentation construct
794 ;; from mentioning keys that run this command.
795 (put 'undefined
'suppress-keymap t
)
797 (defun suppress-keymap (map &optional nodigits
)
798 "Make MAP override all normally self-inserting keys to be undefined.
799 Normally, as an exception, digits and minus-sign are set to make prefix args,
800 but optional second arg NODIGITS non-nil treats them like other chars."
801 (define-key map
[remap self-insert-command
] 'undefined
)
804 (define-key map
"-" 'negative-argument
)
805 ;; Make plain numbers do numeric args.
808 (define-key map
(char-to-string loop
) 'digit-argument
)
809 (setq loop
(1+ loop
))))))
811 (defun make-composed-keymap (maps &optional parent
)
812 "Construct a new keymap composed of MAPS and inheriting from PARENT.
813 When looking up a key in the returned map, the key is looked in each
814 keymap of MAPS in turn until a binding is found.
815 If no binding is found in MAPS, the lookup continues in PARENT, if non-nil.
816 As always with keymap inheritance, a nil binding in MAPS overrides
817 any corresponding binding in PARENT, but it does not override corresponding
818 bindings in other keymaps of MAPS.
819 MAPS can be a list of keymaps or a single keymap.
820 PARENT if non-nil should be a keymap."
822 ,@(if (keymapp maps
) (list maps
) maps
)
825 (defun define-key-after (keymap key definition
&optional after
)
826 "Add binding in KEYMAP for KEY => DEFINITION, right after AFTER's binding.
827 This is like `define-key' except that the binding for KEY is placed
828 just after the binding for the event AFTER, instead of at the beginning
829 of the map. Note that AFTER must be an event type (like KEY), NOT a command
832 If AFTER is t or omitted, the new binding goes at the end of the keymap.
833 AFTER should be a single event type--a symbol or a character, not a sequence.
835 Bindings are always added before any inherited map.
837 The order of bindings in a keymap only matters when it is used as
838 a menu, so this function is not useful for non-menu keymaps."
839 (unless after
(setq after t
))
841 (signal 'wrong-type-argument
(list 'keymapp keymap
)))
843 (if (<= (length key
) 1) (aref key
0)
844 (setq keymap
(lookup-key keymap
846 (butlast (mapcar 'identity key
)))))
847 (aref key
(1- (length key
)))))
848 (let ((tail keymap
) done inserted
)
849 (while (and (not done
) tail
)
850 ;; Delete any earlier bindings for the same key.
851 (if (eq (car-safe (car (cdr tail
))) key
)
852 (setcdr tail
(cdr (cdr tail
))))
853 ;; If we hit an included map, go down that one.
854 (if (keymapp (car tail
)) (setq tail
(car tail
)))
855 ;; When we reach AFTER's binding, insert the new binding after.
856 ;; If we reach an inherited keymap, insert just before that.
857 ;; If we reach the end of this keymap, insert at the end.
858 (if (or (and (eq (car-safe (car tail
)) after
)
860 (eq (car (cdr tail
)) 'keymap
)
863 ;; Stop the scan only if we find a parent keymap.
864 ;; Keep going past the inserted element
865 ;; so we can delete any duplications that come later.
866 (if (eq (car (cdr tail
)) 'keymap
)
868 ;; Don't insert more than once.
870 (setcdr tail
(cons (cons key definition
) (cdr tail
))))
872 (setq tail
(cdr tail
)))))
874 (defun map-keymap-sorted (function keymap
)
875 "Implement `map-keymap' with sorting.
876 Don't call this function; it is for internal use only."
878 (map-keymap (lambda (a b
) (push (cons a b
) list
))
880 (setq list
(sort list
882 (setq a
(car a
) b
(car b
))
884 (if (integerp b
) (< a b
)
887 ;; string< also accepts symbols.
890 (funcall function
(car p
) (cdr p
)))))
892 (defun keymap--menu-item-binding (val)
893 "Return the binding part of a menu-item."
895 ((not (consp val
)) val
) ;Not a menu-item.
896 ((eq 'menu-item
(car val
))
897 (let* ((binding (nth 2 val
))
898 (plist (nthcdr 3 val
))
899 (filter (plist-get plist
:filter
)))
900 (if filter
(funcall filter binding
)
902 ((and (consp (cdr val
)) (stringp (cadr val
)))
906 (t val
))) ;Not a menu-item either.
908 (defun keymap--menu-item-with-binding (item binding
)
909 "Build a menu-item like ITEM but with its binding changed to BINDING."
911 ((not (consp item
)) binding
) ;Not a menu-item.
912 ((eq 'menu-item
(car item
))
913 (setq item
(copy-sequence item
))
914 (let ((tail (nthcdr 2 item
)))
915 (setcar tail binding
)
916 ;; Remove any potential filter.
917 (if (plist-get (cdr tail
) :filter
)
918 (setcdr tail
(plist-put (cdr tail
) :filter nil
))))
920 ((and (consp (cdr item
)) (stringp (cadr item
)))
921 (cons (car item
) (cons (cadr item
) binding
)))
922 (t (cons (car item
) binding
))))
924 (defun keymap--merge-bindings (val1 val2
)
925 "Merge bindings VAL1 and VAL2."
926 (let ((map1 (keymap--menu-item-binding val1
))
927 (map2 (keymap--menu-item-binding val2
)))
928 (if (not (and (keymapp map1
) (keymapp map2
)))
929 ;; There's nothing to merge: val1 takes precedence.
931 (let ((map (list 'keymap map1 map2
))
932 (item (if (keymapp val1
) (if (keymapp val2
) nil val2
) val1
)))
933 (keymap--menu-item-with-binding item map
)))))
935 (defun keymap-canonicalize (map)
936 "Return a simpler equivalent keymap.
937 This resolves inheritance and redefinitions. The returned keymap
938 should behave identically to a copy of KEYMAP w.r.t `lookup-key'
939 and use in active keymaps and menus.
940 Subkeymaps may be modified but are not canonicalized."
941 ;; FIXME: Problem with the difference between a nil binding
942 ;; that hides a binding in an inherited map and a nil binding that's ignored
943 ;; to let some further binding visible. Currently a nil binding hides all.
944 ;; FIXME: we may want to carefully (re)order elements in case they're
948 (prompt (keymap-prompt map
)))
950 (setq map
(map-keymap ;; -internal
953 ;; Treat char-ranges specially.
954 (push (cons key item
) ranges
)
955 (push (cons key item
) bindings
)))
957 ;; Create the new map.
958 (setq map
(funcall (if ranges
'make-keymap
'make-sparse-keymap
) prompt
))
959 (dolist (binding ranges
)
960 ;; Treat char-ranges specially. FIXME: need to merge as well.
961 (define-key map
(vector (car binding
)) (cdr binding
)))
962 ;; Process the bindings starting from the end.
963 (dolist (binding (prog1 bindings
(setq bindings
())))
964 (let* ((key (car binding
))
965 (oldbind (assq key bindings
)))
966 (push (if (not oldbind
)
967 ;; The normal case: no duplicate bindings.
969 ;; This is the second binding for this key.
970 (setq bindings
(delq oldbind bindings
))
971 (cons key
(keymap--merge-bindings (cdr binding
)
974 (nconc map bindings
)))
976 (put 'keyboard-translate-table
'char-table-extra-slots
0)
978 (defun keyboard-translate (from to
)
979 "Translate character FROM to TO on the current terminal.
980 This function creates a `keyboard-translate-table' if necessary
981 and then modifies one entry in it."
982 (or (char-table-p keyboard-translate-table
)
983 (setq keyboard-translate-table
984 (make-char-table 'keyboard-translate-table nil
)))
985 (aset keyboard-translate-table from to
))
987 ;;;; Key binding commands.
989 (defun global-set-key (key command
)
990 "Give KEY a global binding as COMMAND.
991 COMMAND is the command definition to use; usually it is
992 a symbol naming an interactively-callable function.
993 KEY is a key sequence; noninteractively, it is a string or vector
994 of characters or event types, and non-ASCII characters with codes
995 above 127 (such as ISO Latin-1) can be included if you use a vector.
997 Note that if KEY has a local binding in the current buffer,
998 that local binding will continue to shadow any global binding
999 that you make with this function."
1001 (let* ((menu-prompting nil
)
1002 (key (read-key-sequence "Set key globally: ")))
1004 (read-command (format "Set key %s to command: "
1005 (key-description key
))))))
1006 (or (vectorp key
) (stringp key
)
1007 (signal 'wrong-type-argument
(list 'arrayp key
)))
1008 (define-key (current-global-map) key command
))
1010 (defun local-set-key (key command
)
1011 "Give KEY a local binding as COMMAND.
1012 COMMAND is the command definition to use; usually it is
1013 a symbol naming an interactively-callable function.
1014 KEY is a key sequence; noninteractively, it is a string or vector
1015 of characters or event types, and non-ASCII characters with codes
1016 above 127 (such as ISO Latin-1) can be included if you use a vector.
1018 The binding goes in the current buffer's local map, which in most
1019 cases is shared with all other buffers in the same major mode."
1020 (interactive "KSet key locally: \nCSet key %s locally to command: ")
1021 (let ((map (current-local-map)))
1023 (use-local-map (setq map
(make-sparse-keymap))))
1024 (or (vectorp key
) (stringp key
)
1025 (signal 'wrong-type-argument
(list 'arrayp key
)))
1026 (define-key map key command
)))
1028 (defun global-unset-key (key)
1029 "Remove global binding of KEY.
1030 KEY is a string or vector representing a sequence of keystrokes."
1031 (interactive "kUnset key globally: ")
1032 (global-set-key key nil
))
1034 (defun local-unset-key (key)
1035 "Remove local binding of KEY.
1036 KEY is a string or vector representing a sequence of keystrokes."
1037 (interactive "kUnset key locally: ")
1038 (if (current-local-map)
1039 (local-set-key key nil
))
1042 ;;;; substitute-key-definition and its subroutines.
1044 (defvar key-substitution-in-progress nil
1045 "Used internally by `substitute-key-definition'.")
1047 (defun substitute-key-definition (olddef newdef keymap
&optional oldmap prefix
)
1048 "Replace OLDDEF with NEWDEF for any keys in KEYMAP now defined as OLDDEF.
1049 In other words, OLDDEF is replaced with NEWDEF wherever it appears.
1050 Alternatively, if optional fourth argument OLDMAP is specified, we redefine
1051 in KEYMAP as NEWDEF those keys which are defined as OLDDEF in OLDMAP.
1053 If you don't specify OLDMAP, you can usually get the same results
1054 in a cleaner way with command remapping, like this:
1055 (define-key KEYMAP [remap OLDDEF] NEWDEF)
1056 \n(fn OLDDEF NEWDEF KEYMAP &optional OLDMAP)"
1057 ;; Don't document PREFIX in the doc string because we don't want to
1058 ;; advertise it. It's meant for recursive calls only. Here's its
1061 ;; If optional argument PREFIX is specified, it should be a key
1062 ;; prefix, a string. Redefined bindings will then be bound to the
1063 ;; original key, with PREFIX added at the front.
1064 (or prefix
(setq prefix
""))
1065 (let* ((scan (or oldmap keymap
))
1066 (prefix1 (vconcat prefix
[nil]))
1067 (key-substitution-in-progress
1068 (cons scan key-substitution-in-progress)))
1069 ;; Scan OLDMAP, finding each char or event-symbol that
1070 ;; has any definition, and act on it with hack-key.
1073 (aset prefix1 (length prefix) char)
1074 (substitute-key-definition-key defn olddef newdef prefix1 keymap))
1077 (defun substitute-key-definition-key (defn olddef newdef prefix keymap)
1078 (let (inner-def skipped menu-item)
1079 ;; Find the actual command name within the binding.
1080 (if (eq (car-safe defn) 'menu-item)
1081 (setq menu-item defn defn (nth 2 defn))
1082 ;; Skip past menu-prompt.
1083 (while (stringp (car-safe defn))
1084 (push (pop defn) skipped))
1085 ;; Skip past cached key-equivalence data for menu items.
1086 (if (consp (car-safe defn))
1087 (setq defn (cdr defn))))
1088 (if (or (eq defn olddef)
1089 ;; Compare with equal if definition is a key sequence.
1090 ;; That is useful for operating on function-key-map.
1091 (and (or (stringp defn) (vectorp defn))
1092 (equal defn olddef)))
1093 (define-key keymap prefix
1095 (let ((copy (copy-sequence menu-item)))
1096 (setcar (nthcdr 2 copy) newdef)
1098 (nconc (nreverse skipped) newdef)))
1099 ;; Look past a symbol that names a keymap.
1101 (or (indirect-function defn) defn))
1102 ;; For nested keymaps, we use `inner-def' rather than `defn' so as to
1103 ;; avoid autoloading a keymap. This is mostly done to preserve the
1104 ;; original non-autoloading behavior of pre-map-keymap times.
1105 (if (and (keymapp inner-def)
1106 ;; Avoid recursively scanning
1107 ;; where KEYMAP does not have a submap.
1108 (let ((elt (lookup-key keymap prefix)))
1109 (or (null elt) (natnump elt) (keymapp elt)))
1110 ;; Avoid recursively rescanning keymap being scanned.
1111 (not (memq inner-def key-substitution-in-progress)))
1112 ;; If this one isn't being scanned already, scan it now.
1113 (substitute-key-definition olddef newdef keymap inner-def prefix)))))
1116 ;;;; The global keymap tree.
1118 ;; global-map, esc-map, and ctl-x-map have their values set up in
1119 ;; keymap.c; we just give them docstrings here.
1121 (defvar global-map nil
1122 "Default global keymap mapping Emacs keyboard input into commands.
1123 The value is a keymap which is usually (but not necessarily) Emacs's
1127 "Default keymap for ESC (meta) commands.
1128 The normal global definition of the character ESC indirects to this keymap.")
1130 (defvar ctl-x-map nil
1131 "Default keymap for C-x commands.
1132 The normal global definition of the character C-x indirects to this keymap.")
1134 (defvar ctl-x-4-map (make-sparse-keymap)
1135 "Keymap for subcommands of C-x 4.")
1136 (defalias 'ctl-x-4-prefix ctl-x-4-map)
1137 (define-key ctl-x-map "4" 'ctl-x-4-prefix)
1139 (defvar ctl-x-5-map (make-sparse-keymap)
1140 "Keymap for frame commands.")
1141 (defalias 'ctl-x-5-prefix ctl-x-5-map)
1142 (define-key ctl-x-map "5" 'ctl-x-5-prefix)
1145 ;;;; Event manipulation functions.
1147 (defconst listify-key-sequence-1 (logior 128 ?\M-\C-@))
1149 (defun listify-key-sequence (key)
1150 "Convert a key sequence to a list of events."
1153 (mapcar (function (lambda (c)
1155 (logxor c listify-key-sequence-1)
1160 "True if the argument is an event object."
1163 (and (symbolp obj) obj (not (keywordp obj)))
1164 (and (consp obj) (symbolp (car obj))))))
1166 (defun event-modifiers (event)
1167 "Return a list of symbols representing the modifier keys in event EVENT.
1168 The elements of the list may include `meta', `control',
1169 `shift', `hyper', `super', `alt', `click', `double', `triple', `drag',
1171 EVENT may be an event or an event type. If EVENT is a symbol
1172 that has never been used in an event that has been read as input
1173 in the current Emacs session, then this function may fail to include
1174 the `click' modifier."
1177 (setq type (car type)))
1179 ;; Don't read event-symbol-elements directly since we're not
1180 ;; sure the symbol has already been parsed.
1181 (cdr (internal-event-symbol-parse-modifiers type))
1183 (char (logand type (lognot (logior ?\M-\^@ ?\C-\^@ ?\S-\^@
1184 ?\H-\^@ ?\s-\^@ ?\A-\^@)))))
1185 (if (not (zerop (logand type ?\M-\^@)))
1187 (if (or (not (zerop (logand type ?\C-\^@)))
1189 (push 'control list))
1190 (if (or (not (zerop (logand type ?\S-\^@)))
1191 (/= char (downcase char)))
1193 (or (zerop (logand type ?\H-\^@))
1195 (or (zerop (logand type ?\s-\^@))
1197 (or (zerop (logand type ?\A-\^@))
1201 (defun event-basic-type (event)
1202 "Return the basic type of the given event (all modifiers removed).
1203 The value is a printing character (not upper case) or a symbol.
1204 EVENT may be an event or an event type. If EVENT is a symbol
1205 that has never been used in an event that has been read as input
1206 in the current Emacs session, then this function may return nil."
1208 (setq event (car event)))
1210 (car (get event 'event-symbol-elements))
1211 (let* ((base (logand event (1- ?\A-\^@)))
1212 (uncontrolled (if (< base 32) (logior base 64) base)))
1213 ;; There are some numbers that are invalid characters and
1214 ;; cause `downcase' to get an error.
1216 (downcase uncontrolled)
1217 (error uncontrolled)))))
1219 (defsubst mouse-movement-p (object)
1220 "Return non-nil if OBJECT is a mouse movement event."
1221 (eq (car-safe object) 'mouse-movement))
1223 (defun mouse-event-p (object)
1224 "Return non-nil if OBJECT is a mouse click event."
1225 ;; is this really correct? maybe remove mouse-movement?
1226 (memq (event-basic-type object) '(mouse-1 mouse-2 mouse-3 mouse-movement)))
1228 (defun event-start (event)
1229 "Return the starting position of EVENT.
1230 EVENT should be a mouse click, drag, or key press event. If
1231 EVENT is nil, the value of `posn-at-point' is used instead.
1233 The following accessor functions are used to access the elements
1236 `posn-window': The window the event is in.
1237 `posn-area': A symbol identifying the area the event occurred in,
1238 or nil if the event occurred in the text area.
1239 `posn-point': The buffer position of the event.
1240 `posn-x-y': The pixel-based coordinates of the event.
1241 `posn-col-row': The estimated column and row corresponding to the
1242 position of the event.
1243 `posn-actual-col-row': The actual column and row corresponding to the
1244 position of the event.
1245 `posn-string': The string object of the event, which is either
1246 nil or (STRING . POSITION)'.
1247 `posn-image': The image object of the event, if any.
1248 `posn-object': The image or string object of the event, if any.
1249 `posn-timestamp': The time the event occurred, in milliseconds.
1251 For more information, see Info node `(elisp)Click Events'."
1252 (if (consp event) (nth 1 event)
1254 (list (selected-window) (point) '(0 . 0) 0))))
1256 (defun event-end (event)
1257 "Return the ending position of EVENT.
1258 EVENT should be a click, drag, or key press event.
1260 See `event-start' for a description of the value returned."
1261 (if (consp event) (nth (if (consp (nth 2 event)) 2 1) event)
1263 (list (selected-window) (point) '(0 . 0) 0))))
1265 (defsubst event-click-count (event)
1266 "Return the multi-click count of EVENT, a click or drag event.
1267 The return value is a positive integer."
1268 (if (and (consp event) (integerp (nth 2 event))) (nth 2 event) 1))
1270 (defsubst event-line-count (event)
1271 "Return the line count of EVENT, a mousewheel event.
1272 The return value is a positive integer."
1273 (if (and (consp event) (integerp (nth 3 event))) (nth 3 event) 1))
1275 ;;;; Extracting fields of the positions in an event.
1278 "Return non-nil if OBJ appears to be a valid `posn' object specifying a window.
1279 A `posn' object is returned from functions such as `event-start'.
1280 If OBJ is a valid `posn' object, but specifies a frame rather
1281 than a window, return nil."
1282 ;; FIXME: Correct the behavior of this function so that all valid
1283 ;; `posn' objects are recognized, after updating other code that
1284 ;; depends on its present behavior.
1285 (and (windowp (car-safe obj))
1286 (atom (car-safe (setq obj (cdr obj)))) ;AREA-OR-POS.
1287 (integerp (car-safe (car-safe (setq obj (cdr obj))))) ;XOFFSET.
1288 (integerp (car-safe (cdr obj))))) ;TIMESTAMP.
1290 (defsubst posn-window (position)
1291 "Return the window in POSITION.
1292 POSITION should be a list of the form returned by the `event-start'
1293 and `event-end' functions."
1296 (defsubst posn-area (position)
1297 "Return the window area recorded in POSITION, or nil for the text area.
1298 POSITION should be a list of the form returned by the `event-start'
1299 and `event-end' functions."
1300 (let ((area (if (consp (nth 1 position))
1301 (car (nth 1 position))
1303 (and (symbolp area) area)))
1305 (defun posn-point (position)
1306 "Return the buffer location in POSITION.
1307 POSITION should be a list of the form returned by the `event-start'
1308 and `event-end' functions.
1309 Returns nil if POSITION does not correspond to any buffer location (e.g.
1310 a click on a scroll bar)."
1311 (or (nth 5 position)
1312 (let ((pt (nth 1 position)))
1314 ;; Apparently this can also be `vertical-scroll-bar' (bug#13979).
1315 (if (integerp pt) pt)))))
1317 (defun posn-set-point (position)
1318 "Move point to POSITION.
1319 Select the corresponding window as well."
1320 (if (not (windowp (posn-window position)))
1321 (error "Position not in text area of window"))
1322 (select-window (posn-window position))
1323 (if (numberp (posn-point position))
1324 (goto-char (posn-point position))))
1326 (defsubst posn-x-y (position)
1327 "Return the x and y coordinates in POSITION.
1328 The return value has the form (X . Y), where X and Y are given in
1329 pixels. POSITION should be a list of the form returned by
1330 `event-start' and `event-end'."
1333 (declare-function scroll-bar-scale "scroll-bar" (num-denom whole))
1335 (defun posn-col-row (position)
1336 "Return the nominal column and row in POSITION, measured in characters.
1337 The column and row values are approximations calculated from the x
1338 and y coordinates in POSITION and the frame's default character width
1339 and default line height, including spacing.
1340 For a scroll-bar event, the result column is 0, and the row
1341 corresponds to the vertical position of the click in the scroll bar.
1342 POSITION should be a list of the form returned by the `event-start'
1343 and `event-end' functions."
1344 (let* ((pair (posn-x-y position))
1345 (frame-or-window (posn-window position))
1346 (frame (if (framep frame-or-window)
1348 (window-frame frame-or-window)))
1349 (window (when (windowp frame-or-window) frame-or-window))
1350 (area (posn-area position)))
1352 ((null frame-or-window)
1354 ((eq area 'vertical-scroll-bar)
1355 (cons 0 (scroll-bar-scale pair (1- (window-height window)))))
1356 ((eq area 'horizontal-scroll-bar)
1357 (cons (scroll-bar-scale pair (window-width window)) 0))
1359 ;; FIXME: This should take line-spacing properties on
1360 ;; newlines into account.
1361 (let* ((spacing (when (display-graphic-p frame)
1362 (or (with-current-buffer
1363 (window-buffer (frame-selected-window frame))
1365 (frame-parameter frame 'line-spacing)))))
1366 (cond ((floatp spacing)
1367 (setq spacing (truncate (* spacing
1368 (frame-char-height frame)))))
1371 (cons (/ (car pair) (frame-char-width frame))
1372 (/ (cdr pair) (+ (frame-char-height frame) spacing))))))))
1374 (defun posn-actual-col-row (position)
1375 "Return the window row number in POSITION and character number in that row.
1377 Return nil if POSITION does not contain the actual position; in that case
1378 `posn-col-row' can be used to get approximate values.
1379 POSITION should be a list of the form returned by the `event-start'
1380 and `event-end' functions.
1382 This function does not account for the width on display, like the
1383 number of visual columns taken by a TAB or image. If you need
1384 the coordinates of POSITION in character units, you should use
1385 `posn-col-row', not this function."
1388 (defsubst posn-timestamp (position)
1389 "Return the timestamp of POSITION.
1390 POSITION should be a list of the form returned by the `event-start'
1391 and `event-end' functions."
1394 (defun posn-string (position)
1395 "Return the string object of POSITION.
1396 Value is a cons (STRING . STRING-POS), or nil if not a string.
1397 POSITION should be a list of the form returned by the `event-start'
1398 and `event-end' functions."
1399 (let ((x (nth 4 position)))
1400 ;; Apparently this can also be `handle' or `below-handle' (bug#13979).
1401 (when (consp x) x)))
1403 (defsubst posn-image (position)
1404 "Return the image object of POSITION.
1405 Value is a list (image ...), or nil if not an image.
1406 POSITION should be a list of the form returned by the `event-start'
1407 and `event-end' functions."
1410 (defsubst posn-object (position)
1411 "Return the object (image or string) of POSITION.
1412 Value is a list (image ...) for an image object, a cons cell
1413 \(STRING . STRING-POS) for a string object, and nil for a buffer position.
1414 POSITION should be a list of the form returned by the `event-start'
1415 and `event-end' functions."
1416 (or (posn-image position) (posn-string position)))
1418 (defsubst posn-object-x-y (position)
1419 "Return the x and y coordinates relative to the object of POSITION.
1420 The return value has the form (DX . DY), where DX and DY are
1421 given in pixels. POSITION should be a list of the form returned
1422 by `event-start' and `event-end'."
1425 (defsubst posn-object-width-height (position)
1426 "Return the pixel width and height of the object of POSITION.
1427 The return value has the form (WIDTH . HEIGHT). POSITION should
1428 be a list of the form returned by `event-start' and `event-end'."
1432 ;;;; Obsolescent names for functions.
1434 (make-obsolete 'forward-point "use (+ (point) N) instead." "23.1")
1435 (make-obsolete 'buffer-has-markers-at nil "24.3")
1437 (make-obsolete 'invocation-directory "use the variable of the same name."
1439 (make-obsolete 'invocation-name "use the variable of the same name." "27.1")
1442 (make-obsolete 'string-to-unibyte "use `encode-coding-string'." "26.1")
1443 (make-obsolete 'string-as-unibyte "use `encode-coding-string'." "26.1")
1444 (make-obsolete 'string-make-unibyte "use `encode-coding-string'." "26.1")
1445 (make-obsolete 'string-to-multibyte "use `decode-coding-string'." "26.1")
1446 (make-obsolete 'string-as-multibyte "use `decode-coding-string'." "26.1")
1447 (make-obsolete 'string-make-multibyte "use `decode-coding-string'." "26.1")
1450 "Return (log X 10), the log base 10 of X."
1451 (declare (obsolete log "24.4"))
1454 (set-advertised-calling-convention
1455 'all-completions '(string collection &optional predicate) "23.1")
1456 (set-advertised-calling-convention 'unintern '(name obarray) "23.3")
1457 (set-advertised-calling-convention 'indirect-function '(object) "25.1")
1458 (set-advertised-calling-convention 'redirect-frame-focus '(frame focus-frame) "24.3")
1459 (set-advertised-calling-convention 'libxml-parse-xml-region '(start end base-url) "27.1")
1460 (set-advertised-calling-convention 'libxml-parse-html-region '(start end base-url) "27.1")
1462 ;;;; Obsolescence declarations for variables, and aliases.
1464 (make-obsolete-variable 'define-key-rebound-commands nil "23.2")
1465 (make-obsolete-variable 'redisplay-end-trigger-functions 'jit-lock-register "23.1")
1466 (make-obsolete-variable 'deferred-action-list 'post-command-hook "24.1")
1467 (make-obsolete-variable 'deferred-action-function 'post-command-hook "24.1")
1468 (make-obsolete-variable 'redisplay-dont-pause nil "24.5")
1469 (make-obsolete 'window-redisplay-end-trigger nil "23.1")
1470 (make-obsolete 'set-window-redisplay-end-trigger nil "23.1")
1472 (make-obsolete 'process-filter-multibyte-p nil "23.1")
1473 (make-obsolete 'set-process-filter-multibyte nil "23.1")
1475 (make-obsolete-variable 'command-debug-status
1476 "expect it to be removed in a future version." "25.2")
1478 ;; This was introduced in 21.4 for pre-unicode unification. That
1479 ;; usage was rendered obsolete in 23.1 which uses Unicode internally.
1480 ;; Other uses are possible, so this variable is not _really_ obsolete,
1481 ;; but Stefan insists to mark it so.
1482 (make-obsolete-variable 'translation-table-for-input nil "23.1")
1484 (make-obsolete-variable 'x-gtk-use-window-move nil "26.1")
1486 (defvaralias 'messages-buffer-max-lines 'message-log-max)
1488 ;;;; Alternate names for functions - these are not being phased out.
1490 (defalias 'send-string 'process-send-string)
1491 (defalias 'send-region 'process-send-region)
1492 (defalias 'string= 'string-equal)
1493 (defalias 'string< 'string-lessp)
1494 (defalias 'string> 'string-greaterp)
1495 (defalias 'move-marker 'set-marker)
1496 (defalias 'rplaca 'setcar)
1497 (defalias 'rplacd 'setcdr)
1498 (defalias 'beep 'ding) ;preserve lingual purity
1499 (defalias 'indent-to-column 'indent-to)
1500 (defalias 'backward-delete-char 'delete-backward-char)
1501 (defalias 'search-forward-regexp (symbol-function 're-search-forward))
1502 (defalias 'search-backward-regexp (symbol-function 're-search-backward))
1503 (defalias 'int-to-string 'number-to-string)
1504 (defalias 'store-match-data 'set-match-data)
1505 (defalias 'chmod 'set-file-modes)
1506 (defalias 'mkdir 'make-directory)
1507 ;; These are the XEmacs names:
1508 (defalias 'point-at-eol 'line-end-position)
1509 (defalias 'point-at-bol 'line-beginning-position)
1511 (defalias 'user-original-login-name 'user-login-name)
1514 ;;;; Hook manipulation functions.
1516 (defun add-hook (hook function &optional append local)
1517 "Add to the value of HOOK the function FUNCTION.
1518 FUNCTION is not added if already present.
1519 FUNCTION is added (if necessary) at the beginning of the hook list
1520 unless the optional argument APPEND is non-nil, in which case
1521 FUNCTION is added at the end.
1523 The optional fourth argument, LOCAL, if non-nil, says to modify
1524 the hook's buffer-local value rather than its global value.
1525 This makes the hook buffer-local, and it makes t a member of the
1526 buffer-local value. That acts as a flag to run the hook
1527 functions of the global value as well as in the local value.
1529 HOOK should be a symbol, and FUNCTION may be any valid function. If
1530 HOOK is void, it is first set to nil. If HOOK's value is a single
1531 function, it is changed to a list of functions."
1532 (or (boundp hook) (set hook nil))
1533 (or (default-boundp hook) (set-default hook nil))
1534 (if local (unless (local-variable-if-set-p hook)
1535 (set (make-local-variable hook) (list t)))
1536 ;; Detect the case where make-local-variable was used on a hook
1537 ;; and do what we used to do.
1538 (unless (and (consp (symbol-value hook)) (memq t (symbol-value hook)))
1540 (let ((hook-value (if local (symbol-value hook) (default-value hook))))
1541 ;; If the hook value is a single function, turn it into a list.
1542 (when (or (not (listp hook-value)) (functionp hook-value))
1543 (setq hook-value (list hook-value)))
1544 ;; Do the actual addition if necessary
1545 (unless (member function hook-value)
1546 (when (stringp function)
1547 (setq function (purecopy function)))
1550 (append hook-value (list function))
1551 (cons function hook-value))))
1552 ;; Set the actual variable
1555 ;; If HOOK isn't a permanent local,
1556 ;; but FUNCTION wants to survive a change of modes,
1557 ;; mark HOOK as partially permanent.
1558 (and (symbolp function)
1559 (get function 'permanent-local-hook)
1560 (not (get hook 'permanent-local))
1561 (put hook 'permanent-local 'permanent-local-hook))
1562 (set hook hook-value))
1563 (set-default hook hook-value))))
1565 (defun remove-hook (hook function &optional local)
1566 "Remove from the value of HOOK the function FUNCTION.
1567 HOOK should be a symbol, and FUNCTION may be any valid function. If
1568 FUNCTION isn't the value of HOOK, or, if FUNCTION doesn't appear in the
1569 list of hooks to run in HOOK, then nothing is done. See `add-hook'.
1571 The optional third argument, LOCAL, if non-nil, says to modify
1572 the hook's buffer-local value rather than its default value."
1573 (or (boundp hook) (set hook nil))
1574 (or (default-boundp hook) (set-default hook nil))
1575 ;; Do nothing if LOCAL is t but this hook has no local binding.
1576 (unless (and local (not (local-variable-p hook)))
1577 ;; Detect the case where make-local-variable was used on a hook
1578 ;; and do what we used to do.
1579 (when (and (local-variable-p hook)
1580 (not (and (consp (symbol-value hook))
1581 (memq t (symbol-value hook)))))
1583 (let ((hook-value (if local (symbol-value hook) (default-value hook))))
1584 ;; Remove the function, for both the list and the non-list cases.
1585 (if (or (not (listp hook-value)) (eq (car hook-value) 'lambda))
1586 (if (equal hook-value function) (setq hook-value nil))
1587 (setq hook-value (delete function (copy-sequence hook-value))))
1588 ;; If the function is on the global hook, we need to shadow it locally
1589 ;;(when (and local (member function (default-value hook))
1590 ;; (not (member (cons 'not function) hook-value)))
1591 ;; (push (cons 'not function) hook-value))
1592 ;; Set the actual variable
1594 (set-default hook hook-value)
1595 (if (equal hook-value '(t))
1596 (kill-local-variable hook)
1597 (set hook hook-value))))))
1599 (defmacro letrec (binders &rest body)
1600 "Bind variables according to BINDERS then eval BODY.
1601 The value of the last form in BODY is returned.
1602 Each element of BINDERS is a list (SYMBOL VALUEFORM) which binds
1603 SYMBOL to the value of VALUEFORM.
1604 All symbols are bound before the VALUEFORMs are evalled."
1605 ;; Only useful in lexical-binding mode.
1606 ;; As a special-form, we could implement it more efficiently (and cleanly,
1607 ;; making the vars actually unbound during evaluation of the binders).
1608 (declare (debug let) (indent 1))
1609 `(let ,(mapcar #'car binders)
1610 ,@(mapcar (lambda (binder) `(setq ,@binder)) binders)
1613 (defmacro with-wrapper-hook (hook args &rest body)
1614 "Run BODY, using wrapper functions from HOOK with additional ARGS.
1615 HOOK is an abnormal hook. Each hook function in HOOK \"wraps\"
1616 around the preceding ones, like a set of nested `around' advices.
1618 Each hook function should accept an argument list consisting of a
1619 function FUN, followed by the additional arguments in ARGS.
1621 The first hook function in HOOK is passed a FUN that, if it is called
1622 with arguments ARGS, performs BODY (i.e., the default operation).
1623 The FUN passed to each successive hook function is defined based
1624 on the preceding hook functions; if called with arguments ARGS,
1625 it does what the `with-wrapper-hook' call would do if the
1626 preceding hook functions were the only ones present in HOOK.
1628 Each hook function may call its FUN argument as many times as it wishes,
1629 including never. In that case, such a hook function acts to replace
1630 the default definition altogether, and any preceding hook functions.
1631 Of course, a subsequent hook function may do the same thing.
1633 Each hook function definition is used to construct the FUN passed
1634 to the next hook function, if any. The last (or \"outermost\")
1635 FUN is then called once."
1636 (declare (indent 2) (debug (form sexp body))
1637 (obsolete "use a <foo>-function variable modified by `add-function'."
1639 `(subr--with-wrapper-hook-no-warnings ,hook ,args ,@body))
1641 (defmacro subr--with-wrapper-hook-no-warnings (hook args &rest body)
1642 "Like (with-wrapper-hook HOOK ARGS BODY), but without warnings."
1643 ;; We need those two gensyms because CL's lexical scoping is not available
1644 ;; for function arguments :-(
1645 (let ((funs (make-symbol "funs"))
1646 (global (make-symbol "global"))
1647 (argssym (make-symbol "args"))
1648 (runrestofhook (make-symbol "runrestofhook")))
1649 ;; Since the hook is a wrapper, the loop has to be done via
1650 ;; recursion: a given hook function will call its parameter in order to
1651 ;; continue looping.
1652 `(letrec ((,runrestofhook
1653 (lambda (,funs ,global ,argssym)
1654 ;; `funs' holds the functions left on the hook and `global'
1655 ;; holds the functions left on the global part of the hook
1656 ;; (in case the hook is local).
1658 (if (eq t (car ,funs))
1659 (funcall ,runrestofhook
1660 (append ,global (cdr ,funs)) nil ,argssym)
1663 (lambda (,funs ,global &rest ,argssym)
1664 (funcall ,runrestofhook ,funs ,global ,argssym))
1665 (cdr ,funs) ,global)
1667 ;; Once there are no more functions on the hook, run
1668 ;; the original body.
1669 (apply (lambda ,args ,@body) ,argssym)))))
1670 (funcall ,runrestofhook ,hook
1671 ;; The global part of the hook, if any.
1673 `(if (local-variable-p ',hook)
1674 (default-value ',hook)))
1677 (defun add-to-list (list-var element &optional append compare-fn)
1678 "Add ELEMENT to the value of LIST-VAR if it isn't there yet.
1679 The test for presence of ELEMENT is done with `equal', or with
1680 COMPARE-FN if that's non-nil.
1681 If ELEMENT is added, it is added at the beginning of the list,
1682 unless the optional argument APPEND is non-nil, in which case
1683 ELEMENT is added at the end.
1685 The return value is the new value of LIST-VAR.
1687 This is handy to add some elements to configuration variables,
1688 but please do not abuse it in Elisp code, where you are usually
1689 better off using `push' or `cl-pushnew'.
1691 If you want to use `add-to-list' on a variable that is not
1692 defined until a certain package is loaded, you should put the
1693 call to `add-to-list' into a hook function that will be run only
1694 after loading the package. `eval-after-load' provides one way to
1695 do this. In some cases other hooks, such as major mode hooks,
1700 ;; FIXME: Something like this could be used for `set' as well.
1701 (if (or (not (eq 'quote (car-safe list-var)))
1702 (special-variable-p (cadr list-var))
1703 (not (macroexp-const-p append)))
1705 (let* ((sym (cadr list-var))
1706 (append (eval append))
1707 (msg (format-message
1708 "`add-to-list' can't use lexical var `%s'; use `push' or `cl-pushnew'"
1710 ;; Big ugly hack so we only output a warning during
1711 ;; byte-compilation, and so we can use
1712 ;; byte-compile-not-lexical-var-p to silence the warning
1713 ;; when a defvar has been seen but not yet executed.
1715 ;; FIXME: We should also emit a warning for let-bound
1716 ;; variables with dynamic binding.
1717 (when (assq sym byte-compile--lexical-environment)
1718 (byte-compile-report-error msg :fill))))
1720 (macroexp-let2 macroexp-copyable-p x element
1721 `(if ,(if compare-fn
1724 `(cl-member ,x ,sym :test ,compare-fn))
1725 ;; For bootstrapping reasons, don't rely on
1726 ;; cl--compiler-macro-member for the base case.
1730 `(setq ,sym (append ,sym (list ,x)))
1731 `(push ,x ,sym))))))
1732 (if (not (macroexp--compiling-p))
1735 (macroexp--funcall-if-compiled ',warnfun)
1739 (member element (symbol-value list-var)))
1740 ((eq compare-fn 'eq)
1741 (memq element (symbol-value list-var)))
1742 ((eq compare-fn 'eql)
1743 (memql element (symbol-value list-var)))
1745 (let ((lst (symbol-value list-var)))
1747 (not (funcall compare-fn element (car lst))))
1748 (setq lst (cdr lst)))
1750 (symbol-value list-var)
1753 (append (symbol-value list-var) (list element))
1754 (cons element (symbol-value list-var))))))
1757 (defun add-to-ordered-list (list-var element &optional order)
1758 "Add ELEMENT to the value of LIST-VAR if it isn't there yet.
1759 The test for presence of ELEMENT is done with `eq'.
1761 The resulting list is reordered so that the elements are in the
1762 order given by each element's numeric list order. Elements
1763 without a numeric list order are placed at the end of the list.
1765 If the third optional argument ORDER is a number (integer or
1766 float), set the element's list order to the given value. If
1767 ORDER is nil or omitted, do not change the numeric order of
1768 ELEMENT. If ORDER has any other value, remove the numeric order
1769 of ELEMENT if it has one.
1771 The list order for each element is stored in LIST-VAR's
1772 `list-order' property.
1774 The return value is the new value of LIST-VAR."
1775 (let ((ordering (get list-var 'list-order)))
1777 (put list-var 'list-order
1778 (setq ordering (make-hash-table :weakness 'key :test 'eq))))
1780 (puthash element (and (numberp order) order) ordering))
1781 (unless (memq element (symbol-value list-var))
1782 (set list-var (cons element (symbol-value list-var))))
1783 (set list-var (sort (symbol-value list-var)
1785 (let ((oa (gethash a ordering))
1786 (ob (gethash b ordering)))
1791 (defun add-to-history (history-var newelt &optional maxelt keep-all)
1792 "Add NEWELT to the history list stored in the variable HISTORY-VAR.
1793 Return the new history list.
1794 If MAXELT is non-nil, it specifies the maximum length of the history.
1795 Otherwise, the maximum history length is the value of the `history-length'
1796 property on symbol HISTORY-VAR, if set, or the value of the `history-length'
1797 variable. The possible values of maximum length have the same meaning as
1798 the values of `history-length'.
1799 Remove duplicates of NEWELT if `history-delete-duplicates' is non-nil.
1800 If optional fourth arg KEEP-ALL is non-nil, add NEWELT to history even
1801 if it is empty or a duplicate."
1803 (setq maxelt (or (get history-var 'history-length)
1805 (let ((history (symbol-value history-var))
1807 (when (and (listp history)
1809 (not (stringp newelt))
1810 (> (length newelt) 0))
1812 (not (equal (car history) newelt))))
1813 (if history-delete-duplicates
1814 (setq history (delete newelt history)))
1815 (setq history (cons newelt history))
1816 (when (integerp maxelt)
1819 (setq tail (nthcdr (1- maxelt) history))
1821 (setcdr tail nil)))))
1822 (set history-var history)))
1827 (defvar delay-mode-hooks nil
1828 "If non-nil, `run-mode-hooks' should delay running the hooks.")
1829 (defvar-local delayed-mode-hooks nil
1830 "List of delayed mode hooks waiting to be run.")
1831 (put 'delay-mode-hooks 'permanent-local t)
1833 (defvar-local delayed-after-hook-functions nil
1834 "List of delayed :after-hook forms waiting to be run.
1835 These forms come from `define-derived-mode'.")
1837 (defvar change-major-mode-after-body-hook nil
1838 "Normal hook run in major mode functions, before the mode hooks.")
1840 (defvar after-change-major-mode-hook nil
1841 "Normal hook run at the very end of major mode functions.")
1843 (defun run-mode-hooks (&rest hooks)
1844 "Run mode hooks `delayed-mode-hooks' and HOOKS, or delay HOOKS.
1845 Call `hack-local-variables' to set up file local and directory local
1848 If the variable `delay-mode-hooks' is non-nil, does not do anything,
1849 just adds the HOOKS to the list `delayed-mode-hooks'.
1850 Otherwise, runs hooks in the sequence: `change-major-mode-after-body-hook',
1851 `delayed-mode-hooks' (in reverse order), HOOKS, then runs
1852 `hack-local-variables', runs the hook `after-change-major-mode-hook', and
1853 finally evaluates the functions in `delayed-after-hook-functions' (see
1854 `define-derived-mode').
1856 Major mode functions should use this instead of `run-hooks' when
1857 running their FOO-mode-hook."
1858 (if delay-mode-hooks
1860 (dolist (hook hooks)
1861 (push hook delayed-mode-hooks))
1862 ;; Normal case, just run the hook as before plus any delayed hooks.
1863 (setq hooks (nconc (nreverse delayed-mode-hooks) hooks))
1864 (and syntax-propertize-function
1865 (not (local-variable-p 'parse-sexp-lookup-properties))
1866 ;; `syntax-propertize' sets `parse-sexp-lookup-properties' for us, but
1867 ;; in order for the sexp primitives to automatically call
1868 ;; `syntax-propertize' we need `parse-sexp-lookup-properties' to be
1870 (setq-local parse-sexp-lookup-properties t))
1871 (setq delayed-mode-hooks nil)
1872 (apply #'run-hooks (cons 'change-major-mode-after-body-hook hooks))
1873 (if (buffer-file-name)
1874 (with-demoted-errors "File local-variables error: %s"
1875 (hack-local-variables 'no-mode)))
1876 (run-hooks 'after-change-major-mode-hook)
1877 (dolist (fun (prog1 (nreverse delayed-after-hook-functions)
1878 (setq delayed-after-hook-functions nil)))
1881 (defmacro delay-mode-hooks (&rest body)
1882 "Execute BODY, but delay any `run-mode-hooks'.
1883 These hooks will be executed by the first following call to
1884 `run-mode-hooks' that occurs outside any `delay-mode-hooks' form.
1885 Only affects hooks run in the current buffer."
1886 (declare (debug t) (indent 0))
1888 (make-local-variable 'delay-mode-hooks)
1889 (let ((delay-mode-hooks t))
1892 ;; PUBLIC: find if the current mode derives from another.
1894 (defun provided-mode-derived-p (mode &rest modes)
1895 "Non-nil if MODE is derived from one of MODES.
1896 Uses the `derived-mode-parent' property of the symbol to trace backwards.
1897 If you just want to check `major-mode', use `derived-mode-p'."
1898 (while (and (not (memq mode modes))
1899 (setq mode (get mode 'derived-mode-parent))))
1902 (defun derived-mode-p (&rest modes)
1903 "Non-nil if the current major mode is derived from one of MODES.
1904 Uses the `derived-mode-parent' property of the symbol to trace backwards."
1905 (apply #'provided-mode-derived-p major-mode modes))
1909 ;; If a minor mode is not defined with define-minor-mode,
1910 ;; add it here explicitly.
1911 ;; isearch-mode is deliberately excluded, since you should
1912 ;; not call it yourself.
1913 (defvar minor-mode-list '(auto-save-mode auto-fill-mode abbrev-mode
1914 overwrite-mode view-mode
1916 "List of all minor mode functions.")
1918 (defun add-minor-mode (toggle name &optional keymap after toggle-fun)
1919 "Register a new minor mode.
1921 This is an XEmacs-compatibility function. Use `define-minor-mode' instead.
1923 TOGGLE is a symbol which is the name of a buffer-local variable that
1924 is toggled on or off to say whether the minor mode is active or not.
1926 NAME specifies what will appear in the mode line when the minor mode
1927 is active. NAME should be either a string starting with a space, or a
1928 symbol whose value is such a string.
1930 Optional KEYMAP is the keymap for the minor mode that will be added
1931 to `minor-mode-map-alist'.
1933 Optional AFTER specifies that TOGGLE should be added after AFTER
1934 in `minor-mode-alist'.
1936 Optional TOGGLE-FUN is an interactive function to toggle the mode.
1937 It defaults to (and should by convention be) TOGGLE.
1939 If TOGGLE has a non-nil `:included' property, an entry for the mode is
1940 included in the mode-line minor mode menu.
1941 If TOGGLE has a `:menu-tag', that is used for the menu item's label."
1942 (unless (memq toggle minor-mode-list)
1943 (push toggle minor-mode-list))
1945 (unless toggle-fun (setq toggle-fun toggle))
1946 (unless (eq toggle-fun toggle)
1947 (put toggle :minor-mode-function toggle-fun))
1948 ;; Add the name to the minor-mode-alist.
1950 (let ((existing (assq toggle minor-mode-alist)))
1952 (setcdr existing (list name))
1953 (let ((tail minor-mode-alist) found)
1954 (while (and tail (not found))
1955 (if (eq after (caar tail))
1957 (setq tail (cdr tail))))
1959 (let ((rest (cdr found)))
1961 (nconc found (list (list toggle name)) rest))
1962 (push (list toggle name) minor-mode-alist))))))
1963 ;; Add the toggle to the minor-modes menu if requested.
1964 (when (get toggle :included)
1965 (define-key mode-line-mode-menu
1969 (or (get toggle :menu-tag)
1970 (if (stringp name) name (symbol-name toggle)))
1971 (let ((mode-name (if (symbolp name) (symbol-value name))))
1972 (if (and (stringp mode-name) (string-match "[^ ]+" mode-name))
1973 (concat " (" (match-string 0 mode-name) ")"))))
1975 :button (cons :toggle toggle))))
1977 ;; Add the map to the minor-mode-map-alist.
1979 (let ((existing (assq toggle minor-mode-map-alist)))
1981 (setcdr existing keymap)
1982 (let ((tail minor-mode-map-alist) found)
1983 (while (and tail (not found))
1984 (if (eq after (caar tail))
1986 (setq tail (cdr tail))))
1988 (let ((rest (cdr found)))
1990 (nconc found (list (cons toggle keymap)) rest))
1991 (push (cons toggle keymap) minor-mode-map-alist)))))))
1995 (defsubst autoloadp (object)
1996 "Non-nil if OBJECT is an autoload."
1997 (eq 'autoload (car-safe object)))
1999 ;; (defun autoload-type (object)
2000 ;; "Returns the type of OBJECT or `function' or `command' if the type is nil.
2001 ;; OBJECT should be an autoload object."
2002 ;; (when (autoloadp object)
2003 ;; (let ((type (nth 3 object)))
2004 ;; (cond ((null type) (if (nth 2 object) 'command 'function))
2005 ;; ((eq 'keymap t) 'macro)
2008 ;; (defalias 'autoload-file #'cadr
2009 ;; "Return the name of the file from which AUTOLOAD will be loaded.
2010 ;; \n\(fn AUTOLOAD)")
2012 (defun define-symbol-prop (symbol prop val)
2013 "Define the property PROP of SYMBOL to be VAL.
2014 This is to `put' what `defalias' is to `fset'."
2015 ;; Can't use `cl-pushnew' here (nor `push' on (cdr foo)).
2016 ;; (cl-pushnew symbol (alist-get prop
2017 ;; (alist-get 'define-symbol-props
2018 ;; current-load-list)))
2019 (let ((sps (assq 'define-symbol-props current-load-list)))
2021 (setq sps (list 'define-symbol-props))
2022 (push sps current-load-list))
2023 (let ((ps (assq prop sps)))
2025 (setq ps (list prop))
2026 (setcdr sps (cons ps (cdr sps))))
2027 (unless (member symbol (cdr ps))
2028 (setcdr ps (cons symbol (cdr ps))))))
2029 (put symbol prop val))
2031 (defun symbol-file (symbol &optional type)
2032 "Return the name of the file that defined SYMBOL.
2033 The value is normally an absolute file name. It can also be nil,
2034 if the definition is not associated with any file. If SYMBOL
2035 specifies an autoloaded function, the value can be a relative
2036 file name without extension.
2038 If TYPE is nil, then any kind of definition is acceptable. If
2039 TYPE is `defun', `defvar', or `defface', that specifies function
2040 definition, variable definition, or face definition only.
2041 Otherwise TYPE is assumed to be a symbol property."
2042 (if (and (or (null type) (eq type 'defun))
2044 (autoloadp (symbol-function symbol)))
2045 (nth 1 (symbol-function symbol))
2047 (pcase-dolist (`(,file . ,elems) load-history)
2049 (if (eq type 'defvar)
2050 ;; Variables are present just as their names.
2051 (member symbol elems)
2052 ;; Many other types are represented as (TYPE . NAME).
2053 (or (member (cons type symbol) elems)
2054 (memq symbol (alist-get type
2055 (alist-get 'define-symbol-props
2057 ;; We accept all types, so look for variable def
2058 ;; and then for any other kind.
2059 (or (member symbol elems)
2060 (let ((match (rassq symbol elems)))
2062 (not (eq 'require (car match)))))))
2063 (throw 'found file))))))
2065 (defun locate-library (library &optional nosuffix path interactive-call)
2066 "Show the precise file name of Emacs library LIBRARY.
2067 LIBRARY should be a relative file name of the library, a string.
2068 It can omit the suffix (a.k.a. file-name extension) if NOSUFFIX is
2069 nil (which is the default, see below).
2070 This command searches the directories in `load-path' like `\\[load-library]'
2071 to find the file that `\\[load-library] RET LIBRARY RET' would load.
2072 Optional second arg NOSUFFIX non-nil means don't add suffixes `load-suffixes'
2073 to the specified name LIBRARY.
2075 If the optional third arg PATH is specified, that list of directories
2076 is used instead of `load-path'.
2078 When called from a program, the file name is normally returned as a
2079 string. When run interactively, the argument INTERACTIVE-CALL is t,
2080 and the file name is displayed in the echo area."
2081 (interactive (list (completing-read "Locate library: "
2083 'locate-file-completion-table
2084 load-path (get-load-suffixes)))
2087 (let ((file (locate-file library
2089 (append (unless nosuffix (get-load-suffixes))
2090 load-file-rep-suffixes))))
2091 (if interactive-call
2093 (message "Library is file %s" (abbreviate-file-name file))
2094 (message "No library %s in search path" library)))
2100 (defun start-process (name buffer program &rest program-args)
2101 "Start a program in a subprocess. Return the process object for it.
2102 NAME is name for process. It is modified if necessary to make it unique.
2103 BUFFER is the buffer (or buffer name) to associate with the process.
2105 Process output (both standard output and standard error streams)
2106 goes at end of BUFFER, unless you specify a filter function to
2107 handle the output. BUFFER may also be nil, meaning that this
2108 process is not associated with any buffer.
2110 PROGRAM is the program file name. It is searched for in `exec-path'
2111 \(which see). If nil, just associate a pty with the buffer. Remaining
2112 arguments PROGRAM-ARGS are strings to give program as arguments.
2114 If you want to separate standard output from standard error, use
2115 `make-process' or invoke the command through a shell and redirect
2116 one of them using the shell syntax.
2118 The process runs in `default-directory' if that is local (as
2119 determined by `unhandled-file-name-directory'), or \"~\"
2120 otherwise. If you want to run a process in a remote directory
2121 use `start-file-process'."
2122 (unless (fboundp 'make-process)
2123 (error "Emacs was compiled without subprocess support"))
2124 (apply #'make-process
2125 (append (list :name name :buffer buffer)
2127 (list :command (cons program program-args))))))
2129 (defun process-lines (program &rest args)
2130 "Execute PROGRAM with ARGS, returning its output as a list of lines.
2131 Signal an error if the program returns with a non-zero exit status."
2133 (let ((status (apply 'call-process program nil (current-buffer) nil args)))
2134 (unless (eq status 0)
2135 (error "%s exited with status %s" program status))
2136 (goto-char (point-min))
2139 (setq lines (cons (buffer-substring-no-properties
2140 (line-beginning-position)
2141 (line-end-position))
2144 (nreverse lines)))))
2146 (defun process-live-p (process)
2147 "Returns non-nil if PROCESS is alive.
2148 A process is considered alive if its status is `run', `open',
2149 `listen', `connect' or `stop'. Value is nil if PROCESS is not a
2151 (and (processp process)
2152 (memq (process-status process)
2153 '(run open listen connect stop))))
2155 (defun process-kill-buffer-query-function ()
2156 "Ask before killing a buffer that has a running process."
2157 (let ((process (get-buffer-process (current-buffer))))
2159 (not (memq (process-status process) '(run stop open listen)))
2160 (not (process-query-on-exit-flag process))
2162 (format "Buffer %S has a running process; kill it? "
2163 (buffer-name (current-buffer)))))))
2165 (add-hook 'kill-buffer-query-functions 'process-kill-buffer-query-function)
2167 ;; process plist management
2169 (defun process-get (process propname)
2170 "Return the value of PROCESS' PROPNAME property.
2171 This is the last value stored with `(process-put PROCESS PROPNAME VALUE)'."
2172 (plist-get (process-plist process) propname))
2174 (defun process-put (process propname value)
2175 "Change PROCESS' PROPNAME property to VALUE.
2176 It can be retrieved with `(process-get PROCESS PROPNAME)'."
2177 (set-process-plist process
2178 (plist-put (process-plist process) propname value)))
2181 ;;;; Input and display facilities.
2183 (defconst read-key-empty-map (make-sparse-keymap))
2185 (defvar read-key-delay 0.01) ;Fast enough for 100Hz repeat rate, hopefully.
2187 (defun read-key (&optional prompt)
2188 "Read a key from the keyboard.
2189 Contrary to `read-event' this will not return a raw event but instead will
2190 obey the input decoding and translations usually done by `read-key-sequence'.
2191 So escape sequences and keyboard encoding are taken into account.
2192 When there's an ambiguity because the key looks like the prefix of
2193 some sort of escape sequence, the ambiguity is resolved via `read-key-delay'."
2194 ;; This overriding-terminal-local-map binding also happens to
2195 ;; disable quail's input methods, so although read-key-sequence
2196 ;; always inherits the input method, in practice read-key does not
2197 ;; inherit the input method (at least not if it's based on quail).
2198 (let ((overriding-terminal-local-map nil)
2199 (overriding-local-map read-key-empty-map)
2201 (old-global-map (current-global-map))
2202 (timer (run-with-idle-timer
2203 ;; Wait long enough that Emacs has the time to receive and
2204 ;; process all the raw events associated with the single-key.
2205 ;; But don't wait too long, or the user may find the delay
2206 ;; annoying (or keep hitting more keys which may then get
2207 ;; lost or misinterpreted).
2208 ;; This is only relevant for keys which Emacs perceives as
2209 ;; "prefixes", such as C-x (because of the C-x 8 map in
2210 ;; key-translate-table and the C-x @ map in function-key-map)
2211 ;; or ESC (because of terminal escape sequences in
2212 ;; input-decode-map).
2215 (let ((keys (this-command-keys-vector)))
2216 (unless (zerop (length keys))
2217 ;; `keys' is non-empty, so the user has hit at least
2218 ;; one key; there's no point waiting any longer, even
2219 ;; though read-key-sequence thinks we should wait
2220 ;; for more input to decide how to interpret the
2222 (throw 'read-key keys)))))))
2226 (let ((map (make-sparse-keymap)))
2227 ;; Don't hide the menu-bar and tool-bar entries.
2228 (define-key map [menu-bar] (lookup-key global-map [menu-bar]))
2229 (define-key map [tool-bar]
2230 ;; This hack avoids evaluating the :filter (Bug#9922).
2231 (or (cdr (assq 'tool-bar global-map))
2232 (lookup-key global-map [tool-bar])))
2235 (catch 'read-key (read-key-sequence-vector prompt nil t)))
2236 (key (aref keys 0)))
2237 (if (and (> (length keys) 1)
2238 (memq key '(mode-line header-line
2239 left-fringe right-fringe)))
2242 (cancel-timer timer)
2243 ;; For some reason, `read-key(-sequence)' leaves the prompt in the echo
2244 ;; area, whereas `read-event' seems to empty it just before returning
2245 ;; (bug#22714). So, let's mimic the behavior of `read-event'.
2247 (use-global-map old-global-map))))
2249 (defvar read-passwd-map
2250 ;; BEWARE: `defconst' would purecopy it, breaking the sharing with
2251 ;; minibuffer-local-map along the way!
2252 (let ((map (make-sparse-keymap)))
2253 (set-keymap-parent map minibuffer-local-map)
2254 (define-key map "\C-u" #'delete-minibuffer-contents) ;bug#12570
2256 "Keymap used while reading passwords.")
2258 (defun read-passwd (prompt &optional confirm default)
2259 "Read a password, prompting with PROMPT, and return it.
2260 If optional CONFIRM is non-nil, read the password twice to make sure.
2261 Optional DEFAULT is a default password to use instead of empty input.
2263 This function echoes `.' for each character that the user types.
2264 You could let-bind `read-hide-char' to another hiding character, though.
2266 Once the caller uses the password, it can erase the password
2267 by doing (clear-string STRING)."
2270 (while (not success)
2271 (let ((first (read-passwd prompt nil default))
2272 (second (read-passwd "Confirm password: " nil default)))
2273 (if (equal first second)
2275 (and (arrayp second) (not (eq first second)) (clear-string second))
2276 (setq success first))
2277 (and (arrayp first) (clear-string first))
2278 (and (arrayp second) (clear-string second))
2279 (message "Password not repeated accurately; please start over")
2282 (let ((hide-chars-fun
2283 (lambda (beg end _len)
2284 (clear-this-command-keys)
2285 (setq beg (min end (max (minibuffer-prompt-end)
2287 (dotimes (i (- end beg))
2288 (put-text-property (+ i beg) (+ 1 i beg)
2289 'display (string (or read-hide-char ?.))))))
2291 (minibuffer-with-setup-hook
2293 (setq minibuf (current-buffer))
2294 ;; Turn off electricity.
2295 (setq-local post-self-insert-hook nil)
2296 (setq-local buffer-undo-list t)
2297 (setq-local select-active-regions nil)
2298 (use-local-map read-passwd-map)
2299 (setq-local inhibit-modification-hooks nil) ;bug#15501.
2300 (setq-local show-paren-mode nil) ;bug#16091.
2301 (add-hook 'after-change-functions hide-chars-fun nil 'local))
2303 (let ((enable-recursive-minibuffers t)
2304 (read-hide-char (or read-hide-char ?.)))
2305 (read-string prompt nil t default)) ; t = "no history"
2306 (when (buffer-live-p minibuf)
2307 (with-current-buffer minibuf
2308 ;; Not sure why but it seems that there might be cases where the
2309 ;; minibuffer is not always properly reset later on, so undo
2310 ;; whatever we've done here (bug#11392).
2311 (remove-hook 'after-change-functions hide-chars-fun 'local)
2312 (kill-local-variable 'post-self-insert-hook)
2313 ;; And of course, don't keep the sensitive data around.
2314 (erase-buffer))))))))
2316 (defun read-number (prompt &optional default)
2317 "Read a numeric value in the minibuffer, prompting with PROMPT.
2318 DEFAULT specifies a default value to return if the user just types RET.
2319 The value of DEFAULT is inserted into PROMPT.
2320 This function is used by the `interactive' code letter `n'."
2322 (default1 (if (consp default) (car default) default)))
2325 (if (string-match "\\(\\):[ \t]*\\'" prompt)
2326 (replace-match (format " (default %s)" default1) t t prompt 1)
2327 (replace-regexp-in-string "[ \t]*\\'"
2328 (format " (default %s) " default1)
2332 (let ((str (read-from-minibuffer
2333 prompt nil nil nil nil
2336 (mapcar 'number-to-string (delq nil default))
2337 (number-to-string default))))))
2340 ((zerop (length str)) default1)
2341 ((stringp str) (read str))))
2344 (message "Please enter a number.")
2349 (defun read-char-choice (prompt chars &optional inhibit-keyboard-quit)
2350 "Read and return one of CHARS, prompting for PROMPT.
2351 Any input that is not one of CHARS is ignored.
2353 If optional argument INHIBIT-KEYBOARD-QUIT is non-nil, ignore
2354 keyboard-quit events while waiting for a valid input."
2355 (unless (consp chars)
2356 (error "Called `read-char-choice' without valid char choices"))
2357 (let (char done show-help (helpbuf " *Char Help*"))
2358 (let ((cursor-in-echo-area t)
2359 (executing-kbd-macro executing-kbd-macro)
2361 (save-window-excursion ; in case we call help-form-show
2363 (unless (get-text-property 0 'face prompt)
2364 (setq prompt (propertize prompt 'face 'minibuffer-prompt)))
2365 (setq char (let ((inhibit-quit inhibit-keyboard-quit))
2367 (and show-help (buffer-live-p (get-buffer helpbuf))
2368 (kill-buffer helpbuf))
2370 ((not (numberp char)))
2371 ;; If caller has set help-form, that's enough.
2372 ;; They don't explicitly have to add help-char to chars.
2379 ((and executing-kbd-macro (= char -1))
2380 ;; read-event returns -1 if we are in a kbd macro and
2381 ;; there are no more events in the macro. Attempt to
2382 ;; get an event interactively.
2383 (setq executing-kbd-macro nil))
2384 ((not inhibit-keyboard-quit)
2386 ((and (null esc-flag) (eq char ?\e))
2388 ((memq char '(?\C-g ?\e))
2389 (keyboard-quit))))))))
2390 ;; Display the question with the answer. But without cursor-in-echo-area.
2391 (message "%s%s" prompt (char-to-string char))
2394 (defun sit-for (seconds &optional nodisp obsolete)
2395 "Redisplay, then wait for SECONDS seconds. Stop when input is available.
2396 SECONDS may be a floating-point value.
2397 \(On operating systems that do not support waiting for fractions of a
2398 second, floating-point values are rounded down to the nearest integer.)
2400 If optional arg NODISP is t, don't redisplay, just wait for input.
2401 Redisplay does not happen if input is available before it starts.
2403 Value is t if waited the full time with no input arriving, and nil otherwise.
2405 An obsolete, but still supported form is
2406 \(sit-for SECONDS &optional MILLISECONDS NODISP)
2407 where the optional arg MILLISECONDS specifies an additional wait period,
2408 in milliseconds; this was useful when Emacs was built without
2409 floating point support."
2410 (declare (advertised-calling-convention (seconds &optional nodisp) "22.1"))
2411 ;; This used to be implemented in C until the following discussion:
2412 ;; https://lists.gnu.org/r/emacs-devel/2006-07/msg00401.html
2413 ;; Then it was moved here using an implementation based on an idle timer,
2414 ;; which was then replaced by the use of read-event.
2415 (if (numberp nodisp)
2416 (setq seconds (+ seconds (* 1e-3 nodisp))
2418 (if obsolete (setq nodisp obsolete)))
2423 ((input-pending-p t)
2426 ;; We are going to call read-event below, which will record
2427 ;; the next key as part of the macro, even if that key
2428 ;; invokes kmacro-end-macro, so if we are recording a macro,
2429 ;; the macro will recursively call itself. In addition, when
2430 ;; that key is removed from unread-command-events, it will be
2431 ;; recorded the second time, so the macro will have each key
2432 ;; doubled. This used to happen if a macro was defined with
2433 ;; Flyspell mode active (because Flyspell calls sit-for in its
2434 ;; post-command-hook, see bug #21329.) To avoid all that, we
2435 ;; simply disable the wait when we are recording a macro.
2437 (or nodisp (redisplay)))
2439 (or nodisp (redisplay))
2440 ;; FIXME: we should not read-event here at all, because it's much too
2441 ;; difficult to reliably "undo" a read-event by pushing it onto
2442 ;; unread-command-events.
2443 ;; For bug#14782, we need read-event to do the keyboard-coding-system
2444 ;; decoding (hence non-nil as second arg under POSIX ttys).
2445 ;; For bug#15614, we need read-event not to inherit-input-method.
2446 ;; So we temporarily suspend input-method-function.
2447 (let ((read (let ((input-method-function nil))
2448 (read-event nil t seconds))))
2451 ;; https://lists.gnu.org/r/emacs-devel/2006-10/msg00394.html
2452 ;; We want `read' appear in the next command's this-command-event
2453 ;; but not in the current one.
2454 ;; By pushing (cons t read), we indicate that `read' has not
2455 ;; yet been recorded in this-command-keys, so it will be recorded
2456 ;; next time it's read.
2457 ;; And indeed the `seconds' argument to read-event correctly
2458 ;; prevented recording this event in the current command's
2459 ;; this-command-keys.
2460 (push (cons t read) unread-command-events)
2463 ;; Behind display-popup-menus-p test.
2464 (declare-function x-popup-dialog "menu.c" (position contents &optional header))
2466 (defun y-or-n-p (prompt)
2467 "Ask user a \"y or n\" question.
2468 Return t if answer is \"y\" and nil if it is \"n\".
2469 PROMPT is the string to display to ask the question. It should
2470 end in a space; `y-or-n-p' adds \"(y or n) \" to it.
2472 No confirmation of the answer is requested; a single character is
2473 enough. SPC also means yes, and DEL means no.
2475 To be precise, this function translates user input into responses
2476 by consulting the bindings in `query-replace-map'; see the
2477 documentation of that variable for more information. In this
2478 case, the useful bindings are `act', `skip', `recenter',
2479 `scroll-up', `scroll-down', and `quit'.
2480 An `act' response means yes, and a `skip' response means no.
2481 A `quit' response means to invoke `keyboard-quit'.
2482 If the user enters `recenter', `scroll-up', or `scroll-down'
2483 responses, perform the requested window recentering or scrolling
2486 Under a windowing system a dialog box will be used if `last-nonmenu-event'
2487 is nil and `use-dialog-box' is non-nil."
2488 ;; ¡Beware! when I tried to edebug this code, Emacs got into a weird state
2489 ;; where all the keys were unbound (i.e. it somehow got triggered
2490 ;; within read-key, apparently). I had to kill it.
2491 (let ((answer 'recenter)
2492 (padded (lambda (prompt &optional dialog)
2493 (let ((l (length prompt)))
2495 (if (or (zerop l) (eq ?\s (aref prompt (1- l))))
2497 (if dialog "" "(y or n) "))))))
2500 (setq prompt (funcall padded prompt))
2501 (let ((temp-prompt prompt))
2502 (while (not (memq answer '(act skip)))
2503 (let ((str (read-string temp-prompt)))
2504 (cond ((member str '("y" "Y")) (setq answer 'act))
2505 ((member str '("n" "N")) (setq answer 'skip))
2506 (t (setq temp-prompt (concat "Please answer y or n. "
2508 ((and (display-popup-menus-p)
2509 last-input-event ; not during startup
2510 (listp last-nonmenu-event)
2512 (setq prompt (funcall padded prompt t)
2513 answer (x-popup-dialog t `(,prompt ("Yes" . act) ("No" . skip)))))
2515 (setq prompt (funcall padded prompt))
2517 (let* ((scroll-actions '(recenter scroll-up scroll-down
2518 scroll-other-window scroll-other-window-down))
2520 (let ((cursor-in-echo-area t))
2521 (when minibuffer-auto-raise
2522 (raise-frame (window-frame (minibuffer-window))))
2523 (read-key (propertize (if (memq answer scroll-actions)
2525 (concat "Please answer y or n. "
2527 'face 'minibuffer-prompt)))))
2528 (setq answer (lookup-key query-replace-map (vector key) t))
2530 ((memq answer '(skip act)) nil)
2531 ((eq answer 'recenter)
2533 ((eq answer 'scroll-up)
2534 (ignore-errors (scroll-up-command)) t)
2535 ((eq answer 'scroll-down)
2536 (ignore-errors (scroll-down-command)) t)
2537 ((eq answer 'scroll-other-window)
2538 (ignore-errors (scroll-other-window)) t)
2539 ((eq answer 'scroll-other-window-down)
2540 (ignore-errors (scroll-other-window-down)) t)
2541 ((or (memq answer '(exit-prefix quit)) (eq key ?\e))
2542 (signal 'quit nil) t)
2546 (let ((ret (eq answer 'act)))
2547 (unless noninteractive
2548 (message "%s%c" prompt (if ret ?y ?n)))
2552 ;;; Atomic change groups.
2554 (defmacro atomic-change-group (&rest body)
2555 "Like `progn' but perform BODY as an atomic change group.
2556 This means that if BODY exits abnormally,
2557 all of its changes to the current buffer are undone.
2558 This works regardless of whether undo is enabled in the buffer.
2560 This mechanism is transparent to ordinary use of undo;
2561 if undo is enabled in the buffer and BODY succeeds, the
2562 user can undo the change normally."
2563 (declare (indent 0) (debug t))
2564 (let ((handle (make-symbol "--change-group-handle--"))
2565 (success (make-symbol "--change-group-success--")))
2566 `(let ((,handle (prepare-change-group))
2567 ;; Don't truncate any undo data in the middle of this.
2568 (undo-outer-limit nil)
2569 (undo-limit most-positive-fixnum)
2570 (undo-strong-limit most-positive-fixnum)
2574 ;; This is inside the unwind-protect because
2575 ;; it enables undo if that was disabled; we need
2576 ;; to make sure that it gets disabled again.
2577 (activate-change-group ,handle)
2578 (prog1 ,(macroexp-progn body)
2580 ;; Either of these functions will disable undo
2581 ;; if it was disabled before.
2583 (accept-change-group ,handle)
2584 (cancel-change-group ,handle))))))
2586 (defun prepare-change-group (&optional buffer)
2587 "Return a handle for the current buffer's state, for a change group.
2588 If you specify BUFFER, make a handle for BUFFER's state instead.
2590 Pass the handle to `activate-change-group' afterward to initiate
2591 the actual changes of the change group.
2593 To finish the change group, call either `accept-change-group' or
2594 `cancel-change-group' passing the same handle as argument. Call
2595 `accept-change-group' to accept the changes in the group as final;
2596 call `cancel-change-group' to undo them all. You should use
2597 `unwind-protect' to make sure the group is always finished. The call
2598 to `activate-change-group' should be inside the `unwind-protect'.
2599 Once you finish the group, don't use the handle again--don't try to
2600 finish the same group twice. For a simple example of correct use, see
2601 the source code of `atomic-change-group'.
2603 The handle records only the specified buffer. To make a multibuffer
2604 change group, call this function once for each buffer you want to
2605 cover, then use `nconc' to combine the returned values, like this:
2607 (nconc (prepare-change-group buffer-1)
2608 (prepare-change-group buffer-2))
2610 You can then activate that multibuffer change group with a single
2611 call to `activate-change-group' and finish it with a single call
2612 to `accept-change-group' or `cancel-change-group'."
2615 (list (cons buffer (with-current-buffer buffer buffer-undo-list)))
2616 (list (cons (current-buffer) buffer-undo-list))))
2618 (defun activate-change-group (handle)
2619 "Activate a change group made with `prepare-change-group' (which see)."
2620 (dolist (elt handle)
2621 (with-current-buffer (car elt)
2622 (if (eq buffer-undo-list t)
2623 (setq buffer-undo-list nil)))))
2625 (defun accept-change-group (handle)
2626 "Finish a change group made with `prepare-change-group' (which see).
2627 This finishes the change group by accepting its changes as final."
2628 (dolist (elt handle)
2629 (with-current-buffer (car elt)
2630 (if (eq (cdr elt) t)
2631 (setq buffer-undo-list t)))))
2633 (defun cancel-change-group (handle)
2634 "Finish a change group made with `prepare-change-group' (which see).
2635 This finishes the change group by reverting all of its changes."
2636 (dolist (elt handle)
2637 (with-current-buffer (car elt)
2638 (setq elt (cdr elt))
2640 ;; Widen buffer temporarily so if the buffer was narrowed within
2641 ;; the body of `atomic-change-group' all changes can be undone.
2643 (let ((old-car (car-safe elt))
2644 (old-cdr (cdr-safe elt)))
2647 ;; Temporarily truncate the undo log at ELT.
2649 (setcar elt nil) (setcdr elt nil))
2650 (unless (eq last-command 'undo) (undo-start))
2651 ;; Make sure there's no confusion.
2652 (when (and (consp elt) (not (eq elt (last pending-undo-list))))
2653 (error "Undoing to some unrelated state"))
2656 (while (listp pending-undo-list) (undo-more 1)))
2657 ;; Revert the undo info to what it was when we grabbed
2659 (setq buffer-undo-list elt))
2660 ;; Reset the modified cons cell ELT to its original content.
2662 (setcar elt old-car)
2663 (setcdr elt old-cdr))))))))
2665 ;;;; Display-related functions.
2667 ;; For compatibility.
2668 (define-obsolete-function-alias 'redraw-modeline
2669 'force-mode-line-update "24.3")
2671 (defun momentary-string-display (string pos &optional exit-char message)
2672 "Momentarily display STRING in the buffer at POS.
2673 Display remains until next event is input.
2674 If POS is a marker, only its position is used; its buffer is ignored.
2675 Optional third arg EXIT-CHAR can be a character, event or event
2676 description list. EXIT-CHAR defaults to SPC. If the input is
2677 EXIT-CHAR it is swallowed; otherwise it is then available as
2678 input (as a command if nothing else).
2679 Display MESSAGE (optional fourth arg) in the echo area.
2680 If MESSAGE is nil, instructions to type EXIT-CHAR are displayed there."
2681 (or exit-char (setq exit-char ?\s))
2682 (let ((ol (make-overlay pos pos))
2683 (str (copy-sequence string)))
2687 (overlay-put ol 'after-string str)
2689 ;; To avoid trouble with out-of-bounds position
2691 ;; If the string end is off screen, recenter now.
2692 (if (<= (window-end nil t) pos)
2693 (recenter (/ (window-height) 2))))
2694 (message (or message "Type %s to continue editing.")
2695 (single-key-description exit-char))
2696 (let ((event (read-key)))
2697 ;; `exit-char' can be an event, or an event description list.
2698 (or (eq event exit-char)
2699 (eq event (event-convert-list exit-char))
2700 (setq unread-command-events
2701 (append (this-single-command-raw-keys)
2702 unread-command-events)))))
2703 (delete-overlay ol))))
2706 ;;;; Overlay operations
2708 (defun copy-overlay (o)
2709 "Return a copy of overlay O."
2710 (let ((o1 (if (overlay-buffer o)
2711 (make-overlay (overlay-start o) (overlay-end o)
2712 ;; FIXME: there's no easy way to find the
2713 ;; insertion-type of the two markers.
2715 (let ((o1 (make-overlay (point-min) (point-min))))
2718 (props (overlay-properties o)))
2720 (overlay-put o1 (pop props) (pop props)))
2723 (defun remove-overlays (&optional beg end name val)
2724 "Clear BEG and END of overlays whose property NAME has value VAL.
2725 Overlays might be moved and/or split.
2726 BEG and END default respectively to the beginning and end of buffer."
2727 ;; This speeds up the loops over overlays.
2728 (unless beg (setq beg (point-min)))
2729 (unless end (setq end (point-max)))
2730 (overlay-recenter end)
2732 (setq beg (prog1 end (setq end beg))))
2734 (dolist (o (overlays-in beg end))
2735 (when (eq (overlay-get o name) val)
2736 ;; Either push this overlay outside beg...end
2737 ;; or split it to exclude beg...end
2738 ;; or delete it entirely (if it is contained in beg...end).
2739 (if (< (overlay-start o) beg)
2740 (if (> (overlay-end o) end)
2742 (move-overlay (copy-overlay o)
2743 (overlay-start o) beg)
2744 (move-overlay o end (overlay-end o)))
2745 (move-overlay o (overlay-start o) beg))
2746 (if (> (overlay-end o) end)
2747 (move-overlay o end (overlay-end o))
2748 (delete-overlay o)))))))
2752 (defvar suspend-hook nil
2753 "Normal hook run by `suspend-emacs', before suspending.")
2755 (defvar suspend-resume-hook nil
2756 "Normal hook run by `suspend-emacs', after Emacs is continued.")
2758 (defvar temp-buffer-show-hook nil
2759 "Normal hook run by `with-output-to-temp-buffer' after displaying the buffer.
2760 When the hook runs, the temporary buffer is current, and the window it
2761 was displayed in is selected.")
2763 (defvar temp-buffer-setup-hook nil
2764 "Normal hook run by `with-output-to-temp-buffer' at the start.
2765 When the hook runs, the temporary buffer is current.
2766 This hook is normally set up with a function to put the buffer in Help
2769 (defconst user-emacs-directory
2770 (if (eq system-type 'ms-dos)
2771 ;; MS-DOS cannot have initial dot.
2774 "Directory beneath which additional per-user Emacs-specific files are placed.
2775 Various programs in Emacs store information in this directory.
2776 Note that this should end with a directory separator.
2777 See also `locate-user-emacs-file'.")
2779 ;;;; Misc. useful functions.
2781 (defsubst buffer-narrowed-p ()
2782 "Return non-nil if the current buffer is narrowed."
2783 (/= (- (point-max) (point-min)) (buffer-size)))
2785 (defun find-tag-default-bounds ()
2786 "Determine the boundaries of the default tag, based on text at point.
2787 Return a cons cell with the beginning and end of the found tag.
2788 If there is no plausible default, return nil."
2789 (bounds-of-thing-at-point 'symbol))
2791 (defun find-tag-default ()
2792 "Determine default tag to search for, based on text at point.
2793 If there is no plausible default, return nil."
2794 (let ((bounds (find-tag-default-bounds)))
2796 (buffer-substring-no-properties (car bounds) (cdr bounds)))))
2798 (defun find-tag-default-as-regexp ()
2799 "Return regexp that matches the default tag at point.
2800 If there is no tag at point, return nil.
2802 When in a major mode that does not provide its own
2803 `find-tag-default-function', return a regexp that matches the
2804 symbol at point exactly."
2805 (let ((tag (funcall (or find-tag-default-function
2806 (get major-mode 'find-tag-default-function)
2807 'find-tag-default))))
2808 (if tag (regexp-quote tag))))
2810 (defun find-tag-default-as-symbol-regexp ()
2811 "Return regexp that matches the default tag at point as symbol.
2812 If there is no tag at point, return nil.
2814 When in a major mode that does not provide its own
2815 `find-tag-default-function', return a regexp that matches the
2816 symbol at point exactly."
2817 (let ((tag-regexp (find-tag-default-as-regexp)))
2819 (eq (or find-tag-default-function
2820 (get major-mode 'find-tag-default-function)
2823 (format "\\_<%s\\_>" tag-regexp)
2826 (defun play-sound (sound)
2827 "SOUND is a list of the form `(sound KEYWORD VALUE...)'.
2828 The following keywords are recognized:
2830 :file FILE - read sound data from FILE. If FILE isn't an
2831 absolute file name, it is searched in `data-directory'.
2833 :data DATA - read sound data from string DATA.
2835 Exactly one of :file or :data must be present.
2837 :volume VOL - set volume to VOL. VOL must an integer in the
2838 range 0..100 or a float in the range 0..1.0. If not specified,
2839 don't change the volume setting of the sound device.
2841 :device DEVICE - play sound on DEVICE. If not specified,
2842 a system-dependent default device name is used.
2844 Note: :data and :device are currently not supported on Windows."
2845 (if (fboundp 'play-sound-internal)
2846 (play-sound-internal sound)
2847 (error "This Emacs binary lacks sound support")))
2849 (declare-function w32-shell-dos-semantics "w32-fns" nil)
2851 (defun shell-quote-argument (argument)
2852 "Quote ARGUMENT for passing as argument to an inferior shell.
2854 This function is designed to work with the syntax of your system's
2855 standard shell, and might produce incorrect results with unusual shells.
2856 See Info node `(elisp)Security Considerations'."
2858 ((eq system-type 'ms-dos)
2859 ;; Quote using double quotes, but escape any existing quotes in
2860 ;; the argument with backslashes.
2864 (if (or (null (string-match "[^\"]" argument))
2865 (< (match-end 0) (length argument)))
2866 (while (string-match "[\"]" argument start)
2867 (setq end (match-beginning 0)
2868 result (concat result (substring argument start end)
2869 "\\" (substring argument end (1+ end)))
2871 (concat "\"" result (substring argument start) "\"")))
2873 ((and (eq system-type 'windows-nt) (w32-shell-dos-semantics))
2875 ;; First, quote argument so that CommandLineToArgvW will
2876 ;; understand it. See
2877 ;; http://msdn.microsoft.com/en-us/library/17w5ykft%28v=vs.85%29.aspx
2878 ;; After we perform that level of quoting, escape shell
2879 ;; metacharacters so that cmd won't mangle our argument. If the
2880 ;; argument contains no double quote characters, we can just
2881 ;; surround it with double quotes. Otherwise, we need to prefix
2882 ;; each shell metacharacter with a caret.
2885 ;; escape backslashes at end of string
2886 (replace-regexp-in-string
2889 ;; escape backslashes and quotes in string body
2890 (replace-regexp-in-string
2895 (if (string-match "[%!\"]" argument)
2898 (replace-regexp-in-string
2899 "\\([%!()\"<>&|^]\\)"
2903 (concat "\"" argument "\"")))
2906 (if (equal argument "")
2908 ;; Quote everything except POSIX filename characters.
2909 ;; This should be safe enough even for really weird shells.
2910 (replace-regexp-in-string
2912 (replace-regexp-in-string "[^-0-9a-zA-Z_./\n]" "\\\\\\&" argument))))
2915 (defsubst string-to-list (string)
2916 "Return a list of characters in STRING."
2917 (append string nil))
2919 (defsubst string-to-vector (string)
2920 "Return a vector of characters in STRING."
2923 (defun string-or-null-p (object)
2924 "Return t if OBJECT is a string or nil.
2925 Otherwise, return nil."
2926 (or (stringp object) (null object)))
2928 (defun booleanp (object)
2929 "Return t if OBJECT is one of the two canonical boolean values: t or nil.
2930 Otherwise, return nil."
2931 (and (memq object '(nil t)) t))
2933 (defun special-form-p (object)
2934 "Non-nil if and only if OBJECT is a special form."
2935 (if (and (symbolp object) (fboundp object))
2936 (setq object (indirect-function object)))
2937 (and (subrp object) (eq (cdr (subr-arity object)) 'unevalled)))
2939 (defun macrop (object)
2940 "Non-nil if and only if OBJECT is a macro."
2941 (let ((def (indirect-function object)))
2943 (or (eq 'macro (car def))
2944 (and (autoloadp def) (memq (nth 4 def) '(macro t)))))))
2946 (defun field-at-pos (pos)
2947 "Return the field at position POS, taking stickiness etc into account."
2948 (let ((raw-field (get-char-property (field-beginning pos) 'field)))
2949 (if (eq raw-field 'boundary)
2950 (get-char-property (1- (field-end pos)) 'field)
2953 (defun sha1 (object &optional start end binary)
2954 "Return the SHA1 (Secure Hash Algorithm) of an OBJECT.
2955 OBJECT is either a string or a buffer. Optional arguments START and
2956 END are character positions specifying which portion of OBJECT for
2957 computing the hash. If BINARY is non-nil, return a string in binary
2959 (secure-hash 'sha1 object start end binary))
2961 (defun function-get (f prop &optional autoload)
2962 "Return the value of property PROP of function F.
2963 If AUTOLOAD is non-nil and F is autoloaded, try to autoload it
2964 in the hope that it will set PROP. If AUTOLOAD is `macro', only do it
2965 if it's an autoloaded macro."
2967 (while (and (symbolp f)
2968 (null (setq val (get f prop)))
2970 (let ((fundef (symbol-function f)))
2971 (if (and autoload (autoloadp fundef)
2973 (autoload-do-load fundef f
2974 (if (eq autoload 'macro)
2976 nil ;Re-try `get' on the same `f'.
2980 ;;;; Support for yanking and text properties.
2981 ;; Why here in subr.el rather than in simple.el? --Stef
2983 (defvar yank-handled-properties)
2984 (defvar yank-excluded-properties)
2986 (defun remove-yank-excluded-properties (start end)
2987 "Process text properties between START and END, inserted for a `yank'.
2988 Perform the handling specified by `yank-handled-properties', then
2989 remove properties specified by `yank-excluded-properties'."
2990 (let ((inhibit-read-only t))
2991 (dolist (handler yank-handled-properties)
2992 (let ((prop (car handler))
2995 (while (< run-start end)
2996 (let ((value (get-text-property run-start prop))
2997 (run-end (next-single-property-change
2998 run-start prop nil end)))
2999 (funcall fun value run-start run-end)
3000 (setq run-start run-end)))))
3001 (if (eq yank-excluded-properties t)
3002 (set-text-properties start end nil)
3003 (remove-list-of-text-properties start end yank-excluded-properties))))
3005 (defvar yank-undo-function)
3007 (defun insert-for-yank (string)
3008 "Insert STRING at point for the `yank' command.
3010 This function is like `insert', except it honors the variables
3011 `yank-handled-properties' and `yank-excluded-properties', and the
3012 `yank-handler' text property, in the way that `yank' does."
3014 (while (setq to (next-single-property-change 0 'yank-handler string))
3015 (insert-for-yank-1 (substring string 0 to))
3016 (setq string (substring string to))))
3017 (insert-for-yank-1 string))
3019 (defun insert-for-yank-1 (string)
3020 "Helper for `insert-for-yank', which see."
3021 (let* ((handler (and (stringp string)
3022 (get-text-property 0 'yank-handler string)))
3023 (param (or (nth 1 handler) string))
3025 (inhibit-read-only inhibit-read-only)
3028 (setq yank-undo-function t)
3029 (if (nth 0 handler) ; FUNCTION
3030 (funcall (car handler) param)
3034 ;; Prevent read-only properties from interfering with the
3035 ;; following text property changes.
3036 (setq inhibit-read-only t)
3038 (unless (nth 2 handler) ; NOEXCLUDE
3039 (remove-yank-excluded-properties opoint end))
3041 ;; If last inserted char has properties, mark them as rear-nonsticky.
3042 (if (and (> end opoint)
3043 (text-properties-at (1- end)))
3044 (put-text-property (1- end) end 'rear-nonsticky t))
3046 (if (eq yank-undo-function t) ; not set by FUNCTION
3047 (setq yank-undo-function (nth 3 handler))) ; UNDO
3048 (if (nth 4 handler) ; COMMAND
3049 (setq this-command (nth 4 handler)))))
3051 (defun insert-buffer-substring-no-properties (buffer &optional start end)
3052 "Insert before point a substring of BUFFER, without text properties.
3053 BUFFER may be a buffer or a buffer name.
3054 Arguments START and END are character positions specifying the substring.
3055 They default to the values of (point-min) and (point-max) in BUFFER."
3056 (let ((opoint (point)))
3057 (insert-buffer-substring buffer start end)
3058 (let ((inhibit-read-only t))
3059 (set-text-properties opoint (point) nil))))
3061 (defun insert-buffer-substring-as-yank (buffer &optional start end)
3062 "Insert before point a part of BUFFER, stripping some text properties.
3063 BUFFER may be a buffer or a buffer name.
3064 Arguments START and END are character positions specifying the substring.
3065 They default to the values of (point-min) and (point-max) in BUFFER.
3066 Before insertion, process text properties according to
3067 `yank-handled-properties' and `yank-excluded-properties'."
3068 ;; Since the buffer text should not normally have yank-handler properties,
3069 ;; there is no need to handle them here.
3070 (let ((opoint (point)))
3071 (insert-buffer-substring buffer start end)
3072 (remove-yank-excluded-properties opoint (point))))
3074 (defun yank-handle-font-lock-face-property (face start end)
3075 "If `font-lock-defaults' is nil, apply FACE as a `face' property.
3076 START and END denote the start and end of the text to act on.
3077 Do nothing if FACE is nil."
3079 (null font-lock-defaults)
3080 (put-text-property start end 'face face)))
3082 ;; This removes `mouse-face' properties in *Help* buffer buttons:
3083 ;; https://lists.gnu.org/r/emacs-devel/2002-04/msg00648.html
3084 (defun yank-handle-category-property (category start end)
3085 "Apply property category CATEGORY's properties between START and END."
3087 (let ((start2 start))
3088 (while (< start2 end)
3089 (let ((end2 (next-property-change start2 nil end))
3090 (original (text-properties-at start2)))
3091 (set-text-properties start2 end2 (symbol-plist category))
3092 (add-text-properties start2 end2 original)
3093 (setq start2 end2))))))
3096 ;;;; Synchronous shell commands.
3098 (defun start-process-shell-command (name buffer &rest args)
3099 "Start a program in a subprocess. Return the process object for it.
3100 NAME is name for process. It is modified if necessary to make it unique.
3101 BUFFER is the buffer (or buffer name) to associate with the process.
3102 Process output goes at end of that buffer, unless you specify
3103 an output stream or filter function to handle the output.
3104 BUFFER may be also nil, meaning that this process is not associated
3106 COMMAND is the shell command to run.
3108 An old calling convention accepted any number of arguments after COMMAND,
3109 which were just concatenated to COMMAND. This is still supported but strongly
3111 (declare (advertised-calling-convention (name buffer command) "23.1"))
3112 ;; We used to use `exec' to replace the shell with the command,
3113 ;; but that failed to handle (...) and semicolon, etc.
3114 (start-process name buffer shell-file-name shell-command-switch
3115 (mapconcat 'identity args " ")))
3117 (defun start-file-process-shell-command (name buffer &rest args)
3118 "Start a program in a subprocess. Return the process object for it.
3119 Similar to `start-process-shell-command', but calls `start-file-process'."
3120 (declare (advertised-calling-convention (name buffer command) "23.1"))
3123 (if (file-remote-p default-directory) "/bin/sh" shell-file-name)
3124 (if (file-remote-p default-directory) "-c" shell-command-switch)
3125 (mapconcat 'identity args " ")))
3127 (defun call-process-shell-command (command &optional infile buffer display
3129 "Execute the shell command COMMAND synchronously in separate process.
3130 The remaining arguments are optional.
3131 The program's input comes from file INFILE (nil means `/dev/null').
3132 Insert output in BUFFER before point; t means current buffer;
3133 nil for BUFFER means discard it; 0 means discard and don't wait.
3134 BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,
3135 REAL-BUFFER says what to do with standard output, as above,
3136 while STDERR-FILE says what to do with standard error in the child.
3137 STDERR-FILE may be nil (discard standard error output),
3138 t (mix it with ordinary output), or a file name string.
3140 Fourth arg DISPLAY non-nil means redisplay buffer as output is inserted.
3141 Wildcards and redirection are handled as usual in the shell.
3143 If BUFFER is 0, `call-process-shell-command' returns immediately with value nil.
3144 Otherwise it waits for COMMAND to terminate and returns a numeric exit
3145 status or a signal description string.
3146 If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.
3148 An old calling convention accepted any number of arguments after DISPLAY,
3149 which were just concatenated to COMMAND. This is still supported but strongly
3151 (declare (advertised-calling-convention
3152 (command &optional infile buffer display) "24.5"))
3153 ;; We used to use `exec' to replace the shell with the command,
3154 ;; but that failed to handle (...) and semicolon, etc.
3155 (call-process shell-file-name
3156 infile buffer display
3157 shell-command-switch
3158 (mapconcat 'identity (cons command args) " ")))
3160 (defun process-file-shell-command (command &optional infile buffer display
3162 "Process files synchronously in a separate process.
3163 Similar to `call-process-shell-command', but calls `process-file'."
3164 (declare (advertised-calling-convention
3165 (command &optional infile buffer display) "24.5"))
3167 (if (file-remote-p default-directory) "/bin/sh" shell-file-name)
3168 infile buffer display
3169 (if (file-remote-p default-directory) "-c" shell-command-switch)
3170 (mapconcat 'identity (cons command args) " ")))
3172 (defun call-shell-region (start end command &optional delete buffer)
3173 "Send text from START to END as input to an inferior shell running COMMAND.
3174 Delete the text if fourth arg DELETE is non-nil.
3176 Insert output in BUFFER before point; t means current buffer; nil for
3177 BUFFER means discard it; 0 means discard and don't wait; and `(:file
3178 FILE)', where FILE is a file name string, means that it should be
3179 written to that file (if the file already exists it is overwritten).
3180 BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,
3181 REAL-BUFFER says what to do with standard output, as above,
3182 while STDERR-FILE says what to do with standard error in the child.
3183 STDERR-FILE may be nil (discard standard error output),
3184 t (mix it with ordinary output), or a file name string.
3186 If BUFFER is 0, `call-shell-region' returns immediately with value nil.
3187 Otherwise it waits for COMMAND to terminate
3188 and returns a numeric exit status or a signal description string.
3189 If you quit, the process is killed with SIGINT, or SIGKILL if you quit again."
3190 (call-process-region start end
3191 shell-file-name delete buffer nil
3192 shell-command-switch command))
3194 ;;;; Lisp macros to do various things temporarily.
3196 (defmacro track-mouse (&rest body)
3197 "Evaluate BODY with mouse movement events enabled.
3198 Within a `track-mouse' form, mouse motion generates input events that
3199 you can read with `read-event'.
3200 Normally, mouse motion is ignored."
3201 (declare (debug t) (indent 0))
3202 `(internal--track-mouse (lambda () ,@body)))
3204 (defmacro with-current-buffer (buffer-or-name &rest body)
3205 "Execute the forms in BODY with BUFFER-OR-NAME temporarily current.
3206 BUFFER-OR-NAME must be a buffer or the name of an existing buffer.
3207 The value returned is the value of the last form in BODY. See
3208 also `with-temp-buffer'."
3209 (declare (indent 1) (debug t))
3210 `(save-current-buffer
3211 (set-buffer ,buffer-or-name)
3214 (defun internal--before-with-selected-window (window)
3215 (let ((other-frame (window-frame window)))
3216 (list window (selected-window)
3217 ;; Selecting a window on another frame also changes that
3218 ;; frame's frame-selected-window. We must save&restore it.
3219 (unless (eq (selected-frame) other-frame)
3220 (frame-selected-window other-frame))
3221 ;; Also remember the top-frame if on ttys.
3222 (unless (eq (selected-frame) other-frame)
3223 (tty-top-frame other-frame)))))
3225 (defun internal--after-with-selected-window (state)
3226 ;; First reset frame-selected-window.
3227 (when (window-live-p (nth 2 state))
3228 ;; We don't use set-frame-selected-window because it does not
3229 ;; pass the `norecord' argument to Fselect_window.
3230 (select-window (nth 2 state) 'norecord)
3231 (and (frame-live-p (nth 3 state))
3232 (not (eq (tty-top-frame) (nth 3 state)))
3233 (select-frame (nth 3 state) 'norecord)))
3234 ;; Then reset the actual selected-window.
3235 (when (window-live-p (nth 1 state))
3236 (select-window (nth 1 state) 'norecord)))
3238 (defmacro with-selected-window (window &rest body)
3239 "Execute the forms in BODY with WINDOW as the selected window.
3240 The value returned is the value of the last form in BODY.
3242 This macro saves and restores the selected window, as well as the
3243 selected window of each frame. It does not change the order of
3244 recently selected windows. If the previously selected window of
3245 some frame is no longer live at the end of BODY, that frame's
3246 selected window is left alone. If the selected window is no
3247 longer live, then whatever window is selected at the end of BODY
3250 This macro uses `save-current-buffer' to save and restore the
3251 current buffer, since otherwise its normal operation could
3252 potentially make a different buffer current. It does not alter
3253 the buffer list ordering."
3254 (declare (indent 1) (debug t))
3255 `(let ((save-selected-window--state
3256 (internal--before-with-selected-window ,window)))
3257 (save-current-buffer
3259 (progn (select-window (car save-selected-window--state) 'norecord)
3261 (internal--after-with-selected-window save-selected-window--state)))))
3263 (defmacro with-selected-frame (frame &rest body)
3264 "Execute the forms in BODY with FRAME as the selected frame.
3265 The value returned is the value of the last form in BODY.
3267 This macro saves and restores the selected frame, and changes the
3268 order of neither the recently selected windows nor the buffers in
3270 (declare (indent 1) (debug t))
3271 (let ((old-frame (make-symbol "old-frame"))
3272 (old-buffer (make-symbol "old-buffer")))
3273 `(let ((,old-frame (selected-frame))
3274 (,old-buffer (current-buffer)))
3276 (progn (select-frame ,frame 'norecord)
3278 (when (frame-live-p ,old-frame)
3279 (select-frame ,old-frame 'norecord))
3280 (when (buffer-live-p ,old-buffer)
3281 (set-buffer ,old-buffer))))))
3283 (defmacro save-window-excursion (&rest body)
3284 "Execute BODY, then restore previous window configuration.
3285 This macro saves the window configuration on the selected frame,
3286 executes BODY, then calls `set-window-configuration' to restore
3287 the saved window configuration. The return value is the last
3288 form in BODY. The window configuration is also restored if BODY
3291 BEWARE: Most uses of this macro introduce bugs.
3292 E.g. it should not be used to try and prevent some code from opening
3293 a new window, since that window may sometimes appear in another frame,
3294 in which case `save-window-excursion' cannot help."
3295 (declare (indent 0) (debug t))
3296 (let ((c (make-symbol "wconfig")))
3297 `(let ((,c (current-window-configuration)))
3298 (unwind-protect (progn ,@body)
3299 (set-window-configuration ,c)))))
3301 (defun internal-temp-output-buffer-show (buffer)
3302 "Internal function for `with-output-to-temp-buffer'."
3303 (with-current-buffer buffer
3304 (set-buffer-modified-p nil)
3305 (goto-char (point-min)))
3307 (if temp-buffer-show-function
3308 (funcall temp-buffer-show-function buffer)
3309 (with-current-buffer buffer
3311 (let ((window-combination-limit
3312 ;; When `window-combination-limit' equals
3313 ;; `temp-buffer' or `temp-buffer-resize' and
3314 ;; `temp-buffer-resize-mode' is enabled in this
3315 ;; buffer bind it to t so resizing steals space
3316 ;; preferably from the window that was split.
3317 (if (or (eq window-combination-limit 'temp-buffer)
3318 (and (eq window-combination-limit
3319 'temp-buffer-resize)
3320 temp-buffer-resize-mode))
3322 window-combination-limit)))
3323 (display-buffer buffer)))
3324 (frame (and window (window-frame window))))
3326 (unless (eq frame (selected-frame))
3327 (make-frame-visible frame))
3328 (setq minibuffer-scroll-window window)
3329 (set-window-hscroll window 0)
3330 ;; Don't try this with NOFORCE non-nil!
3331 (set-window-start window (point-min) t)
3332 ;; This should not be necessary.
3333 (set-window-point window (point-min))
3334 ;; Run `temp-buffer-show-hook', with the chosen window selected.
3335 (with-selected-window window
3336 (run-hooks 'temp-buffer-show-hook))))))
3340 ;; Doc is very similar to with-temp-buffer-window.
3341 (defmacro with-output-to-temp-buffer (bufname &rest body)
3342 "Bind `standard-output' to buffer BUFNAME, eval BODY, then show that buffer.
3344 This construct makes buffer BUFNAME empty before running BODY.
3345 It does not make the buffer current for BODY.
3346 Instead it binds `standard-output' to that buffer, so that output
3347 generated with `prin1' and similar functions in BODY goes into
3350 At the end of BODY, this marks buffer BUFNAME unmodified and displays
3351 it in a window, but does not select it. The normal way to do this is
3352 by calling `display-buffer', then running `temp-buffer-show-hook'.
3353 However, if `temp-buffer-show-function' is non-nil, it calls that
3354 function instead (and does not run `temp-buffer-show-hook'). The
3355 function gets one argument, the buffer to display.
3357 The return value of `with-output-to-temp-buffer' is the value of the
3358 last form in BODY. If BODY does not finish normally, the buffer
3359 BUFNAME is not displayed.
3361 This runs the hook `temp-buffer-setup-hook' before BODY,
3362 with the buffer BUFNAME temporarily current. It runs the hook
3363 `temp-buffer-show-hook' after displaying buffer BUFNAME, with that
3364 buffer temporarily current, and the window that was used to display it
3365 temporarily selected. But it doesn't run `temp-buffer-show-hook'
3366 if it uses `temp-buffer-show-function'.
3368 By default, the setup hook puts the buffer into Help mode before running BODY.
3369 If BODY does not change the major mode, the show hook makes the buffer
3370 read-only, and scans it for function and variable names to make them into
3371 clickable cross-references.
3373 See the related form `with-temp-buffer-window'."
3375 (let ((old-dir (make-symbol "old-dir"))
3376 (buf (make-symbol "buf")))
3377 `(let* ((,old-dir default-directory)
3379 (with-current-buffer (get-buffer-create ,bufname)
3380 (prog1 (current-buffer)
3381 (kill-all-local-variables)
3382 ;; FIXME: delete_all_overlays
3383 (setq default-directory ,old-dir)
3384 (setq buffer-read-only nil)
3385 (setq buffer-file-name nil)
3386 (setq buffer-undo-list t)
3387 (let ((inhibit-read-only t)
3388 (inhibit-modification-hooks t))
3390 (run-hooks 'temp-buffer-setup-hook)))))
3391 (standard-output ,buf))
3392 (prog1 (progn ,@body)
3393 (internal-temp-output-buffer-show ,buf)))))
3395 (defmacro with-temp-file (file &rest body)
3396 "Create a new buffer, evaluate BODY there, and write the buffer to FILE.
3397 The value returned is the value of the last form in BODY.
3398 See also `with-temp-buffer'."
3399 (declare (indent 1) (debug t))
3400 (let ((temp-file (make-symbol "temp-file"))
3401 (temp-buffer (make-symbol "temp-buffer")))
3402 `(let ((,temp-file ,file)
3404 (get-buffer-create (generate-new-buffer-name " *temp file*"))))
3407 (with-current-buffer ,temp-buffer
3409 (with-current-buffer ,temp-buffer
3410 (write-region nil nil ,temp-file nil 0)))
3411 (and (buffer-name ,temp-buffer)
3412 (kill-buffer ,temp-buffer))))))
3414 (defmacro with-temp-message (message &rest body)
3415 "Display MESSAGE temporarily if non-nil while BODY is evaluated.
3416 The original message is restored to the echo area after BODY has finished.
3417 The value returned is the value of the last form in BODY.
3418 MESSAGE is written to the message log buffer if `message-log-max' is non-nil.
3419 If MESSAGE is nil, the echo area and message log buffer are unchanged.
3420 Use a MESSAGE of \"\" to temporarily clear the echo area."
3421 (declare (debug t) (indent 1))
3422 (let ((current-message (make-symbol "current-message"))
3423 (temp-message (make-symbol "with-temp-message")))
3424 `(let ((,temp-message ,message)
3429 (setq ,current-message (current-message))
3430 (message "%s" ,temp-message))
3433 (if ,current-message
3434 (message "%s" ,current-message)
3437 (defmacro with-temp-buffer (&rest body)
3438 "Create a temporary buffer, and evaluate BODY there like `progn'.
3439 See also `with-temp-file' and `with-output-to-string'."
3440 (declare (indent 0) (debug t))
3441 (let ((temp-buffer (make-symbol "temp-buffer")))
3442 `(let ((,temp-buffer (generate-new-buffer " *temp*")))
3443 ;; FIXME: kill-buffer can change current-buffer in some odd cases.
3444 (with-current-buffer ,temp-buffer
3447 (and (buffer-name ,temp-buffer)
3448 (kill-buffer ,temp-buffer)))))))
3450 (defmacro with-silent-modifications (&rest body)
3451 "Execute BODY, pretending it does not modify the buffer.
3452 This macro is typically used around modifications of
3453 text properties which do not really affect the buffer's content.
3454 If BODY performs real modifications to the buffer's text, other
3455 than cosmetic ones, undo data may become corrupted.
3457 This macro will run BODY normally, but doesn't count its buffer
3458 modifications as being buffer modifications. This affects things
3459 like `buffer-modified-p', checking whether the file is locked by
3460 someone else, running buffer modification hooks, and other things
3462 (declare (debug t) (indent 0))
3463 (let ((modified (make-symbol "modified")))
3464 `(let* ((,modified (buffer-modified-p))
3465 (buffer-undo-list t)
3466 (inhibit-read-only t)
3467 (inhibit-modification-hooks t))
3472 (restore-buffer-modified-p nil))))))
3474 (defmacro with-output-to-string (&rest body)
3475 "Execute BODY, return the text it sent to `standard-output', as a string."
3476 (declare (indent 0) (debug t))
3477 `(let ((standard-output
3478 (get-buffer-create (generate-new-buffer-name " *string-output*"))))
3481 (let ((standard-output standard-output))
3483 (with-current-buffer standard-output
3485 (kill-buffer standard-output))))
3487 (defmacro with-local-quit (&rest body)
3488 "Execute BODY, allowing quits to terminate BODY but not escape further.
3489 When a quit terminates BODY, `with-local-quit' returns nil but
3490 requests another quit. That quit will be processed as soon as quitting
3491 is allowed once again. (Immediately, if `inhibit-quit' is nil.)"
3492 (declare (debug t) (indent 0))
3493 `(condition-case nil
3494 (let ((inhibit-quit nil))
3496 (quit (setq quit-flag t)
3497 ;; This call is to give a chance to handle quit-flag
3498 ;; in case inhibit-quit is nil.
3499 ;; Without this, it will not be handled until the next function
3500 ;; call, and that might allow it to exit thru a condition-case
3501 ;; that intends to handle the quit signal next time.
3502 (eval '(ignore nil)))))
3504 ;; Don't throw `throw-on-input' on those events by default.
3505 (setq while-no-input-ignore-events
3506 '(focus-in focus-out help-echo iconify-frame
3507 make-frame-visible selection-request))
3509 (defmacro while-no-input (&rest body)
3510 "Execute BODY only as long as there's no pending input.
3511 If input arrives, that ends the execution of BODY,
3512 and `while-no-input' returns t. Quitting makes it return nil.
3513 If BODY finishes, `while-no-input' returns whatever value BODY produced."
3514 (declare (debug t) (indent 0))
3515 (let ((catch-sym (make-symbol "input")))
3518 (let ((throw-on-input ',catch-sym))
3519 (or (input-pending-p)
3520 (progn ,@body)))))))
3522 (defmacro condition-case-unless-debug (var bodyform &rest handlers)
3523 "Like `condition-case' except that it does not prevent debugging.
3524 More specifically if `debug-on-error' is set then the debugger will be invoked
3525 even if this catches the signal."
3526 (declare (debug condition-case) (indent 2))
3527 `(condition-case ,var
3529 ,@(mapcar (lambda (handler)
3530 `((debug ,@(if (listp (car handler)) (car handler)
3531 (list (car handler))))
3535 (define-obsolete-function-alias 'condition-case-no-debug
3536 'condition-case-unless-debug "24.1")
3538 (defmacro with-demoted-errors (format &rest body)
3539 "Run BODY and demote any errors to simple messages.
3540 FORMAT is a string passed to `message' to format any error message.
3541 It should contain a single %-sequence; e.g., \"Error: %S\".
3543 If `debug-on-error' is non-nil, run BODY without catching its errors.
3544 This is to be used around code which is not expected to signal an error
3545 but which should be robust in the unexpected case that an error is signaled.
3547 For backward compatibility, if FORMAT is not a constant string, it
3548 is assumed to be part of BODY, in which case the message format
3549 used is \"Error: %S\"."
3550 (declare (debug t) (indent 1))
3551 (let ((err (make-symbol "err"))
3552 (format (if (and (stringp format) body) format
3554 (if format (push format body))))))
3555 `(condition-case-unless-debug ,err
3556 ,(macroexp-progn body)
3557 (error (message ,format ,err) nil))))
3559 (defmacro combine-after-change-calls (&rest body)
3560 "Execute BODY, but don't call the after-change functions till the end.
3561 If BODY makes changes in the buffer, they are recorded
3562 and the functions on `after-change-functions' are called several times
3563 when BODY is finished.
3564 The return value is the value of the last form in BODY.
3566 If `before-change-functions' is non-nil, then calls to the after-change
3567 functions can't be deferred, so in that case this macro has no effect.
3569 Do not alter `after-change-functions' or `before-change-functions'
3571 (declare (indent 0) (debug t))
3573 (let ((combine-after-change-calls t))
3575 (combine-after-change-execute)))
3577 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3578 (defvar undo--combining-change-calls nil
3579 "Non-nil when `combine-change-calls-1' is running.")
3581 (defun combine-change-calls-1 (beg end body)
3582 "Evaluate BODY, running the change hooks just once, for region \(BEG END).
3584 Firstly, `before-change-functions' is invoked for the region
3585 \(BEG END), then BODY (a function) is evaluated with
3586 `before-change-functions' and `after-change-functions' bound to
3587 nil, then finally `after-change-functions' is invoked on the
3588 updated region (BEG NEW-END) with a calculated OLD-LEN argument.
3589 If `inhibit-modification-hooks' is initially non-nil, the change
3592 The result of `combine-change-calls-1' is the value returned by
3593 BODY. BODY must not make a different buffer current, except
3594 temporarily. It must not make any changes to the buffer outside
3595 the specified region. It must not change
3596 `before-change-functions' or `after-change-functions'.
3598 Additionally, the buffer modifications of BODY are recorded on
3599 the buffer's undo list as a single \(apply ...) entry containing
3600 the function `undo--wrap-and-run-primitive-undo'."
3601 (let ((old-bul buffer-undo-list)
3602 (end-marker (copy-marker end t))
3604 (if undo--combining-change-calls
3605 (setq result (funcall body))
3606 (let ((undo--combining-change-calls t))
3607 (if (not inhibit-modification-hooks)
3608 (run-hook-with-args 'before-change-functions beg end))
3609 (if (eq buffer-undo-list t)
3610 (setq result (funcall body))
3611 (let (;; (inhibit-modification-hooks t)
3612 before-change-functions after-change-functions)
3613 (setq result (funcall body)))
3618 (marker-position end-marker)
3619 #'undo--wrap-and-run-primitive-undo
3620 beg (marker-position end-marker) buffer-undo-list))
3621 (ptr buffer-undo-list))
3622 (if (not (eq buffer-undo-list old-bul))
3624 (while (and (not (eq (cdr ptr) old-bul))
3625 ;; In case garbage collection has removed OLD-BUL.
3627 ;; Don't include a timestamp entry.
3628 (not (and (consp (cdr ptr))
3631 (setq old-bul (cdr ptr)))))
3632 (setq ptr (cdr ptr)))
3634 (message "combine-change-calls: buffer-undo-list broken"))
3636 (push ap-elt buffer-undo-list)
3637 (setcdr buffer-undo-list old-bul)))))
3638 (if (not inhibit-modification-hooks)
3639 (run-hook-with-args 'after-change-functions
3640 beg (marker-position end-marker)
3642 (set-marker end-marker nil)
3645 (defmacro combine-change-calls (beg end &rest body)
3646 "Evaluate BODY, running the change hooks just once.
3648 BODY is a sequence of lisp forms to evaluate. BEG and END bound
3649 the region the change hooks will be run for.
3651 Firstly, `before-change-functions' is invoked for the region
3652 \(BEG END), then the BODY forms are evaluated with
3653 `before-change-functions' and `after-change-functions' bound to
3654 nil, and finally `after-change-functions' is invoked on the
3655 updated region. The change hooks are not run if
3656 `inhibit-modification-hooks' is initially non-nil.
3658 The result of `combine-change-calls' is the value returned by the
3659 last of the BODY forms to be evaluated. BODY may not make a
3660 different buffer current, except temporarily. BODY may not
3661 change the buffer outside the specified region. It must not
3662 change `before-change-functions' or `after-change-functions'.
3664 Additionally, the buffer modifications of BODY are recorded on
3665 the buffer's undo list as a single \(apply ...) entry containing
3666 the function `undo--wrap-and-run-primitive-undo'. "
3667 `(combine-change-calls-1 ,beg ,end (lambda () ,@body)))
3669 (defun undo--wrap-and-run-primitive-undo (beg end list)
3670 "Call `primitive-undo' on the undo elements in LIST.
3672 This function is intended to be called purely by `undo' as the
3673 function in an \(apply DELTA BEG END FUNNAME . ARGS) undo
3674 element. It invokes `before-change-functions' and
3675 `after-change-functions' once each for the entire region \(BEG
3676 END) rather than once for each individual change.
3678 Additionally the fresh \"redo\" elements which are generated on
3679 `buffer-undo-list' will themselves be \"enclosed\" in
3680 `undo--wrap-and-run-primitive-undo'.
3682 Undo elements of this form are generated by the macro
3683 `combine-change-calls'."
3684 (combine-change-calls beg end
3686 (setq list (primitive-undo 1 list)))))
3688 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3690 (defmacro with-case-table (table &rest body)
3691 "Execute the forms in BODY with TABLE as the current case table.
3692 The value returned is the value of the last form in BODY."
3693 (declare (indent 1) (debug t))
3694 (let ((old-case-table (make-symbol "table"))
3695 (old-buffer (make-symbol "buffer")))
3696 `(let ((,old-case-table (current-case-table))
3697 (,old-buffer (current-buffer)))
3699 (progn (set-case-table ,table)
3701 (with-current-buffer ,old-buffer
3702 (set-case-table ,old-case-table))))))
3704 (defmacro with-file-modes (modes &rest body)
3705 "Execute BODY with default file permissions temporarily set to MODES.
3706 MODES is as for `set-default-file-modes'."
3707 (declare (indent 1) (debug t))
3708 (let ((umask (make-symbol "umask")))
3709 `(let ((,umask (default-file-modes)))
3712 (set-default-file-modes ,modes)
3714 (set-default-file-modes ,umask)))))
3717 ;;; Matching and match data.
3719 (defvar save-match-data-internal)
3721 ;; We use save-match-data-internal as the local variable because
3722 ;; that works ok in practice (people should not use that variable elsewhere).
3723 ;; We used to use an uninterned symbol; the compiler handles that properly
3724 ;; now, but it generates slower code.
3725 (defmacro save-match-data (&rest body)
3726 "Execute the BODY forms, restoring the global value of the match data.
3727 The value returned is the value of the last form in BODY."
3728 ;; It is better not to use backquote here,
3729 ;; because that makes a bootstrapping problem
3730 ;; if you need to recompile all the Lisp files using interpreted code.
3731 (declare (indent 0) (debug t))
3733 '((save-match-data-internal (match-data)))
3734 (list 'unwind-protect
3736 ;; It is safe to free (evaporate) markers immediately here,
3737 ;; as Lisp programs should not copy from save-match-data-internal.
3738 '(set-match-data save-match-data-internal 'evaporate))))
3740 (defun match-string (num &optional string)
3741 "Return string of text matched by last search.
3742 NUM specifies which parenthesized expression in the last regexp.
3743 Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
3744 Zero means the entire text matched by the whole regexp or whole string.
3745 STRING should be given if the last search was by `string-match' on STRING.
3746 If STRING is nil, the current buffer should be the same buffer
3747 the search/match was performed in."
3748 (if (match-beginning num)
3750 (substring string (match-beginning num) (match-end num))
3751 (buffer-substring (match-beginning num) (match-end num)))))
3753 (defun match-string-no-properties (num &optional string)
3754 "Return string of text matched by last search, without text properties.
3755 NUM specifies which parenthesized expression in the last regexp.
3756 Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
3757 Zero means the entire text matched by the whole regexp or whole string.
3758 STRING should be given if the last search was by `string-match' on STRING.
3759 If STRING is nil, the current buffer should be the same buffer
3760 the search/match was performed in."
3761 (if (match-beginning num)
3763 (substring-no-properties string (match-beginning num)
3765 (buffer-substring-no-properties (match-beginning num)
3769 (defun match-substitute-replacement (replacement
3770 &optional fixedcase literal string subexp)
3771 "Return REPLACEMENT as it will be inserted by `replace-match'.
3772 In other words, all back-references in the form `\\&' and `\\N'
3773 are substituted with actual strings matched by the last search.
3774 Optional FIXEDCASE, LITERAL, STRING and SUBEXP have the same
3775 meaning as for `replace-match'."
3776 (let ((match (match-string 0 string)))
3778 (set-match-data (mapcar (lambda (x)
3780 (- x (match-beginning 0))
3783 (replace-match replacement fixedcase literal match subexp))))
3786 (defun looking-back (regexp &optional limit greedy)
3787 "Return non-nil if text before point matches regular expression REGEXP.
3788 Like `looking-at' except matches before point, and is slower.
3789 LIMIT if non-nil speeds up the search by specifying a minimum
3790 starting position, to avoid checking matches that would start
3793 If GREEDY is non-nil, extend the match backwards as far as
3794 possible, stopping when a single additional previous character
3795 cannot be part of a match for REGEXP. When the match is
3796 extended, its starting position is allowed to occur before
3799 As a general recommendation, try to avoid using `looking-back'
3800 wherever possible, since it is slow."
3802 (advertised-calling-convention (regexp limit &optional greedy) "25.1"))
3803 (let ((start (point))
3806 (and (re-search-backward (concat "\\(?:" regexp "\\)\\=") limit t)
3808 (if (and greedy pos)
3810 (narrow-to-region (point-min) start)
3811 (while (and (> pos (point-min))
3815 (looking-at (concat "\\(?:" regexp "\\)\\'"))))
3816 (setq pos (1- pos)))
3819 (looking-at (concat "\\(?:" regexp "\\)\\'")))))
3822 (defsubst looking-at-p (regexp)
3824 Same as `looking-at' except this function does not change the match data."
3825 (let ((inhibit-changing-match-data t))
3826 (looking-at regexp)))
3828 (defsubst string-match-p (regexp string &optional start)
3830 Same as `string-match' except this function does not change the match data."
3831 (let ((inhibit-changing-match-data t))
3832 (string-match regexp string start)))
3834 (defun subregexp-context-p (regexp pos &optional start)
3835 "Return non-nil if POS is in a normal subregexp context in REGEXP.
3836 A subregexp context is one where a sub-regexp can appear.
3837 A non-subregexp context is for example within brackets, or within a
3838 repetition bounds operator `\\=\\{...\\}', or right after a `\\'.
3839 If START is non-nil, it should be a position in REGEXP, smaller
3840 than POS, and known to be in a subregexp context."
3841 ;; Here's one possible implementation, with the great benefit that it
3842 ;; reuses the regexp-matcher's own parser, so it understands all the
3843 ;; details of the syntax. A disadvantage is that it needs to match the
3847 (string-match (substring regexp (or start 0) pos) "")
3850 (not (member (cadr err) '("Unmatched [ or [^"
3852 "Trailing backslash")))))
3853 ;; An alternative implementation:
3854 ;; (defconst re-context-re
3855 ;; (let* ((harmless-ch "[^\\[]")
3856 ;; (harmless-esc "\\\\[^{]")
3857 ;; (class-harmless-ch "[^][]")
3858 ;; (class-lb-harmless "[^]:]")
3859 ;; (class-lb-colon-maybe-charclass ":\\([a-z]+:]\\)?")
3860 ;; (class-lb (concat "\\[\\(" class-lb-harmless
3861 ;; "\\|" class-lb-colon-maybe-charclass "\\)"))
3863 ;; (concat "\\[^?]?"
3864 ;; "\\(" class-harmless-ch
3865 ;; "\\|" class-lb "\\)*"
3866 ;; "\\[?]")) ; special handling for bare [ at end of re
3867 ;; (braces "\\\\{[0-9,]+\\\\}"))
3868 ;; (concat "\\`\\(" harmless-ch "\\|" harmless-esc
3869 ;; "\\|" class "\\|" braces "\\)*\\'"))
3870 ;; "Matches any prefix that corresponds to a normal subregexp context.")
3871 ;; (string-match re-context-re (substring regexp (or start 0) pos))
3876 (defconst split-string-default-separators "[ \f\t\n\r\v]+"
3877 "The default value of separators for `split-string'.
3879 A regexp matching strings of whitespace. May be locale-dependent
3880 \(as yet unimplemented). Should not match non-breaking spaces.
3882 Warning: binding this to a different value and using it as default is
3883 likely to have undesired semantics.")
3885 ;; The specification says that if both SEPARATORS and OMIT-NULLS are
3886 ;; defaulted, OMIT-NULLS should be treated as t. Simplifying the logical
3887 ;; expression leads to the equivalent implementation that if SEPARATORS
3888 ;; is defaulted, OMIT-NULLS is treated as t.
3889 (defun split-string (string &optional separators omit-nulls trim)
3890 "Split STRING into substrings bounded by matches for SEPARATORS.
3892 The beginning and end of STRING, and each match for SEPARATORS, are
3893 splitting points. The substrings matching SEPARATORS are removed, and
3894 the substrings between the splitting points are collected as a list,
3897 If SEPARATORS is non-nil, it should be a regular expression matching text
3898 which separates, but is not part of, the substrings. If nil it defaults to
3899 `split-string-default-separators', normally \"[ \\f\\t\\n\\r\\v]+\", and
3900 OMIT-NULLS is forced to t.
3902 If OMIT-NULLS is t, zero-length substrings are omitted from the list (so
3903 that for the default value of SEPARATORS leading and trailing whitespace
3904 are effectively trimmed). If nil, all zero-length substrings are retained,
3905 which correctly parses CSV format, for example.
3907 If TRIM is non-nil, it should be a regular expression to match
3908 text to trim from the beginning and end of each substring. If trimming
3909 makes the substring empty, it is treated as null.
3911 If you want to trim whitespace from the substrings, the reliably correct
3912 way is using TRIM. Making SEPARATORS match that whitespace gives incorrect
3913 results when there is whitespace at the start or end of STRING. If you
3914 see such calls to `split-string', please fix them.
3916 Note that the effect of `(split-string STRING)' is the same as
3917 `(split-string STRING split-string-default-separators t)'. In the rare
3918 case that you wish to retain zero-length substrings when splitting on
3919 whitespace, use `(split-string STRING split-string-default-separators)'.
3921 Modifies the match data; use `save-match-data' if necessary."
3922 (let* ((keep-nulls (not (if separators omit-nulls t)))
3923 (rexp (or separators split-string-default-separators))
3929 ;; Push the substring in range THIS-START to THIS-END
3930 ;; onto LIST, trimming it and perhaps discarding it.
3933 ;; Discard the trim from start of this substring.
3934 (let ((tem (string-match trim string this-start)))
3935 (and (eq tem this-start)
3936 (setq this-start (match-end 0)))))
3938 (when (or keep-nulls (< this-start this-end))
3939 (let ((this (substring string this-start this-end)))
3941 ;; Discard the trim from end of this substring.
3943 (let ((tem (string-match (concat trim "\\'") this 0)))
3944 (and tem (< tem (length this))
3945 (setq this (substring this 0 tem)))))
3947 ;; Trimming could make it empty; check again.
3948 (when (or keep-nulls (> (length this) 0))
3949 (push this list)))))))
3951 (while (and (string-match rexp string
3953 (= start (match-beginning 0))
3954 (< start (length string)))
3956 (< start (length string)))
3958 (setq this-start start this-end (match-beginning 0)
3959 start (match-end 0))
3963 ;; Handle the substring at the end of STRING.
3964 (setq this-start start this-end (length string))
3969 (defun combine-and-quote-strings (strings &optional separator)
3970 "Concatenate the STRINGS, adding the SEPARATOR (default \" \").
3971 This tries to quote the strings to avoid ambiguity such that
3972 (split-string-and-unquote (combine-and-quote-strings strs)) == strs
3973 Only some SEPARATORs will work properly.
3975 Note that this is not intended to protect STRINGS from
3976 interpretation by shells, use `shell-quote-argument' for that."
3977 (let* ((sep (or separator " "))
3978 (re (concat "[\\\"]" "\\|" (regexp-quote sep))))
3981 (if (string-match re str)
3982 (concat "\"" (replace-regexp-in-string "[\\\"]" "\\\\\\&" str) "\"")
3986 (defun split-string-and-unquote (string &optional separator)
3987 "Split the STRING into a list of strings.
3988 It understands Emacs Lisp quoting within STRING, such that
3989 (split-string-and-unquote (combine-and-quote-strings strs)) == strs
3990 The SEPARATOR regexp defaults to \"\\s-+\"."
3991 (let ((sep (or separator "\\s-+"))
3992 (i (string-match "\"" string)))
3994 (split-string string sep t) ; no quoting: easy
3995 (append (unless (eq i 0) (split-string (substring string 0 i) sep t))
3996 (let ((rfs (read-from-string string i)))
3998 (split-string-and-unquote (substring string (cdr rfs))
4002 ;;;; Replacement in strings.
4004 (defun subst-char-in-string (fromchar tochar string &optional inplace)
4005 "Replace FROMCHAR with TOCHAR in STRING each time it occurs.
4006 Unless optional argument INPLACE is non-nil, return a new string."
4007 (let ((i (length string))
4008 (newstr (if inplace string (copy-sequence string))))
4011 (if (eq (aref newstr i) fromchar)
4012 (aset newstr i tochar)))
4015 (defun replace-regexp-in-string (regexp rep string &optional
4016 fixedcase literal subexp start)
4017 "Replace all matches for REGEXP with REP in STRING.
4019 Return a new string containing the replacements.
4021 Optional arguments FIXEDCASE, LITERAL and SUBEXP are like the
4022 arguments with the same names of function `replace-match'. If START
4023 is non-nil, start replacements at that index in STRING.
4025 REP is either a string used as the NEWTEXT arg of `replace-match' or a
4026 function. If it is a function, it is called with the actual text of each
4027 match, and its value is used as the replacement text. When REP is called,
4028 the match data are the result of matching REGEXP against a substring
4029 of STRING, the same substring that is the actual text of the match which
4030 is passed to REP as its argument.
4032 To replace only the first match (if any), make REGEXP match up to \\\\='
4033 and replace a sub-expression, e.g.
4034 (replace-regexp-in-string \"\\\\(foo\\\\).*\\\\\\='\" \"bar\" \" foo foo\" nil nil 1)
4037 ;; To avoid excessive consing from multiple matches in long strings,
4038 ;; don't just call `replace-match' continually. Walk down the
4039 ;; string looking for matches of REGEXP and building up a (reversed)
4040 ;; list MATCHES. This comprises segments of STRING which weren't
4041 ;; matched interspersed with replacements for segments that were.
4042 ;; [For a `large' number of replacements it's more efficient to
4043 ;; operate in a temporary buffer; we can't tell from the function's
4044 ;; args whether to choose the buffer-based implementation, though it
4045 ;; might be reasonable to do so for long enough STRING.]
4046 (let ((l (length string))
4047 (start (or start 0))
4050 (while (and (< start l) (string-match regexp string start))
4051 (setq mb (match-beginning 0)
4053 ;; If we matched the empty string, make sure we advance by one char
4054 (when (= me mb) (setq me (min l (1+ mb))))
4055 ;; Generate a replacement for the matched substring.
4056 ;; Operate only on the substring to minimize string consing.
4057 ;; Set up match data for the substring for replacement;
4058 ;; presumably this is likely to be faster than munging the
4059 ;; match data directly in Lisp.
4060 (string-match regexp (setq str (substring string mb me)))
4062 (cons (replace-match (if (stringp rep)
4064 (funcall rep (match-string 0 str)))
4065 fixedcase literal str subexp)
4066 (cons (substring string start mb) ; unmatched prefix
4069 ;; Reconstruct a string from the pieces.
4070 (setq matches (cons (substring string start l) matches)) ; leftover
4071 (apply #'concat (nreverse matches)))))
4073 (defun string-prefix-p (prefix string &optional ignore-case)
4074 "Return non-nil if PREFIX is a prefix of STRING.
4075 If IGNORE-CASE is non-nil, the comparison is done without paying attention
4076 to case differences."
4077 (let ((prefix-length (length prefix)))
4078 (if (> prefix-length (length string)) nil
4079 (eq t (compare-strings prefix 0 prefix-length string
4080 0 prefix-length ignore-case)))))
4082 (defun string-suffix-p (suffix string &optional ignore-case)
4083 "Return non-nil if SUFFIX is a suffix of STRING.
4084 If IGNORE-CASE is non-nil, the comparison is done without paying
4085 attention to case differences."
4086 (let ((start-pos (- (length string) (length suffix))))
4087 (and (>= start-pos 0)
4088 (eq t (compare-strings suffix nil nil
4089 string start-pos nil ignore-case)))))
4091 (defun bidi-string-mark-left-to-right (str)
4092 "Return a string that can be safely inserted in left-to-right text.
4094 Normally, inserting a string with right-to-left (RTL) script into
4095 a buffer may cause some subsequent text to be displayed as part
4096 of the RTL segment (usually this affects punctuation characters).
4097 This function returns a string which displays as STR but forces
4098 subsequent text to be displayed as left-to-right.
4100 If STR contains any RTL character, this function returns a string
4101 consisting of STR followed by an invisible left-to-right mark
4102 \(LRM) character. Otherwise, it returns STR."
4103 (unless (stringp str)
4104 (signal 'wrong-type-argument (list 'stringp str)))
4105 (if (string-match "\\cR" str)
4106 (concat str (propertize (string ?\x200e) 'invisible t))
4109 (defun string-greaterp (string1 string2)
4110 "Return non-nil if STRING1 is greater than STRING2 in lexicographic order.
4111 Case is significant.
4112 Symbols are also allowed; their print names are used instead."
4113 (string-lessp string2 string1))
4116 ;;;; Specifying things to do later.
4118 (defun load-history-regexp (file)
4119 "Form a regexp to find FILE in `load-history'.
4120 FILE, a string, is described in the function `eval-after-load'."
4121 (if (file-name-absolute-p file)
4122 (setq file (file-truename file)))
4123 (concat (if (file-name-absolute-p file) "\\`" "\\(\\`\\|/\\)")
4125 (if (file-name-extension file)
4127 ;; Note: regexp-opt can't be used here, since we need to call
4128 ;; this before Emacs has been fully started. 2006-05-21
4129 (concat "\\(" (mapconcat 'regexp-quote load-suffixes "\\|") "\\)?"))
4130 "\\(" (mapconcat 'regexp-quote jka-compr-load-suffixes "\\|")
4133 (defun load-history-filename-element (file-regexp)
4134 "Get the first elt of `load-history' whose car matches FILE-REGEXP.
4135 Return nil if there isn't one."
4136 (let* ((loads load-history)
4137 (load-elt (and loads (car loads))))
4140 (or (null (car load-elt))
4141 (not (string-match file-regexp (car load-elt)))))
4142 (setq loads (cdr loads)
4143 load-elt (and loads (car loads)))))
4146 (put 'eval-after-load 'lisp-indent-function 1)
4147 (defun eval-after-load (file form)
4148 "Arrange that if FILE is loaded, FORM will be run immediately afterwards.
4149 If FILE is already loaded, evaluate FORM right now.
4150 FORM can be an Elisp expression (in which case it's passed to `eval'),
4151 or a function (in which case it's passed to `funcall' with no argument).
4153 If a matching file is loaded again, FORM will be evaluated again.
4155 If FILE is a string, it may be either an absolute or a relative file
4156 name, and may have an extension (e.g. \".el\") or may lack one, and
4157 additionally may or may not have an extension denoting a compressed
4158 format (e.g. \".gz\").
4160 When FILE is absolute, this first converts it to a true name by chasing
4161 symbolic links. Only a file of this name (see next paragraph regarding
4162 extensions) will trigger the evaluation of FORM. When FILE is relative,
4163 a file whose absolute true name ends in FILE will trigger evaluation.
4165 When FILE lacks an extension, a file name with any extension will trigger
4166 evaluation. Otherwise, its extension must match FILE's. A further
4167 extension for a compressed format (e.g. \".gz\") on FILE will not affect
4170 Alternatively, FILE can be a feature (i.e. a symbol), in which case FORM
4171 is evaluated at the end of any file that `provide's this feature.
4172 If the feature is provided when evaluating code not associated with a
4173 file, FORM is evaluated immediately after the provide statement.
4175 Usually FILE is just a library name like \"font-lock\" or a feature name
4178 This function makes or adds to an entry on `after-load-alist'."
4179 (declare (compiler-macro
4181 (if (eq 'quote (car-safe form))
4182 ;; Quote with lambda so the compiler can look inside.
4183 `(eval-after-load ,file (lambda () ,(nth 1 form)))
4185 ;; Add this FORM into after-load-alist (regardless of whether we'll be
4186 ;; evaluating it now).
4187 (let* ((regexp-or-feature
4189 (setq file (purecopy (load-history-regexp file)))
4191 (elt (assoc regexp-or-feature after-load-alist))
4193 (if (functionp form) form
4194 ;; Try to use the "current" lexical/dynamic mode for `form'.
4195 (eval `(lambda () ,form) lexical-binding))))
4197 (setq elt (list regexp-or-feature))
4198 (push elt after-load-alist))
4199 ;; Is there an already loaded file whose name (or `provide' name)
4201 (prog1 (if (if (stringp file)
4202 (load-history-filename-element regexp-or-feature)
4206 (if (not (symbolp regexp-or-feature)) func
4207 ;; For features, the after-load-alist elements get run when
4208 ;; `provide' is called rather than at the end of the file.
4209 ;; So add an indirection to make sure that `func' is really run
4210 ;; "after-load" in case the provide call happens early.
4212 (if (not load-file-name)
4213 ;; Not being provided from a file, run func right now.
4215 (let ((lfn load-file-name)
4216 ;; Don't use letrec, because equal (in
4217 ;; add/remove-hook) would get trapped in a cycle.
4218 (fun (make-symbol "eval-after-load-helper")))
4219 (fset fun (lambda (file)
4220 (when (equal file lfn)
4221 (remove-hook 'after-load-functions fun)
4223 (add-hook 'after-load-functions fun 'append)))))))
4224 ;; Add FORM to the element unless it's already there.
4225 (unless (member delayed-func (cdr elt))
4226 (nconc elt (list delayed-func)))))))
4228 (defmacro with-eval-after-load (file &rest body)
4229 "Execute BODY after FILE is loaded.
4230 FILE is normally a feature name, but it can also be a file name,
4231 in case that file does not provide any feature. See `eval-after-load'
4232 for more details about the different forms of FILE and their semantics."
4233 (declare (indent 1) (debug t))
4234 `(eval-after-load ,file (lambda () ,@body)))
4236 (defvar after-load-functions nil
4237 "Special hook run after loading a file.
4238 Each function there is called with a single argument, the absolute
4239 name of the file just loaded.")
4241 (defun do-after-load-evaluation (abs-file)
4242 "Evaluate all `eval-after-load' forms, if any, for ABS-FILE.
4243 ABS-FILE, a string, should be the absolute true name of a file just loaded.
4244 This function is called directly from the C code."
4245 ;; Run the relevant eval-after-load forms.
4246 (dolist (a-l-element after-load-alist)
4247 (when (and (stringp (car a-l-element))
4248 (string-match-p (car a-l-element) abs-file))
4249 ;; discard the file name regexp
4250 (mapc #'funcall (cdr a-l-element))))
4251 ;; Complain when the user uses obsolete files.
4252 (when (string-match-p "/obsolete/\\([^/]*\\)\\'" abs-file)
4253 ;; Maybe we should just use display-warning? This seems yucky...
4254 (let* ((file (file-name-nondirectory abs-file))
4255 (msg (format "Package %s is obsolete!"
4257 (string-match "\\.elc?\\>" file)))))
4258 ;; Cribbed from cl--compiling-file.
4259 (if (and (boundp 'byte-compile--outbuffer)
4260 (bufferp (symbol-value 'byte-compile--outbuffer))
4261 (equal (buffer-name (symbol-value 'byte-compile--outbuffer))
4262 " *Compiler Output*"))
4263 ;; Don't warn about obsolete files using other obsolete files.
4264 (unless (and (stringp byte-compile-current-file)
4265 (string-match-p "/obsolete/[^/]*\\'"
4267 byte-compile-current-file
4268 byte-compile-root-dir)))
4269 (byte-compile-warn "%s" msg))
4270 (run-with-timer 0 nil
4275 ;; Finally, run any other hook.
4276 (run-hook-with-args 'after-load-functions abs-file))
4278 (defun eval-next-after-load (file)
4279 "Read the following input sexp, and run it whenever FILE is loaded.
4280 This makes or adds to an entry on `after-load-alist'.
4281 FILE should be the name of a library, with no directory name."
4282 (declare (obsolete eval-after-load "23.2"))
4283 (eval-after-load file (read)))
4286 (defun display-delayed-warnings ()
4287 "Display delayed warnings from `delayed-warnings-list'.
4288 Used from `delayed-warnings-hook' (which see)."
4289 (dolist (warning (nreverse delayed-warnings-list))
4290 (apply 'display-warning warning))
4291 (setq delayed-warnings-list nil))
4293 (defun collapse-delayed-warnings ()
4294 "Remove duplicates from `delayed-warnings-list'.
4295 Collapse identical adjacent warnings into one (plus count).
4296 Used from `delayed-warnings-hook' (which see)."
4299 (while delayed-warnings-list
4300 (setq warning (pop delayed-warnings-list))
4301 (if (equal warning (car delayed-warnings-list))
4302 (setq count (1+ count))
4304 (setcdr warning (cons (format "%s [%d times]" (cadr warning) count)
4307 (push warning collapsed)))
4308 (setq delayed-warnings-list (nreverse collapsed))))
4310 ;; At present this is only used for Emacs internals.
4311 ;; Ref https://lists.gnu.org/r/emacs-devel/2012-02/msg00085.html
4312 (defvar delayed-warnings-hook '(collapse-delayed-warnings
4313 display-delayed-warnings)
4314 "Normal hook run to process and display delayed warnings.
4315 By default, this hook contains functions to consolidate the
4316 warnings listed in `delayed-warnings-list', display them, and set
4317 `delayed-warnings-list' back to nil.")
4319 (defun delay-warning (type message &optional level buffer-name)
4320 "Display a delayed warning.
4321 Aside from going through `delayed-warnings-list', this is equivalent
4322 to `display-warning'."
4323 (push (list type message level buffer-name) delayed-warnings-list))
4326 ;;;; invisibility specs
4328 (defun add-to-invisibility-spec (element)
4329 "Add ELEMENT to `buffer-invisibility-spec'.
4330 See documentation for `buffer-invisibility-spec' for the kind of elements
4332 (if (eq buffer-invisibility-spec t)
4333 (setq buffer-invisibility-spec (list t)))
4334 (setq buffer-invisibility-spec
4335 (cons element buffer-invisibility-spec)))
4337 (defun remove-from-invisibility-spec (element)
4338 "Remove ELEMENT from `buffer-invisibility-spec'."
4339 (setq buffer-invisibility-spec
4340 (if (consp buffer-invisibility-spec)
4341 (delete element buffer-invisibility-spec)
4346 (defmacro with-syntax-table (table &rest body)
4347 "Evaluate BODY with syntax table of current buffer set to TABLE.
4348 The syntax table of the current buffer is saved, BODY is evaluated, and the
4349 saved table is restored, even in case of an abnormal exit.
4350 Value is what BODY returns."
4351 (declare (debug t) (indent 1))
4352 (let ((old-table (make-symbol "table"))
4353 (old-buffer (make-symbol "buffer")))
4354 `(let ((,old-table (syntax-table))
4355 (,old-buffer (current-buffer)))
4358 (set-syntax-table ,table)
4360 (save-current-buffer
4361 (set-buffer ,old-buffer)
4362 (set-syntax-table ,old-table))))))
4364 (defun make-syntax-table (&optional oldtable)
4365 "Return a new syntax table.
4366 Create a syntax table which inherits from OLDTABLE (if non-nil) or
4367 from `standard-syntax-table' otherwise."
4368 (let ((table (make-char-table 'syntax-table nil)))
4369 (set-char-table-parent table (or oldtable (standard-syntax-table)))
4372 (defun syntax-after (pos)
4373 "Return the raw syntax descriptor for the char after POS.
4374 If POS is outside the buffer's accessible portion, return nil."
4375 (unless (or (< pos (point-min)) (>= pos (point-max)))
4376 (let ((st (if parse-sexp-lookup-properties
4377 (get-char-property pos 'syntax-table))))
4379 (aref (or st (syntax-table)) (char-after pos))))))
4381 (defun syntax-class (syntax)
4382 "Return the code for the syntax class described by SYNTAX.
4384 SYNTAX should be a raw syntax descriptor; the return value is a
4385 integer which encodes the corresponding syntax class. See Info
4386 node `(elisp)Syntax Table Internals' for a list of codes.
4388 If SYNTAX is nil, return nil."
4389 (and syntax (logand (car syntax) 65535)))
4391 ;; Utility motion commands
4393 (defvar word-move-empty-char-table nil
4394 "Used in `forward-word-strictly' and `backward-word-strictly'
4395 to countermand the effect of `find-word-boundary-function-table'.")
4397 (defun forward-word-strictly (&optional arg)
4398 "Move point forward ARG words (backward if ARG is negative).
4399 If ARG is omitted or nil, move point forward one word.
4401 If an edge of the buffer or a field boundary is reached, point is left there
4402 and the function returns nil. Field boundaries are not noticed if
4403 `inhibit-field-text-motion' is non-nil.
4405 This function is like `forward-word', but it is not affected
4406 by `find-word-boundary-function-table'. It is also not interactive."
4407 (let ((find-word-boundary-function-table
4408 (if (char-table-p word-move-empty-char-table)
4409 word-move-empty-char-table
4410 (setq word-move-empty-char-table (make-char-table nil)))))
4411 (forward-word (or arg 1))))
4413 (defun backward-word-strictly (&optional arg)
4414 "Move backward until encountering the beginning of a word.
4415 With argument ARG, do this that many times.
4416 If ARG is omitted or nil, move point backward one word.
4418 This function is like `forward-word', but it is not affected
4419 by `find-word-boundary-function-table'. It is also not interactive."
4420 (let ((find-word-boundary-function-table
4421 (if (char-table-p word-move-empty-char-table)
4422 word-move-empty-char-table
4423 (setq word-move-empty-char-table (make-char-table nil)))))
4424 (forward-word (- (or arg 1)))))
4428 (defun forward-whitespace (arg)
4429 "Move point to the end of the next sequence of whitespace chars.
4430 Each such sequence may be a single newline, or a sequence of
4431 consecutive space and/or tab characters.
4432 With prefix argument ARG, do it ARG times if positive, or move
4433 backwards ARG times if negative."
4436 (re-search-forward "[ \t]+\\|\n" nil 'move arg)
4438 (if (re-search-backward "[ \t]+\\|\n" nil 'move)
4439 (or (eq (char-after (match-beginning 0)) ?\n)
4440 (skip-chars-backward " \t")))
4441 (setq arg (1+ arg)))))
4445 (defun forward-symbol (arg)
4446 "Move point to the next position that is the end of a symbol.
4447 A symbol is any sequence of characters that are in either the
4448 word constituent or symbol constituent syntax class.
4449 With prefix argument ARG, do it ARG times if positive, or move
4450 backwards ARG times if negative."
4453 (re-search-forward "\\(\\sw\\|\\s_\\)+" nil 'move arg)
4455 (if (re-search-backward "\\(\\sw\\|\\s_\\)+" nil 'move)
4456 (skip-syntax-backward "w_"))
4457 (setq arg (1+ arg)))))
4461 (defun forward-same-syntax (&optional arg)
4462 "Move point past all characters with the same syntax class.
4463 With prefix argument ARG, do it ARG times if positive, or move
4464 backwards ARG times if negative."
4466 (or arg (setq arg 1))
4468 (skip-syntax-backward
4469 (char-to-string (char-syntax (char-before))))
4470 (setq arg (1+ arg)))
4472 (skip-syntax-forward (char-to-string (char-syntax (char-after))))
4473 (setq arg (1- arg))))
4478 (defvar text-clone--maintaining nil)
4480 (defun text-clone--maintain (ol1 after beg end &optional _len)
4481 "Propagate the changes made under the overlay OL1 to the other clones.
4482 This is used on the `modification-hooks' property of text clones."
4483 (when (and after (not undo-in-progress)
4484 (not text-clone--maintaining)
4485 (overlay-start ol1))
4486 (let ((margin (if (overlay-get ol1 'text-clone-spreadp) 1 0)))
4487 (setq beg (max beg (+ (overlay-start ol1) margin)))
4488 (setq end (min end (- (overlay-end ol1) margin)))
4491 (when (overlay-get ol1 'text-clone-syntax)
4492 ;; Check content of the clone's text.
4493 (let ((cbeg (+ (overlay-start ol1) margin))
4494 (cend (- (overlay-end ol1) margin)))
4497 (if (not (re-search-forward
4498 (overlay-get ol1 'text-clone-syntax) cend t))
4499 ;; Mark the overlay for deletion.
4501 (when (< (match-end 0) cend)
4502 ;; Shrink the clone at its end.
4503 (setq end (min end (match-end 0)))
4504 (move-overlay ol1 (overlay-start ol1)
4505 (+ (match-end 0) margin)))
4506 (when (> (match-beginning 0) cbeg)
4507 ;; Shrink the clone at its beginning.
4508 (setq beg (max (match-beginning 0) beg))
4509 (move-overlay ol1 (- (match-beginning 0) margin)
4510 (overlay-end ol1)))))))
4511 ;; Now go ahead and update the clones.
4512 (let ((head (- beg (overlay-start ol1)))
4513 (tail (- (overlay-end ol1) end))
4514 (str (buffer-substring beg end))
4516 (text-clone--maintaining t))
4517 (dolist (ol2 (overlay-get ol1 'text-clones))
4518 (let ((oe (overlay-end ol2)))
4519 (unless (or (eq ol1 ol2) (null oe))
4520 (setq nothing-left nil)
4521 (let ((mod-beg (+ (overlay-start ol2) head)))
4522 ;;(overlay-put ol2 'modification-hooks nil)
4523 (goto-char (- (overlay-end ol2) tail))
4524 (unless (> mod-beg (point))
4525 (save-excursion (insert str))
4526 (delete-region mod-beg (point)))
4527 ;;(overlay-put ol2 'modification-hooks '(text-clone--maintain))
4529 (if nothing-left (delete-overlay ol1))))))))
4531 (defun text-clone-create (start end &optional spreadp syntax)
4532 "Create a text clone of START...END at point.
4533 Text clones are chunks of text that are automatically kept identical:
4534 changes done to one of the clones will be immediately propagated to the other.
4536 The buffer's content at point is assumed to be already identical to
4537 the one between START and END.
4538 If SYNTAX is provided it's a regexp that describes the possible text of
4539 the clones; the clone will be shrunk or killed if necessary to ensure that
4540 its text matches the regexp.
4541 If SPREADP is non-nil it indicates that text inserted before/after the
4542 clone should be incorporated in the clone."
4543 ;; To deal with SPREADP we can either use an overlay with `nil t' along
4544 ;; with insert-(behind|in-front-of)-hooks or use a slightly larger overlay
4545 ;; (with a one-char margin at each end) with `t nil'.
4546 ;; We opted for a larger overlay because it behaves better in the case
4547 ;; where the clone is reduced to the empty string (we want the overlay to
4548 ;; stay when the clone's content is the empty string and we want to use
4549 ;; `evaporate' to make sure those overlays get deleted when needed).
4551 (let* ((pt-end (+ (point) (- end start)))
4552 (start-margin (if (or (not spreadp) (bobp) (<= start (point-min)))
4554 (end-margin (if (or (not spreadp)
4555 (>= pt-end (point-max))
4556 (>= start (point-max)))
4558 ;; FIXME: Reuse overlays at point to extend dups!
4559 (ol1 (make-overlay (- start start-margin) (+ end end-margin) nil t))
4560 (ol2 (make-overlay (- (point) start-margin) (+ pt-end end-margin) nil t))
4561 (dups (list ol1 ol2)))
4562 (overlay-put ol1 'modification-hooks '(text-clone--maintain))
4563 (when spreadp (overlay-put ol1 'text-clone-spreadp t))
4564 (when syntax (overlay-put ol1 'text-clone-syntax syntax))
4565 ;;(overlay-put ol1 'face 'underline)
4566 (overlay-put ol1 'evaporate t)
4567 (overlay-put ol1 'text-clones dups)
4569 (overlay-put ol2 'modification-hooks '(text-clone--maintain))
4570 (when spreadp (overlay-put ol2 'text-clone-spreadp t))
4571 (when syntax (overlay-put ol2 'text-clone-syntax syntax))
4572 ;;(overlay-put ol2 'face 'underline)
4573 (overlay-put ol2 'evaporate t)
4574 (overlay-put ol2 'text-clones dups)))
4576 ;;;; Mail user agents.
4578 ;; Here we include just enough for other packages to be able
4581 (defun define-mail-user-agent (symbol composefunc sendfunc
4582 &optional abortfunc hookvar)
4583 "Define a symbol to identify a mail-sending package for `mail-user-agent'.
4585 SYMBOL can be any Lisp symbol. Its function definition and/or
4586 value as a variable do not matter for this usage; we use only certain
4587 properties on its property list, to encode the rest of the arguments.
4589 COMPOSEFUNC is program callable function that composes an outgoing
4590 mail message buffer. This function should set up the basics of the
4591 buffer without requiring user interaction. It should populate the
4592 standard mail headers, leaving the `to:' and `subject:' headers blank
4595 COMPOSEFUNC should accept several optional arguments--the same
4596 arguments that `compose-mail' takes. See that function's documentation.
4598 SENDFUNC is the command a user would run to send the message.
4600 Optional ABORTFUNC is the command a user would run to abort the
4601 message. For mail packages that don't have a separate abort function,
4602 this can be `kill-buffer' (the equivalent of omitting this argument).
4604 Optional HOOKVAR is a hook variable that gets run before the message
4605 is actually sent. Callers that use the `mail-user-agent' may
4606 install a hook function temporarily on this hook variable.
4607 If HOOKVAR is nil, `mail-send-hook' is used.
4609 The properties used on SYMBOL are `composefunc', `sendfunc',
4610 `abortfunc', and `hookvar'."
4611 (put symbol 'composefunc composefunc)
4612 (put symbol 'sendfunc sendfunc)
4613 (put symbol 'abortfunc (or abortfunc 'kill-buffer))
4614 (put symbol 'hookvar (or hookvar 'mail-send-hook)))
4617 (defun backtrace--print-frame (evald func args flags)
4618 "Print a trace of a single stack frame to `standard-output'.
4619 EVALD, FUNC, ARGS, FLAGS are as in `mapbacktrace'."
4620 (princ (if (plist-get flags :debug-on-exit) "* " " "))
4622 ((and evald (not debugger-stack-frame-as-list))
4624 (if args (cl-prin1 args) (princ "()")))
4626 (cl-prin1 (cons func args))))
4630 "Print a trace of Lisp function calls currently active.
4631 Output stream used is value of `standard-output'."
4632 (let ((print-level (or print-level 8))
4633 (print-escape-control-characters t))
4634 (mapbacktrace #'backtrace--print-frame 'backtrace)))
4636 (defun backtrace-frames (&optional base)
4637 "Collect all frames of current backtrace into a list.
4638 If non-nil, BASE should be a function, and frames before its
4639 nearest activation frames are discarded."
4641 (mapbacktrace (lambda (&rest frame) (push frame frames))
4642 (or base 'backtrace-frames))
4645 (defun backtrace-frame (nframes &optional base)
4646 "Return the function and arguments NFRAMES up from current execution point.
4647 If non-nil, BASE should be a function, and NFRAMES counts from its
4648 nearest activation frame.
4649 If the frame has not evaluated the arguments yet (or is a special form),
4650 the value is (nil FUNCTION ARG-FORMS...).
4651 If the frame has evaluated its arguments and called its function already,
4652 the value is (t FUNCTION ARG-VALUES...).
4653 A &rest arg is represented as the tail of the list ARG-VALUES.
4654 FUNCTION is whatever was supplied as car of evaluated list,
4655 or a lambda expression for macro calls.
4656 If NFRAMES is more than the number of frames, the value is nil."
4657 (backtrace-frame--internal
4658 (lambda (evald func args _) `(,evald ,func ,@args))
4659 nframes (or base 'backtrace-frame)))
4662 (defvar called-interactively-p-functions nil
4663 "Special hook called to skip special frames in `called-interactively-p'.
4664 The functions are called with 3 arguments: (I FRAME1 FRAME2),
4665 where FRAME1 is a \"current frame\", FRAME2 is the next frame,
4666 I is the index of the frame after FRAME2. It should return nil
4667 if those frames don't seem special and otherwise, it should return
4668 the number of frames to skip (minus 1).")
4670 (defconst internal--funcall-interactively
4671 (symbol-function 'funcall-interactively))
4673 (defun called-interactively-p (&optional kind)
4674 "Return t if the containing function was called by `call-interactively'.
4675 If KIND is `interactive', then only return t if the call was made
4676 interactively by the user, i.e. not in `noninteractive' mode nor
4677 when `executing-kbd-macro'.
4678 If KIND is `any', on the other hand, it will return t for any kind of
4679 interactive call, including being called as the binding of a key or
4680 from a keyboard macro, even in `noninteractive' mode.
4682 This function is very brittle, it may fail to return the intended result when
4683 the code is debugged, advised, or instrumented in some form. Some macros and
4684 special forms (such as `condition-case') may also sometimes wrap their bodies
4685 in a `lambda', so any call to `called-interactively-p' from those bodies will
4686 indicate whether that lambda (rather than the surrounding function) was called
4689 Instead of using this function, it is cleaner and more reliable to give your
4690 function an extra optional argument whose `interactive' spec specifies
4691 non-nil unconditionally (\"p\" is a good way to do this), or via
4692 \(not (or executing-kbd-macro noninteractive)).
4694 The only known proper use of `interactive' for KIND is in deciding
4695 whether to display a helpful message, or how to display it. If you're
4696 thinking of using it for any other purpose, it is quite likely that
4697 you're making a mistake. Think: what do you want to do when the
4698 command is called from a keyboard macro?"
4699 (declare (advertised-calling-convention (kind) "23.1"))
4700 (when (not (and (eq kind 'interactive)
4701 (or executing-kbd-macro noninteractive)))
4702 (let* ((i 1) ;; 0 is the called-interactively-p frame.
4706 (setq frame nextframe)
4707 (setq nextframe (backtrace-frame i 'called-interactively-p))
4708 ;; (message "Frame %d = %S" i nextframe)
4710 (funcall get-next-frame) ;; Get the first frame.
4712 ;; FIXME: The edebug and advice handling should be made modular and
4713 ;; provided directly by edebug.el and nadvice.el.
4715 ;; frame =(backtrace-frame i-2)
4716 ;; nextframe=(backtrace-frame i-1)
4717 (funcall get-next-frame)
4718 ;; `pcase' would be a fairly good fit here, but it sometimes moves
4719 ;; branches within local functions, which then messes up the
4720 ;; `backtrace-frame' data we get,
4722 ;; Skip special forms (from non-compiled code).
4723 (and frame (null (car frame)))
4724 ;; Skip also `interactive-p' (because we don't want to know if
4725 ;; interactive-p was called interactively but if it's caller was)
4726 ;; and `byte-code' (idem; this appears in subexpressions of things
4727 ;; like condition-case, which are wrapped in a separate bytecode
4729 ;; FIXME: For lexical-binding code, this is much worse,
4730 ;; because the frames look like "byte-code -> funcall -> #[...]",
4731 ;; which is not a reliable signature.
4732 (memq (nth 1 frame) '(interactive-p 'byte-code))
4733 ;; Skip package-specific stack-frames.
4734 (let ((skip (run-hook-with-args-until-success
4735 'called-interactively-p-functions
4736 i frame nextframe)))
4740 (_ (setq i (+ i skip -1)) (funcall get-next-frame)))))))
4741 ;; Now `frame' should be "the function from which we were called".
4742 (pcase (cons frame nextframe)
4743 ;; No subr calls `interactive-p', so we can rule that out.
4744 (`((,_ ,(pred (lambda (f) (subrp (indirect-function f)))) . ,_) . ,_) nil)
4745 ;; In case #<subr funcall-interactively> without going through the
4746 ;; `funcall-interactively' symbol (bug#3984).
4747 (`(,_ . (t ,(pred (lambda (f)
4748 (eq internal--funcall-interactively
4749 (indirect-function f))))
4753 (defun interactive-p ()
4754 "Return t if the containing function was run directly by user input.
4755 This means that the function was called with `call-interactively'
4756 \(which includes being called as the binding of a key)
4757 and input is currently coming from the keyboard (not a keyboard macro),
4758 and Emacs is not running in batch mode (`noninteractive' is nil).
4760 The only known proper use of `interactive-p' is in deciding whether to
4761 display a helpful message, or how to display it. If you're thinking
4762 of using it for any other purpose, it is quite likely that you're
4763 making a mistake. Think: what do you want to do when the command is
4764 called from a keyboard macro or in batch mode?
4766 To test whether your function was called with `call-interactively',
4767 either (i) add an extra optional argument and give it an `interactive'
4768 spec that specifies non-nil unconditionally (such as \"p\"); or (ii)
4769 use `called-interactively-p'.
4771 To test whether a function can be called interactively, use
4773 (declare (obsolete called-interactively-p "23.2"))
4774 (called-interactively-p 'interactive))
4776 (defun internal-push-keymap (keymap symbol)
4777 (let ((map (symbol-value symbol)))
4778 (unless (memq keymap map)
4779 (unless (memq 'add-keymap-witness (symbol-value symbol))
4780 (setq map (make-composed-keymap nil (symbol-value symbol)))
4781 (push 'add-keymap-witness (cdr map))
4783 (push keymap (cdr map)))))
4785 (defun internal-pop-keymap (keymap symbol)
4786 (let ((map (symbol-value symbol)))
4787 (when (memq keymap map)
4788 (setf (cdr map) (delq keymap (cdr map))))
4789 (let ((tail (cddr map)))
4790 (and (or (null tail) (keymapp tail))
4791 (eq 'add-keymap-witness (nth 1 map))
4792 (set symbol tail)))))
4794 (define-obsolete-function-alias
4795 'set-temporary-overlay-map 'set-transient-map "24.4")
4797 (defun set-transient-map (map &optional keep-pred on-exit)
4798 "Set MAP as a temporary keymap taking precedence over other keymaps.
4799 Normally, MAP is used only once, to look up the very next key.
4800 However, if the optional argument KEEP-PRED is t, MAP stays
4801 active if a key from MAP is used. KEEP-PRED can also be a
4802 function of no arguments: it is called from `pre-command-hook' and
4803 if it returns non-nil, then MAP stays active.
4805 Optional arg ON-EXIT, if non-nil, specifies a function that is
4806 called, with no arguments, after MAP is deactivated.
4808 This uses `overriding-terminal-local-map' which takes precedence over all other
4809 keymaps. As usual, if no match for a key is found in MAP, the normal key
4810 lookup sequence then continues.
4812 This returns an \"exit function\", which can be called with no argument
4813 to deactivate this transient map, regardless of KEEP-PRED."
4814 (let* ((clearfun (make-symbol "clear-transient-map"))
4817 (internal-pop-keymap map 'overriding-terminal-local-map)
4818 (remove-hook 'pre-command-hook clearfun)
4819 (when on-exit (funcall on-exit)))))
4820 ;; Don't use letrec, because equal (in add/remove-hook) would get trapped
4824 (with-demoted-errors "set-transient-map PCH: %S"
4826 ((null keep-pred) nil)
4827 ((and (not (eq map (cadr overriding-terminal-local-map)))
4828 (memq map (cddr overriding-terminal-local-map)))
4829 ;; There's presumably some other transient-map in
4830 ;; effect. Wait for that one to terminate before we
4831 ;; remove ourselves.
4832 ;; For example, if isearch and C-u both use transient
4833 ;; maps, then the lifetime of the C-u should be nested
4834 ;; within isearch's, so the pre-command-hook of
4835 ;; isearch should be suspended during the C-u one so
4836 ;; we don't exit isearch just because we hit 1 after
4837 ;; C-u and that 1 exits isearch whereas it doesn't
4841 (let ((mc (lookup-key map (this-command-keys-vector))))
4842 ;; If the key is unbound `this-command` is
4843 ;; nil and so is `mc`.
4844 (and mc (eq this-command mc))))
4845 (t (funcall keep-pred)))
4846 (funcall exitfun)))))
4847 (add-hook 'pre-command-hook clearfun)
4848 (internal-push-keymap map 'overriding-terminal-local-map)
4851 ;;;; Progress reporters.
4853 ;; Progress reporter has the following structure:
4855 ;; (NEXT-UPDATE-VALUE . [NEXT-UPDATE-TIME
4862 ;; This weirdness is for optimization reasons: we want
4863 ;; `progress-reporter-update' to be as fast as possible, so
4864 ;; `(car reporter)' is better than `(aref reporter 0)'.
4866 ;; NEXT-UPDATE-TIME is a float. While `float-time' loses a couple
4867 ;; digits of precision, it doesn't really matter here. On the other
4868 ;; hand, it greatly simplifies the code.
4870 (defsubst progress-reporter-update (reporter &optional value)
4871 "Report progress of an operation in the echo area.
4872 REPORTER should be the result of a call to `make-progress-reporter'.
4874 If REPORTER is a numerical progress reporter---i.e. if it was
4875 made using non-nil MIN-VALUE and MAX-VALUE arguments to
4876 `make-progress-reporter'---then VALUE should be a number between
4877 MIN-VALUE and MAX-VALUE.
4879 If REPORTER is a non-numerical reporter, VALUE should be nil.
4881 This function is relatively inexpensive. If the change since
4882 last update is too small or insufficient time has passed, it does
4884 (when (or (not (numberp value)) ; For pulsing reporter
4885 (>= value (car reporter))) ; For numerical reporter
4886 (progress-reporter-do-update reporter value)))
4888 (defun make-progress-reporter (message &optional min-value max-value
4889 current-value min-change min-time)
4890 "Return progress reporter object for use with `progress-reporter-update'.
4892 MESSAGE is shown in the echo area, with a status indicator
4893 appended to the end. When you call `progress-reporter-done', the
4894 word \"done\" is printed after the MESSAGE. You can change the
4895 MESSAGE of an existing progress reporter by calling
4896 `progress-reporter-force-update'.
4898 MIN-VALUE and MAX-VALUE, if non-nil, are starting (0% complete)
4899 and final (100% complete) states of operation; the latter should
4900 be larger. In this case, the status message shows the percentage
4903 If MIN-VALUE and/or MAX-VALUE is omitted or nil, the status
4904 message shows a \"spinning\", non-numeric indicator.
4906 Optional CURRENT-VALUE is the initial progress; the default is
4908 Optional MIN-CHANGE is the minimal change in percents to report;
4910 CURRENT-VALUE and MIN-CHANGE do not have any effect if MIN-VALUE
4911 and/or MAX-VALUE are nil.
4913 Optional MIN-TIME specifies the minimum interval time between
4914 echo area updates (default is 0.2 seconds.) If the OS is not
4915 capable of measuring fractions of seconds, this parameter is
4916 effectively rounded up."
4917 (when (string-match "[[:alnum:]]\\'" message)
4918 (setq message (concat message "...")))
4920 (setq min-time 0.2))
4922 ;; Force a call to `message' now
4923 (cons (or min-value 0)
4924 (vector (if (>= min-time 0.02)
4929 (if min-change (max (min min-change 50) 1) 1)
4931 (progress-reporter-update reporter (or current-value min-value))
4934 (defun progress-reporter-force-update (reporter &optional value new-message)
4935 "Report progress of an operation in the echo area unconditionally.
4937 The first two arguments are the same as in `progress-reporter-update'.
4938 NEW-MESSAGE, if non-nil, sets a new message for the reporter."
4939 (let ((parameters (cdr reporter)))
4941 (aset parameters 3 new-message))
4942 (when (aref parameters 0)
4943 (aset parameters 0 (float-time)))
4944 (progress-reporter-do-update reporter value)))
4946 (defvar progress-reporter--pulse-characters ["-" "\\" "|" "/"]
4947 "Characters to use for pulsing progress reporters.")
4949 (defun progress-reporter-do-update (reporter value)
4950 (let* ((parameters (cdr reporter))
4951 (update-time (aref parameters 0))
4952 (min-value (aref parameters 1))
4953 (max-value (aref parameters 2))
4954 (text (aref parameters 3))
4956 ;; See if enough time has passed since the last update.
4957 (or (not update-time)
4958 (when (>= (float-time) update-time)
4959 ;; Calculate time for the next update
4960 (aset parameters 0 (+ update-time (aref parameters 5)))))))
4961 (cond ((and min-value max-value)
4962 ;; Numerical indicator
4963 (let* ((one-percent (/ (- max-value min-value) 100.0))
4964 (percentage (if (= max-value min-value)
4966 (truncate (/ (- value min-value)
4968 ;; Calculate NEXT-UPDATE-VALUE. If we are not printing
4969 ;; message because not enough time has passed, use 1
4970 ;; instead of MIN-CHANGE. This makes delays between echo
4971 ;; area updates closer to MIN-TIME.
4973 (min (+ min-value (* (+ percentage
4974 (if enough-time-passed
4980 (when (integerp value)
4981 (setcar reporter (ceiling (car reporter))))
4982 ;; Only print message if enough time has passed
4983 (when enough-time-passed
4984 (if (> percentage 0)
4985 (message "%s%d%%" text percentage)
4986 (message "%s" text)))))
4987 ;; Pulsing indicator
4989 (let ((index (mod (1+ (car reporter)) 4))
4990 (message-log-max nil))
4991 (setcar reporter index)
4994 (aref progress-reporter--pulse-characters
4997 (defun progress-reporter-done (reporter)
4998 "Print reporter's message followed by word \"done\" in echo area."
4999 (message "%sdone" (aref (cdr reporter) 3)))
5001 (defmacro dotimes-with-progress-reporter (spec message &rest body)
5002 "Loop a certain number of times and report progress in the echo area.
5003 Evaluate BODY with VAR bound to successive integers running from
5004 0, inclusive, to COUNT, exclusive. Then evaluate RESULT to get
5005 the return value (nil if RESULT is omitted).
5007 At each iteration MESSAGE followed by progress percentage is
5008 printed in the echo area. After the loop is finished, MESSAGE
5009 followed by word \"done\" is printed. This macro is a
5010 convenience wrapper around `make-progress-reporter' and friends.
5012 \(fn (VAR COUNT [RESULT]) MESSAGE BODY...)"
5013 (declare (indent 2) (debug ((symbolp form &optional form) form body)))
5014 (let ((temp (make-symbol "--dotimes-temp--"))
5015 (temp2 (make-symbol "--dotimes-temp2--"))
5019 (,(car spec) ,start)
5020 (,temp2 (make-progress-reporter ,message ,start ,end)))
5021 (while (< ,(car spec) ,temp)
5023 (progress-reporter-update ,temp2
5024 (setq ,(car spec) (1+ ,(car spec)))))
5025 (progress-reporter-done ,temp2)
5026 nil ,@(cdr (cdr spec)))))
5029 ;;;; Comparing version strings.
5031 (defconst version-separator "."
5032 "Specify the string used to separate the version elements.
5034 Usually the separator is \".\", but it can be any other string.")
5037 (defconst version-regexp-alist
5038 '(("^[-._+ ]?snapshot$" . -4)
5039 ;; treat "1.2.3-20050920" and "1.2-3" as snapshot releases
5041 ;; treat "1.2.3-CVS" as snapshot release
5042 ("^[-._+ ]?\\(cvs\\|git\\|bzr\\|svn\\|hg\\|darcs\\)$" . -4)
5043 ("^[-._+ ]?alpha$" . -3)
5044 ("^[-._+ ]?beta$" . -2)
5045 ("^[-._+ ]?\\(pre\\|rc\\)$" . -1))
5046 "Specify association between non-numeric version and its priority.
5048 This association is used to handle version string like \"1.0pre2\",
5049 \"0.9alpha1\", etc. It's used by `version-to-list' (which see) to convert the
5050 non-numeric part of a version string to an integer. For example:
5052 String Version Integer List Version
5053 \"0.9snapshot\" (0 9 -4)
5054 \"1.0-git\" (1 0 -4)
5055 \"1.0.cvs\" (1 0 -4)
5056 \"1.0pre2\" (1 0 -1 2)
5057 \"1.0PRE2\" (1 0 -1 2)
5058 \"22.8beta3\" (22 8 -2 3)
5059 \"22.8 Beta3\" (22 8 -2 3)
5060 \"0.9alpha1\" (0 9 -3 1)
5061 \"0.9AlphA1\" (0 9 -3 1)
5062 \"0.9 alpha\" (0 9 -3)
5064 Each element has the following form:
5070 REGEXP regexp used to match non-numeric part of a version string.
5071 It should begin with the `^' anchor and end with a `$' to
5072 prevent false hits. Letter-case is ignored while matching
5075 PRIORITY a negative integer specifying non-numeric priority of REGEXP.")
5078 (defun version-to-list (ver)
5079 "Convert version string VER into a list of integers.
5081 The version syntax is given by the following EBNF:
5083 VERSION ::= NUMBER ( SEPARATOR NUMBER )*.
5085 NUMBER ::= (0|1|2|3|4|5|6|7|8|9)+.
5087 SEPARATOR ::= `version-separator' (which see)
5088 | `version-regexp-alist' (which see).
5090 The NUMBER part is optional if SEPARATOR is a match for an element
5091 in `version-regexp-alist'.
5093 Examples of valid version syntax:
5095 1.0pre2 1.0.7.5 22.8beta3 0.9alpha1 6.9.30Beta 2.4.snapshot .5
5097 Examples of invalid version syntax:
5099 1.0prepre2 1.0..7.5 22.8X3 alpha3.2
5101 Examples of version conversion:
5103 Version String Version as a List of Integers
5105 \"0.9 alpha\" (0 9 -3)
5106 \"0.9AlphA1\" (0 9 -3 1)
5107 \"0.9snapshot\" (0 9 -4)
5108 \"1.0-git\" (1 0 -4)
5109 \"1.0.7.5\" (1 0 7 5)
5110 \"1.0.cvs\" (1 0 -4)
5111 \"1.0PRE2\" (1 0 -1 2)
5112 \"1.0pre2\" (1 0 -1 2)
5113 \"22.8 Beta3\" (22 8 -2 3)
5114 \"22.8beta3\" (22 8 -2 3)
5116 See documentation for `version-separator' and `version-regexp-alist'."
5117 (unless (stringp ver)
5118 (error "Version must be a string"))
5119 ;; Change .x.y to 0.x.y
5120 (if (and (>= (length ver) (length version-separator))
5121 (string-equal (substring ver 0 (length version-separator))
5123 (setq ver (concat "0" ver)))
5124 (unless (string-match-p "^[0-9]" ver)
5125 (error "Invalid version syntax: `%s' (must start with a number)" ver))
5129 (case-fold-search t) ; ignore case in matching
5131 ;; Parse the version-string up to a separator until there are none left
5132 (while (and (setq s (string-match "[0-9]+" ver i))
5134 ;; Add the numeric part to the beginning of the version list;
5135 ;; lst gets reversed at the end
5136 (setq lst (cons (string-to-number (substring ver i (match-end 0)))
5139 ;; handle non-numeric part
5140 (when (and (setq s (string-match "[^0-9]+" ver i))
5142 (setq s (substring ver i (match-end 0))
5144 ;; handle alpha, beta, pre, etc. separator
5145 (unless (string= s version-separator)
5146 (setq al version-regexp-alist)
5147 (while (and al (not (string-match (caar al) s)))
5150 (push (cdar al) lst))
5151 ;; Convert 22.3a to 22.3.1, 22.3b to 22.3.2, etc., but only if
5152 ;; the letter is the end of the version-string, to avoid
5153 ;; 22.8X3 being valid
5154 ((and (string-match "^[-._+ ]?\\([a-zA-Z]\\)$" s)
5156 (push (- (aref (downcase (match-string 1 s)) 0) ?a -1)
5158 (t (error "Invalid version syntax: `%s'" ver))))))
5161 (defun version-list-< (l1 l2)
5162 "Return t if L1, a list specification of a version, is lower than L2.
5164 Note that a version specified by the list (1) is equal to (1 0),
5165 \(1 0 0), (1 0 0 0), etc. That is, the trailing zeros are insignificant.
5166 Also, a version given by the list (1) is higher than (1 -1), which in
5167 turn is higher than (1 -2), which is higher than (1 -3)."
5168 (while (and l1 l2 (= (car l1) (car l2)))
5172 ;; l1 not null and l2 not null
5173 ((and l1 l2) (< (car l1) (car l2)))
5174 ;; l1 null and l2 null ==> l1 length = l2 length
5175 ((and (null l1) (null l2)) nil)
5176 ;; l1 not null and l2 null ==> l1 length > l2 length
5177 (l1 (< (version-list-not-zero l1) 0))
5178 ;; l1 null and l2 not null ==> l2 length > l1 length
5179 (t (< 0 (version-list-not-zero l2)))))
5182 (defun version-list-= (l1 l2)
5183 "Return t if L1, a list specification of a version, is equal to L2.
5185 Note that a version specified by the list (1) is equal to (1 0),
5186 \(1 0 0), (1 0 0 0), etc. That is, the trailing zeros are insignificant.
5187 Also, a version given by the list (1) is higher than (1 -1), which in
5188 turn is higher than (1 -2), which is higher than (1 -3)."
5189 (while (and l1 l2 (= (car l1) (car l2)))
5193 ;; l1 not null and l2 not null
5195 ;; l1 null and l2 null ==> l1 length = l2 length
5196 ((and (null l1) (null l2)))
5197 ;; l1 not null and l2 null ==> l1 length > l2 length
5198 (l1 (zerop (version-list-not-zero l1)))
5199 ;; l1 null and l2 not null ==> l2 length > l1 length
5200 (t (zerop (version-list-not-zero l2)))))
5203 (defun version-list-<= (l1 l2)
5204 "Return t if L1, a list specification of a version, is lower or equal to L2.
5206 Note that integer list (1) is equal to (1 0), (1 0 0), (1 0 0 0),
5207 etc. That is, the trailing zeroes are insignificant. Also, integer
5208 list (1) is greater than (1 -1) which is greater than (1 -2)
5209 which is greater than (1 -3)."
5210 (while (and l1 l2 (= (car l1) (car l2)))
5214 ;; l1 not null and l2 not null
5215 ((and l1 l2) (< (car l1) (car l2)))
5216 ;; l1 null and l2 null ==> l1 length = l2 length
5217 ((and (null l1) (null l2)))
5218 ;; l1 not null and l2 null ==> l1 length > l2 length
5219 (l1 (<= (version-list-not-zero l1) 0))
5220 ;; l1 null and l2 not null ==> l2 length > l1 length
5221 (t (<= 0 (version-list-not-zero l2)))))
5223 (defun version-list-not-zero (lst)
5224 "Return the first non-zero element of LST, which is a list of integers.
5226 If all LST elements are zeros or LST is nil, return zero."
5227 (while (and lst (zerop (car lst)))
5228 (setq lst (cdr lst)))
5231 ;; there is no element different of zero
5235 (defun version< (v1 v2)
5236 "Return t if version V1 is lower (older) than V2.
5238 Note that version string \"1\" is equal to \"1.0\", \"1.0.0\", \"1.0.0.0\",
5239 etc. That is, the trailing \".0\"s are insignificant. Also, version
5240 string \"1\" is higher (newer) than \"1pre\", which is higher than \"1beta\",
5241 which is higher than \"1alpha\", which is higher than \"1snapshot\".
5242 Also, \"-GIT\", \"-CVS\" and \"-NNN\" are treated as snapshot versions."
5243 (version-list-< (version-to-list v1) (version-to-list v2)))
5245 (defun version<= (v1 v2)
5246 "Return t if version V1 is lower (older) than or equal to V2.
5248 Note that version string \"1\" is equal to \"1.0\", \"1.0.0\", \"1.0.0.0\",
5249 etc. That is, the trailing \".0\"s are insignificant. Also, version
5250 string \"1\" is higher (newer) than \"1pre\", which is higher than \"1beta\",
5251 which is higher than \"1alpha\", which is higher than \"1snapshot\".
5252 Also, \"-GIT\", \"-CVS\" and \"-NNN\" are treated as snapshot versions."
5253 (version-list-<= (version-to-list v1) (version-to-list v2)))
5255 (defun version= (v1 v2)
5256 "Return t if version V1 is equal to V2.
5258 Note that version string \"1\" is equal to \"1.0\", \"1.0.0\", \"1.0.0.0\",
5259 etc. That is, the trailing \".0\"s are insignificant. Also, version
5260 string \"1\" is higher (newer) than \"1pre\", which is higher than \"1beta\",
5261 which is higher than \"1alpha\", which is higher than \"1snapshot\".
5262 Also, \"-GIT\", \"-CVS\" and \"-NNN\" are treated as snapshot versions."
5263 (version-list-= (version-to-list v1) (version-to-list v2)))
5265 (defvar package--builtin-versions
5266 ;; Mostly populated by loaddefs.el via autoload-builtin-package-versions.
5267 (purecopy `((emacs . ,(version-to-list emacs-version))))
5268 "Alist giving the version of each versioned builtin package.
5269 I.e. each element of the list is of the form (NAME . VERSION) where
5270 NAME is the package name as a symbol, and VERSION is its version
5273 (defun package--description-file (dir)
5274 (concat (let ((subdir (file-name-nondirectory
5275 (directory-file-name dir))))
5276 (if (string-match "\\([^.].*?\\)-\\([0-9]+\\(?:[.][0-9]+\\|\\(?:pre\\|beta\\|alpha\\)[0-9]+\\)*\\)" subdir)
5277 (match-string 1 subdir) subdir))
5283 (defmacro with-mutex (mutex &rest body)
5284 "Invoke BODY with MUTEX held, releasing MUTEX when done.
5285 This is the simplest safe way to acquire and release a mutex."
5286 (declare (indent 1) (debug t))
5287 (let ((sym (make-symbol "mutex")))
5288 `(let ((,sym ,mutex))
5292 (mutex-unlock ,sym)))))
5297 (defvar definition-prefixes (make-hash-table :test 'equal)
5298 "Hash table mapping prefixes to the files in which they're used.
5299 This can be used to automatically fetch not-yet-loaded definitions.
5300 More specifically, if there is a value of the form (FILES...) for a string PREFIX
5301 it means that the FILES define variables or functions with names that start
5304 Note that it does not imply that all definitions starting with PREFIX can
5305 be found in those files. E.g. if prefix is \"gnus-article-\" there might
5306 still be definitions of the form \"gnus-article-toto-titi\" in other files, which would
5307 presumably appear in this table under another prefix such as \"gnus-\"
5308 or \"gnus-article-toto-\".")
5310 (defun register-definition-prefixes (file prefixes)
5311 "Register that FILE uses PREFIXES."
5312 (dolist (prefix prefixes)
5313 (puthash prefix (cons file (gethash prefix definition-prefixes))
5314 definition-prefixes)))
5316 (defconst menu-bar-separator '("--")
5317 "Separator for menus.")
5319 ;; The following statement ought to be in print.c, but `provide' can't
5321 ;; https://lists.gnu.org/r/emacs-devel/2009-08/msg00236.html
5322 (when (hash-table-p (car (read-from-string
5323 (prin1-to-string (make-hash-table)))))
5324 (provide 'hashtable-print-readable))
5326 ;; This is used in lisp/Makefile.in and in leim/Makefile.in to
5327 ;; generate file names for autoloads, custom-deps, and finder-data.
5328 (defun unmsys--file-name (file)
5329 "Produce the canonical file name for FILE from its MSYS form.
5331 On systems other than MS-Windows, just returns FILE.
5332 On MS-Windows, converts /d/foo/bar form of file names
5333 passed by MSYS Make into d:/foo/bar that Emacs can grok.
5335 This function is called from lisp/Makefile and leim/Makefile."
5336 (when (and (eq system-type 'windows-nt)
5337 (string-match "\\`/[a-zA-Z]/" file))
5338 (setq file (concat (substring file 1 2) ":" (substring file 2))))
5342 ;;; subr.el ends here