Allow 'browse-url-emacs' to fetch URL in the selected window
[emacs.git] / lisp / subr.el
blob113bd978b63e9150fb1d390b6826ba5cb49194ee
1 ;;; subr.el --- basic lisp subroutines for Emacs -*- lexical-binding:t -*-
3 ;; Copyright (C) 1985-1986, 1992, 1994-1995, 1999-2018 Free Software
4 ;; Foundation, Inc.
6 ;; Maintainer: emacs-devel@gnu.org
7 ;; Keywords: internal
8 ;; Package: emacs
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
36 definition for FN.
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,
55 e.g., `defstruct'.
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.
64 nil)
67 ;;;; Basic Lisp macros.
69 (defalias 'not 'null)
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."
75 (declare (debug t))
76 `(prog1 ,form
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."
83 (declare (debug t))
84 form)
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)]
115 def-body)))
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)))
140 (if (symbolp place)
141 ;; Important special case, to avoid triggering GV too early in
142 ;; the bootstrap.
143 (list 'setq place
144 (list 'cons newelt place))
145 (require 'macroexp)
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
154 change the list."
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.
160 `(car-safe
161 ,(if (symbolp place)
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.
173 \(fn COND BODY...)"
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.
182 \(fn COND BODY...)"
183 (declare (indent 1) (debug t))
184 (cons 'if (cons cond (cons nil body))))
186 (defmacro dolist (spec &rest body)
187 "Loop over a list.
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)))
193 (unless (consp spec)
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
199 ;; use dolist.
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.
206 (if lexical-binding
207 `(let ((,temp ,(nth 1 spec)))
208 (while ,temp
209 (let ((,(car spec) (car ,temp)))
210 ,@body
211 (setq ,temp (cdr ,temp))))
212 ,@(cdr (cdr spec)))
213 `(let ((,temp ,(nth 1 spec))
214 ,(car spec))
215 (while ,temp
216 (setq ,(car spec) (car ,temp))
217 ,@body
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
232 ;; use dotimes.
233 ;; FIXME: This cost disappears in byte-compiled lexical-binding files.
234 (let ((temp '--dotimes-limit--)
235 (start 0)
236 (end (nth 1 spec)))
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.
240 (if lexical-binding
241 (let ((counter '--dotimes-counter--))
242 `(let ((,temp ,end)
243 (,counter ,start))
244 (while (< ,counter ,temp)
245 (let ((,(car spec) ,counter))
246 ,@body)
247 (setq ,counter (1+ ,counter)))
248 ,@(if (cddr spec)
249 ;; FIXME: This let often leads to "unused var" warnings.
250 `((let ((,(car spec) ,counter)) ,@(cddr spec))))))
251 `(let ((,temp ,end)
252 (,(car spec) ,start))
253 (while (< ,(car spec) ,temp)
254 ,@body
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.
270 nil)
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."
296 (interactive)
297 nil)
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))
331 (let ((conditions
332 (if (consp parent)
333 (apply #'append
334 (mapcar (lambda (parent)
335 (cons parent
336 (or (get parent 'error-conditions)
337 (error "Unknown signal `%s'" parent))))
338 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
349 configuration."
350 (and (consp object)
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
358 was called."
359 (lambda (&rest args2)
360 (apply fun (append args args2))))
363 ;;;; List functions.
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))
379 (setq i (1- i)))
380 x)))
382 (defun caar (x)
383 "Return the car of the car of X."
384 (declare (compiler-macro internal--compiler-macro-cXXr))
385 (car (car x)))
387 (defun cadr (x)
388 "Return the car of the cdr of X."
389 (declare (compiler-macro internal--compiler-macro-cXXr))
390 (car (cdr x)))
392 (defun cdar (x)
393 "Return the cdr of the car of X."
394 (declare (compiler-macro internal--compiler-macro-cXXr))
395 (cdr (car x)))
397 (defun cddr (x)
398 "Return the cdr of the cdr of X."
399 (declare (compiler-macro internal--compiler-macro-cXXr))
400 (cdr (cdr x)))
402 (defun caaar (x)
403 "Return the `car' of the `car' of the `car' of X."
404 (declare (compiler-macro internal--compiler-macro-cXXr))
405 (car (car (car x))))
407 (defun caadr (x)
408 "Return the `car' of the `car' of the `cdr' of X."
409 (declare (compiler-macro internal--compiler-macro-cXXr))
410 (car (car (cdr x))))
412 (defun cadar (x)
413 "Return the `car' of the `cdr' of the `car' of X."
414 (declare (compiler-macro internal--compiler-macro-cXXr))
415 (car (cdr (car x))))
417 (defun caddr (x)
418 "Return the `car' of the `cdr' of the `cdr' of X."
419 (declare (compiler-macro internal--compiler-macro-cXXr))
420 (car (cdr (cdr x))))
422 (defun cdaar (x)
423 "Return the `cdr' of the `car' of the `car' of X."
424 (declare (compiler-macro internal--compiler-macro-cXXr))
425 (cdr (car (car x))))
427 (defun cdadr (x)
428 "Return the `cdr' of the `car' of the `cdr' of X."
429 (declare (compiler-macro internal--compiler-macro-cXXr))
430 (cdr (car (cdr x))))
432 (defun cddar (x)
433 "Return the `cdr' of the `cdr' of the `car' of X."
434 (declare (compiler-macro internal--compiler-macro-cXXr))
435 (cdr (cdr (car x))))
437 (defun cdddr (x)
438 "Return the `cdr' of the `cdr' of the `cdr' of X."
439 (declare (compiler-macro internal--compiler-macro-cXXr))
440 (cdr (cdr (cdr x))))
442 (defun caaaar (x)
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)))))
447 (defun caaadr (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)))))
452 (defun caadar (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)))))
457 (defun caaddr (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)))))
462 (defun cadaar (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)))))
467 (defun cadadr (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)))))
472 (defun caddar (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)))))
477 (defun cadddr (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)))))
482 (defun cdaaar (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)))))
487 (defun cdaadr (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)))))
492 (defun cdadar (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)))))
497 (defun cdaddr (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)))))
502 (defun cddaar (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)))))
507 (defun cddadr (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)))))
512 (defun cdddar (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)))))
517 (defun cddddr (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."
527 (if n
528 (and (>= n 0)
529 (let ((m (safe-length list)))
530 (if (< n m) (nthcdr (- m n) list) list)))
531 (and 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
537 copy."
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)))
545 (or n (setq n 1))
546 (and (< n m)
547 (progn
548 (if (> n 0) (setcdr (nthcdr (- (1- m) n) list) nil))
549 list))))
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))))
556 (= 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
562 one is kept."
563 (let ((l (length list)))
564 (if (> l 100)
565 (let ((hash (make-hash-table :test #'equal :size l))
566 (tail list) retail)
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))
572 (puthash elt t hash)
573 (setq tail retail)))))
574 (let ((tail list))
575 (while tail
576 (setcdr tail (delete (car tail) (cdr tail)))
577 (setq tail (cdr tail))))))
578 list)
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
584 non-nil."
585 (let ((tail list) last)
586 (while (cdr tail)
587 (if (equal (car tail) (cadr tail))
588 (setcdr tail (cddr tail))
589 (setq last tail
590 tail (cdr tail))))
591 (if (and circular
592 last
593 (equal (car tail) (car list)))
594 (setcdr last nil)))
595 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))
621 (list from)
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))
625 (if (> inc 0)
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)
630 n (1+ n)
631 last next
632 next (+ from (* n inc))))
633 (while (and (<= next last) (>= next to))
634 (setq seq (cons next seq)
635 n (1+ n)
636 next (+ from (* n inc)))))
637 (nreverse seq))))
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."
644 (if (consp tree)
645 (let (result)
646 (while (consp tree)
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)))
658 tree)
659 tree)))
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,
668 and (ii) KEY.
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)))
681 value))
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."
688 (while (and list
689 (not (and (stringp (car list))
690 (eq t (compare-strings elt 0 nil (car list) 0 nil t)))))
691 (setq list (cdr list)))
692 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))))
709 alist)
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))))
730 alist)
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)
742 (assq key alist)
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'."
749 (if (nlistp seq)
750 ;; If SEQ isn't a list, there's no need to copy SEQ because
751 ;; `delete' will return a new object.
752 (delete elt seq)
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))))
760 (if (memq elt list)
761 (delq elt (copy-sequence list))
762 list))
764 ;;;; Keymap support.
766 (defun kbd (keys)
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
771 `edmacro-mode')."
772 ;; Don't use a defalias, since the `pure' property is only true for
773 ;; the calling convention of `kbd'.
774 (read-kbd-macro keys))
775 (put 'kbd 'pure t)
777 (defun undefined ()
778 "Beep to tell the user this binding is undefined."
779 (interactive)
780 (ding)
781 (if defining-kbd-macro
782 (error "%s is undefined" (key-description (this-single-command-keys)))
783 (message "%s is undefined" (key-description (this-single-command-keys))))
784 (force-mode-line-update)
785 ;; If this is a down-mouse event, don't reset prefix-arg;
786 ;; pass it to the command run by the up event.
787 (setq prefix-arg
788 (when (memq 'down (event-modifiers last-command-event))
789 current-prefix-arg)))
791 ;; Prevent the \{...} documentation construct
792 ;; from mentioning keys that run this command.
793 (put 'undefined 'suppress-keymap t)
795 (defun suppress-keymap (map &optional nodigits)
796 "Make MAP override all normally self-inserting keys to be undefined.
797 Normally, as an exception, digits and minus-sign are set to make prefix args,
798 but optional second arg NODIGITS non-nil treats them like other chars."
799 (define-key map [remap self-insert-command] 'undefined)
800 (or nodigits
801 (let (loop)
802 (define-key map "-" 'negative-argument)
803 ;; Make plain numbers do numeric args.
804 (setq loop ?0)
805 (while (<= loop ?9)
806 (define-key map (char-to-string loop) 'digit-argument)
807 (setq loop (1+ loop))))))
809 (defun make-composed-keymap (maps &optional parent)
810 "Construct a new keymap composed of MAPS and inheriting from PARENT.
811 When looking up a key in the returned map, the key is looked in each
812 keymap of MAPS in turn until a binding is found.
813 If no binding is found in MAPS, the lookup continues in PARENT, if non-nil.
814 As always with keymap inheritance, a nil binding in MAPS overrides
815 any corresponding binding in PARENT, but it does not override corresponding
816 bindings in other keymaps of MAPS.
817 MAPS can be a list of keymaps or a single keymap.
818 PARENT if non-nil should be a keymap."
819 `(keymap
820 ,@(if (keymapp maps) (list maps) maps)
821 ,@parent))
823 (defun define-key-after (keymap key definition &optional after)
824 "Add binding in KEYMAP for KEY => DEFINITION, right after AFTER's binding.
825 This is like `define-key' except that the binding for KEY is placed
826 just after the binding for the event AFTER, instead of at the beginning
827 of the map. Note that AFTER must be an event type (like KEY), NOT a command
828 \(like DEFINITION).
830 If AFTER is t or omitted, the new binding goes at the end of the keymap.
831 AFTER should be a single event type--a symbol or a character, not a sequence.
833 Bindings are always added before any inherited map.
835 The order of bindings in a keymap only matters when it is used as
836 a menu, so this function is not useful for non-menu keymaps."
837 (unless after (setq after t))
838 (or (keymapp keymap)
839 (signal 'wrong-type-argument (list 'keymapp keymap)))
840 (setq key
841 (if (<= (length key) 1) (aref key 0)
842 (setq keymap (lookup-key keymap
843 (apply 'vector
844 (butlast (mapcar 'identity key)))))
845 (aref key (1- (length key)))))
846 (let ((tail keymap) done inserted)
847 (while (and (not done) tail)
848 ;; Delete any earlier bindings for the same key.
849 (if (eq (car-safe (car (cdr tail))) key)
850 (setcdr tail (cdr (cdr tail))))
851 ;; If we hit an included map, go down that one.
852 (if (keymapp (car tail)) (setq tail (car tail)))
853 ;; When we reach AFTER's binding, insert the new binding after.
854 ;; If we reach an inherited keymap, insert just before that.
855 ;; If we reach the end of this keymap, insert at the end.
856 (if (or (and (eq (car-safe (car tail)) after)
857 (not (eq after t)))
858 (eq (car (cdr tail)) 'keymap)
859 (null (cdr tail)))
860 (progn
861 ;; Stop the scan only if we find a parent keymap.
862 ;; Keep going past the inserted element
863 ;; so we can delete any duplications that come later.
864 (if (eq (car (cdr tail)) 'keymap)
865 (setq done t))
866 ;; Don't insert more than once.
867 (or inserted
868 (setcdr tail (cons (cons key definition) (cdr tail))))
869 (setq inserted t)))
870 (setq tail (cdr tail)))))
872 (defun map-keymap-sorted (function keymap)
873 "Implement `map-keymap' with sorting.
874 Don't call this function; it is for internal use only."
875 (let (list)
876 (map-keymap (lambda (a b) (push (cons a b) list))
877 keymap)
878 (setq list (sort list
879 (lambda (a b)
880 (setq a (car a) b (car b))
881 (if (integerp a)
882 (if (integerp b) (< a b)
884 (if (integerp b) t
885 ;; string< also accepts symbols.
886 (string< a b))))))
887 (dolist (p list)
888 (funcall function (car p) (cdr p)))))
890 (defun keymap--menu-item-binding (val)
891 "Return the binding part of a menu-item."
892 (cond
893 ((not (consp val)) val) ;Not a menu-item.
894 ((eq 'menu-item (car val))
895 (let* ((binding (nth 2 val))
896 (plist (nthcdr 3 val))
897 (filter (plist-get plist :filter)))
898 (if filter (funcall filter binding)
899 binding)))
900 ((and (consp (cdr val)) (stringp (cadr val)))
901 (cddr val))
902 ((stringp (car val))
903 (cdr val))
904 (t val))) ;Not a menu-item either.
906 (defun keymap--menu-item-with-binding (item binding)
907 "Build a menu-item like ITEM but with its binding changed to BINDING."
908 (cond
909 ((not (consp item)) binding) ;Not a menu-item.
910 ((eq 'menu-item (car item))
911 (setq item (copy-sequence item))
912 (let ((tail (nthcdr 2 item)))
913 (setcar tail binding)
914 ;; Remove any potential filter.
915 (if (plist-get (cdr tail) :filter)
916 (setcdr tail (plist-put (cdr tail) :filter nil))))
917 item)
918 ((and (consp (cdr item)) (stringp (cadr item)))
919 (cons (car item) (cons (cadr item) binding)))
920 (t (cons (car item) binding))))
922 (defun keymap--merge-bindings (val1 val2)
923 "Merge bindings VAL1 and VAL2."
924 (let ((map1 (keymap--menu-item-binding val1))
925 (map2 (keymap--menu-item-binding val2)))
926 (if (not (and (keymapp map1) (keymapp map2)))
927 ;; There's nothing to merge: val1 takes precedence.
928 val1
929 (let ((map (list 'keymap map1 map2))
930 (item (if (keymapp val1) (if (keymapp val2) nil val2) val1)))
931 (keymap--menu-item-with-binding item map)))))
933 (defun keymap-canonicalize (map)
934 "Return a simpler equivalent keymap.
935 This resolves inheritance and redefinitions. The returned keymap
936 should behave identically to a copy of KEYMAP w.r.t `lookup-key'
937 and use in active keymaps and menus.
938 Subkeymaps may be modified but are not canonicalized."
939 ;; FIXME: Problem with the difference between a nil binding
940 ;; that hides a binding in an inherited map and a nil binding that's ignored
941 ;; to let some further binding visible. Currently a nil binding hides all.
942 ;; FIXME: we may want to carefully (re)order elements in case they're
943 ;; menu-entries.
944 (let ((bindings ())
945 (ranges ())
946 (prompt (keymap-prompt map)))
947 (while (keymapp map)
948 (setq map (map-keymap ;; -internal
949 (lambda (key item)
950 (if (consp key)
951 ;; Treat char-ranges specially.
952 (push (cons key item) ranges)
953 (push (cons key item) bindings)))
954 map)))
955 ;; Create the new map.
956 (setq map (funcall (if ranges 'make-keymap 'make-sparse-keymap) prompt))
957 (dolist (binding ranges)
958 ;; Treat char-ranges specially. FIXME: need to merge as well.
959 (define-key map (vector (car binding)) (cdr binding)))
960 ;; Process the bindings starting from the end.
961 (dolist (binding (prog1 bindings (setq bindings ())))
962 (let* ((key (car binding))
963 (oldbind (assq key bindings)))
964 (push (if (not oldbind)
965 ;; The normal case: no duplicate bindings.
966 binding
967 ;; This is the second binding for this key.
968 (setq bindings (delq oldbind bindings))
969 (cons key (keymap--merge-bindings (cdr binding)
970 (cdr oldbind))))
971 bindings)))
972 (nconc map bindings)))
974 (put 'keyboard-translate-table 'char-table-extra-slots 0)
976 (defun keyboard-translate (from to)
977 "Translate character FROM to TO on the current terminal.
978 This function creates a `keyboard-translate-table' if necessary
979 and then modifies one entry in it."
980 (or (char-table-p keyboard-translate-table)
981 (setq keyboard-translate-table
982 (make-char-table 'keyboard-translate-table nil)))
983 (aset keyboard-translate-table from to))
985 ;;;; Key binding commands.
987 (defun global-set-key (key command)
988 "Give KEY a global binding as COMMAND.
989 COMMAND is the command definition to use; usually it is
990 a symbol naming an interactively-callable function.
991 KEY is a key sequence; noninteractively, it is a string or vector
992 of characters or event types, and non-ASCII characters with codes
993 above 127 (such as ISO Latin-1) can be included if you use a vector.
995 Note that if KEY has a local binding in the current buffer,
996 that local binding will continue to shadow any global binding
997 that you make with this function."
998 (interactive
999 (let* ((menu-prompting nil)
1000 (key (read-key-sequence "Set key globally: ")))
1001 (list key
1002 (read-command (format "Set key %s to command: "
1003 (key-description key))))))
1004 (or (vectorp key) (stringp key)
1005 (signal 'wrong-type-argument (list 'arrayp key)))
1006 (define-key (current-global-map) key command))
1008 (defun local-set-key (key command)
1009 "Give KEY a local binding as COMMAND.
1010 COMMAND is the command definition to use; usually it is
1011 a symbol naming an interactively-callable function.
1012 KEY is a key sequence; noninteractively, it is a string or vector
1013 of characters or event types, and non-ASCII characters with codes
1014 above 127 (such as ISO Latin-1) can be included if you use a vector.
1016 The binding goes in the current buffer's local map, which in most
1017 cases is shared with all other buffers in the same major mode."
1018 (interactive "KSet key locally: \nCSet key %s locally to command: ")
1019 (let ((map (current-local-map)))
1020 (or map
1021 (use-local-map (setq map (make-sparse-keymap))))
1022 (or (vectorp key) (stringp key)
1023 (signal 'wrong-type-argument (list 'arrayp key)))
1024 (define-key map key command)))
1026 (defun global-unset-key (key)
1027 "Remove global binding of KEY.
1028 KEY is a string or vector representing a sequence of keystrokes."
1029 (interactive "kUnset key globally: ")
1030 (global-set-key key nil))
1032 (defun local-unset-key (key)
1033 "Remove local binding of KEY.
1034 KEY is a string or vector representing a sequence of keystrokes."
1035 (interactive "kUnset key locally: ")
1036 (if (current-local-map)
1037 (local-set-key key nil))
1038 nil)
1040 ;;;; substitute-key-definition and its subroutines.
1042 (defvar key-substitution-in-progress nil
1043 "Used internally by `substitute-key-definition'.")
1045 (defun substitute-key-definition (olddef newdef keymap &optional oldmap prefix)
1046 "Replace OLDDEF with NEWDEF for any keys in KEYMAP now defined as OLDDEF.
1047 In other words, OLDDEF is replaced with NEWDEF wherever it appears.
1048 Alternatively, if optional fourth argument OLDMAP is specified, we redefine
1049 in KEYMAP as NEWDEF those keys which are defined as OLDDEF in OLDMAP.
1051 If you don't specify OLDMAP, you can usually get the same results
1052 in a cleaner way with command remapping, like this:
1053 (define-key KEYMAP [remap OLDDEF] NEWDEF)
1054 \n(fn OLDDEF NEWDEF KEYMAP &optional OLDMAP)"
1055 ;; Don't document PREFIX in the doc string because we don't want to
1056 ;; advertise it. It's meant for recursive calls only. Here's its
1057 ;; meaning
1059 ;; If optional argument PREFIX is specified, it should be a key
1060 ;; prefix, a string. Redefined bindings will then be bound to the
1061 ;; original key, with PREFIX added at the front.
1062 (or prefix (setq prefix ""))
1063 (let* ((scan (or oldmap keymap))
1064 (prefix1 (vconcat prefix [nil]))
1065 (key-substitution-in-progress
1066 (cons scan key-substitution-in-progress)))
1067 ;; Scan OLDMAP, finding each char or event-symbol that
1068 ;; has any definition, and act on it with hack-key.
1069 (map-keymap
1070 (lambda (char defn)
1071 (aset prefix1 (length prefix) char)
1072 (substitute-key-definition-key defn olddef newdef prefix1 keymap))
1073 scan)))
1075 (defun substitute-key-definition-key (defn olddef newdef prefix keymap)
1076 (let (inner-def skipped menu-item)
1077 ;; Find the actual command name within the binding.
1078 (if (eq (car-safe defn) 'menu-item)
1079 (setq menu-item defn defn (nth 2 defn))
1080 ;; Skip past menu-prompt.
1081 (while (stringp (car-safe defn))
1082 (push (pop defn) skipped))
1083 ;; Skip past cached key-equivalence data for menu items.
1084 (if (consp (car-safe defn))
1085 (setq defn (cdr defn))))
1086 (if (or (eq defn olddef)
1087 ;; Compare with equal if definition is a key sequence.
1088 ;; That is useful for operating on function-key-map.
1089 (and (or (stringp defn) (vectorp defn))
1090 (equal defn olddef)))
1091 (define-key keymap prefix
1092 (if menu-item
1093 (let ((copy (copy-sequence menu-item)))
1094 (setcar (nthcdr 2 copy) newdef)
1095 copy)
1096 (nconc (nreverse skipped) newdef)))
1097 ;; Look past a symbol that names a keymap.
1098 (setq inner-def
1099 (or (indirect-function defn) defn))
1100 ;; For nested keymaps, we use `inner-def' rather than `defn' so as to
1101 ;; avoid autoloading a keymap. This is mostly done to preserve the
1102 ;; original non-autoloading behavior of pre-map-keymap times.
1103 (if (and (keymapp inner-def)
1104 ;; Avoid recursively scanning
1105 ;; where KEYMAP does not have a submap.
1106 (let ((elt (lookup-key keymap prefix)))
1107 (or (null elt) (natnump elt) (keymapp elt)))
1108 ;; Avoid recursively rescanning keymap being scanned.
1109 (not (memq inner-def key-substitution-in-progress)))
1110 ;; If this one isn't being scanned already, scan it now.
1111 (substitute-key-definition olddef newdef keymap inner-def prefix)))))
1114 ;;;; The global keymap tree.
1116 ;; global-map, esc-map, and ctl-x-map have their values set up in
1117 ;; keymap.c; we just give them docstrings here.
1119 (defvar global-map nil
1120 "Default global keymap mapping Emacs keyboard input into commands.
1121 The value is a keymap which is usually (but not necessarily) Emacs's
1122 global map.")
1124 (defvar esc-map nil
1125 "Default keymap for ESC (meta) commands.
1126 The normal global definition of the character ESC indirects to this keymap.")
1128 (defvar ctl-x-map nil
1129 "Default keymap for C-x commands.
1130 The normal global definition of the character C-x indirects to this keymap.")
1132 (defvar ctl-x-4-map (make-sparse-keymap)
1133 "Keymap for subcommands of C-x 4.")
1134 (defalias 'ctl-x-4-prefix ctl-x-4-map)
1135 (define-key ctl-x-map "4" 'ctl-x-4-prefix)
1137 (defvar ctl-x-5-map (make-sparse-keymap)
1138 "Keymap for frame commands.")
1139 (defalias 'ctl-x-5-prefix ctl-x-5-map)
1140 (define-key ctl-x-map "5" 'ctl-x-5-prefix)
1143 ;;;; Event manipulation functions.
1145 (defconst listify-key-sequence-1 (logior 128 ?\M-\C-@))
1147 (defun listify-key-sequence (key)
1148 "Convert a key sequence to a list of events."
1149 (if (vectorp key)
1150 (append key nil)
1151 (mapcar (function (lambda (c)
1152 (if (> c 127)
1153 (logxor c listify-key-sequence-1)
1154 c)))
1155 key)))
1157 (defun eventp (obj)
1158 "True if the argument is an event object."
1159 (when obj
1160 (or (integerp obj)
1161 (and (symbolp obj) obj (not (keywordp obj)))
1162 (and (consp obj) (symbolp (car obj))))))
1164 (defun event-modifiers (event)
1165 "Return a list of symbols representing the modifier keys in event EVENT.
1166 The elements of the list may include `meta', `control',
1167 `shift', `hyper', `super', `alt', `click', `double', `triple', `drag',
1168 and `down'.
1169 EVENT may be an event or an event type. If EVENT is a symbol
1170 that has never been used in an event that has been read as input
1171 in the current Emacs session, then this function may fail to include
1172 the `click' modifier."
1173 (let ((type event))
1174 (if (listp type)
1175 (setq type (car type)))
1176 (if (symbolp type)
1177 ;; Don't read event-symbol-elements directly since we're not
1178 ;; sure the symbol has already been parsed.
1179 (cdr (internal-event-symbol-parse-modifiers type))
1180 (let ((list nil)
1181 (char (logand type (lognot (logior ?\M-\^@ ?\C-\^@ ?\S-\^@
1182 ?\H-\^@ ?\s-\^@ ?\A-\^@)))))
1183 (if (not (zerop (logand type ?\M-\^@)))
1184 (push 'meta list))
1185 (if (or (not (zerop (logand type ?\C-\^@)))
1186 (< char 32))
1187 (push 'control list))
1188 (if (or (not (zerop (logand type ?\S-\^@)))
1189 (/= char (downcase char)))
1190 (push 'shift list))
1191 (or (zerop (logand type ?\H-\^@))
1192 (push 'hyper list))
1193 (or (zerop (logand type ?\s-\^@))
1194 (push 'super list))
1195 (or (zerop (logand type ?\A-\^@))
1196 (push 'alt list))
1197 list))))
1199 (defun event-basic-type (event)
1200 "Return the basic type of the given event (all modifiers removed).
1201 The value is a printing character (not upper case) or a symbol.
1202 EVENT may be an event or an event type. If EVENT is a symbol
1203 that has never been used in an event that has been read as input
1204 in the current Emacs session, then this function may return nil."
1205 (if (consp event)
1206 (setq event (car event)))
1207 (if (symbolp event)
1208 (car (get event 'event-symbol-elements))
1209 (let* ((base (logand event (1- ?\A-\^@)))
1210 (uncontrolled (if (< base 32) (logior base 64) base)))
1211 ;; There are some numbers that are invalid characters and
1212 ;; cause `downcase' to get an error.
1213 (condition-case ()
1214 (downcase uncontrolled)
1215 (error uncontrolled)))))
1217 (defsubst mouse-movement-p (object)
1218 "Return non-nil if OBJECT is a mouse movement event."
1219 (eq (car-safe object) 'mouse-movement))
1221 (defun mouse-event-p (object)
1222 "Return non-nil if OBJECT is a mouse click event."
1223 ;; is this really correct? maybe remove mouse-movement?
1224 (memq (event-basic-type object) '(mouse-1 mouse-2 mouse-3 mouse-movement)))
1226 (defun event-start (event)
1227 "Return the starting position of EVENT.
1228 EVENT should be a mouse click, drag, or key press event. If
1229 EVENT is nil, the value of `posn-at-point' is used instead.
1231 The following accessor functions are used to access the elements
1232 of the position:
1234 `posn-window': The window the event is in.
1235 `posn-area': A symbol identifying the area the event occurred in,
1236 or nil if the event occurred in the text area.
1237 `posn-point': The buffer position of the event.
1238 `posn-x-y': The pixel-based coordinates of the event.
1239 `posn-col-row': The estimated column and row corresponding to the
1240 position of the event.
1241 `posn-actual-col-row': The actual column and row corresponding to the
1242 position of the event.
1243 `posn-string': The string object of the event, which is either
1244 nil or (STRING . POSITION)'.
1245 `posn-image': The image object of the event, if any.
1246 `posn-object': The image or string object of the event, if any.
1247 `posn-timestamp': The time the event occurred, in milliseconds.
1249 For more information, see Info node `(elisp)Click Events'."
1250 (if (consp event) (nth 1 event)
1251 (or (posn-at-point)
1252 (list (selected-window) (point) '(0 . 0) 0))))
1254 (defun event-end (event)
1255 "Return the ending position of EVENT.
1256 EVENT should be a click, drag, or key press event.
1258 See `event-start' for a description of the value returned."
1259 (if (consp event) (nth (if (consp (nth 2 event)) 2 1) event)
1260 (or (posn-at-point)
1261 (list (selected-window) (point) '(0 . 0) 0))))
1263 (defsubst event-click-count (event)
1264 "Return the multi-click count of EVENT, a click or drag event.
1265 The return value is a positive integer."
1266 (if (and (consp event) (integerp (nth 2 event))) (nth 2 event) 1))
1268 (defsubst event-line-count (event)
1269 "Return the line count of EVENT, a mousewheel event.
1270 The return value is a positive integer."
1271 (if (and (consp event) (integerp (nth 3 event))) (nth 3 event) 1))
1273 ;;;; Extracting fields of the positions in an event.
1275 (defun posnp (obj)
1276 "Return non-nil if OBJ appears to be a valid `posn' object specifying a window.
1277 A `posn' object is returned from functions such as `event-start'.
1278 If OBJ is a valid `posn' object, but specifies a frame rather
1279 than a window, return nil."
1280 ;; FIXME: Correct the behavior of this function so that all valid
1281 ;; `posn' objects are recognized, after updating other code that
1282 ;; depends on its present behavior.
1283 (and (windowp (car-safe obj))
1284 (atom (car-safe (setq obj (cdr obj)))) ;AREA-OR-POS.
1285 (integerp (car-safe (car-safe (setq obj (cdr obj))))) ;XOFFSET.
1286 (integerp (car-safe (cdr obj))))) ;TIMESTAMP.
1288 (defsubst posn-window (position)
1289 "Return the window in POSITION.
1290 POSITION should be a list of the form returned by the `event-start'
1291 and `event-end' functions."
1292 (nth 0 position))
1294 (defsubst posn-area (position)
1295 "Return the window area recorded in POSITION, or nil for the text area.
1296 POSITION should be a list of the form returned by the `event-start'
1297 and `event-end' functions."
1298 (let ((area (if (consp (nth 1 position))
1299 (car (nth 1 position))
1300 (nth 1 position))))
1301 (and (symbolp area) area)))
1303 (defun posn-point (position)
1304 "Return the buffer location in POSITION.
1305 POSITION should be a list of the form returned by the `event-start'
1306 and `event-end' functions.
1307 Returns nil if POSITION does not correspond to any buffer location (e.g.
1308 a click on a scroll bar)."
1309 (or (nth 5 position)
1310 (let ((pt (nth 1 position)))
1311 (or (car-safe pt)
1312 ;; Apparently this can also be `vertical-scroll-bar' (bug#13979).
1313 (if (integerp pt) pt)))))
1315 (defun posn-set-point (position)
1316 "Move point to POSITION.
1317 Select the corresponding window as well."
1318 (if (not (windowp (posn-window position)))
1319 (error "Position not in text area of window"))
1320 (select-window (posn-window position))
1321 (if (numberp (posn-point position))
1322 (goto-char (posn-point position))))
1324 (defsubst posn-x-y (position)
1325 "Return the x and y coordinates in POSITION.
1326 The return value has the form (X . Y), where X and Y are given in
1327 pixels. POSITION should be a list of the form returned by
1328 `event-start' and `event-end'."
1329 (nth 2 position))
1331 (declare-function scroll-bar-scale "scroll-bar" (num-denom whole))
1333 (defun posn-col-row (position)
1334 "Return the nominal column and row in POSITION, measured in characters.
1335 The column and row values are approximations calculated from the x
1336 and y coordinates in POSITION and the frame's default character width
1337 and default line height, including spacing.
1338 For a scroll-bar event, the result column is 0, and the row
1339 corresponds to the vertical position of the click in the scroll bar.
1340 POSITION should be a list of the form returned by the `event-start'
1341 and `event-end' functions."
1342 (let* ((pair (posn-x-y position))
1343 (frame-or-window (posn-window position))
1344 (frame (if (framep frame-or-window)
1345 frame-or-window
1346 (window-frame frame-or-window)))
1347 (window (when (windowp frame-or-window) frame-or-window))
1348 (area (posn-area position)))
1349 (cond
1350 ((null frame-or-window)
1351 '(0 . 0))
1352 ((eq area 'vertical-scroll-bar)
1353 (cons 0 (scroll-bar-scale pair (1- (window-height window)))))
1354 ((eq area 'horizontal-scroll-bar)
1355 (cons (scroll-bar-scale pair (window-width window)) 0))
1357 ;; FIXME: This should take line-spacing properties on
1358 ;; newlines into account.
1359 (let* ((spacing (when (display-graphic-p frame)
1360 (or (with-current-buffer
1361 (window-buffer (frame-selected-window frame))
1362 line-spacing)
1363 (frame-parameter frame 'line-spacing)))))
1364 (cond ((floatp spacing)
1365 (setq spacing (truncate (* spacing
1366 (frame-char-height frame)))))
1367 ((null spacing)
1368 (setq spacing 0)))
1369 (cons (/ (car pair) (frame-char-width frame))
1370 (/ (cdr pair) (+ (frame-char-height frame) spacing))))))))
1372 (defun posn-actual-col-row (position)
1373 "Return the window row number in POSITION and character number in that row.
1375 Return nil if POSITION does not contain the actual position; in that case
1376 `posn-col-row' can be used to get approximate values.
1377 POSITION should be a list of the form returned by the `event-start'
1378 and `event-end' functions.
1380 This function does not account for the width on display, like the
1381 number of visual columns taken by a TAB or image. If you need
1382 the coordinates of POSITION in character units, you should use
1383 `posn-col-row', not this function."
1384 (nth 6 position))
1386 (defsubst posn-timestamp (position)
1387 "Return the timestamp of POSITION.
1388 POSITION should be a list of the form returned by the `event-start'
1389 and `event-end' functions."
1390 (nth 3 position))
1392 (defun posn-string (position)
1393 "Return the string object of POSITION.
1394 Value is a cons (STRING . STRING-POS), or nil if not a string.
1395 POSITION should be a list of the form returned by the `event-start'
1396 and `event-end' functions."
1397 (let ((x (nth 4 position)))
1398 ;; Apparently this can also be `handle' or `below-handle' (bug#13979).
1399 (when (consp x) x)))
1401 (defsubst posn-image (position)
1402 "Return the image object of POSITION.
1403 Value is a list (image ...), or nil if not an image.
1404 POSITION should be a list of the form returned by the `event-start'
1405 and `event-end' functions."
1406 (nth 7 position))
1408 (defsubst posn-object (position)
1409 "Return the object (image or string) of POSITION.
1410 Value is a list (image ...) for an image object, a cons cell
1411 \(STRING . STRING-POS) for a string object, and nil for a buffer position.
1412 POSITION should be a list of the form returned by the `event-start'
1413 and `event-end' functions."
1414 (or (posn-image position) (posn-string position)))
1416 (defsubst posn-object-x-y (position)
1417 "Return the x and y coordinates relative to the object of POSITION.
1418 The return value has the form (DX . DY), where DX and DY are
1419 given in pixels. POSITION should be a list of the form returned
1420 by `event-start' and `event-end'."
1421 (nth 8 position))
1423 (defsubst posn-object-width-height (position)
1424 "Return the pixel width and height of the object of POSITION.
1425 The return value has the form (WIDTH . HEIGHT). POSITION should
1426 be a list of the form returned by `event-start' and `event-end'."
1427 (nth 9 position))
1430 ;;;; Obsolescent names for functions.
1432 (make-obsolete 'forward-point "use (+ (point) N) instead." "23.1")
1433 (make-obsolete 'buffer-has-markers-at nil "24.3")
1435 (make-obsolete 'invocation-directory "use the variable of the same name."
1436 "27.1")
1437 (make-obsolete 'invocation-name "use the variable of the same name." "27.1")
1439 ;; bug#23850
1440 (make-obsolete 'string-to-unibyte "use `encode-coding-string'." "26.1")
1441 (make-obsolete 'string-as-unibyte "use `encode-coding-string'." "26.1")
1442 (make-obsolete 'string-make-unibyte "use `encode-coding-string'." "26.1")
1443 (make-obsolete 'string-to-multibyte "use `decode-coding-string'." "26.1")
1444 (make-obsolete 'string-as-multibyte "use `decode-coding-string'." "26.1")
1445 (make-obsolete 'string-make-multibyte "use `decode-coding-string'." "26.1")
1447 (defun log10 (x)
1448 "Return (log X 10), the log base 10 of X."
1449 (declare (obsolete log "24.4"))
1450 (log x 10))
1452 (set-advertised-calling-convention
1453 'all-completions '(string collection &optional predicate) "23.1")
1454 (set-advertised-calling-convention 'unintern '(name obarray) "23.3")
1455 (set-advertised-calling-convention 'indirect-function '(object) "25.1")
1456 (set-advertised-calling-convention 'redirect-frame-focus '(frame focus-frame) "24.3")
1458 ;;;; Obsolescence declarations for variables, and aliases.
1460 (make-obsolete-variable 'define-key-rebound-commands nil "23.2")
1461 (make-obsolete-variable 'redisplay-end-trigger-functions 'jit-lock-register "23.1")
1462 (make-obsolete-variable 'deferred-action-list 'post-command-hook "24.1")
1463 (make-obsolete-variable 'deferred-action-function 'post-command-hook "24.1")
1464 (make-obsolete-variable 'redisplay-dont-pause nil "24.5")
1465 (make-obsolete 'window-redisplay-end-trigger nil "23.1")
1466 (make-obsolete 'set-window-redisplay-end-trigger nil "23.1")
1468 (make-obsolete 'process-filter-multibyte-p nil "23.1")
1469 (make-obsolete 'set-process-filter-multibyte nil "23.1")
1471 (make-obsolete-variable 'command-debug-status
1472 "expect it to be removed in a future version." "25.2")
1474 ;; This was introduced in 21.4 for pre-unicode unification. That
1475 ;; usage was rendered obsolete in 23.1 which uses Unicode internally.
1476 ;; Other uses are possible, so this variable is not _really_ obsolete,
1477 ;; but Stefan insists to mark it so.
1478 (make-obsolete-variable 'translation-table-for-input nil "23.1")
1480 (make-obsolete-variable 'x-gtk-use-window-move nil "26.1")
1482 (defvaralias 'messages-buffer-max-lines 'message-log-max)
1484 ;;;; Alternate names for functions - these are not being phased out.
1486 (defalias 'send-string 'process-send-string)
1487 (defalias 'send-region 'process-send-region)
1488 (defalias 'string= 'string-equal)
1489 (defalias 'string< 'string-lessp)
1490 (defalias 'string> 'string-greaterp)
1491 (defalias 'move-marker 'set-marker)
1492 (defalias 'rplaca 'setcar)
1493 (defalias 'rplacd 'setcdr)
1494 (defalias 'beep 'ding) ;preserve lingual purity
1495 (defalias 'indent-to-column 'indent-to)
1496 (defalias 'backward-delete-char 'delete-backward-char)
1497 (defalias 'search-forward-regexp (symbol-function 're-search-forward))
1498 (defalias 'search-backward-regexp (symbol-function 're-search-backward))
1499 (defalias 'int-to-string 'number-to-string)
1500 (defalias 'store-match-data 'set-match-data)
1501 (defalias 'chmod 'set-file-modes)
1502 (defalias 'mkdir 'make-directory)
1503 ;; These are the XEmacs names:
1504 (defalias 'point-at-eol 'line-end-position)
1505 (defalias 'point-at-bol 'line-beginning-position)
1507 (defalias 'user-original-login-name 'user-login-name)
1510 ;;;; Hook manipulation functions.
1512 (defun add-hook (hook function &optional append local)
1513 "Add to the value of HOOK the function FUNCTION.
1514 FUNCTION is not added if already present.
1515 FUNCTION is added (if necessary) at the beginning of the hook list
1516 unless the optional argument APPEND is non-nil, in which case
1517 FUNCTION is added at the end.
1519 The optional fourth argument, LOCAL, if non-nil, says to modify
1520 the hook's buffer-local value rather than its global value.
1521 This makes the hook buffer-local, and it makes t a member of the
1522 buffer-local value. That acts as a flag to run the hook
1523 functions of the global value as well as in the local value.
1525 HOOK should be a symbol, and FUNCTION may be any valid function. If
1526 HOOK is void, it is first set to nil. If HOOK's value is a single
1527 function, it is changed to a list of functions."
1528 (or (boundp hook) (set hook nil))
1529 (or (default-boundp hook) (set-default hook nil))
1530 (if local (unless (local-variable-if-set-p hook)
1531 (set (make-local-variable hook) (list t)))
1532 ;; Detect the case where make-local-variable was used on a hook
1533 ;; and do what we used to do.
1534 (unless (and (consp (symbol-value hook)) (memq t (symbol-value hook)))
1535 (setq local t)))
1536 (let ((hook-value (if local (symbol-value hook) (default-value hook))))
1537 ;; If the hook value is a single function, turn it into a list.
1538 (when (or (not (listp hook-value)) (functionp hook-value))
1539 (setq hook-value (list hook-value)))
1540 ;; Do the actual addition if necessary
1541 (unless (member function hook-value)
1542 (when (stringp function)
1543 (setq function (purecopy function)))
1544 (setq hook-value
1545 (if append
1546 (append hook-value (list function))
1547 (cons function hook-value))))
1548 ;; Set the actual variable
1549 (if local
1550 (progn
1551 ;; If HOOK isn't a permanent local,
1552 ;; but FUNCTION wants to survive a change of modes,
1553 ;; mark HOOK as partially permanent.
1554 (and (symbolp function)
1555 (get function 'permanent-local-hook)
1556 (not (get hook 'permanent-local))
1557 (put hook 'permanent-local 'permanent-local-hook))
1558 (set hook hook-value))
1559 (set-default hook hook-value))))
1561 (defun remove-hook (hook function &optional local)
1562 "Remove from the value of HOOK the function FUNCTION.
1563 HOOK should be a symbol, and FUNCTION may be any valid function. If
1564 FUNCTION isn't the value of HOOK, or, if FUNCTION doesn't appear in the
1565 list of hooks to run in HOOK, then nothing is done. See `add-hook'.
1567 The optional third argument, LOCAL, if non-nil, says to modify
1568 the hook's buffer-local value rather than its default value."
1569 (or (boundp hook) (set hook nil))
1570 (or (default-boundp hook) (set-default hook nil))
1571 ;; Do nothing if LOCAL is t but this hook has no local binding.
1572 (unless (and local (not (local-variable-p hook)))
1573 ;; Detect the case where make-local-variable was used on a hook
1574 ;; and do what we used to do.
1575 (when (and (local-variable-p hook)
1576 (not (and (consp (symbol-value hook))
1577 (memq t (symbol-value hook)))))
1578 (setq local t))
1579 (let ((hook-value (if local (symbol-value hook) (default-value hook))))
1580 ;; Remove the function, for both the list and the non-list cases.
1581 (if (or (not (listp hook-value)) (eq (car hook-value) 'lambda))
1582 (if (equal hook-value function) (setq hook-value nil))
1583 (setq hook-value (delete function (copy-sequence hook-value))))
1584 ;; If the function is on the global hook, we need to shadow it locally
1585 ;;(when (and local (member function (default-value hook))
1586 ;; (not (member (cons 'not function) hook-value)))
1587 ;; (push (cons 'not function) hook-value))
1588 ;; Set the actual variable
1589 (if (not local)
1590 (set-default hook hook-value)
1591 (if (equal hook-value '(t))
1592 (kill-local-variable hook)
1593 (set hook hook-value))))))
1595 (defmacro letrec (binders &rest body)
1596 "Bind variables according to BINDERS then eval BODY.
1597 The value of the last form in BODY is returned.
1598 Each element of BINDERS is a list (SYMBOL VALUEFORM) which binds
1599 SYMBOL to the value of VALUEFORM.
1600 All symbols are bound before the VALUEFORMs are evalled."
1601 ;; Only useful in lexical-binding mode.
1602 ;; As a special-form, we could implement it more efficiently (and cleanly,
1603 ;; making the vars actually unbound during evaluation of the binders).
1604 (declare (debug let) (indent 1))
1605 `(let ,(mapcar #'car binders)
1606 ,@(mapcar (lambda (binder) `(setq ,@binder)) binders)
1607 ,@body))
1609 (defmacro with-wrapper-hook (hook args &rest body)
1610 "Run BODY, using wrapper functions from HOOK with additional ARGS.
1611 HOOK is an abnormal hook. Each hook function in HOOK \"wraps\"
1612 around the preceding ones, like a set of nested `around' advices.
1614 Each hook function should accept an argument list consisting of a
1615 function FUN, followed by the additional arguments in ARGS.
1617 The first hook function in HOOK is passed a FUN that, if it is called
1618 with arguments ARGS, performs BODY (i.e., the default operation).
1619 The FUN passed to each successive hook function is defined based
1620 on the preceding hook functions; if called with arguments ARGS,
1621 it does what the `with-wrapper-hook' call would do if the
1622 preceding hook functions were the only ones present in HOOK.
1624 Each hook function may call its FUN argument as many times as it wishes,
1625 including never. In that case, such a hook function acts to replace
1626 the default definition altogether, and any preceding hook functions.
1627 Of course, a subsequent hook function may do the same thing.
1629 Each hook function definition is used to construct the FUN passed
1630 to the next hook function, if any. The last (or \"outermost\")
1631 FUN is then called once."
1632 (declare (indent 2) (debug (form sexp body))
1633 (obsolete "use a <foo>-function variable modified by `add-function'."
1634 "24.4"))
1635 `(subr--with-wrapper-hook-no-warnings ,hook ,args ,@body))
1637 (defmacro subr--with-wrapper-hook-no-warnings (hook args &rest body)
1638 "Like (with-wrapper-hook HOOK ARGS BODY), but without warnings."
1639 ;; We need those two gensyms because CL's lexical scoping is not available
1640 ;; for function arguments :-(
1641 (let ((funs (make-symbol "funs"))
1642 (global (make-symbol "global"))
1643 (argssym (make-symbol "args"))
1644 (runrestofhook (make-symbol "runrestofhook")))
1645 ;; Since the hook is a wrapper, the loop has to be done via
1646 ;; recursion: a given hook function will call its parameter in order to
1647 ;; continue looping.
1648 `(letrec ((,runrestofhook
1649 (lambda (,funs ,global ,argssym)
1650 ;; `funs' holds the functions left on the hook and `global'
1651 ;; holds the functions left on the global part of the hook
1652 ;; (in case the hook is local).
1653 (if (consp ,funs)
1654 (if (eq t (car ,funs))
1655 (funcall ,runrestofhook
1656 (append ,global (cdr ,funs)) nil ,argssym)
1657 (apply (car ,funs)
1658 (apply-partially
1659 (lambda (,funs ,global &rest ,argssym)
1660 (funcall ,runrestofhook ,funs ,global ,argssym))
1661 (cdr ,funs) ,global)
1662 ,argssym))
1663 ;; Once there are no more functions on the hook, run
1664 ;; the original body.
1665 (apply (lambda ,args ,@body) ,argssym)))))
1666 (funcall ,runrestofhook ,hook
1667 ;; The global part of the hook, if any.
1668 ,(if (symbolp hook)
1669 `(if (local-variable-p ',hook)
1670 (default-value ',hook)))
1671 (list ,@args)))))
1673 (defun add-to-list (list-var element &optional append compare-fn)
1674 "Add ELEMENT to the value of LIST-VAR if it isn't there yet.
1675 The test for presence of ELEMENT is done with `equal', or with
1676 COMPARE-FN if that's non-nil.
1677 If ELEMENT is added, it is added at the beginning of the list,
1678 unless the optional argument APPEND is non-nil, in which case
1679 ELEMENT is added at the end.
1681 The return value is the new value of LIST-VAR.
1683 This is handy to add some elements to configuration variables,
1684 but please do not abuse it in Elisp code, where you are usually
1685 better off using `push' or `cl-pushnew'.
1687 If you want to use `add-to-list' on a variable that is not
1688 defined until a certain package is loaded, you should put the
1689 call to `add-to-list' into a hook function that will be run only
1690 after loading the package. `eval-after-load' provides one way to
1691 do this. In some cases other hooks, such as major mode hooks,
1692 can do the job."
1693 (declare
1694 (compiler-macro
1695 (lambda (exp)
1696 ;; FIXME: Something like this could be used for `set' as well.
1697 (if (or (not (eq 'quote (car-safe list-var)))
1698 (special-variable-p (cadr list-var))
1699 (not (macroexp-const-p append)))
1701 (let* ((sym (cadr list-var))
1702 (append (eval append))
1703 (msg (format-message
1704 "`add-to-list' can't use lexical var `%s'; use `push' or `cl-pushnew'"
1705 sym))
1706 ;; Big ugly hack so we only output a warning during
1707 ;; byte-compilation, and so we can use
1708 ;; byte-compile-not-lexical-var-p to silence the warning
1709 ;; when a defvar has been seen but not yet executed.
1710 (warnfun (lambda ()
1711 ;; FIXME: We should also emit a warning for let-bound
1712 ;; variables with dynamic binding.
1713 (when (assq sym byte-compile--lexical-environment)
1714 (byte-compile-report-error msg :fill))))
1715 (code
1716 (macroexp-let2 macroexp-copyable-p x element
1717 `(if ,(if compare-fn
1718 (progn
1719 (require 'cl-lib)
1720 `(cl-member ,x ,sym :test ,compare-fn))
1721 ;; For bootstrapping reasons, don't rely on
1722 ;; cl--compiler-macro-member for the base case.
1723 `(member ,x ,sym))
1724 ,sym
1725 ,(if append
1726 `(setq ,sym (append ,sym (list ,x)))
1727 `(push ,x ,sym))))))
1728 (if (not (macroexp--compiling-p))
1729 code
1730 `(progn
1731 (macroexp--funcall-if-compiled ',warnfun)
1732 ,code)))))))
1733 (if (cond
1734 ((null compare-fn)
1735 (member element (symbol-value list-var)))
1736 ((eq compare-fn 'eq)
1737 (memq element (symbol-value list-var)))
1738 ((eq compare-fn 'eql)
1739 (memql element (symbol-value list-var)))
1741 (let ((lst (symbol-value list-var)))
1742 (while (and lst
1743 (not (funcall compare-fn element (car lst))))
1744 (setq lst (cdr lst)))
1745 lst)))
1746 (symbol-value list-var)
1747 (set list-var
1748 (if append
1749 (append (symbol-value list-var) (list element))
1750 (cons element (symbol-value list-var))))))
1753 (defun add-to-ordered-list (list-var element &optional order)
1754 "Add ELEMENT to the value of LIST-VAR if it isn't there yet.
1755 The test for presence of ELEMENT is done with `eq'.
1757 The resulting list is reordered so that the elements are in the
1758 order given by each element's numeric list order. Elements
1759 without a numeric list order are placed at the end of the list.
1761 If the third optional argument ORDER is a number (integer or
1762 float), set the element's list order to the given value. If
1763 ORDER is nil or omitted, do not change the numeric order of
1764 ELEMENT. If ORDER has any other value, remove the numeric order
1765 of ELEMENT if it has one.
1767 The list order for each element is stored in LIST-VAR's
1768 `list-order' property.
1770 The return value is the new value of LIST-VAR."
1771 (let ((ordering (get list-var 'list-order)))
1772 (unless ordering
1773 (put list-var 'list-order
1774 (setq ordering (make-hash-table :weakness 'key :test 'eq))))
1775 (when order
1776 (puthash element (and (numberp order) order) ordering))
1777 (unless (memq element (symbol-value list-var))
1778 (set list-var (cons element (symbol-value list-var))))
1779 (set list-var (sort (symbol-value list-var)
1780 (lambda (a b)
1781 (let ((oa (gethash a ordering))
1782 (ob (gethash b ordering)))
1783 (if (and oa ob)
1784 (< oa ob)
1785 oa)))))))
1787 (defun add-to-history (history-var newelt &optional maxelt keep-all)
1788 "Add NEWELT to the history list stored in the variable HISTORY-VAR.
1789 Return the new history list.
1790 If MAXELT is non-nil, it specifies the maximum length of the history.
1791 Otherwise, the maximum history length is the value of the `history-length'
1792 property on symbol HISTORY-VAR, if set, or the value of the `history-length'
1793 variable. The possible values of maximum length have the same meaning as
1794 the values of `history-length'.
1795 Remove duplicates of NEWELT if `history-delete-duplicates' is non-nil.
1796 If optional fourth arg KEEP-ALL is non-nil, add NEWELT to history even
1797 if it is empty or a duplicate."
1798 (unless maxelt
1799 (setq maxelt (or (get history-var 'history-length)
1800 history-length)))
1801 (let ((history (symbol-value history-var))
1802 tail)
1803 (when (and (listp history)
1804 (or keep-all
1805 (not (stringp newelt))
1806 (> (length newelt) 0))
1807 (or keep-all
1808 (not (equal (car history) newelt))))
1809 (if history-delete-duplicates
1810 (setq history (delete newelt history)))
1811 (setq history (cons newelt history))
1812 (when (integerp maxelt)
1813 (if (= 0 maxelt)
1814 (setq history nil)
1815 (setq tail (nthcdr (1- maxelt) history))
1816 (when (consp tail)
1817 (setcdr tail nil)))))
1818 (set history-var history)))
1821 ;;;; Mode hooks.
1823 (defvar delay-mode-hooks nil
1824 "If non-nil, `run-mode-hooks' should delay running the hooks.")
1825 (defvar-local delayed-mode-hooks nil
1826 "List of delayed mode hooks waiting to be run.")
1827 (put 'delay-mode-hooks 'permanent-local t)
1829 (defvar-local delayed-after-hook-functions nil
1830 "List of delayed :after-hook forms waiting to be run.
1831 These forms come from `define-derived-mode'.")
1833 (defvar change-major-mode-after-body-hook nil
1834 "Normal hook run in major mode functions, before the mode hooks.")
1836 (defvar after-change-major-mode-hook nil
1837 "Normal hook run at the very end of major mode functions.")
1839 (defun run-mode-hooks (&rest hooks)
1840 "Run mode hooks `delayed-mode-hooks' and HOOKS, or delay HOOKS.
1841 Call `hack-local-variables' to set up file local and directory local
1842 variables.
1844 If the variable `delay-mode-hooks' is non-nil, does not do anything,
1845 just adds the HOOKS to the list `delayed-mode-hooks'.
1846 Otherwise, runs hooks in the sequence: `change-major-mode-after-body-hook',
1847 `delayed-mode-hooks' (in reverse order), HOOKS, then runs
1848 `hack-local-variables', runs the hook `after-change-major-mode-hook', and
1849 finally evaluates the functions in `delayed-after-hook-functions' (see
1850 `define-derived-mode').
1852 Major mode functions should use this instead of `run-hooks' when
1853 running their FOO-mode-hook."
1854 (if delay-mode-hooks
1855 ;; Delaying case.
1856 (dolist (hook hooks)
1857 (push hook delayed-mode-hooks))
1858 ;; Normal case, just run the hook as before plus any delayed hooks.
1859 (setq hooks (nconc (nreverse delayed-mode-hooks) hooks))
1860 (and syntax-propertize-function
1861 (not (local-variable-p 'parse-sexp-lookup-properties))
1862 ;; `syntax-propertize' sets `parse-sexp-lookup-properties' for us, but
1863 ;; in order for the sexp primitives to automatically call
1864 ;; `syntax-propertize' we need `parse-sexp-lookup-properties' to be
1865 ;; set first.
1866 (setq-local parse-sexp-lookup-properties t))
1867 (setq delayed-mode-hooks nil)
1868 (apply #'run-hooks (cons 'change-major-mode-after-body-hook hooks))
1869 (if (buffer-file-name)
1870 (with-demoted-errors "File local-variables error: %s"
1871 (hack-local-variables 'no-mode)))
1872 (run-hooks 'after-change-major-mode-hook)
1873 (dolist (fun (prog1 (nreverse delayed-after-hook-functions)
1874 (setq delayed-after-hook-functions nil)))
1875 (funcall fun))))
1877 (defmacro delay-mode-hooks (&rest body)
1878 "Execute BODY, but delay any `run-mode-hooks'.
1879 These hooks will be executed by the first following call to
1880 `run-mode-hooks' that occurs outside any `delay-mode-hooks' form.
1881 Only affects hooks run in the current buffer."
1882 (declare (debug t) (indent 0))
1883 `(progn
1884 (make-local-variable 'delay-mode-hooks)
1885 (let ((delay-mode-hooks t))
1886 ,@body)))
1888 ;; PUBLIC: find if the current mode derives from another.
1890 (defun provided-mode-derived-p (mode &rest modes)
1891 "Non-nil if MODE is derived from one of MODES.
1892 Uses the `derived-mode-parent' property of the symbol to trace backwards.
1893 If you just want to check `major-mode', use `derived-mode-p'."
1894 (while (and (not (memq mode modes))
1895 (setq mode (get mode 'derived-mode-parent))))
1896 mode)
1898 (defun derived-mode-p (&rest modes)
1899 "Non-nil if the current major mode is derived from one of MODES.
1900 Uses the `derived-mode-parent' property of the symbol to trace backwards."
1901 (apply #'provided-mode-derived-p major-mode modes))
1903 ;;;; Minor modes.
1905 ;; If a minor mode is not defined with define-minor-mode,
1906 ;; add it here explicitly.
1907 ;; isearch-mode is deliberately excluded, since you should
1908 ;; not call it yourself.
1909 (defvar minor-mode-list '(auto-save-mode auto-fill-mode abbrev-mode
1910 overwrite-mode view-mode
1911 hs-minor-mode)
1912 "List of all minor mode functions.")
1914 (defun add-minor-mode (toggle name &optional keymap after toggle-fun)
1915 "Register a new minor mode.
1917 This is an XEmacs-compatibility function. Use `define-minor-mode' instead.
1919 TOGGLE is a symbol which is the name of a buffer-local variable that
1920 is toggled on or off to say whether the minor mode is active or not.
1922 NAME specifies what will appear in the mode line when the minor mode
1923 is active. NAME should be either a string starting with a space, or a
1924 symbol whose value is such a string.
1926 Optional KEYMAP is the keymap for the minor mode that will be added
1927 to `minor-mode-map-alist'.
1929 Optional AFTER specifies that TOGGLE should be added after AFTER
1930 in `minor-mode-alist'.
1932 Optional TOGGLE-FUN is an interactive function to toggle the mode.
1933 It defaults to (and should by convention be) TOGGLE.
1935 If TOGGLE has a non-nil `:included' property, an entry for the mode is
1936 included in the mode-line minor mode menu.
1937 If TOGGLE has a `:menu-tag', that is used for the menu item's label."
1938 (unless (memq toggle minor-mode-list)
1939 (push toggle minor-mode-list))
1941 (unless toggle-fun (setq toggle-fun toggle))
1942 (unless (eq toggle-fun toggle)
1943 (put toggle :minor-mode-function toggle-fun))
1944 ;; Add the name to the minor-mode-alist.
1945 (when name
1946 (let ((existing (assq toggle minor-mode-alist)))
1947 (if existing
1948 (setcdr existing (list name))
1949 (let ((tail minor-mode-alist) found)
1950 (while (and tail (not found))
1951 (if (eq after (caar tail))
1952 (setq found tail)
1953 (setq tail (cdr tail))))
1954 (if found
1955 (let ((rest (cdr found)))
1956 (setcdr found nil)
1957 (nconc found (list (list toggle name)) rest))
1958 (push (list toggle name) minor-mode-alist))))))
1959 ;; Add the toggle to the minor-modes menu if requested.
1960 (when (get toggle :included)
1961 (define-key mode-line-mode-menu
1962 (vector toggle)
1963 (list 'menu-item
1964 (concat
1965 (or (get toggle :menu-tag)
1966 (if (stringp name) name (symbol-name toggle)))
1967 (let ((mode-name (if (symbolp name) (symbol-value name))))
1968 (if (and (stringp mode-name) (string-match "[^ ]+" mode-name))
1969 (concat " (" (match-string 0 mode-name) ")"))))
1970 toggle-fun
1971 :button (cons :toggle toggle))))
1973 ;; Add the map to the minor-mode-map-alist.
1974 (when keymap
1975 (let ((existing (assq toggle minor-mode-map-alist)))
1976 (if existing
1977 (setcdr existing keymap)
1978 (let ((tail minor-mode-map-alist) found)
1979 (while (and tail (not found))
1980 (if (eq after (caar tail))
1981 (setq found tail)
1982 (setq tail (cdr tail))))
1983 (if found
1984 (let ((rest (cdr found)))
1985 (setcdr found nil)
1986 (nconc found (list (cons toggle keymap)) rest))
1987 (push (cons toggle keymap) minor-mode-map-alist)))))))
1989 ;;;; Load history
1991 (defsubst autoloadp (object)
1992 "Non-nil if OBJECT is an autoload."
1993 (eq 'autoload (car-safe object)))
1995 ;; (defun autoload-type (object)
1996 ;; "Returns the type of OBJECT or `function' or `command' if the type is nil.
1997 ;; OBJECT should be an autoload object."
1998 ;; (when (autoloadp object)
1999 ;; (let ((type (nth 3 object)))
2000 ;; (cond ((null type) (if (nth 2 object) 'command 'function))
2001 ;; ((eq 'keymap t) 'macro)
2002 ;; (type)))))
2004 ;; (defalias 'autoload-file #'cadr
2005 ;; "Return the name of the file from which AUTOLOAD will be loaded.
2006 ;; \n\(fn AUTOLOAD)")
2008 (defun define-symbol-prop (symbol prop val)
2009 "Define the property PROP of SYMBOL to be VAL.
2010 This is to `put' what `defalias' is to `fset'."
2011 ;; Can't use `cl-pushnew' here (nor `push' on (cdr foo)).
2012 ;; (cl-pushnew symbol (alist-get prop
2013 ;; (alist-get 'define-symbol-props
2014 ;; current-load-list)))
2015 (let ((sps (assq 'define-symbol-props current-load-list)))
2016 (unless sps
2017 (setq sps (list 'define-symbol-props))
2018 (push sps current-load-list))
2019 (let ((ps (assq prop sps)))
2020 (unless ps
2021 (setq ps (list prop))
2022 (setcdr sps (cons ps (cdr sps))))
2023 (unless (member symbol (cdr ps))
2024 (setcdr ps (cons symbol (cdr ps))))))
2025 (put symbol prop val))
2027 (defun symbol-file (symbol &optional type)
2028 "Return the name of the file that defined SYMBOL.
2029 The value is normally an absolute file name. It can also be nil,
2030 if the definition is not associated with any file. If SYMBOL
2031 specifies an autoloaded function, the value can be a relative
2032 file name without extension.
2034 If TYPE is nil, then any kind of definition is acceptable. If
2035 TYPE is `defun', `defvar', or `defface', that specifies function
2036 definition, variable definition, or face definition only.
2037 Otherwise TYPE is assumed to be a symbol property."
2038 (if (and (or (null type) (eq type 'defun))
2039 (symbolp symbol)
2040 (autoloadp (symbol-function symbol)))
2041 (nth 1 (symbol-function symbol))
2042 (catch 'found
2043 (pcase-dolist (`(,file . ,elems) load-history)
2044 (when (if type
2045 (if (eq type 'defvar)
2046 ;; Variables are present just as their names.
2047 (member symbol elems)
2048 ;; Many other types are represented as (TYPE . NAME).
2049 (or (member (cons type symbol) elems)
2050 (memq symbol (alist-get type
2051 (alist-get 'define-symbol-props
2052 elems)))))
2053 ;; We accept all types, so look for variable def
2054 ;; and then for any other kind.
2055 (or (member symbol elems)
2056 (let ((match (rassq symbol elems)))
2057 (and match
2058 (not (eq 'require (car match)))))))
2059 (throw 'found file))))))
2061 (defun locate-library (library &optional nosuffix path interactive-call)
2062 "Show the precise file name of Emacs library LIBRARY.
2063 LIBRARY should be a relative file name of the library, a string.
2064 It can omit the suffix (a.k.a. file-name extension) if NOSUFFIX is
2065 nil (which is the default, see below).
2066 This command searches the directories in `load-path' like `\\[load-library]'
2067 to find the file that `\\[load-library] RET LIBRARY RET' would load.
2068 Optional second arg NOSUFFIX non-nil means don't add suffixes `load-suffixes'
2069 to the specified name LIBRARY.
2071 If the optional third arg PATH is specified, that list of directories
2072 is used instead of `load-path'.
2074 When called from a program, the file name is normally returned as a
2075 string. When run interactively, the argument INTERACTIVE-CALL is t,
2076 and the file name is displayed in the echo area."
2077 (interactive (list (completing-read "Locate library: "
2078 (apply-partially
2079 'locate-file-completion-table
2080 load-path (get-load-suffixes)))
2081 nil nil
2083 (let ((file (locate-file library
2084 (or path load-path)
2085 (append (unless nosuffix (get-load-suffixes))
2086 load-file-rep-suffixes))))
2087 (if interactive-call
2088 (if file
2089 (message "Library is file %s" (abbreviate-file-name file))
2090 (message "No library %s in search path" library)))
2091 file))
2094 ;;;; Process stuff.
2096 (defun start-process (name buffer program &rest program-args)
2097 "Start a program in a subprocess. Return the process object for it.
2098 NAME is name for process. It is modified if necessary to make it unique.
2099 BUFFER is the buffer (or buffer name) to associate with the process.
2101 Process output (both standard output and standard error streams)
2102 goes at end of BUFFER, unless you specify a filter function to
2103 handle the output. BUFFER may also be nil, meaning that this
2104 process is not associated with any buffer.
2106 PROGRAM is the program file name. It is searched for in `exec-path'
2107 \(which see). If nil, just associate a pty with the buffer. Remaining
2108 arguments PROGRAM-ARGS are strings to give program as arguments.
2110 If you want to separate standard output from standard error, use
2111 `make-process' or invoke the command through a shell and redirect
2112 one of them using the shell syntax.
2114 The process runs in `default-directory' if that is local (as
2115 determined by `unhandled-file-name-directory'), or \"~\"
2116 otherwise. If you want to run a process in a remote directory
2117 use `start-file-process'."
2118 (unless (fboundp 'make-process)
2119 (error "Emacs was compiled without subprocess support"))
2120 (apply #'make-process
2121 (append (list :name name :buffer buffer)
2122 (if program
2123 (list :command (cons program program-args))))))
2125 (defun process-lines (program &rest args)
2126 "Execute PROGRAM with ARGS, returning its output as a list of lines.
2127 Signal an error if the program returns with a non-zero exit status."
2128 (with-temp-buffer
2129 (let ((status (apply 'call-process program nil (current-buffer) nil args)))
2130 (unless (eq status 0)
2131 (error "%s exited with status %s" program status))
2132 (goto-char (point-min))
2133 (let (lines)
2134 (while (not (eobp))
2135 (setq lines (cons (buffer-substring-no-properties
2136 (line-beginning-position)
2137 (line-end-position))
2138 lines))
2139 (forward-line 1))
2140 (nreverse lines)))))
2142 (defun process-live-p (process)
2143 "Returns non-nil if PROCESS is alive.
2144 A process is considered alive if its status is `run', `open',
2145 `listen', `connect' or `stop'. Value is nil if PROCESS is not a
2146 process."
2147 (and (processp process)
2148 (memq (process-status process)
2149 '(run open listen connect stop))))
2151 (defun process-kill-buffer-query-function ()
2152 "Ask before killing a buffer that has a running process."
2153 (let ((process (get-buffer-process (current-buffer))))
2154 (or (not process)
2155 (not (memq (process-status process) '(run stop open listen)))
2156 (not (process-query-on-exit-flag process))
2157 (yes-or-no-p
2158 (format "Buffer %S has a running process; kill it? "
2159 (buffer-name (current-buffer)))))))
2161 (add-hook 'kill-buffer-query-functions 'process-kill-buffer-query-function)
2163 ;; process plist management
2165 (defun process-get (process propname)
2166 "Return the value of PROCESS' PROPNAME property.
2167 This is the last value stored with `(process-put PROCESS PROPNAME VALUE)'."
2168 (plist-get (process-plist process) propname))
2170 (defun process-put (process propname value)
2171 "Change PROCESS' PROPNAME property to VALUE.
2172 It can be retrieved with `(process-get PROCESS PROPNAME)'."
2173 (set-process-plist process
2174 (plist-put (process-plist process) propname value)))
2177 ;;;; Input and display facilities.
2179 (defconst read-key-empty-map (make-sparse-keymap))
2181 (defvar read-key-delay 0.01) ;Fast enough for 100Hz repeat rate, hopefully.
2183 (defun read-key (&optional prompt)
2184 "Read a key from the keyboard.
2185 Contrary to `read-event' this will not return a raw event but instead will
2186 obey the input decoding and translations usually done by `read-key-sequence'.
2187 So escape sequences and keyboard encoding are taken into account.
2188 When there's an ambiguity because the key looks like the prefix of
2189 some sort of escape sequence, the ambiguity is resolved via `read-key-delay'."
2190 ;; This overriding-terminal-local-map binding also happens to
2191 ;; disable quail's input methods, so although read-key-sequence
2192 ;; always inherits the input method, in practice read-key does not
2193 ;; inherit the input method (at least not if it's based on quail).
2194 (let ((overriding-terminal-local-map nil)
2195 (overriding-local-map read-key-empty-map)
2196 (echo-keystrokes 0)
2197 (old-global-map (current-global-map))
2198 (timer (run-with-idle-timer
2199 ;; Wait long enough that Emacs has the time to receive and
2200 ;; process all the raw events associated with the single-key.
2201 ;; But don't wait too long, or the user may find the delay
2202 ;; annoying (or keep hitting more keys which may then get
2203 ;; lost or misinterpreted).
2204 ;; This is only relevant for keys which Emacs perceives as
2205 ;; "prefixes", such as C-x (because of the C-x 8 map in
2206 ;; key-translate-table and the C-x @ map in function-key-map)
2207 ;; or ESC (because of terminal escape sequences in
2208 ;; input-decode-map).
2209 read-key-delay t
2210 (lambda ()
2211 (let ((keys (this-command-keys-vector)))
2212 (unless (zerop (length keys))
2213 ;; `keys' is non-empty, so the user has hit at least
2214 ;; one key; there's no point waiting any longer, even
2215 ;; though read-key-sequence thinks we should wait
2216 ;; for more input to decide how to interpret the
2217 ;; current input.
2218 (throw 'read-key keys)))))))
2219 (unwind-protect
2220 (progn
2221 (use-global-map
2222 (let ((map (make-sparse-keymap)))
2223 ;; Don't hide the menu-bar and tool-bar entries.
2224 (define-key map [menu-bar] (lookup-key global-map [menu-bar]))
2225 (define-key map [tool-bar]
2226 ;; This hack avoids evaluating the :filter (Bug#9922).
2227 (or (cdr (assq 'tool-bar global-map))
2228 (lookup-key global-map [tool-bar])))
2229 map))
2230 (let* ((keys
2231 (catch 'read-key (read-key-sequence-vector prompt nil t)))
2232 (key (aref keys 0)))
2233 (if (and (> (length keys) 1)
2234 (memq key '(mode-line header-line
2235 left-fringe right-fringe)))
2236 (aref keys 1)
2237 key)))
2238 (cancel-timer timer)
2239 ;; For some reason, `read-key(-sequence)' leaves the prompt in the echo
2240 ;; area, whereas `read-event' seems to empty it just before returning
2241 ;; (bug#22714). So, let's mimic the behavior of `read-event'.
2242 (message nil)
2243 (use-global-map old-global-map))))
2245 (defvar read-passwd-map
2246 ;; BEWARE: `defconst' would purecopy it, breaking the sharing with
2247 ;; minibuffer-local-map along the way!
2248 (let ((map (make-sparse-keymap)))
2249 (set-keymap-parent map minibuffer-local-map)
2250 (define-key map "\C-u" #'delete-minibuffer-contents) ;bug#12570
2251 map)
2252 "Keymap used while reading passwords.")
2254 (defun read-passwd (prompt &optional confirm default)
2255 "Read a password, prompting with PROMPT, and return it.
2256 If optional CONFIRM is non-nil, read the password twice to make sure.
2257 Optional DEFAULT is a default password to use instead of empty input.
2259 This function echoes `.' for each character that the user types.
2260 You could let-bind `read-hide-char' to another hiding character, though.
2262 Once the caller uses the password, it can erase the password
2263 by doing (clear-string STRING)."
2264 (if confirm
2265 (let (success)
2266 (while (not success)
2267 (let ((first (read-passwd prompt nil default))
2268 (second (read-passwd "Confirm password: " nil default)))
2269 (if (equal first second)
2270 (progn
2271 (and (arrayp second) (not (eq first second)) (clear-string second))
2272 (setq success first))
2273 (and (arrayp first) (clear-string first))
2274 (and (arrayp second) (clear-string second))
2275 (message "Password not repeated accurately; please start over")
2276 (sit-for 1))))
2277 success)
2278 (let ((hide-chars-fun
2279 (lambda (beg end _len)
2280 (clear-this-command-keys)
2281 (setq beg (min end (max (minibuffer-prompt-end)
2282 beg)))
2283 (dotimes (i (- end beg))
2284 (put-text-property (+ i beg) (+ 1 i beg)
2285 'display (string (or read-hide-char ?.))))))
2286 minibuf)
2287 (minibuffer-with-setup-hook
2288 (lambda ()
2289 (setq minibuf (current-buffer))
2290 ;; Turn off electricity.
2291 (setq-local post-self-insert-hook nil)
2292 (setq-local buffer-undo-list t)
2293 (setq-local select-active-regions nil)
2294 (use-local-map read-passwd-map)
2295 (setq-local inhibit-modification-hooks nil) ;bug#15501.
2296 (setq-local show-paren-mode nil) ;bug#16091.
2297 (add-hook 'after-change-functions hide-chars-fun nil 'local))
2298 (unwind-protect
2299 (let ((enable-recursive-minibuffers t)
2300 (read-hide-char (or read-hide-char ?.)))
2301 (read-string prompt nil t default)) ; t = "no history"
2302 (when (buffer-live-p minibuf)
2303 (with-current-buffer minibuf
2304 ;; Not sure why but it seems that there might be cases where the
2305 ;; minibuffer is not always properly reset later on, so undo
2306 ;; whatever we've done here (bug#11392).
2307 (remove-hook 'after-change-functions hide-chars-fun 'local)
2308 (kill-local-variable 'post-self-insert-hook)
2309 ;; And of course, don't keep the sensitive data around.
2310 (erase-buffer))))))))
2312 (defun read-number (prompt &optional default)
2313 "Read a numeric value in the minibuffer, prompting with PROMPT.
2314 DEFAULT specifies a default value to return if the user just types RET.
2315 The value of DEFAULT is inserted into PROMPT.
2316 This function is used by the `interactive' code letter `n'."
2317 (let ((n nil)
2318 (default1 (if (consp default) (car default) default)))
2319 (when default1
2320 (setq prompt
2321 (if (string-match "\\(\\):[ \t]*\\'" prompt)
2322 (replace-match (format " (default %s)" default1) t t prompt 1)
2323 (replace-regexp-in-string "[ \t]*\\'"
2324 (format " (default %s) " default1)
2325 prompt t t))))
2326 (while
2327 (progn
2328 (let ((str (read-from-minibuffer
2329 prompt nil nil nil nil
2330 (when default
2331 (if (consp default)
2332 (mapcar 'number-to-string (delq nil default))
2333 (number-to-string default))))))
2334 (condition-case nil
2335 (setq n (cond
2336 ((zerop (length str)) default1)
2337 ((stringp str) (read str))))
2338 (error nil)))
2339 (unless (numberp n)
2340 (message "Please enter a number.")
2341 (sit-for 1)
2342 t)))
2345 (defun read-char-choice (prompt chars &optional inhibit-keyboard-quit)
2346 "Read and return one of CHARS, prompting for PROMPT.
2347 Any input that is not one of CHARS is ignored.
2349 If optional argument INHIBIT-KEYBOARD-QUIT is non-nil, ignore
2350 keyboard-quit events while waiting for a valid input."
2351 (unless (consp chars)
2352 (error "Called `read-char-choice' without valid char choices"))
2353 (let (char done show-help (helpbuf " *Char Help*"))
2354 (let ((cursor-in-echo-area t)
2355 (executing-kbd-macro executing-kbd-macro)
2356 (esc-flag nil))
2357 (save-window-excursion ; in case we call help-form-show
2358 (while (not done)
2359 (unless (get-text-property 0 'face prompt)
2360 (setq prompt (propertize prompt 'face 'minibuffer-prompt)))
2361 (setq char (let ((inhibit-quit inhibit-keyboard-quit))
2362 (read-key prompt)))
2363 (and show-help (buffer-live-p (get-buffer helpbuf))
2364 (kill-buffer helpbuf))
2365 (cond
2366 ((not (numberp char)))
2367 ;; If caller has set help-form, that's enough.
2368 ;; They don't explicitly have to add help-char to chars.
2369 ((and help-form
2370 (eq char help-char)
2371 (setq show-help t)
2372 (help-form-show)))
2373 ((memq char chars)
2374 (setq done t))
2375 ((and executing-kbd-macro (= char -1))
2376 ;; read-event returns -1 if we are in a kbd macro and
2377 ;; there are no more events in the macro. Attempt to
2378 ;; get an event interactively.
2379 (setq executing-kbd-macro nil))
2380 ((not inhibit-keyboard-quit)
2381 (cond
2382 ((and (null esc-flag) (eq char ?\e))
2383 (setq esc-flag t))
2384 ((memq char '(?\C-g ?\e))
2385 (keyboard-quit))))))))
2386 ;; Display the question with the answer. But without cursor-in-echo-area.
2387 (message "%s%s" prompt (char-to-string char))
2388 char))
2390 (defun sit-for (seconds &optional nodisp obsolete)
2391 "Redisplay, then wait for SECONDS seconds. Stop when input is available.
2392 SECONDS may be a floating-point value.
2393 \(On operating systems that do not support waiting for fractions of a
2394 second, floating-point values are rounded down to the nearest integer.)
2396 If optional arg NODISP is t, don't redisplay, just wait for input.
2397 Redisplay does not happen if input is available before it starts.
2399 Value is t if waited the full time with no input arriving, and nil otherwise.
2401 An obsolete, but still supported form is
2402 \(sit-for SECONDS &optional MILLISECONDS NODISP)
2403 where the optional arg MILLISECONDS specifies an additional wait period,
2404 in milliseconds; this was useful when Emacs was built without
2405 floating point support."
2406 (declare (advertised-calling-convention (seconds &optional nodisp) "22.1"))
2407 ;; This used to be implemented in C until the following discussion:
2408 ;; https://lists.gnu.org/r/emacs-devel/2006-07/msg00401.html
2409 ;; Then it was moved here using an implementation based on an idle timer,
2410 ;; which was then replaced by the use of read-event.
2411 (if (numberp nodisp)
2412 (setq seconds (+ seconds (* 1e-3 nodisp))
2413 nodisp obsolete)
2414 (if obsolete (setq nodisp obsolete)))
2415 (cond
2416 (noninteractive
2417 (sleep-for seconds)
2419 ((input-pending-p t)
2420 nil)
2421 ((or (<= seconds 0)
2422 ;; We are going to call read-event below, which will record
2423 ;; the next key as part of the macro, even if that key
2424 ;; invokes kmacro-end-macro, so if we are recording a macro,
2425 ;; the macro will recursively call itself. In addition, when
2426 ;; that key is removed from unread-command-events, it will be
2427 ;; recorded the second time, so the macro will have each key
2428 ;; doubled. This used to happen if a macro was defined with
2429 ;; Flyspell mode active (because Flyspell calls sit-for in its
2430 ;; post-command-hook, see bug #21329.) To avoid all that, we
2431 ;; simply disable the wait when we are recording a macro.
2432 defining-kbd-macro)
2433 (or nodisp (redisplay)))
2435 (or nodisp (redisplay))
2436 ;; FIXME: we should not read-event here at all, because it's much too
2437 ;; difficult to reliably "undo" a read-event by pushing it onto
2438 ;; unread-command-events.
2439 ;; For bug#14782, we need read-event to do the keyboard-coding-system
2440 ;; decoding (hence non-nil as second arg under POSIX ttys).
2441 ;; For bug#15614, we need read-event not to inherit-input-method.
2442 ;; So we temporarily suspend input-method-function.
2443 (let ((read (let ((input-method-function nil))
2444 (read-event nil t seconds))))
2445 (or (null read)
2446 (progn
2447 ;; https://lists.gnu.org/r/emacs-devel/2006-10/msg00394.html
2448 ;; We want `read' appear in the next command's this-command-event
2449 ;; but not in the current one.
2450 ;; By pushing (cons t read), we indicate that `read' has not
2451 ;; yet been recorded in this-command-keys, so it will be recorded
2452 ;; next time it's read.
2453 ;; And indeed the `seconds' argument to read-event correctly
2454 ;; prevented recording this event in the current command's
2455 ;; this-command-keys.
2456 (push (cons t read) unread-command-events)
2457 nil))))))
2459 ;; Behind display-popup-menus-p test.
2460 (declare-function x-popup-dialog "menu.c" (position contents &optional header))
2462 (defun y-or-n-p (prompt)
2463 "Ask user a \"y or n\" question.
2464 Return t if answer is \"y\" and nil if it is \"n\".
2465 PROMPT is the string to display to ask the question. It should
2466 end in a space; `y-or-n-p' adds \"(y or n) \" to it.
2468 No confirmation of the answer is requested; a single character is
2469 enough. SPC also means yes, and DEL means no.
2471 To be precise, this function translates user input into responses
2472 by consulting the bindings in `query-replace-map'; see the
2473 documentation of that variable for more information. In this
2474 case, the useful bindings are `act', `skip', `recenter',
2475 `scroll-up', `scroll-down', and `quit'.
2476 An `act' response means yes, and a `skip' response means no.
2477 A `quit' response means to invoke `keyboard-quit'.
2478 If the user enters `recenter', `scroll-up', or `scroll-down'
2479 responses, perform the requested window recentering or scrolling
2480 and ask again.
2482 Under a windowing system a dialog box will be used if `last-nonmenu-event'
2483 is nil and `use-dialog-box' is non-nil."
2484 ;; ¡Beware! when I tried to edebug this code, Emacs got into a weird state
2485 ;; where all the keys were unbound (i.e. it somehow got triggered
2486 ;; within read-key, apparently). I had to kill it.
2487 (let ((answer 'recenter)
2488 (padded (lambda (prompt &optional dialog)
2489 (let ((l (length prompt)))
2490 (concat prompt
2491 (if (or (zerop l) (eq ?\s (aref prompt (1- l))))
2492 "" " ")
2493 (if dialog "" "(y or n) "))))))
2494 (cond
2495 (noninteractive
2496 (setq prompt (funcall padded prompt))
2497 (let ((temp-prompt prompt))
2498 (while (not (memq answer '(act skip)))
2499 (let ((str (read-string temp-prompt)))
2500 (cond ((member str '("y" "Y")) (setq answer 'act))
2501 ((member str '("n" "N")) (setq answer 'skip))
2502 (t (setq temp-prompt (concat "Please answer y or n. "
2503 prompt))))))))
2504 ((and (display-popup-menus-p)
2505 last-input-event ; not during startup
2506 (listp last-nonmenu-event)
2507 use-dialog-box)
2508 (setq prompt (funcall padded prompt t)
2509 answer (x-popup-dialog t `(,prompt ("Yes" . act) ("No" . skip)))))
2511 (setq prompt (funcall padded prompt))
2512 (while
2513 (let* ((scroll-actions '(recenter scroll-up scroll-down
2514 scroll-other-window scroll-other-window-down))
2515 (key
2516 (let ((cursor-in-echo-area t))
2517 (when minibuffer-auto-raise
2518 (raise-frame (window-frame (minibuffer-window))))
2519 (read-key (propertize (if (memq answer scroll-actions)
2520 prompt
2521 (concat "Please answer y or n. "
2522 prompt))
2523 'face 'minibuffer-prompt)))))
2524 (setq answer (lookup-key query-replace-map (vector key) t))
2525 (cond
2526 ((memq answer '(skip act)) nil)
2527 ((eq answer 'recenter)
2528 (recenter) t)
2529 ((eq answer 'scroll-up)
2530 (ignore-errors (scroll-up-command)) t)
2531 ((eq answer 'scroll-down)
2532 (ignore-errors (scroll-down-command)) t)
2533 ((eq answer 'scroll-other-window)
2534 (ignore-errors (scroll-other-window)) t)
2535 ((eq answer 'scroll-other-window-down)
2536 (ignore-errors (scroll-other-window-down)) t)
2537 ((or (memq answer '(exit-prefix quit)) (eq key ?\e))
2538 (signal 'quit nil) t)
2539 (t t)))
2540 (ding)
2541 (discard-input))))
2542 (let ((ret (eq answer 'act)))
2543 (unless noninteractive
2544 (message "%s%c" prompt (if ret ?y ?n)))
2545 ret)))
2548 ;;; Atomic change groups.
2550 (defmacro atomic-change-group (&rest body)
2551 "Like `progn' but perform BODY as an atomic change group.
2552 This means that if BODY exits abnormally,
2553 all of its changes to the current buffer are undone.
2554 This works regardless of whether undo is enabled in the buffer.
2556 This mechanism is transparent to ordinary use of undo;
2557 if undo is enabled in the buffer and BODY succeeds, the
2558 user can undo the change normally."
2559 (declare (indent 0) (debug t))
2560 (let ((handle (make-symbol "--change-group-handle--"))
2561 (success (make-symbol "--change-group-success--")))
2562 `(let ((,handle (prepare-change-group))
2563 ;; Don't truncate any undo data in the middle of this.
2564 (undo-outer-limit nil)
2565 (undo-limit most-positive-fixnum)
2566 (undo-strong-limit most-positive-fixnum)
2567 (,success nil))
2568 (unwind-protect
2569 (progn
2570 ;; This is inside the unwind-protect because
2571 ;; it enables undo if that was disabled; we need
2572 ;; to make sure that it gets disabled again.
2573 (activate-change-group ,handle)
2574 (prog1 ,(macroexp-progn body)
2575 (setq ,success t)))
2576 ;; Either of these functions will disable undo
2577 ;; if it was disabled before.
2578 (if ,success
2579 (accept-change-group ,handle)
2580 (cancel-change-group ,handle))))))
2582 (defun prepare-change-group (&optional buffer)
2583 "Return a handle for the current buffer's state, for a change group.
2584 If you specify BUFFER, make a handle for BUFFER's state instead.
2586 Pass the handle to `activate-change-group' afterward to initiate
2587 the actual changes of the change group.
2589 To finish the change group, call either `accept-change-group' or
2590 `cancel-change-group' passing the same handle as argument. Call
2591 `accept-change-group' to accept the changes in the group as final;
2592 call `cancel-change-group' to undo them all. You should use
2593 `unwind-protect' to make sure the group is always finished. The call
2594 to `activate-change-group' should be inside the `unwind-protect'.
2595 Once you finish the group, don't use the handle again--don't try to
2596 finish the same group twice. For a simple example of correct use, see
2597 the source code of `atomic-change-group'.
2599 The handle records only the specified buffer. To make a multibuffer
2600 change group, call this function once for each buffer you want to
2601 cover, then use `nconc' to combine the returned values, like this:
2603 (nconc (prepare-change-group buffer-1)
2604 (prepare-change-group buffer-2))
2606 You can then activate that multibuffer change group with a single
2607 call to `activate-change-group' and finish it with a single call
2608 to `accept-change-group' or `cancel-change-group'."
2610 (if buffer
2611 (list (cons buffer (with-current-buffer buffer buffer-undo-list)))
2612 (list (cons (current-buffer) buffer-undo-list))))
2614 (defun activate-change-group (handle)
2615 "Activate a change group made with `prepare-change-group' (which see)."
2616 (dolist (elt handle)
2617 (with-current-buffer (car elt)
2618 (if (eq buffer-undo-list t)
2619 (setq buffer-undo-list nil)))))
2621 (defun accept-change-group (handle)
2622 "Finish a change group made with `prepare-change-group' (which see).
2623 This finishes the change group by accepting its changes as final."
2624 (dolist (elt handle)
2625 (with-current-buffer (car elt)
2626 (if (eq (cdr elt) t)
2627 (setq buffer-undo-list t)))))
2629 (defun cancel-change-group (handle)
2630 "Finish a change group made with `prepare-change-group' (which see).
2631 This finishes the change group by reverting all of its changes."
2632 (dolist (elt handle)
2633 (with-current-buffer (car elt)
2634 (setq elt (cdr elt))
2635 (save-restriction
2636 ;; Widen buffer temporarily so if the buffer was narrowed within
2637 ;; the body of `atomic-change-group' all changes can be undone.
2638 (widen)
2639 (let ((old-car (car-safe elt))
2640 (old-cdr (cdr-safe elt)))
2641 (unwind-protect
2642 (progn
2643 ;; Temporarily truncate the undo log at ELT.
2644 (when (consp elt)
2645 (setcar elt nil) (setcdr elt nil))
2646 (unless (eq last-command 'undo) (undo-start))
2647 ;; Make sure there's no confusion.
2648 (when (and (consp elt) (not (eq elt (last pending-undo-list))))
2649 (error "Undoing to some unrelated state"))
2650 ;; Undo it all.
2651 (save-excursion
2652 (while (listp pending-undo-list) (undo-more 1)))
2653 ;; Revert the undo info to what it was when we grabbed
2654 ;; the state.
2655 (setq buffer-undo-list elt))
2656 ;; Reset the modified cons cell ELT to its original content.
2657 (when (consp elt)
2658 (setcar elt old-car)
2659 (setcdr elt old-cdr))))))))
2661 ;;;; Display-related functions.
2663 ;; For compatibility.
2664 (define-obsolete-function-alias 'redraw-modeline
2665 'force-mode-line-update "24.3")
2667 (defun momentary-string-display (string pos &optional exit-char message)
2668 "Momentarily display STRING in the buffer at POS.
2669 Display remains until next event is input.
2670 If POS is a marker, only its position is used; its buffer is ignored.
2671 Optional third arg EXIT-CHAR can be a character, event or event
2672 description list. EXIT-CHAR defaults to SPC. If the input is
2673 EXIT-CHAR it is swallowed; otherwise it is then available as
2674 input (as a command if nothing else).
2675 Display MESSAGE (optional fourth arg) in the echo area.
2676 If MESSAGE is nil, instructions to type EXIT-CHAR are displayed there."
2677 (or exit-char (setq exit-char ?\s))
2678 (let ((ol (make-overlay pos pos))
2679 (str (copy-sequence string)))
2680 (unwind-protect
2681 (progn
2682 (save-excursion
2683 (overlay-put ol 'after-string str)
2684 (goto-char pos)
2685 ;; To avoid trouble with out-of-bounds position
2686 (setq pos (point))
2687 ;; If the string end is off screen, recenter now.
2688 (if (<= (window-end nil t) pos)
2689 (recenter (/ (window-height) 2))))
2690 (message (or message "Type %s to continue editing.")
2691 (single-key-description exit-char))
2692 (let ((event (read-key)))
2693 ;; `exit-char' can be an event, or an event description list.
2694 (or (eq event exit-char)
2695 (eq event (event-convert-list exit-char))
2696 (setq unread-command-events
2697 (append (this-single-command-raw-keys)
2698 unread-command-events)))))
2699 (delete-overlay ol))))
2702 ;;;; Overlay operations
2704 (defun copy-overlay (o)
2705 "Return a copy of overlay O."
2706 (let ((o1 (if (overlay-buffer o)
2707 (make-overlay (overlay-start o) (overlay-end o)
2708 ;; FIXME: there's no easy way to find the
2709 ;; insertion-type of the two markers.
2710 (overlay-buffer o))
2711 (let ((o1 (make-overlay (point-min) (point-min))))
2712 (delete-overlay o1)
2713 o1)))
2714 (props (overlay-properties o)))
2715 (while props
2716 (overlay-put o1 (pop props) (pop props)))
2717 o1))
2719 (defun remove-overlays (&optional beg end name val)
2720 "Clear BEG and END of overlays whose property NAME has value VAL.
2721 Overlays might be moved and/or split.
2722 BEG and END default respectively to the beginning and end of buffer."
2723 ;; This speeds up the loops over overlays.
2724 (unless beg (setq beg (point-min)))
2725 (unless end (setq end (point-max)))
2726 (overlay-recenter end)
2727 (if (< end beg)
2728 (setq beg (prog1 end (setq end beg))))
2729 (save-excursion
2730 (dolist (o (overlays-in beg end))
2731 (when (eq (overlay-get o name) val)
2732 ;; Either push this overlay outside beg...end
2733 ;; or split it to exclude beg...end
2734 ;; or delete it entirely (if it is contained in beg...end).
2735 (if (< (overlay-start o) beg)
2736 (if (> (overlay-end o) end)
2737 (progn
2738 (move-overlay (copy-overlay o)
2739 (overlay-start o) beg)
2740 (move-overlay o end (overlay-end o)))
2741 (move-overlay o (overlay-start o) beg))
2742 (if (> (overlay-end o) end)
2743 (move-overlay o end (overlay-end o))
2744 (delete-overlay o)))))))
2746 ;;;; Miscellanea.
2748 (defvar suspend-hook nil
2749 "Normal hook run by `suspend-emacs', before suspending.")
2751 (defvar suspend-resume-hook nil
2752 "Normal hook run by `suspend-emacs', after Emacs is continued.")
2754 (defvar temp-buffer-show-hook nil
2755 "Normal hook run by `with-output-to-temp-buffer' after displaying the buffer.
2756 When the hook runs, the temporary buffer is current, and the window it
2757 was displayed in is selected.")
2759 (defvar temp-buffer-setup-hook nil
2760 "Normal hook run by `with-output-to-temp-buffer' at the start.
2761 When the hook runs, the temporary buffer is current.
2762 This hook is normally set up with a function to put the buffer in Help
2763 mode.")
2765 (defconst user-emacs-directory
2766 (if (eq system-type 'ms-dos)
2767 ;; MS-DOS cannot have initial dot.
2768 "~/_emacs.d/"
2769 "~/.emacs.d/")
2770 "Directory beneath which additional per-user Emacs-specific files are placed.
2771 Various programs in Emacs store information in this directory.
2772 Note that this should end with a directory separator.
2773 See also `locate-user-emacs-file'.")
2775 ;;;; Misc. useful functions.
2777 (defsubst buffer-narrowed-p ()
2778 "Return non-nil if the current buffer is narrowed."
2779 (/= (- (point-max) (point-min)) (buffer-size)))
2781 (defun find-tag-default-bounds ()
2782 "Determine the boundaries of the default tag, based on text at point.
2783 Return a cons cell with the beginning and end of the found tag.
2784 If there is no plausible default, return nil."
2785 (bounds-of-thing-at-point 'symbol))
2787 (defun find-tag-default ()
2788 "Determine default tag to search for, based on text at point.
2789 If there is no plausible default, return nil."
2790 (let ((bounds (find-tag-default-bounds)))
2791 (when bounds
2792 (buffer-substring-no-properties (car bounds) (cdr bounds)))))
2794 (defun find-tag-default-as-regexp ()
2795 "Return regexp that matches the default tag at point.
2796 If there is no tag at point, return nil.
2798 When in a major mode that does not provide its own
2799 `find-tag-default-function', return a regexp that matches the
2800 symbol at point exactly."
2801 (let ((tag (funcall (or find-tag-default-function
2802 (get major-mode 'find-tag-default-function)
2803 'find-tag-default))))
2804 (if tag (regexp-quote tag))))
2806 (defun find-tag-default-as-symbol-regexp ()
2807 "Return regexp that matches the default tag at point as symbol.
2808 If there is no tag at point, return nil.
2810 When in a major mode that does not provide its own
2811 `find-tag-default-function', return a regexp that matches the
2812 symbol at point exactly."
2813 (let ((tag-regexp (find-tag-default-as-regexp)))
2814 (if (and tag-regexp
2815 (eq (or find-tag-default-function
2816 (get major-mode 'find-tag-default-function)
2817 'find-tag-default)
2818 'find-tag-default))
2819 (format "\\_<%s\\_>" tag-regexp)
2820 tag-regexp)))
2822 (defun play-sound (sound)
2823 "SOUND is a list of the form `(sound KEYWORD VALUE...)'.
2824 The following keywords are recognized:
2826 :file FILE - read sound data from FILE. If FILE isn't an
2827 absolute file name, it is searched in `data-directory'.
2829 :data DATA - read sound data from string DATA.
2831 Exactly one of :file or :data must be present.
2833 :volume VOL - set volume to VOL. VOL must an integer in the
2834 range 0..100 or a float in the range 0..1.0. If not specified,
2835 don't change the volume setting of the sound device.
2837 :device DEVICE - play sound on DEVICE. If not specified,
2838 a system-dependent default device name is used.
2840 Note: :data and :device are currently not supported on Windows."
2841 (if (fboundp 'play-sound-internal)
2842 (play-sound-internal sound)
2843 (error "This Emacs binary lacks sound support")))
2845 (declare-function w32-shell-dos-semantics "w32-fns" nil)
2847 (defun shell-quote-argument (argument)
2848 "Quote ARGUMENT for passing as argument to an inferior shell.
2850 This function is designed to work with the syntax of your system's
2851 standard shell, and might produce incorrect results with unusual shells.
2852 See Info node `(elisp)Security Considerations'."
2853 (cond
2854 ((eq system-type 'ms-dos)
2855 ;; Quote using double quotes, but escape any existing quotes in
2856 ;; the argument with backslashes.
2857 (let ((result "")
2858 (start 0)
2859 end)
2860 (if (or (null (string-match "[^\"]" argument))
2861 (< (match-end 0) (length argument)))
2862 (while (string-match "[\"]" argument start)
2863 (setq end (match-beginning 0)
2864 result (concat result (substring argument start end)
2865 "\\" (substring argument end (1+ end)))
2866 start (1+ end))))
2867 (concat "\"" result (substring argument start) "\"")))
2869 ((and (eq system-type 'windows-nt) (w32-shell-dos-semantics))
2871 ;; First, quote argument so that CommandLineToArgvW will
2872 ;; understand it. See
2873 ;; http://msdn.microsoft.com/en-us/library/17w5ykft%28v=vs.85%29.aspx
2874 ;; After we perform that level of quoting, escape shell
2875 ;; metacharacters so that cmd won't mangle our argument. If the
2876 ;; argument contains no double quote characters, we can just
2877 ;; surround it with double quotes. Otherwise, we need to prefix
2878 ;; each shell metacharacter with a caret.
2880 (setq argument
2881 ;; escape backslashes at end of string
2882 (replace-regexp-in-string
2883 "\\(\\\\*\\)$"
2884 "\\1\\1"
2885 ;; escape backslashes and quotes in string body
2886 (replace-regexp-in-string
2887 "\\(\\\\*\\)\""
2888 "\\1\\1\\\\\""
2889 argument)))
2891 (if (string-match "[%!\"]" argument)
2892 (concat
2893 "^\""
2894 (replace-regexp-in-string
2895 "\\([%!()\"<>&|^]\\)"
2896 "^\\1"
2897 argument)
2898 "^\"")
2899 (concat "\"" argument "\"")))
2902 (if (equal argument "")
2903 "''"
2904 ;; Quote everything except POSIX filename characters.
2905 ;; This should be safe enough even for really weird shells.
2906 (replace-regexp-in-string
2907 "\n" "'\n'"
2908 (replace-regexp-in-string "[^-0-9a-zA-Z_./\n]" "\\\\\\&" argument))))
2911 (defsubst string-to-list (string)
2912 "Return a list of characters in STRING."
2913 (append string nil))
2915 (defsubst string-to-vector (string)
2916 "Return a vector of characters in STRING."
2917 (vconcat string))
2919 (defun string-or-null-p (object)
2920 "Return t if OBJECT is a string or nil.
2921 Otherwise, return nil."
2922 (or (stringp object) (null object)))
2924 (defun booleanp (object)
2925 "Return t if OBJECT is one of the two canonical boolean values: t or nil.
2926 Otherwise, return nil."
2927 (and (memq object '(nil t)) t))
2929 (defun special-form-p (object)
2930 "Non-nil if and only if OBJECT is a special form."
2931 (if (and (symbolp object) (fboundp object))
2932 (setq object (indirect-function object)))
2933 (and (subrp object) (eq (cdr (subr-arity object)) 'unevalled)))
2935 (defun macrop (object)
2936 "Non-nil if and only if OBJECT is a macro."
2937 (let ((def (indirect-function object)))
2938 (when (consp def)
2939 (or (eq 'macro (car def))
2940 (and (autoloadp def) (memq (nth 4 def) '(macro t)))))))
2942 (defun field-at-pos (pos)
2943 "Return the field at position POS, taking stickiness etc into account."
2944 (let ((raw-field (get-char-property (field-beginning pos) 'field)))
2945 (if (eq raw-field 'boundary)
2946 (get-char-property (1- (field-end pos)) 'field)
2947 raw-field)))
2949 (defun sha1 (object &optional start end binary)
2950 "Return the SHA1 (Secure Hash Algorithm) of an OBJECT.
2951 OBJECT is either a string or a buffer. Optional arguments START and
2952 END are character positions specifying which portion of OBJECT for
2953 computing the hash. If BINARY is non-nil, return a string in binary
2954 form."
2955 (secure-hash 'sha1 object start end binary))
2957 (defun function-get (f prop &optional autoload)
2958 "Return the value of property PROP of function F.
2959 If AUTOLOAD is non-nil and F is autoloaded, try to autoload it
2960 in the hope that it will set PROP. If AUTOLOAD is `macro', only do it
2961 if it's an autoloaded macro."
2962 (let ((val nil))
2963 (while (and (symbolp f)
2964 (null (setq val (get f prop)))
2965 (fboundp f))
2966 (let ((fundef (symbol-function f)))
2967 (if (and autoload (autoloadp fundef)
2968 (not (equal fundef
2969 (autoload-do-load fundef f
2970 (if (eq autoload 'macro)
2971 'macro)))))
2972 nil ;Re-try `get' on the same `f'.
2973 (setq f fundef))))
2974 val))
2976 ;;;; Support for yanking and text properties.
2977 ;; Why here in subr.el rather than in simple.el? --Stef
2979 (defvar yank-handled-properties)
2980 (defvar yank-excluded-properties)
2982 (defun remove-yank-excluded-properties (start end)
2983 "Process text properties between START and END, inserted for a `yank'.
2984 Perform the handling specified by `yank-handled-properties', then
2985 remove properties specified by `yank-excluded-properties'."
2986 (let ((inhibit-read-only t))
2987 (dolist (handler yank-handled-properties)
2988 (let ((prop (car handler))
2989 (fun (cdr handler))
2990 (run-start start))
2991 (while (< run-start end)
2992 (let ((value (get-text-property run-start prop))
2993 (run-end (next-single-property-change
2994 run-start prop nil end)))
2995 (funcall fun value run-start run-end)
2996 (setq run-start run-end)))))
2997 (if (eq yank-excluded-properties t)
2998 (set-text-properties start end nil)
2999 (remove-list-of-text-properties start end yank-excluded-properties))))
3001 (defvar yank-undo-function)
3003 (defun insert-for-yank (string)
3004 "Insert STRING at point for the `yank' command.
3006 This function is like `insert', except it honors the variables
3007 `yank-handled-properties' and `yank-excluded-properties', and the
3008 `yank-handler' text property, in the way that `yank' does."
3009 (let (to)
3010 (while (setq to (next-single-property-change 0 'yank-handler string))
3011 (insert-for-yank-1 (substring string 0 to))
3012 (setq string (substring string to))))
3013 (insert-for-yank-1 string))
3015 (defun insert-for-yank-1 (string)
3016 "Helper for `insert-for-yank', which see."
3017 (let* ((handler (and (stringp string)
3018 (get-text-property 0 'yank-handler string)))
3019 (param (or (nth 1 handler) string))
3020 (opoint (point))
3021 (inhibit-read-only inhibit-read-only)
3022 end)
3024 (setq yank-undo-function t)
3025 (if (nth 0 handler) ; FUNCTION
3026 (funcall (car handler) param)
3027 (insert param))
3028 (setq end (point))
3030 ;; Prevent read-only properties from interfering with the
3031 ;; following text property changes.
3032 (setq inhibit-read-only t)
3034 (unless (nth 2 handler) ; NOEXCLUDE
3035 (remove-yank-excluded-properties opoint end))
3037 ;; If last inserted char has properties, mark them as rear-nonsticky.
3038 (if (and (> end opoint)
3039 (text-properties-at (1- end)))
3040 (put-text-property (1- end) end 'rear-nonsticky t))
3042 (if (eq yank-undo-function t) ; not set by FUNCTION
3043 (setq yank-undo-function (nth 3 handler))) ; UNDO
3044 (if (nth 4 handler) ; COMMAND
3045 (setq this-command (nth 4 handler)))))
3047 (defun insert-buffer-substring-no-properties (buffer &optional start end)
3048 "Insert before point a substring of BUFFER, without text properties.
3049 BUFFER may be a buffer or a buffer name.
3050 Arguments START and END are character positions specifying the substring.
3051 They default to the values of (point-min) and (point-max) in BUFFER."
3052 (let ((opoint (point)))
3053 (insert-buffer-substring buffer start end)
3054 (let ((inhibit-read-only t))
3055 (set-text-properties opoint (point) nil))))
3057 (defun insert-buffer-substring-as-yank (buffer &optional start end)
3058 "Insert before point a part of BUFFER, stripping some text properties.
3059 BUFFER may be a buffer or a buffer name.
3060 Arguments START and END are character positions specifying the substring.
3061 They default to the values of (point-min) and (point-max) in BUFFER.
3062 Before insertion, process text properties according to
3063 `yank-handled-properties' and `yank-excluded-properties'."
3064 ;; Since the buffer text should not normally have yank-handler properties,
3065 ;; there is no need to handle them here.
3066 (let ((opoint (point)))
3067 (insert-buffer-substring buffer start end)
3068 (remove-yank-excluded-properties opoint (point))))
3070 (defun yank-handle-font-lock-face-property (face start end)
3071 "If `font-lock-defaults' is nil, apply FACE as a `face' property.
3072 START and END denote the start and end of the text to act on.
3073 Do nothing if FACE is nil."
3074 (and face
3075 (null font-lock-defaults)
3076 (put-text-property start end 'face face)))
3078 ;; This removes `mouse-face' properties in *Help* buffer buttons:
3079 ;; https://lists.gnu.org/r/emacs-devel/2002-04/msg00648.html
3080 (defun yank-handle-category-property (category start end)
3081 "Apply property category CATEGORY's properties between START and END."
3082 (when category
3083 (let ((start2 start))
3084 (while (< start2 end)
3085 (let ((end2 (next-property-change start2 nil end))
3086 (original (text-properties-at start2)))
3087 (set-text-properties start2 end2 (symbol-plist category))
3088 (add-text-properties start2 end2 original)
3089 (setq start2 end2))))))
3092 ;;;; Synchronous shell commands.
3094 (defun start-process-shell-command (name buffer &rest args)
3095 "Start a program in a subprocess. Return the process object for it.
3096 NAME is name for process. It is modified if necessary to make it unique.
3097 BUFFER is the buffer (or buffer name) to associate with the process.
3098 Process output goes at end of that buffer, unless you specify
3099 an output stream or filter function to handle the output.
3100 BUFFER may be also nil, meaning that this process is not associated
3101 with any buffer
3102 COMMAND is the shell command to run.
3104 An old calling convention accepted any number of arguments after COMMAND,
3105 which were just concatenated to COMMAND. This is still supported but strongly
3106 discouraged."
3107 (declare (advertised-calling-convention (name buffer command) "23.1"))
3108 ;; We used to use `exec' to replace the shell with the command,
3109 ;; but that failed to handle (...) and semicolon, etc.
3110 (start-process name buffer shell-file-name shell-command-switch
3111 (mapconcat 'identity args " ")))
3113 (defun start-file-process-shell-command (name buffer &rest args)
3114 "Start a program in a subprocess. Return the process object for it.
3115 Similar to `start-process-shell-command', but calls `start-file-process'."
3116 (declare (advertised-calling-convention (name buffer command) "23.1"))
3117 (start-file-process
3118 name buffer
3119 (if (file-remote-p default-directory) "/bin/sh" shell-file-name)
3120 (if (file-remote-p default-directory) "-c" shell-command-switch)
3121 (mapconcat 'identity args " ")))
3123 (defun call-process-shell-command (command &optional infile buffer display
3124 &rest args)
3125 "Execute the shell command COMMAND synchronously in separate process.
3126 The remaining arguments are optional.
3127 The program's input comes from file INFILE (nil means `/dev/null').
3128 Insert output in BUFFER before point; t means current buffer;
3129 nil for BUFFER means discard it; 0 means discard and don't wait.
3130 BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,
3131 REAL-BUFFER says what to do with standard output, as above,
3132 while STDERR-FILE says what to do with standard error in the child.
3133 STDERR-FILE may be nil (discard standard error output),
3134 t (mix it with ordinary output), or a file name string.
3136 Fourth arg DISPLAY non-nil means redisplay buffer as output is inserted.
3137 Wildcards and redirection are handled as usual in the shell.
3139 If BUFFER is 0, `call-process-shell-command' returns immediately with value nil.
3140 Otherwise it waits for COMMAND to terminate and returns a numeric exit
3141 status or a signal description string.
3142 If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.
3144 An old calling convention accepted any number of arguments after DISPLAY,
3145 which were just concatenated to COMMAND. This is still supported but strongly
3146 discouraged."
3147 (declare (advertised-calling-convention
3148 (command &optional infile buffer display) "24.5"))
3149 ;; We used to use `exec' to replace the shell with the command,
3150 ;; but that failed to handle (...) and semicolon, etc.
3151 (call-process shell-file-name
3152 infile buffer display
3153 shell-command-switch
3154 (mapconcat 'identity (cons command args) " ")))
3156 (defun process-file-shell-command (command &optional infile buffer display
3157 &rest args)
3158 "Process files synchronously in a separate process.
3159 Similar to `call-process-shell-command', but calls `process-file'."
3160 (declare (advertised-calling-convention
3161 (command &optional infile buffer display) "24.5"))
3162 (process-file
3163 (if (file-remote-p default-directory) "/bin/sh" shell-file-name)
3164 infile buffer display
3165 (if (file-remote-p default-directory) "-c" shell-command-switch)
3166 (mapconcat 'identity (cons command args) " ")))
3168 (defun call-shell-region (start end command &optional delete buffer)
3169 "Send text from START to END as input to an inferior shell running COMMAND.
3170 Delete the text if fourth arg DELETE is non-nil.
3172 Insert output in BUFFER before point; t means current buffer; nil for
3173 BUFFER means discard it; 0 means discard and don't wait; and `(:file
3174 FILE)', where FILE is a file name string, means that it should be
3175 written to that file (if the file already exists it is overwritten).
3176 BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,
3177 REAL-BUFFER says what to do with standard output, as above,
3178 while STDERR-FILE says what to do with standard error in the child.
3179 STDERR-FILE may be nil (discard standard error output),
3180 t (mix it with ordinary output), or a file name string.
3182 If BUFFER is 0, `call-shell-region' returns immediately with value nil.
3183 Otherwise it waits for COMMAND to terminate
3184 and returns a numeric exit status or a signal description string.
3185 If you quit, the process is killed with SIGINT, or SIGKILL if you quit again."
3186 (call-process-region start end
3187 shell-file-name delete buffer nil
3188 shell-command-switch command))
3190 ;;;; Lisp macros to do various things temporarily.
3192 (defmacro track-mouse (&rest body)
3193 "Evaluate BODY with mouse movement events enabled.
3194 Within a `track-mouse' form, mouse motion generates input events that
3195 you can read with `read-event'.
3196 Normally, mouse motion is ignored."
3197 (declare (debug t) (indent 0))
3198 `(internal--track-mouse (lambda () ,@body)))
3200 (defmacro with-current-buffer (buffer-or-name &rest body)
3201 "Execute the forms in BODY with BUFFER-OR-NAME temporarily current.
3202 BUFFER-OR-NAME must be a buffer or the name of an existing buffer.
3203 The value returned is the value of the last form in BODY. See
3204 also `with-temp-buffer'."
3205 (declare (indent 1) (debug t))
3206 `(save-current-buffer
3207 (set-buffer ,buffer-or-name)
3208 ,@body))
3210 (defun internal--before-with-selected-window (window)
3211 (let ((other-frame (window-frame window)))
3212 (list window (selected-window)
3213 ;; Selecting a window on another frame also changes that
3214 ;; frame's frame-selected-window. We must save&restore it.
3215 (unless (eq (selected-frame) other-frame)
3216 (frame-selected-window other-frame))
3217 ;; Also remember the top-frame if on ttys.
3218 (unless (eq (selected-frame) other-frame)
3219 (tty-top-frame other-frame)))))
3221 (defun internal--after-with-selected-window (state)
3222 ;; First reset frame-selected-window.
3223 (when (window-live-p (nth 2 state))
3224 ;; We don't use set-frame-selected-window because it does not
3225 ;; pass the `norecord' argument to Fselect_window.
3226 (select-window (nth 2 state) 'norecord)
3227 (and (frame-live-p (nth 3 state))
3228 (not (eq (tty-top-frame) (nth 3 state)))
3229 (select-frame (nth 3 state) 'norecord)))
3230 ;; Then reset the actual selected-window.
3231 (when (window-live-p (nth 1 state))
3232 (select-window (nth 1 state) 'norecord)))
3234 (defmacro with-selected-window (window &rest body)
3235 "Execute the forms in BODY with WINDOW as the selected window.
3236 The value returned is the value of the last form in BODY.
3238 This macro saves and restores the selected window, as well as the
3239 selected window of each frame. It does not change the order of
3240 recently selected windows. If the previously selected window of
3241 some frame is no longer live at the end of BODY, that frame's
3242 selected window is left alone. If the selected window is no
3243 longer live, then whatever window is selected at the end of BODY
3244 remains selected.
3246 This macro uses `save-current-buffer' to save and restore the
3247 current buffer, since otherwise its normal operation could
3248 potentially make a different buffer current. It does not alter
3249 the buffer list ordering."
3250 (declare (indent 1) (debug t))
3251 `(let ((save-selected-window--state
3252 (internal--before-with-selected-window ,window)))
3253 (save-current-buffer
3254 (unwind-protect
3255 (progn (select-window (car save-selected-window--state) 'norecord)
3256 ,@body)
3257 (internal--after-with-selected-window save-selected-window--state)))))
3259 (defmacro with-selected-frame (frame &rest body)
3260 "Execute the forms in BODY with FRAME as the selected frame.
3261 The value returned is the value of the last form in BODY.
3263 This macro saves and restores the selected frame, and changes the
3264 order of neither the recently selected windows nor the buffers in
3265 the buffer list."
3266 (declare (indent 1) (debug t))
3267 (let ((old-frame (make-symbol "old-frame"))
3268 (old-buffer (make-symbol "old-buffer")))
3269 `(let ((,old-frame (selected-frame))
3270 (,old-buffer (current-buffer)))
3271 (unwind-protect
3272 (progn (select-frame ,frame 'norecord)
3273 ,@body)
3274 (when (frame-live-p ,old-frame)
3275 (select-frame ,old-frame 'norecord))
3276 (when (buffer-live-p ,old-buffer)
3277 (set-buffer ,old-buffer))))))
3279 (defmacro save-window-excursion (&rest body)
3280 "Execute BODY, then restore previous window configuration.
3281 This macro saves the window configuration on the selected frame,
3282 executes BODY, then calls `set-window-configuration' to restore
3283 the saved window configuration. The return value is the last
3284 form in BODY. The window configuration is also restored if BODY
3285 exits nonlocally.
3287 BEWARE: Most uses of this macro introduce bugs.
3288 E.g. it should not be used to try and prevent some code from opening
3289 a new window, since that window may sometimes appear in another frame,
3290 in which case `save-window-excursion' cannot help."
3291 (declare (indent 0) (debug t))
3292 (let ((c (make-symbol "wconfig")))
3293 `(let ((,c (current-window-configuration)))
3294 (unwind-protect (progn ,@body)
3295 (set-window-configuration ,c)))))
3297 (defun internal-temp-output-buffer-show (buffer)
3298 "Internal function for `with-output-to-temp-buffer'."
3299 (with-current-buffer buffer
3300 (set-buffer-modified-p nil)
3301 (goto-char (point-min)))
3303 (if temp-buffer-show-function
3304 (funcall temp-buffer-show-function buffer)
3305 (with-current-buffer buffer
3306 (let* ((window
3307 (let ((window-combination-limit
3308 ;; When `window-combination-limit' equals
3309 ;; `temp-buffer' or `temp-buffer-resize' and
3310 ;; `temp-buffer-resize-mode' is enabled in this
3311 ;; buffer bind it to t so resizing steals space
3312 ;; preferably from the window that was split.
3313 (if (or (eq window-combination-limit 'temp-buffer)
3314 (and (eq window-combination-limit
3315 'temp-buffer-resize)
3316 temp-buffer-resize-mode))
3318 window-combination-limit)))
3319 (display-buffer buffer)))
3320 (frame (and window (window-frame window))))
3321 (when window
3322 (unless (eq frame (selected-frame))
3323 (make-frame-visible frame))
3324 (setq minibuffer-scroll-window window)
3325 (set-window-hscroll window 0)
3326 ;; Don't try this with NOFORCE non-nil!
3327 (set-window-start window (point-min) t)
3328 ;; This should not be necessary.
3329 (set-window-point window (point-min))
3330 ;; Run `temp-buffer-show-hook', with the chosen window selected.
3331 (with-selected-window window
3332 (run-hooks 'temp-buffer-show-hook))))))
3333 ;; Return nil.
3334 nil)
3336 ;; Doc is very similar to with-temp-buffer-window.
3337 (defmacro with-output-to-temp-buffer (bufname &rest body)
3338 "Bind `standard-output' to buffer BUFNAME, eval BODY, then show that buffer.
3340 This construct makes buffer BUFNAME empty before running BODY.
3341 It does not make the buffer current for BODY.
3342 Instead it binds `standard-output' to that buffer, so that output
3343 generated with `prin1' and similar functions in BODY goes into
3344 the buffer.
3346 At the end of BODY, this marks buffer BUFNAME unmodified and displays
3347 it in a window, but does not select it. The normal way to do this is
3348 by calling `display-buffer', then running `temp-buffer-show-hook'.
3349 However, if `temp-buffer-show-function' is non-nil, it calls that
3350 function instead (and does not run `temp-buffer-show-hook'). The
3351 function gets one argument, the buffer to display.
3353 The return value of `with-output-to-temp-buffer' is the value of the
3354 last form in BODY. If BODY does not finish normally, the buffer
3355 BUFNAME is not displayed.
3357 This runs the hook `temp-buffer-setup-hook' before BODY,
3358 with the buffer BUFNAME temporarily current. It runs the hook
3359 `temp-buffer-show-hook' after displaying buffer BUFNAME, with that
3360 buffer temporarily current, and the window that was used to display it
3361 temporarily selected. But it doesn't run `temp-buffer-show-hook'
3362 if it uses `temp-buffer-show-function'.
3364 By default, the setup hook puts the buffer into Help mode before running BODY.
3365 If BODY does not change the major mode, the show hook makes the buffer
3366 read-only, and scans it for function and variable names to make them into
3367 clickable cross-references.
3369 See the related form `with-temp-buffer-window'."
3370 (declare (debug t))
3371 (let ((old-dir (make-symbol "old-dir"))
3372 (buf (make-symbol "buf")))
3373 `(let* ((,old-dir default-directory)
3374 (,buf
3375 (with-current-buffer (get-buffer-create ,bufname)
3376 (prog1 (current-buffer)
3377 (kill-all-local-variables)
3378 ;; FIXME: delete_all_overlays
3379 (setq default-directory ,old-dir)
3380 (setq buffer-read-only nil)
3381 (setq buffer-file-name nil)
3382 (setq buffer-undo-list t)
3383 (let ((inhibit-read-only t)
3384 (inhibit-modification-hooks t))
3385 (erase-buffer)
3386 (run-hooks 'temp-buffer-setup-hook)))))
3387 (standard-output ,buf))
3388 (prog1 (progn ,@body)
3389 (internal-temp-output-buffer-show ,buf)))))
3391 (defmacro with-temp-file (file &rest body)
3392 "Create a new buffer, evaluate BODY there, and write the buffer to FILE.
3393 The value returned is the value of the last form in BODY.
3394 See also `with-temp-buffer'."
3395 (declare (indent 1) (debug t))
3396 (let ((temp-file (make-symbol "temp-file"))
3397 (temp-buffer (make-symbol "temp-buffer")))
3398 `(let ((,temp-file ,file)
3399 (,temp-buffer
3400 (get-buffer-create (generate-new-buffer-name " *temp file*"))))
3401 (unwind-protect
3402 (prog1
3403 (with-current-buffer ,temp-buffer
3404 ,@body)
3405 (with-current-buffer ,temp-buffer
3406 (write-region nil nil ,temp-file nil 0)))
3407 (and (buffer-name ,temp-buffer)
3408 (kill-buffer ,temp-buffer))))))
3410 (defmacro with-temp-message (message &rest body)
3411 "Display MESSAGE temporarily if non-nil while BODY is evaluated.
3412 The original message is restored to the echo area after BODY has finished.
3413 The value returned is the value of the last form in BODY.
3414 MESSAGE is written to the message log buffer if `message-log-max' is non-nil.
3415 If MESSAGE is nil, the echo area and message log buffer are unchanged.
3416 Use a MESSAGE of \"\" to temporarily clear the echo area."
3417 (declare (debug t) (indent 1))
3418 (let ((current-message (make-symbol "current-message"))
3419 (temp-message (make-symbol "with-temp-message")))
3420 `(let ((,temp-message ,message)
3421 (,current-message))
3422 (unwind-protect
3423 (progn
3424 (when ,temp-message
3425 (setq ,current-message (current-message))
3426 (message "%s" ,temp-message))
3427 ,@body)
3428 (and ,temp-message
3429 (if ,current-message
3430 (message "%s" ,current-message)
3431 (message nil)))))))
3433 (defmacro with-temp-buffer (&rest body)
3434 "Create a temporary buffer, and evaluate BODY there like `progn'.
3435 See also `with-temp-file' and `with-output-to-string'."
3436 (declare (indent 0) (debug t))
3437 (let ((temp-buffer (make-symbol "temp-buffer")))
3438 `(let ((,temp-buffer (generate-new-buffer " *temp*")))
3439 ;; FIXME: kill-buffer can change current-buffer in some odd cases.
3440 (with-current-buffer ,temp-buffer
3441 (unwind-protect
3442 (progn ,@body)
3443 (and (buffer-name ,temp-buffer)
3444 (kill-buffer ,temp-buffer)))))))
3446 (defmacro with-silent-modifications (&rest body)
3447 "Execute BODY, pretending it does not modify the buffer.
3448 This macro is typically used around modifications of
3449 text properties which do not really affect the buffer's content.
3450 If BODY performs real modifications to the buffer's text, other
3451 than cosmetic ones, undo data may become corrupted.
3453 This macro will run BODY normally, but doesn't count its buffer
3454 modifications as being buffer modifications. This affects things
3455 like `buffer-modified-p', checking whether the file is locked by
3456 someone else, running buffer modification hooks, and other things
3457 of that nature."
3458 (declare (debug t) (indent 0))
3459 (let ((modified (make-symbol "modified")))
3460 `(let* ((,modified (buffer-modified-p))
3461 (buffer-undo-list t)
3462 (inhibit-read-only t)
3463 (inhibit-modification-hooks t))
3464 (unwind-protect
3465 (progn
3466 ,@body)
3467 (unless ,modified
3468 (restore-buffer-modified-p nil))))))
3470 (defmacro with-output-to-string (&rest body)
3471 "Execute BODY, return the text it sent to `standard-output', as a string."
3472 (declare (indent 0) (debug t))
3473 `(let ((standard-output
3474 (get-buffer-create (generate-new-buffer-name " *string-output*"))))
3475 (unwind-protect
3476 (progn
3477 (let ((standard-output standard-output))
3478 ,@body)
3479 (with-current-buffer standard-output
3480 (buffer-string)))
3481 (kill-buffer standard-output))))
3483 (defmacro with-local-quit (&rest body)
3484 "Execute BODY, allowing quits to terminate BODY but not escape further.
3485 When a quit terminates BODY, `with-local-quit' returns nil but
3486 requests another quit. That quit will be processed as soon as quitting
3487 is allowed once again. (Immediately, if `inhibit-quit' is nil.)"
3488 (declare (debug t) (indent 0))
3489 `(condition-case nil
3490 (let ((inhibit-quit nil))
3491 ,@body)
3492 (quit (setq quit-flag t)
3493 ;; This call is to give a chance to handle quit-flag
3494 ;; in case inhibit-quit is nil.
3495 ;; Without this, it will not be handled until the next function
3496 ;; call, and that might allow it to exit thru a condition-case
3497 ;; that intends to handle the quit signal next time.
3498 (eval '(ignore nil)))))
3500 ;; Don't throw `throw-on-input' on those events by default.
3501 (setq while-no-input-ignore-events
3502 '(focus-in focus-out help-echo iconify-frame
3503 make-frame-visible selection-request))
3505 (defmacro while-no-input (&rest body)
3506 "Execute BODY only as long as there's no pending input.
3507 If input arrives, that ends the execution of BODY,
3508 and `while-no-input' returns t. Quitting makes it return nil.
3509 If BODY finishes, `while-no-input' returns whatever value BODY produced."
3510 (declare (debug t) (indent 0))
3511 (let ((catch-sym (make-symbol "input")))
3512 `(with-local-quit
3513 (catch ',catch-sym
3514 (let ((throw-on-input ',catch-sym))
3515 (or (input-pending-p)
3516 (progn ,@body)))))))
3518 (defmacro condition-case-unless-debug (var bodyform &rest handlers)
3519 "Like `condition-case' except that it does not prevent debugging.
3520 More specifically if `debug-on-error' is set then the debugger will be invoked
3521 even if this catches the signal."
3522 (declare (debug condition-case) (indent 2))
3523 `(condition-case ,var
3524 ,bodyform
3525 ,@(mapcar (lambda (handler)
3526 `((debug ,@(if (listp (car handler)) (car handler)
3527 (list (car handler))))
3528 ,@(cdr handler)))
3529 handlers)))
3531 (define-obsolete-function-alias 'condition-case-no-debug
3532 'condition-case-unless-debug "24.1")
3534 (defmacro with-demoted-errors (format &rest body)
3535 "Run BODY and demote any errors to simple messages.
3536 FORMAT is a string passed to `message' to format any error message.
3537 It should contain a single %-sequence; e.g., \"Error: %S\".
3539 If `debug-on-error' is non-nil, run BODY without catching its errors.
3540 This is to be used around code which is not expected to signal an error
3541 but which should be robust in the unexpected case that an error is signaled.
3543 For backward compatibility, if FORMAT is not a constant string, it
3544 is assumed to be part of BODY, in which case the message format
3545 used is \"Error: %S\"."
3546 (declare (debug t) (indent 1))
3547 (let ((err (make-symbol "err"))
3548 (format (if (and (stringp format) body) format
3549 (prog1 "Error: %S"
3550 (if format (push format body))))))
3551 `(condition-case-unless-debug ,err
3552 ,(macroexp-progn body)
3553 (error (message ,format ,err) nil))))
3555 (defmacro combine-after-change-calls (&rest body)
3556 "Execute BODY, but don't call the after-change functions till the end.
3557 If BODY makes changes in the buffer, they are recorded
3558 and the functions on `after-change-functions' are called several times
3559 when BODY is finished.
3560 The return value is the value of the last form in BODY.
3562 If `before-change-functions' is non-nil, then calls to the after-change
3563 functions can't be deferred, so in that case this macro has no effect.
3565 Do not alter `after-change-functions' or `before-change-functions'
3566 in BODY."
3567 (declare (indent 0) (debug t))
3568 `(unwind-protect
3569 (let ((combine-after-change-calls t))
3570 . ,body)
3571 (combine-after-change-execute)))
3573 (defmacro with-case-table (table &rest body)
3574 "Execute the forms in BODY with TABLE as the current case table.
3575 The value returned is the value of the last form in BODY."
3576 (declare (indent 1) (debug t))
3577 (let ((old-case-table (make-symbol "table"))
3578 (old-buffer (make-symbol "buffer")))
3579 `(let ((,old-case-table (current-case-table))
3580 (,old-buffer (current-buffer)))
3581 (unwind-protect
3582 (progn (set-case-table ,table)
3583 ,@body)
3584 (with-current-buffer ,old-buffer
3585 (set-case-table ,old-case-table))))))
3587 (defmacro with-file-modes (modes &rest body)
3588 "Execute BODY with default file permissions temporarily set to MODES.
3589 MODES is as for `set-default-file-modes'."
3590 (declare (indent 1) (debug t))
3591 (let ((umask (make-symbol "umask")))
3592 `(let ((,umask (default-file-modes)))
3593 (unwind-protect
3594 (progn
3595 (set-default-file-modes ,modes)
3596 ,@body)
3597 (set-default-file-modes ,umask)))))
3600 ;;; Matching and match data.
3602 (defvar save-match-data-internal)
3604 ;; We use save-match-data-internal as the local variable because
3605 ;; that works ok in practice (people should not use that variable elsewhere).
3606 ;; We used to use an uninterned symbol; the compiler handles that properly
3607 ;; now, but it generates slower code.
3608 (defmacro save-match-data (&rest body)
3609 "Execute the BODY forms, restoring the global value of the match data.
3610 The value returned is the value of the last form in BODY."
3611 ;; It is better not to use backquote here,
3612 ;; because that makes a bootstrapping problem
3613 ;; if you need to recompile all the Lisp files using interpreted code.
3614 (declare (indent 0) (debug t))
3615 (list 'let
3616 '((save-match-data-internal (match-data)))
3617 (list 'unwind-protect
3618 (cons 'progn body)
3619 ;; It is safe to free (evaporate) markers immediately here,
3620 ;; as Lisp programs should not copy from save-match-data-internal.
3621 '(set-match-data save-match-data-internal 'evaporate))))
3623 (defun match-string (num &optional string)
3624 "Return string of text matched by last search.
3625 NUM specifies which parenthesized expression in the last regexp.
3626 Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
3627 Zero means the entire text matched by the whole regexp or whole string.
3628 STRING should be given if the last search was by `string-match' on STRING.
3629 If STRING is nil, the current buffer should be the same buffer
3630 the search/match was performed in."
3631 (if (match-beginning num)
3632 (if string
3633 (substring string (match-beginning num) (match-end num))
3634 (buffer-substring (match-beginning num) (match-end num)))))
3636 (defun match-string-no-properties (num &optional string)
3637 "Return string of text matched by last search, without text properties.
3638 NUM specifies which parenthesized expression in the last regexp.
3639 Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
3640 Zero means the entire text matched by the whole regexp or whole string.
3641 STRING should be given if the last search was by `string-match' on STRING.
3642 If STRING is nil, the current buffer should be the same buffer
3643 the search/match was performed in."
3644 (if (match-beginning num)
3645 (if string
3646 (substring-no-properties string (match-beginning num)
3647 (match-end num))
3648 (buffer-substring-no-properties (match-beginning num)
3649 (match-end num)))))
3652 (defun match-substitute-replacement (replacement
3653 &optional fixedcase literal string subexp)
3654 "Return REPLACEMENT as it will be inserted by `replace-match'.
3655 In other words, all back-references in the form `\\&' and `\\N'
3656 are substituted with actual strings matched by the last search.
3657 Optional FIXEDCASE, LITERAL, STRING and SUBEXP have the same
3658 meaning as for `replace-match'."
3659 (let ((match (match-string 0 string)))
3660 (save-match-data
3661 (set-match-data (mapcar (lambda (x)
3662 (if (numberp x)
3663 (- x (match-beginning 0))
3665 (match-data t)))
3666 (replace-match replacement fixedcase literal match subexp))))
3669 (defun looking-back (regexp &optional limit greedy)
3670 "Return non-nil if text before point matches regular expression REGEXP.
3671 Like `looking-at' except matches before point, and is slower.
3672 LIMIT if non-nil speeds up the search by specifying a minimum
3673 starting position, to avoid checking matches that would start
3674 before LIMIT.
3676 If GREEDY is non-nil, extend the match backwards as far as
3677 possible, stopping when a single additional previous character
3678 cannot be part of a match for REGEXP. When the match is
3679 extended, its starting position is allowed to occur before
3680 LIMIT.
3682 As a general recommendation, try to avoid using `looking-back'
3683 wherever possible, since it is slow."
3684 (declare
3685 (advertised-calling-convention (regexp limit &optional greedy) "25.1"))
3686 (let ((start (point))
3687 (pos
3688 (save-excursion
3689 (and (re-search-backward (concat "\\(?:" regexp "\\)\\=") limit t)
3690 (point)))))
3691 (if (and greedy pos)
3692 (save-restriction
3693 (narrow-to-region (point-min) start)
3694 (while (and (> pos (point-min))
3695 (save-excursion
3696 (goto-char pos)
3697 (backward-char 1)
3698 (looking-at (concat "\\(?:" regexp "\\)\\'"))))
3699 (setq pos (1- pos)))
3700 (save-excursion
3701 (goto-char pos)
3702 (looking-at (concat "\\(?:" regexp "\\)\\'")))))
3703 (not (null pos))))
3705 (defsubst looking-at-p (regexp)
3707 Same as `looking-at' except this function does not change the match data."
3708 (let ((inhibit-changing-match-data t))
3709 (looking-at regexp)))
3711 (defsubst string-match-p (regexp string &optional start)
3713 Same as `string-match' except this function does not change the match data."
3714 (let ((inhibit-changing-match-data t))
3715 (string-match regexp string start)))
3717 (defun subregexp-context-p (regexp pos &optional start)
3718 "Return non-nil if POS is in a normal subregexp context in REGEXP.
3719 A subregexp context is one where a sub-regexp can appear.
3720 A non-subregexp context is for example within brackets, or within a
3721 repetition bounds operator `\\=\\{...\\}', or right after a `\\'.
3722 If START is non-nil, it should be a position in REGEXP, smaller
3723 than POS, and known to be in a subregexp context."
3724 ;; Here's one possible implementation, with the great benefit that it
3725 ;; reuses the regexp-matcher's own parser, so it understands all the
3726 ;; details of the syntax. A disadvantage is that it needs to match the
3727 ;; error string.
3728 (condition-case err
3729 (progn
3730 (string-match (substring regexp (or start 0) pos) "")
3732 (invalid-regexp
3733 (not (member (cadr err) '("Unmatched [ or [^"
3734 "Unmatched \\{"
3735 "Trailing backslash")))))
3736 ;; An alternative implementation:
3737 ;; (defconst re-context-re
3738 ;; (let* ((harmless-ch "[^\\[]")
3739 ;; (harmless-esc "\\\\[^{]")
3740 ;; (class-harmless-ch "[^][]")
3741 ;; (class-lb-harmless "[^]:]")
3742 ;; (class-lb-colon-maybe-charclass ":\\([a-z]+:]\\)?")
3743 ;; (class-lb (concat "\\[\\(" class-lb-harmless
3744 ;; "\\|" class-lb-colon-maybe-charclass "\\)"))
3745 ;; (class
3746 ;; (concat "\\[^?]?"
3747 ;; "\\(" class-harmless-ch
3748 ;; "\\|" class-lb "\\)*"
3749 ;; "\\[?]")) ; special handling for bare [ at end of re
3750 ;; (braces "\\\\{[0-9,]+\\\\}"))
3751 ;; (concat "\\`\\(" harmless-ch "\\|" harmless-esc
3752 ;; "\\|" class "\\|" braces "\\)*\\'"))
3753 ;; "Matches any prefix that corresponds to a normal subregexp context.")
3754 ;; (string-match re-context-re (substring regexp (or start 0) pos))
3757 ;;;; split-string
3759 (defconst split-string-default-separators "[ \f\t\n\r\v]+"
3760 "The default value of separators for `split-string'.
3762 A regexp matching strings of whitespace. May be locale-dependent
3763 \(as yet unimplemented). Should not match non-breaking spaces.
3765 Warning: binding this to a different value and using it as default is
3766 likely to have undesired semantics.")
3768 ;; The specification says that if both SEPARATORS and OMIT-NULLS are
3769 ;; defaulted, OMIT-NULLS should be treated as t. Simplifying the logical
3770 ;; expression leads to the equivalent implementation that if SEPARATORS
3771 ;; is defaulted, OMIT-NULLS is treated as t.
3772 (defun split-string (string &optional separators omit-nulls trim)
3773 "Split STRING into substrings bounded by matches for SEPARATORS.
3775 The beginning and end of STRING, and each match for SEPARATORS, are
3776 splitting points. The substrings matching SEPARATORS are removed, and
3777 the substrings between the splitting points are collected as a list,
3778 which is returned.
3780 If SEPARATORS is non-nil, it should be a regular expression matching text
3781 which separates, but is not part of, the substrings. If nil it defaults to
3782 `split-string-default-separators', normally \"[ \\f\\t\\n\\r\\v]+\", and
3783 OMIT-NULLS is forced to t.
3785 If OMIT-NULLS is t, zero-length substrings are omitted from the list (so
3786 that for the default value of SEPARATORS leading and trailing whitespace
3787 are effectively trimmed). If nil, all zero-length substrings are retained,
3788 which correctly parses CSV format, for example.
3790 If TRIM is non-nil, it should be a regular expression to match
3791 text to trim from the beginning and end of each substring. If trimming
3792 makes the substring empty, it is treated as null.
3794 If you want to trim whitespace from the substrings, the reliably correct
3795 way is using TRIM. Making SEPARATORS match that whitespace gives incorrect
3796 results when there is whitespace at the start or end of STRING. If you
3797 see such calls to `split-string', please fix them.
3799 Note that the effect of `(split-string STRING)' is the same as
3800 `(split-string STRING split-string-default-separators t)'. In the rare
3801 case that you wish to retain zero-length substrings when splitting on
3802 whitespace, use `(split-string STRING split-string-default-separators)'.
3804 Modifies the match data; use `save-match-data' if necessary."
3805 (let* ((keep-nulls (not (if separators omit-nulls t)))
3806 (rexp (or separators split-string-default-separators))
3807 (start 0)
3808 this-start this-end
3809 notfirst
3810 (list nil)
3811 (push-one
3812 ;; Push the substring in range THIS-START to THIS-END
3813 ;; onto LIST, trimming it and perhaps discarding it.
3814 (lambda ()
3815 (when trim
3816 ;; Discard the trim from start of this substring.
3817 (let ((tem (string-match trim string this-start)))
3818 (and (eq tem this-start)
3819 (setq this-start (match-end 0)))))
3821 (when (or keep-nulls (< this-start this-end))
3822 (let ((this (substring string this-start this-end)))
3824 ;; Discard the trim from end of this substring.
3825 (when trim
3826 (let ((tem (string-match (concat trim "\\'") this 0)))
3827 (and tem (< tem (length this))
3828 (setq this (substring this 0 tem)))))
3830 ;; Trimming could make it empty; check again.
3831 (when (or keep-nulls (> (length this) 0))
3832 (push this list)))))))
3834 (while (and (string-match rexp string
3835 (if (and notfirst
3836 (= start (match-beginning 0))
3837 (< start (length string)))
3838 (1+ start) start))
3839 (< start (length string)))
3840 (setq notfirst t)
3841 (setq this-start start this-end (match-beginning 0)
3842 start (match-end 0))
3844 (funcall push-one))
3846 ;; Handle the substring at the end of STRING.
3847 (setq this-start start this-end (length string))
3848 (funcall push-one)
3850 (nreverse list)))
3852 (defun combine-and-quote-strings (strings &optional separator)
3853 "Concatenate the STRINGS, adding the SEPARATOR (default \" \").
3854 This tries to quote the strings to avoid ambiguity such that
3855 (split-string-and-unquote (combine-and-quote-strings strs)) == strs
3856 Only some SEPARATORs will work properly.
3858 Note that this is not intended to protect STRINGS from
3859 interpretation by shells, use `shell-quote-argument' for that."
3860 (let* ((sep (or separator " "))
3861 (re (concat "[\\\"]" "\\|" (regexp-quote sep))))
3862 (mapconcat
3863 (lambda (str)
3864 (if (string-match re str)
3865 (concat "\"" (replace-regexp-in-string "[\\\"]" "\\\\\\&" str) "\"")
3866 str))
3867 strings sep)))
3869 (defun split-string-and-unquote (string &optional separator)
3870 "Split the STRING into a list of strings.
3871 It understands Emacs Lisp quoting within STRING, such that
3872 (split-string-and-unquote (combine-and-quote-strings strs)) == strs
3873 The SEPARATOR regexp defaults to \"\\s-+\"."
3874 (let ((sep (or separator "\\s-+"))
3875 (i (string-match "\"" string)))
3876 (if (null i)
3877 (split-string string sep t) ; no quoting: easy
3878 (append (unless (eq i 0) (split-string (substring string 0 i) sep t))
3879 (let ((rfs (read-from-string string i)))
3880 (cons (car rfs)
3881 (split-string-and-unquote (substring string (cdr rfs))
3882 sep)))))))
3885 ;;;; Replacement in strings.
3887 (defun subst-char-in-string (fromchar tochar string &optional inplace)
3888 "Replace FROMCHAR with TOCHAR in STRING each time it occurs.
3889 Unless optional argument INPLACE is non-nil, return a new string."
3890 (let ((i (length string))
3891 (newstr (if inplace string (copy-sequence string))))
3892 (while (> i 0)
3893 (setq i (1- i))
3894 (if (eq (aref newstr i) fromchar)
3895 (aset newstr i tochar)))
3896 newstr))
3898 (defun replace-regexp-in-string (regexp rep string &optional
3899 fixedcase literal subexp start)
3900 "Replace all matches for REGEXP with REP in STRING.
3902 Return a new string containing the replacements.
3904 Optional arguments FIXEDCASE, LITERAL and SUBEXP are like the
3905 arguments with the same names of function `replace-match'. If START
3906 is non-nil, start replacements at that index in STRING.
3908 REP is either a string used as the NEWTEXT arg of `replace-match' or a
3909 function. If it is a function, it is called with the actual text of each
3910 match, and its value is used as the replacement text. When REP is called,
3911 the match data are the result of matching REGEXP against a substring
3912 of STRING, the same substring that is the actual text of the match which
3913 is passed to REP as its argument.
3915 To replace only the first match (if any), make REGEXP match up to \\\\='
3916 and replace a sub-expression, e.g.
3917 (replace-regexp-in-string \"\\\\(foo\\\\).*\\\\\\='\" \"bar\" \" foo foo\" nil nil 1)
3918 => \" bar foo\""
3920 ;; To avoid excessive consing from multiple matches in long strings,
3921 ;; don't just call `replace-match' continually. Walk down the
3922 ;; string looking for matches of REGEXP and building up a (reversed)
3923 ;; list MATCHES. This comprises segments of STRING which weren't
3924 ;; matched interspersed with replacements for segments that were.
3925 ;; [For a `large' number of replacements it's more efficient to
3926 ;; operate in a temporary buffer; we can't tell from the function's
3927 ;; args whether to choose the buffer-based implementation, though it
3928 ;; might be reasonable to do so for long enough STRING.]
3929 (let ((l (length string))
3930 (start (or start 0))
3931 matches str mb me)
3932 (save-match-data
3933 (while (and (< start l) (string-match regexp string start))
3934 (setq mb (match-beginning 0)
3935 me (match-end 0))
3936 ;; If we matched the empty string, make sure we advance by one char
3937 (when (= me mb) (setq me (min l (1+ mb))))
3938 ;; Generate a replacement for the matched substring.
3939 ;; Operate only on the substring to minimize string consing.
3940 ;; Set up match data for the substring for replacement;
3941 ;; presumably this is likely to be faster than munging the
3942 ;; match data directly in Lisp.
3943 (string-match regexp (setq str (substring string mb me)))
3944 (setq matches
3945 (cons (replace-match (if (stringp rep)
3947 (funcall rep (match-string 0 str)))
3948 fixedcase literal str subexp)
3949 (cons (substring string start mb) ; unmatched prefix
3950 matches)))
3951 (setq start me))
3952 ;; Reconstruct a string from the pieces.
3953 (setq matches (cons (substring string start l) matches)) ; leftover
3954 (apply #'concat (nreverse matches)))))
3956 (defun string-prefix-p (prefix string &optional ignore-case)
3957 "Return non-nil if PREFIX is a prefix of STRING.
3958 If IGNORE-CASE is non-nil, the comparison is done without paying attention
3959 to case differences."
3960 (let ((prefix-length (length prefix)))
3961 (if (> prefix-length (length string)) nil
3962 (eq t (compare-strings prefix 0 prefix-length string
3963 0 prefix-length ignore-case)))))
3965 (defun string-suffix-p (suffix string &optional ignore-case)
3966 "Return non-nil if SUFFIX is a suffix of STRING.
3967 If IGNORE-CASE is non-nil, the comparison is done without paying
3968 attention to case differences."
3969 (let ((start-pos (- (length string) (length suffix))))
3970 (and (>= start-pos 0)
3971 (eq t (compare-strings suffix nil nil
3972 string start-pos nil ignore-case)))))
3974 (defun bidi-string-mark-left-to-right (str)
3975 "Return a string that can be safely inserted in left-to-right text.
3977 Normally, inserting a string with right-to-left (RTL) script into
3978 a buffer may cause some subsequent text to be displayed as part
3979 of the RTL segment (usually this affects punctuation characters).
3980 This function returns a string which displays as STR but forces
3981 subsequent text to be displayed as left-to-right.
3983 If STR contains any RTL character, this function returns a string
3984 consisting of STR followed by an invisible left-to-right mark
3985 \(LRM) character. Otherwise, it returns STR."
3986 (unless (stringp str)
3987 (signal 'wrong-type-argument (list 'stringp str)))
3988 (if (string-match "\\cR" str)
3989 (concat str (propertize (string ?\x200e) 'invisible t))
3990 str))
3992 (defun string-greaterp (string1 string2)
3993 "Return non-nil if STRING1 is greater than STRING2 in lexicographic order.
3994 Case is significant.
3995 Symbols are also allowed; their print names are used instead."
3996 (string-lessp string2 string1))
3999 ;;;; Specifying things to do later.
4001 (defun load-history-regexp (file)
4002 "Form a regexp to find FILE in `load-history'.
4003 FILE, a string, is described in the function `eval-after-load'."
4004 (if (file-name-absolute-p file)
4005 (setq file (file-truename file)))
4006 (concat (if (file-name-absolute-p file) "\\`" "\\(\\`\\|/\\)")
4007 (regexp-quote file)
4008 (if (file-name-extension file)
4010 ;; Note: regexp-opt can't be used here, since we need to call
4011 ;; this before Emacs has been fully started. 2006-05-21
4012 (concat "\\(" (mapconcat 'regexp-quote load-suffixes "\\|") "\\)?"))
4013 "\\(" (mapconcat 'regexp-quote jka-compr-load-suffixes "\\|")
4014 "\\)?\\'"))
4016 (defun load-history-filename-element (file-regexp)
4017 "Get the first elt of `load-history' whose car matches FILE-REGEXP.
4018 Return nil if there isn't one."
4019 (let* ((loads load-history)
4020 (load-elt (and loads (car loads))))
4021 (save-match-data
4022 (while (and loads
4023 (or (null (car load-elt))
4024 (not (string-match file-regexp (car load-elt)))))
4025 (setq loads (cdr loads)
4026 load-elt (and loads (car loads)))))
4027 load-elt))
4029 (put 'eval-after-load 'lisp-indent-function 1)
4030 (defun eval-after-load (file form)
4031 "Arrange that if FILE is loaded, FORM will be run immediately afterwards.
4032 If FILE is already loaded, evaluate FORM right now.
4033 FORM can be an Elisp expression (in which case it's passed to `eval'),
4034 or a function (in which case it's passed to `funcall' with no argument).
4036 If a matching file is loaded again, FORM will be evaluated again.
4038 If FILE is a string, it may be either an absolute or a relative file
4039 name, and may have an extension (e.g. \".el\") or may lack one, and
4040 additionally may or may not have an extension denoting a compressed
4041 format (e.g. \".gz\").
4043 When FILE is absolute, this first converts it to a true name by chasing
4044 symbolic links. Only a file of this name (see next paragraph regarding
4045 extensions) will trigger the evaluation of FORM. When FILE is relative,
4046 a file whose absolute true name ends in FILE will trigger evaluation.
4048 When FILE lacks an extension, a file name with any extension will trigger
4049 evaluation. Otherwise, its extension must match FILE's. A further
4050 extension for a compressed format (e.g. \".gz\") on FILE will not affect
4051 this name matching.
4053 Alternatively, FILE can be a feature (i.e. a symbol), in which case FORM
4054 is evaluated at the end of any file that `provide's this feature.
4055 If the feature is provided when evaluating code not associated with a
4056 file, FORM is evaluated immediately after the provide statement.
4058 Usually FILE is just a library name like \"font-lock\" or a feature name
4059 like `font-lock'.
4061 This function makes or adds to an entry on `after-load-alist'."
4062 (declare (compiler-macro
4063 (lambda (whole)
4064 (if (eq 'quote (car-safe form))
4065 ;; Quote with lambda so the compiler can look inside.
4066 `(eval-after-load ,file (lambda () ,(nth 1 form)))
4067 whole))))
4068 ;; Add this FORM into after-load-alist (regardless of whether we'll be
4069 ;; evaluating it now).
4070 (let* ((regexp-or-feature
4071 (if (stringp file)
4072 (setq file (purecopy (load-history-regexp file)))
4073 file))
4074 (elt (assoc regexp-or-feature after-load-alist))
4075 (func
4076 (if (functionp form) form
4077 ;; Try to use the "current" lexical/dynamic mode for `form'.
4078 (eval `(lambda () ,form) lexical-binding))))
4079 (unless elt
4080 (setq elt (list regexp-or-feature))
4081 (push elt after-load-alist))
4082 ;; Is there an already loaded file whose name (or `provide' name)
4083 ;; matches FILE?
4084 (prog1 (if (if (stringp file)
4085 (load-history-filename-element regexp-or-feature)
4086 (featurep file))
4087 (funcall func))
4088 (let ((delayed-func
4089 (if (not (symbolp regexp-or-feature)) func
4090 ;; For features, the after-load-alist elements get run when
4091 ;; `provide' is called rather than at the end of the file.
4092 ;; So add an indirection to make sure that `func' is really run
4093 ;; "after-load" in case the provide call happens early.
4094 (lambda ()
4095 (if (not load-file-name)
4096 ;; Not being provided from a file, run func right now.
4097 (funcall func)
4098 (let ((lfn load-file-name)
4099 ;; Don't use letrec, because equal (in
4100 ;; add/remove-hook) would get trapped in a cycle.
4101 (fun (make-symbol "eval-after-load-helper")))
4102 (fset fun (lambda (file)
4103 (when (equal file lfn)
4104 (remove-hook 'after-load-functions fun)
4105 (funcall func))))
4106 (add-hook 'after-load-functions fun 'append)))))))
4107 ;; Add FORM to the element unless it's already there.
4108 (unless (member delayed-func (cdr elt))
4109 (nconc elt (list delayed-func)))))))
4111 (defmacro with-eval-after-load (file &rest body)
4112 "Execute BODY after FILE is loaded.
4113 FILE is normally a feature name, but it can also be a file name,
4114 in case that file does not provide any feature. See `eval-after-load'
4115 for more details about the different forms of FILE and their semantics."
4116 (declare (indent 1) (debug t))
4117 `(eval-after-load ,file (lambda () ,@body)))
4119 (defvar after-load-functions nil
4120 "Special hook run after loading a file.
4121 Each function there is called with a single argument, the absolute
4122 name of the file just loaded.")
4124 (defun do-after-load-evaluation (abs-file)
4125 "Evaluate all `eval-after-load' forms, if any, for ABS-FILE.
4126 ABS-FILE, a string, should be the absolute true name of a file just loaded.
4127 This function is called directly from the C code."
4128 ;; Run the relevant eval-after-load forms.
4129 (dolist (a-l-element after-load-alist)
4130 (when (and (stringp (car a-l-element))
4131 (string-match-p (car a-l-element) abs-file))
4132 ;; discard the file name regexp
4133 (mapc #'funcall (cdr a-l-element))))
4134 ;; Complain when the user uses obsolete files.
4135 (when (string-match-p "/obsolete/\\([^/]*\\)\\'" abs-file)
4136 ;; Maybe we should just use display-warning? This seems yucky...
4137 (let* ((file (file-name-nondirectory abs-file))
4138 (msg (format "Package %s is obsolete!"
4139 (substring file 0
4140 (string-match "\\.elc?\\>" file)))))
4141 ;; Cribbed from cl--compiling-file.
4142 (if (and (boundp 'byte-compile--outbuffer)
4143 (bufferp (symbol-value 'byte-compile--outbuffer))
4144 (equal (buffer-name (symbol-value 'byte-compile--outbuffer))
4145 " *Compiler Output*"))
4146 ;; Don't warn about obsolete files using other obsolete files.
4147 (unless (and (stringp byte-compile-current-file)
4148 (string-match-p "/obsolete/[^/]*\\'"
4149 (expand-file-name
4150 byte-compile-current-file
4151 byte-compile-root-dir)))
4152 (byte-compile-warn "%s" msg))
4153 (run-with-timer 0 nil
4154 (lambda (msg)
4155 (message "%s" msg))
4156 msg))))
4158 ;; Finally, run any other hook.
4159 (run-hook-with-args 'after-load-functions abs-file))
4161 (defun eval-next-after-load (file)
4162 "Read the following input sexp, and run it whenever FILE is loaded.
4163 This makes or adds to an entry on `after-load-alist'.
4164 FILE should be the name of a library, with no directory name."
4165 (declare (obsolete eval-after-load "23.2"))
4166 (eval-after-load file (read)))
4169 (defun display-delayed-warnings ()
4170 "Display delayed warnings from `delayed-warnings-list'.
4171 Used from `delayed-warnings-hook' (which see)."
4172 (dolist (warning (nreverse delayed-warnings-list))
4173 (apply 'display-warning warning))
4174 (setq delayed-warnings-list nil))
4176 (defun collapse-delayed-warnings ()
4177 "Remove duplicates from `delayed-warnings-list'.
4178 Collapse identical adjacent warnings into one (plus count).
4179 Used from `delayed-warnings-hook' (which see)."
4180 (let ((count 1)
4181 collapsed warning)
4182 (while delayed-warnings-list
4183 (setq warning (pop delayed-warnings-list))
4184 (if (equal warning (car delayed-warnings-list))
4185 (setq count (1+ count))
4186 (when (> count 1)
4187 (setcdr warning (cons (format "%s [%d times]" (cadr warning) count)
4188 (cddr warning)))
4189 (setq count 1))
4190 (push warning collapsed)))
4191 (setq delayed-warnings-list (nreverse collapsed))))
4193 ;; At present this is only used for Emacs internals.
4194 ;; Ref https://lists.gnu.org/r/emacs-devel/2012-02/msg00085.html
4195 (defvar delayed-warnings-hook '(collapse-delayed-warnings
4196 display-delayed-warnings)
4197 "Normal hook run to process and display delayed warnings.
4198 By default, this hook contains functions to consolidate the
4199 warnings listed in `delayed-warnings-list', display them, and set
4200 `delayed-warnings-list' back to nil.")
4202 (defun delay-warning (type message &optional level buffer-name)
4203 "Display a delayed warning.
4204 Aside from going through `delayed-warnings-list', this is equivalent
4205 to `display-warning'."
4206 (push (list type message level buffer-name) delayed-warnings-list))
4209 ;;;; invisibility specs
4211 (defun add-to-invisibility-spec (element)
4212 "Add ELEMENT to `buffer-invisibility-spec'.
4213 See documentation for `buffer-invisibility-spec' for the kind of elements
4214 that can be added."
4215 (if (eq buffer-invisibility-spec t)
4216 (setq buffer-invisibility-spec (list t)))
4217 (setq buffer-invisibility-spec
4218 (cons element buffer-invisibility-spec)))
4220 (defun remove-from-invisibility-spec (element)
4221 "Remove ELEMENT from `buffer-invisibility-spec'."
4222 (setq buffer-invisibility-spec
4223 (if (consp buffer-invisibility-spec)
4224 (delete element buffer-invisibility-spec)
4225 (list t))))
4227 ;;;; Syntax tables.
4229 (defmacro with-syntax-table (table &rest body)
4230 "Evaluate BODY with syntax table of current buffer set to TABLE.
4231 The syntax table of the current buffer is saved, BODY is evaluated, and the
4232 saved table is restored, even in case of an abnormal exit.
4233 Value is what BODY returns."
4234 (declare (debug t) (indent 1))
4235 (let ((old-table (make-symbol "table"))
4236 (old-buffer (make-symbol "buffer")))
4237 `(let ((,old-table (syntax-table))
4238 (,old-buffer (current-buffer)))
4239 (unwind-protect
4240 (progn
4241 (set-syntax-table ,table)
4242 ,@body)
4243 (save-current-buffer
4244 (set-buffer ,old-buffer)
4245 (set-syntax-table ,old-table))))))
4247 (defun make-syntax-table (&optional oldtable)
4248 "Return a new syntax table.
4249 Create a syntax table which inherits from OLDTABLE (if non-nil) or
4250 from `standard-syntax-table' otherwise."
4251 (let ((table (make-char-table 'syntax-table nil)))
4252 (set-char-table-parent table (or oldtable (standard-syntax-table)))
4253 table))
4255 (defun syntax-after (pos)
4256 "Return the raw syntax descriptor for the char after POS.
4257 If POS is outside the buffer's accessible portion, return nil."
4258 (unless (or (< pos (point-min)) (>= pos (point-max)))
4259 (let ((st (if parse-sexp-lookup-properties
4260 (get-char-property pos 'syntax-table))))
4261 (if (consp st) st
4262 (aref (or st (syntax-table)) (char-after pos))))))
4264 (defun syntax-class (syntax)
4265 "Return the code for the syntax class described by SYNTAX.
4267 SYNTAX should be a raw syntax descriptor; the return value is a
4268 integer which encodes the corresponding syntax class. See Info
4269 node `(elisp)Syntax Table Internals' for a list of codes.
4271 If SYNTAX is nil, return nil."
4272 (and syntax (logand (car syntax) 65535)))
4274 ;; Utility motion commands
4276 (defvar word-move-empty-char-table nil
4277 "Used in `forward-word-strictly' and `backward-word-strictly'
4278 to countermand the effect of `find-word-boundary-function-table'.")
4280 (defun forward-word-strictly (&optional arg)
4281 "Move point forward ARG words (backward if ARG is negative).
4282 If ARG is omitted or nil, move point forward one word.
4283 Normally returns t.
4284 If an edge of the buffer or a field boundary is reached, point is left there
4285 and the function returns nil. Field boundaries are not noticed if
4286 `inhibit-field-text-motion' is non-nil.
4288 This function is like `forward-word', but it is not affected
4289 by `find-word-boundary-function-table'. It is also not interactive."
4290 (let ((find-word-boundary-function-table
4291 (if (char-table-p word-move-empty-char-table)
4292 word-move-empty-char-table
4293 (setq word-move-empty-char-table (make-char-table nil)))))
4294 (forward-word (or arg 1))))
4296 (defun backward-word-strictly (&optional arg)
4297 "Move backward until encountering the beginning of a word.
4298 With argument ARG, do this that many times.
4299 If ARG is omitted or nil, move point backward one word.
4301 This function is like `forward-word', but it is not affected
4302 by `find-word-boundary-function-table'. It is also not interactive."
4303 (let ((find-word-boundary-function-table
4304 (if (char-table-p word-move-empty-char-table)
4305 word-move-empty-char-table
4306 (setq word-move-empty-char-table (make-char-table nil)))))
4307 (forward-word (- (or arg 1)))))
4309 ;; Whitespace
4311 (defun forward-whitespace (arg)
4312 "Move point to the end of the next sequence of whitespace chars.
4313 Each such sequence may be a single newline, or a sequence of
4314 consecutive space and/or tab characters.
4315 With prefix argument ARG, do it ARG times if positive, or move
4316 backwards ARG times if negative."
4317 (interactive "^p")
4318 (if (natnump arg)
4319 (re-search-forward "[ \t]+\\|\n" nil 'move arg)
4320 (while (< arg 0)
4321 (if (re-search-backward "[ \t]+\\|\n" nil 'move)
4322 (or (eq (char-after (match-beginning 0)) ?\n)
4323 (skip-chars-backward " \t")))
4324 (setq arg (1+ arg)))))
4326 ;; Symbols
4328 (defun forward-symbol (arg)
4329 "Move point to the next position that is the end of a symbol.
4330 A symbol is any sequence of characters that are in either the
4331 word constituent or symbol constituent syntax class.
4332 With prefix argument ARG, do it ARG times if positive, or move
4333 backwards ARG times if negative."
4334 (interactive "^p")
4335 (if (natnump arg)
4336 (re-search-forward "\\(\\sw\\|\\s_\\)+" nil 'move arg)
4337 (while (< arg 0)
4338 (if (re-search-backward "\\(\\sw\\|\\s_\\)+" nil 'move)
4339 (skip-syntax-backward "w_"))
4340 (setq arg (1+ arg)))))
4342 ;; Syntax blocks
4344 (defun forward-same-syntax (&optional arg)
4345 "Move point past all characters with the same syntax class.
4346 With prefix argument ARG, do it ARG times if positive, or move
4347 backwards ARG times if negative."
4348 (interactive "^p")
4349 (or arg (setq arg 1))
4350 (while (< arg 0)
4351 (skip-syntax-backward
4352 (char-to-string (char-syntax (char-before))))
4353 (setq arg (1+ arg)))
4354 (while (> arg 0)
4355 (skip-syntax-forward (char-to-string (char-syntax (char-after))))
4356 (setq arg (1- arg))))
4359 ;;;; Text clones
4361 (defvar text-clone--maintaining nil)
4363 (defun text-clone--maintain (ol1 after beg end &optional _len)
4364 "Propagate the changes made under the overlay OL1 to the other clones.
4365 This is used on the `modification-hooks' property of text clones."
4366 (when (and after (not undo-in-progress)
4367 (not text-clone--maintaining)
4368 (overlay-start ol1))
4369 (let ((margin (if (overlay-get ol1 'text-clone-spreadp) 1 0)))
4370 (setq beg (max beg (+ (overlay-start ol1) margin)))
4371 (setq end (min end (- (overlay-end ol1) margin)))
4372 (when (<= beg end)
4373 (save-excursion
4374 (when (overlay-get ol1 'text-clone-syntax)
4375 ;; Check content of the clone's text.
4376 (let ((cbeg (+ (overlay-start ol1) margin))
4377 (cend (- (overlay-end ol1) margin)))
4378 (goto-char cbeg)
4379 (save-match-data
4380 (if (not (re-search-forward
4381 (overlay-get ol1 'text-clone-syntax) cend t))
4382 ;; Mark the overlay for deletion.
4383 (setq end cbeg)
4384 (when (< (match-end 0) cend)
4385 ;; Shrink the clone at its end.
4386 (setq end (min end (match-end 0)))
4387 (move-overlay ol1 (overlay-start ol1)
4388 (+ (match-end 0) margin)))
4389 (when (> (match-beginning 0) cbeg)
4390 ;; Shrink the clone at its beginning.
4391 (setq beg (max (match-beginning 0) beg))
4392 (move-overlay ol1 (- (match-beginning 0) margin)
4393 (overlay-end ol1)))))))
4394 ;; Now go ahead and update the clones.
4395 (let ((head (- beg (overlay-start ol1)))
4396 (tail (- (overlay-end ol1) end))
4397 (str (buffer-substring beg end))
4398 (nothing-left t)
4399 (text-clone--maintaining t))
4400 (dolist (ol2 (overlay-get ol1 'text-clones))
4401 (let ((oe (overlay-end ol2)))
4402 (unless (or (eq ol1 ol2) (null oe))
4403 (setq nothing-left nil)
4404 (let ((mod-beg (+ (overlay-start ol2) head)))
4405 ;;(overlay-put ol2 'modification-hooks nil)
4406 (goto-char (- (overlay-end ol2) tail))
4407 (unless (> mod-beg (point))
4408 (save-excursion (insert str))
4409 (delete-region mod-beg (point)))
4410 ;;(overlay-put ol2 'modification-hooks '(text-clone--maintain))
4411 ))))
4412 (if nothing-left (delete-overlay ol1))))))))
4414 (defun text-clone-create (start end &optional spreadp syntax)
4415 "Create a text clone of START...END at point.
4416 Text clones are chunks of text that are automatically kept identical:
4417 changes done to one of the clones will be immediately propagated to the other.
4419 The buffer's content at point is assumed to be already identical to
4420 the one between START and END.
4421 If SYNTAX is provided it's a regexp that describes the possible text of
4422 the clones; the clone will be shrunk or killed if necessary to ensure that
4423 its text matches the regexp.
4424 If SPREADP is non-nil it indicates that text inserted before/after the
4425 clone should be incorporated in the clone."
4426 ;; To deal with SPREADP we can either use an overlay with `nil t' along
4427 ;; with insert-(behind|in-front-of)-hooks or use a slightly larger overlay
4428 ;; (with a one-char margin at each end) with `t nil'.
4429 ;; We opted for a larger overlay because it behaves better in the case
4430 ;; where the clone is reduced to the empty string (we want the overlay to
4431 ;; stay when the clone's content is the empty string and we want to use
4432 ;; `evaporate' to make sure those overlays get deleted when needed).
4434 (let* ((pt-end (+ (point) (- end start)))
4435 (start-margin (if (or (not spreadp) (bobp) (<= start (point-min)))
4436 0 1))
4437 (end-margin (if (or (not spreadp)
4438 (>= pt-end (point-max))
4439 (>= start (point-max)))
4440 0 1))
4441 ;; FIXME: Reuse overlays at point to extend dups!
4442 (ol1 (make-overlay (- start start-margin) (+ end end-margin) nil t))
4443 (ol2 (make-overlay (- (point) start-margin) (+ pt-end end-margin) nil t))
4444 (dups (list ol1 ol2)))
4445 (overlay-put ol1 'modification-hooks '(text-clone--maintain))
4446 (when spreadp (overlay-put ol1 'text-clone-spreadp t))
4447 (when syntax (overlay-put ol1 'text-clone-syntax syntax))
4448 ;;(overlay-put ol1 'face 'underline)
4449 (overlay-put ol1 'evaporate t)
4450 (overlay-put ol1 'text-clones dups)
4452 (overlay-put ol2 'modification-hooks '(text-clone--maintain))
4453 (when spreadp (overlay-put ol2 'text-clone-spreadp t))
4454 (when syntax (overlay-put ol2 'text-clone-syntax syntax))
4455 ;;(overlay-put ol2 'face 'underline)
4456 (overlay-put ol2 'evaporate t)
4457 (overlay-put ol2 'text-clones dups)))
4459 ;;;; Mail user agents.
4461 ;; Here we include just enough for other packages to be able
4462 ;; to define them.
4464 (defun define-mail-user-agent (symbol composefunc sendfunc
4465 &optional abortfunc hookvar)
4466 "Define a symbol to identify a mail-sending package for `mail-user-agent'.
4468 SYMBOL can be any Lisp symbol. Its function definition and/or
4469 value as a variable do not matter for this usage; we use only certain
4470 properties on its property list, to encode the rest of the arguments.
4472 COMPOSEFUNC is program callable function that composes an outgoing
4473 mail message buffer. This function should set up the basics of the
4474 buffer without requiring user interaction. It should populate the
4475 standard mail headers, leaving the `to:' and `subject:' headers blank
4476 by default.
4478 COMPOSEFUNC should accept several optional arguments--the same
4479 arguments that `compose-mail' takes. See that function's documentation.
4481 SENDFUNC is the command a user would run to send the message.
4483 Optional ABORTFUNC is the command a user would run to abort the
4484 message. For mail packages that don't have a separate abort function,
4485 this can be `kill-buffer' (the equivalent of omitting this argument).
4487 Optional HOOKVAR is a hook variable that gets run before the message
4488 is actually sent. Callers that use the `mail-user-agent' may
4489 install a hook function temporarily on this hook variable.
4490 If HOOKVAR is nil, `mail-send-hook' is used.
4492 The properties used on SYMBOL are `composefunc', `sendfunc',
4493 `abortfunc', and `hookvar'."
4494 (put symbol 'composefunc composefunc)
4495 (put symbol 'sendfunc sendfunc)
4496 (put symbol 'abortfunc (or abortfunc 'kill-buffer))
4497 (put symbol 'hookvar (or hookvar 'mail-send-hook)))
4500 (defun backtrace--print-frame (evald func args flags)
4501 "Print a trace of a single stack frame to `standard-output'.
4502 EVALD, FUNC, ARGS, FLAGS are as in `mapbacktrace'."
4503 (princ (if (plist-get flags :debug-on-exit) "* " " "))
4504 (cond
4505 ((and evald (not debugger-stack-frame-as-list))
4506 (cl-prin1 func)
4507 (if args (cl-prin1 args) (princ "()")))
4509 (cl-prin1 (cons func args))))
4510 (princ "\n"))
4512 (defun backtrace ()
4513 "Print a trace of Lisp function calls currently active.
4514 Output stream used is value of `standard-output'."
4515 (let ((print-level (or print-level 8))
4516 (print-escape-control-characters t))
4517 (mapbacktrace #'backtrace--print-frame 'backtrace)))
4519 (defun backtrace-frames (&optional base)
4520 "Collect all frames of current backtrace into a list.
4521 If non-nil, BASE should be a function, and frames before its
4522 nearest activation frames are discarded."
4523 (let ((frames nil))
4524 (mapbacktrace (lambda (&rest frame) (push frame frames))
4525 (or base 'backtrace-frames))
4526 (nreverse frames)))
4528 (defun backtrace-frame (nframes &optional base)
4529 "Return the function and arguments NFRAMES up from current execution point.
4530 If non-nil, BASE should be a function, and NFRAMES counts from its
4531 nearest activation frame.
4532 If the frame has not evaluated the arguments yet (or is a special form),
4533 the value is (nil FUNCTION ARG-FORMS...).
4534 If the frame has evaluated its arguments and called its function already,
4535 the value is (t FUNCTION ARG-VALUES...).
4536 A &rest arg is represented as the tail of the list ARG-VALUES.
4537 FUNCTION is whatever was supplied as car of evaluated list,
4538 or a lambda expression for macro calls.
4539 If NFRAMES is more than the number of frames, the value is nil."
4540 (backtrace-frame--internal
4541 (lambda (evald func args _) `(,evald ,func ,@args))
4542 nframes (or base 'backtrace-frame)))
4545 (defvar called-interactively-p-functions nil
4546 "Special hook called to skip special frames in `called-interactively-p'.
4547 The functions are called with 3 arguments: (I FRAME1 FRAME2),
4548 where FRAME1 is a \"current frame\", FRAME2 is the next frame,
4549 I is the index of the frame after FRAME2. It should return nil
4550 if those frames don't seem special and otherwise, it should return
4551 the number of frames to skip (minus 1).")
4553 (defconst internal--funcall-interactively
4554 (symbol-function 'funcall-interactively))
4556 (defun called-interactively-p (&optional kind)
4557 "Return t if the containing function was called by `call-interactively'.
4558 If KIND is `interactive', then only return t if the call was made
4559 interactively by the user, i.e. not in `noninteractive' mode nor
4560 when `executing-kbd-macro'.
4561 If KIND is `any', on the other hand, it will return t for any kind of
4562 interactive call, including being called as the binding of a key or
4563 from a keyboard macro, even in `noninteractive' mode.
4565 This function is very brittle, it may fail to return the intended result when
4566 the code is debugged, advised, or instrumented in some form. Some macros and
4567 special forms (such as `condition-case') may also sometimes wrap their bodies
4568 in a `lambda', so any call to `called-interactively-p' from those bodies will
4569 indicate whether that lambda (rather than the surrounding function) was called
4570 interactively.
4572 Instead of using this function, it is cleaner and more reliable to give your
4573 function an extra optional argument whose `interactive' spec specifies
4574 non-nil unconditionally (\"p\" is a good way to do this), or via
4575 \(not (or executing-kbd-macro noninteractive)).
4577 The only known proper use of `interactive' for KIND is in deciding
4578 whether to display a helpful message, or how to display it. If you're
4579 thinking of using it for any other purpose, it is quite likely that
4580 you're making a mistake. Think: what do you want to do when the
4581 command is called from a keyboard macro?"
4582 (declare (advertised-calling-convention (kind) "23.1"))
4583 (when (not (and (eq kind 'interactive)
4584 (or executing-kbd-macro noninteractive)))
4585 (let* ((i 1) ;; 0 is the called-interactively-p frame.
4586 frame nextframe
4587 (get-next-frame
4588 (lambda ()
4589 (setq frame nextframe)
4590 (setq nextframe (backtrace-frame i 'called-interactively-p))
4591 ;; (message "Frame %d = %S" i nextframe)
4592 (setq i (1+ i)))))
4593 (funcall get-next-frame) ;; Get the first frame.
4594 (while
4595 ;; FIXME: The edebug and advice handling should be made modular and
4596 ;; provided directly by edebug.el and nadvice.el.
4597 (progn
4598 ;; frame =(backtrace-frame i-2)
4599 ;; nextframe=(backtrace-frame i-1)
4600 (funcall get-next-frame)
4601 ;; `pcase' would be a fairly good fit here, but it sometimes moves
4602 ;; branches within local functions, which then messes up the
4603 ;; `backtrace-frame' data we get,
4605 ;; Skip special forms (from non-compiled code).
4606 (and frame (null (car frame)))
4607 ;; Skip also `interactive-p' (because we don't want to know if
4608 ;; interactive-p was called interactively but if it's caller was)
4609 ;; and `byte-code' (idem; this appears in subexpressions of things
4610 ;; like condition-case, which are wrapped in a separate bytecode
4611 ;; chunk).
4612 ;; FIXME: For lexical-binding code, this is much worse,
4613 ;; because the frames look like "byte-code -> funcall -> #[...]",
4614 ;; which is not a reliable signature.
4615 (memq (nth 1 frame) '(interactive-p 'byte-code))
4616 ;; Skip package-specific stack-frames.
4617 (let ((skip (run-hook-with-args-until-success
4618 'called-interactively-p-functions
4619 i frame nextframe)))
4620 (pcase skip
4621 (`nil nil)
4622 (`0 t)
4623 (_ (setq i (+ i skip -1)) (funcall get-next-frame)))))))
4624 ;; Now `frame' should be "the function from which we were called".
4625 (pcase (cons frame nextframe)
4626 ;; No subr calls `interactive-p', so we can rule that out.
4627 (`((,_ ,(pred (lambda (f) (subrp (indirect-function f)))) . ,_) . ,_) nil)
4628 ;; In case #<subr funcall-interactively> without going through the
4629 ;; `funcall-interactively' symbol (bug#3984).
4630 (`(,_ . (t ,(pred (lambda (f)
4631 (eq internal--funcall-interactively
4632 (indirect-function f))))
4633 . ,_))
4634 t)))))
4636 (defun interactive-p ()
4637 "Return t if the containing function was run directly by user input.
4638 This means that the function was called with `call-interactively'
4639 \(which includes being called as the binding of a key)
4640 and input is currently coming from the keyboard (not a keyboard macro),
4641 and Emacs is not running in batch mode (`noninteractive' is nil).
4643 The only known proper use of `interactive-p' is in deciding whether to
4644 display a helpful message, or how to display it. If you're thinking
4645 of using it for any other purpose, it is quite likely that you're
4646 making a mistake. Think: what do you want to do when the command is
4647 called from a keyboard macro or in batch mode?
4649 To test whether your function was called with `call-interactively',
4650 either (i) add an extra optional argument and give it an `interactive'
4651 spec that specifies non-nil unconditionally (such as \"p\"); or (ii)
4652 use `called-interactively-p'.
4654 To test whether a function can be called interactively, use
4655 `commandp'."
4656 (declare (obsolete called-interactively-p "23.2"))
4657 (called-interactively-p 'interactive))
4659 (defun internal-push-keymap (keymap symbol)
4660 (let ((map (symbol-value symbol)))
4661 (unless (memq keymap map)
4662 (unless (memq 'add-keymap-witness (symbol-value symbol))
4663 (setq map (make-composed-keymap nil (symbol-value symbol)))
4664 (push 'add-keymap-witness (cdr map))
4665 (set symbol map))
4666 (push keymap (cdr map)))))
4668 (defun internal-pop-keymap (keymap symbol)
4669 (let ((map (symbol-value symbol)))
4670 (when (memq keymap map)
4671 (setf (cdr map) (delq keymap (cdr map))))
4672 (let ((tail (cddr map)))
4673 (and (or (null tail) (keymapp tail))
4674 (eq 'add-keymap-witness (nth 1 map))
4675 (set symbol tail)))))
4677 (define-obsolete-function-alias
4678 'set-temporary-overlay-map 'set-transient-map "24.4")
4680 (defun set-transient-map (map &optional keep-pred on-exit)
4681 "Set MAP as a temporary keymap taking precedence over other keymaps.
4682 Normally, MAP is used only once, to look up the very next key.
4683 However, if the optional argument KEEP-PRED is t, MAP stays
4684 active if a key from MAP is used. KEEP-PRED can also be a
4685 function of no arguments: it is called from `pre-command-hook' and
4686 if it returns non-nil, then MAP stays active.
4688 Optional arg ON-EXIT, if non-nil, specifies a function that is
4689 called, with no arguments, after MAP is deactivated.
4691 This uses `overriding-terminal-local-map' which takes precedence over all other
4692 keymaps. As usual, if no match for a key is found in MAP, the normal key
4693 lookup sequence then continues.
4695 This returns an \"exit function\", which can be called with no argument
4696 to deactivate this transient map, regardless of KEEP-PRED."
4697 (let* ((clearfun (make-symbol "clear-transient-map"))
4698 (exitfun
4699 (lambda ()
4700 (internal-pop-keymap map 'overriding-terminal-local-map)
4701 (remove-hook 'pre-command-hook clearfun)
4702 (when on-exit (funcall on-exit)))))
4703 ;; Don't use letrec, because equal (in add/remove-hook) would get trapped
4704 ;; in a cycle.
4705 (fset clearfun
4706 (lambda ()
4707 (with-demoted-errors "set-transient-map PCH: %S"
4708 (unless (cond
4709 ((null keep-pred) nil)
4710 ((and (not (eq map (cadr overriding-terminal-local-map)))
4711 (memq map (cddr overriding-terminal-local-map)))
4712 ;; There's presumably some other transient-map in
4713 ;; effect. Wait for that one to terminate before we
4714 ;; remove ourselves.
4715 ;; For example, if isearch and C-u both use transient
4716 ;; maps, then the lifetime of the C-u should be nested
4717 ;; within isearch's, so the pre-command-hook of
4718 ;; isearch should be suspended during the C-u one so
4719 ;; we don't exit isearch just because we hit 1 after
4720 ;; C-u and that 1 exits isearch whereas it doesn't
4721 ;; exit C-u.
4723 ((eq t keep-pred)
4724 (let ((mc (lookup-key map (this-command-keys-vector))))
4725 ;; If the key is unbound `this-command` is
4726 ;; nil and so is `mc`.
4727 (and mc (eq this-command mc))))
4728 (t (funcall keep-pred)))
4729 (funcall exitfun)))))
4730 (add-hook 'pre-command-hook clearfun)
4731 (internal-push-keymap map 'overriding-terminal-local-map)
4732 exitfun))
4734 ;;;; Progress reporters.
4736 ;; Progress reporter has the following structure:
4738 ;; (NEXT-UPDATE-VALUE . [NEXT-UPDATE-TIME
4739 ;; MIN-VALUE
4740 ;; MAX-VALUE
4741 ;; MESSAGE
4742 ;; MIN-CHANGE
4743 ;; MIN-TIME])
4745 ;; This weirdness is for optimization reasons: we want
4746 ;; `progress-reporter-update' to be as fast as possible, so
4747 ;; `(car reporter)' is better than `(aref reporter 0)'.
4749 ;; NEXT-UPDATE-TIME is a float. While `float-time' loses a couple
4750 ;; digits of precision, it doesn't really matter here. On the other
4751 ;; hand, it greatly simplifies the code.
4753 (defsubst progress-reporter-update (reporter &optional value)
4754 "Report progress of an operation in the echo area.
4755 REPORTER should be the result of a call to `make-progress-reporter'.
4757 If REPORTER is a numerical progress reporter---i.e. if it was
4758 made using non-nil MIN-VALUE and MAX-VALUE arguments to
4759 `make-progress-reporter'---then VALUE should be a number between
4760 MIN-VALUE and MAX-VALUE.
4762 If REPORTER is a non-numerical reporter, VALUE should be nil.
4764 This function is relatively inexpensive. If the change since
4765 last update is too small or insufficient time has passed, it does
4766 nothing."
4767 (when (or (not (numberp value)) ; For pulsing reporter
4768 (>= value (car reporter))) ; For numerical reporter
4769 (progress-reporter-do-update reporter value)))
4771 (defun make-progress-reporter (message &optional min-value max-value
4772 current-value min-change min-time)
4773 "Return progress reporter object for use with `progress-reporter-update'.
4775 MESSAGE is shown in the echo area, with a status indicator
4776 appended to the end. When you call `progress-reporter-done', the
4777 word \"done\" is printed after the MESSAGE. You can change the
4778 MESSAGE of an existing progress reporter by calling
4779 `progress-reporter-force-update'.
4781 MIN-VALUE and MAX-VALUE, if non-nil, are starting (0% complete)
4782 and final (100% complete) states of operation; the latter should
4783 be larger. In this case, the status message shows the percentage
4784 progress.
4786 If MIN-VALUE and/or MAX-VALUE is omitted or nil, the status
4787 message shows a \"spinning\", non-numeric indicator.
4789 Optional CURRENT-VALUE is the initial progress; the default is
4790 MIN-VALUE.
4791 Optional MIN-CHANGE is the minimal change in percents to report;
4792 the default is 1%.
4793 CURRENT-VALUE and MIN-CHANGE do not have any effect if MIN-VALUE
4794 and/or MAX-VALUE are nil.
4796 Optional MIN-TIME specifies the minimum interval time between
4797 echo area updates (default is 0.2 seconds.) If the OS is not
4798 capable of measuring fractions of seconds, this parameter is
4799 effectively rounded up."
4800 (when (string-match "[[:alnum:]]\\'" message)
4801 (setq message (concat message "...")))
4802 (unless min-time
4803 (setq min-time 0.2))
4804 (let ((reporter
4805 ;; Force a call to `message' now
4806 (cons (or min-value 0)
4807 (vector (if (>= min-time 0.02)
4808 (float-time) nil)
4809 min-value
4810 max-value
4811 message
4812 (if min-change (max (min min-change 50) 1) 1)
4813 min-time))))
4814 (progress-reporter-update reporter (or current-value min-value))
4815 reporter))
4817 (defun progress-reporter-force-update (reporter &optional value new-message)
4818 "Report progress of an operation in the echo area unconditionally.
4820 The first two arguments are the same as in `progress-reporter-update'.
4821 NEW-MESSAGE, if non-nil, sets a new message for the reporter."
4822 (let ((parameters (cdr reporter)))
4823 (when new-message
4824 (aset parameters 3 new-message))
4825 (when (aref parameters 0)
4826 (aset parameters 0 (float-time)))
4827 (progress-reporter-do-update reporter value)))
4829 (defvar progress-reporter--pulse-characters ["-" "\\" "|" "/"]
4830 "Characters to use for pulsing progress reporters.")
4832 (defun progress-reporter-do-update (reporter value)
4833 (let* ((parameters (cdr reporter))
4834 (update-time (aref parameters 0))
4835 (min-value (aref parameters 1))
4836 (max-value (aref parameters 2))
4837 (text (aref parameters 3))
4838 (enough-time-passed
4839 ;; See if enough time has passed since the last update.
4840 (or (not update-time)
4841 (when (>= (float-time) update-time)
4842 ;; Calculate time for the next update
4843 (aset parameters 0 (+ update-time (aref parameters 5)))))))
4844 (cond ((and min-value max-value)
4845 ;; Numerical indicator
4846 (let* ((one-percent (/ (- max-value min-value) 100.0))
4847 (percentage (if (= max-value min-value)
4849 (truncate (/ (- value min-value)
4850 one-percent)))))
4851 ;; Calculate NEXT-UPDATE-VALUE. If we are not printing
4852 ;; message because not enough time has passed, use 1
4853 ;; instead of MIN-CHANGE. This makes delays between echo
4854 ;; area updates closer to MIN-TIME.
4855 (setcar reporter
4856 (min (+ min-value (* (+ percentage
4857 (if enough-time-passed
4858 ;; MIN-CHANGE
4859 (aref parameters 4)
4861 one-percent))
4862 max-value))
4863 (when (integerp value)
4864 (setcar reporter (ceiling (car reporter))))
4865 ;; Only print message if enough time has passed
4866 (when enough-time-passed
4867 (if (> percentage 0)
4868 (message "%s%d%%" text percentage)
4869 (message "%s" text)))))
4870 ;; Pulsing indicator
4871 (enough-time-passed
4872 (let ((index (mod (1+ (car reporter)) 4))
4873 (message-log-max nil))
4874 (setcar reporter index)
4875 (message "%s %s"
4876 text
4877 (aref progress-reporter--pulse-characters
4878 index)))))))
4880 (defun progress-reporter-done (reporter)
4881 "Print reporter's message followed by word \"done\" in echo area."
4882 (message "%sdone" (aref (cdr reporter) 3)))
4884 (defmacro dotimes-with-progress-reporter (spec message &rest body)
4885 "Loop a certain number of times and report progress in the echo area.
4886 Evaluate BODY with VAR bound to successive integers running from
4887 0, inclusive, to COUNT, exclusive. Then evaluate RESULT to get
4888 the return value (nil if RESULT is omitted).
4890 At each iteration MESSAGE followed by progress percentage is
4891 printed in the echo area. After the loop is finished, MESSAGE
4892 followed by word \"done\" is printed. This macro is a
4893 convenience wrapper around `make-progress-reporter' and friends.
4895 \(fn (VAR COUNT [RESULT]) MESSAGE BODY...)"
4896 (declare (indent 2) (debug ((symbolp form &optional form) form body)))
4897 (let ((temp (make-symbol "--dotimes-temp--"))
4898 (temp2 (make-symbol "--dotimes-temp2--"))
4899 (start 0)
4900 (end (nth 1 spec)))
4901 `(let ((,temp ,end)
4902 (,(car spec) ,start)
4903 (,temp2 (make-progress-reporter ,message ,start ,end)))
4904 (while (< ,(car spec) ,temp)
4905 ,@body
4906 (progress-reporter-update ,temp2
4907 (setq ,(car spec) (1+ ,(car spec)))))
4908 (progress-reporter-done ,temp2)
4909 nil ,@(cdr (cdr spec)))))
4912 ;;;; Comparing version strings.
4914 (defconst version-separator "."
4915 "Specify the string used to separate the version elements.
4917 Usually the separator is \".\", but it can be any other string.")
4920 (defconst version-regexp-alist
4921 '(("^[-._+ ]?snapshot$" . -4)
4922 ;; treat "1.2.3-20050920" and "1.2-3" as snapshot releases
4923 ("^[-._+]$" . -4)
4924 ;; treat "1.2.3-CVS" as snapshot release
4925 ("^[-._+ ]?\\(cvs\\|git\\|bzr\\|svn\\|hg\\|darcs\\)$" . -4)
4926 ("^[-._+ ]?alpha$" . -3)
4927 ("^[-._+ ]?beta$" . -2)
4928 ("^[-._+ ]?\\(pre\\|rc\\)$" . -1))
4929 "Specify association between non-numeric version and its priority.
4931 This association is used to handle version string like \"1.0pre2\",
4932 \"0.9alpha1\", etc. It's used by `version-to-list' (which see) to convert the
4933 non-numeric part of a version string to an integer. For example:
4935 String Version Integer List Version
4936 \"0.9snapshot\" (0 9 -4)
4937 \"1.0-git\" (1 0 -4)
4938 \"1.0.cvs\" (1 0 -4)
4939 \"1.0pre2\" (1 0 -1 2)
4940 \"1.0PRE2\" (1 0 -1 2)
4941 \"22.8beta3\" (22 8 -2 3)
4942 \"22.8 Beta3\" (22 8 -2 3)
4943 \"0.9alpha1\" (0 9 -3 1)
4944 \"0.9AlphA1\" (0 9 -3 1)
4945 \"0.9 alpha\" (0 9 -3)
4947 Each element has the following form:
4949 (REGEXP . PRIORITY)
4951 Where:
4953 REGEXP regexp used to match non-numeric part of a version string.
4954 It should begin with the `^' anchor and end with a `$' to
4955 prevent false hits. Letter-case is ignored while matching
4956 REGEXP.
4958 PRIORITY a negative integer specifying non-numeric priority of REGEXP.")
4961 (defun version-to-list (ver)
4962 "Convert version string VER into a list of integers.
4964 The version syntax is given by the following EBNF:
4966 VERSION ::= NUMBER ( SEPARATOR NUMBER )*.
4968 NUMBER ::= (0|1|2|3|4|5|6|7|8|9)+.
4970 SEPARATOR ::= `version-separator' (which see)
4971 | `version-regexp-alist' (which see).
4973 The NUMBER part is optional if SEPARATOR is a match for an element
4974 in `version-regexp-alist'.
4976 Examples of valid version syntax:
4978 1.0pre2 1.0.7.5 22.8beta3 0.9alpha1 6.9.30Beta 2.4.snapshot .5
4980 Examples of invalid version syntax:
4982 1.0prepre2 1.0..7.5 22.8X3 alpha3.2
4984 Examples of version conversion:
4986 Version String Version as a List of Integers
4987 \".5\" (0 5)
4988 \"0.9 alpha\" (0 9 -3)
4989 \"0.9AlphA1\" (0 9 -3 1)
4990 \"0.9snapshot\" (0 9 -4)
4991 \"1.0-git\" (1 0 -4)
4992 \"1.0.7.5\" (1 0 7 5)
4993 \"1.0.cvs\" (1 0 -4)
4994 \"1.0PRE2\" (1 0 -1 2)
4995 \"1.0pre2\" (1 0 -1 2)
4996 \"22.8 Beta3\" (22 8 -2 3)
4997 \"22.8beta3\" (22 8 -2 3)
4999 See documentation for `version-separator' and `version-regexp-alist'."
5000 (unless (stringp ver)
5001 (error "Version must be a string"))
5002 ;; Change .x.y to 0.x.y
5003 (if (and (>= (length ver) (length version-separator))
5004 (string-equal (substring ver 0 (length version-separator))
5005 version-separator))
5006 (setq ver (concat "0" ver)))
5007 (unless (string-match-p "^[0-9]" ver)
5008 (error "Invalid version syntax: `%s' (must start with a number)" ver))
5010 (save-match-data
5011 (let ((i 0)
5012 (case-fold-search t) ; ignore case in matching
5013 lst s al)
5014 ;; Parse the version-string up to a separator until there are none left
5015 (while (and (setq s (string-match "[0-9]+" ver i))
5016 (= s i))
5017 ;; Add the numeric part to the beginning of the version list;
5018 ;; lst gets reversed at the end
5019 (setq lst (cons (string-to-number (substring ver i (match-end 0)))
5020 lst)
5021 i (match-end 0))
5022 ;; handle non-numeric part
5023 (when (and (setq s (string-match "[^0-9]+" ver i))
5024 (= s i))
5025 (setq s (substring ver i (match-end 0))
5026 i (match-end 0))
5027 ;; handle alpha, beta, pre, etc. separator
5028 (unless (string= s version-separator)
5029 (setq al version-regexp-alist)
5030 (while (and al (not (string-match (caar al) s)))
5031 (setq al (cdr al)))
5032 (cond (al
5033 (push (cdar al) lst))
5034 ;; Convert 22.3a to 22.3.1, 22.3b to 22.3.2, etc., but only if
5035 ;; the letter is the end of the version-string, to avoid
5036 ;; 22.8X3 being valid
5037 ((and (string-match "^[-._+ ]?\\([a-zA-Z]\\)$" s)
5038 (= i (length ver)))
5039 (push (- (aref (downcase (match-string 1 s)) 0) ?a -1)
5040 lst))
5041 (t (error "Invalid version syntax: `%s'" ver))))))
5042 (nreverse lst))))
5044 (defun version-list-< (l1 l2)
5045 "Return t if L1, a list specification of a version, is lower than L2.
5047 Note that a version specified by the list (1) is equal to (1 0),
5048 \(1 0 0), (1 0 0 0), etc. That is, the trailing zeros are insignificant.
5049 Also, a version given by the list (1) is higher than (1 -1), which in
5050 turn is higher than (1 -2), which is higher than (1 -3)."
5051 (while (and l1 l2 (= (car l1) (car l2)))
5052 (setq l1 (cdr l1)
5053 l2 (cdr l2)))
5054 (cond
5055 ;; l1 not null and l2 not null
5056 ((and l1 l2) (< (car l1) (car l2)))
5057 ;; l1 null and l2 null ==> l1 length = l2 length
5058 ((and (null l1) (null l2)) nil)
5059 ;; l1 not null and l2 null ==> l1 length > l2 length
5060 (l1 (< (version-list-not-zero l1) 0))
5061 ;; l1 null and l2 not null ==> l2 length > l1 length
5062 (t (< 0 (version-list-not-zero l2)))))
5065 (defun version-list-= (l1 l2)
5066 "Return t if L1, a list specification of a version, is equal to L2.
5068 Note that a version specified by the list (1) is equal to (1 0),
5069 \(1 0 0), (1 0 0 0), etc. That is, the trailing zeros are insignificant.
5070 Also, a version given by the list (1) is higher than (1 -1), which in
5071 turn is higher than (1 -2), which is higher than (1 -3)."
5072 (while (and l1 l2 (= (car l1) (car l2)))
5073 (setq l1 (cdr l1)
5074 l2 (cdr l2)))
5075 (cond
5076 ;; l1 not null and l2 not null
5077 ((and l1 l2) nil)
5078 ;; l1 null and l2 null ==> l1 length = l2 length
5079 ((and (null l1) (null l2)))
5080 ;; l1 not null and l2 null ==> l1 length > l2 length
5081 (l1 (zerop (version-list-not-zero l1)))
5082 ;; l1 null and l2 not null ==> l2 length > l1 length
5083 (t (zerop (version-list-not-zero l2)))))
5086 (defun version-list-<= (l1 l2)
5087 "Return t if L1, a list specification of a version, is lower or equal to L2.
5089 Note that integer list (1) is equal to (1 0), (1 0 0), (1 0 0 0),
5090 etc. That is, the trailing zeroes are insignificant. Also, integer
5091 list (1) is greater than (1 -1) which is greater than (1 -2)
5092 which is greater than (1 -3)."
5093 (while (and l1 l2 (= (car l1) (car l2)))
5094 (setq l1 (cdr l1)
5095 l2 (cdr l2)))
5096 (cond
5097 ;; l1 not null and l2 not null
5098 ((and l1 l2) (< (car l1) (car l2)))
5099 ;; l1 null and l2 null ==> l1 length = l2 length
5100 ((and (null l1) (null l2)))
5101 ;; l1 not null and l2 null ==> l1 length > l2 length
5102 (l1 (<= (version-list-not-zero l1) 0))
5103 ;; l1 null and l2 not null ==> l2 length > l1 length
5104 (t (<= 0 (version-list-not-zero l2)))))
5106 (defun version-list-not-zero (lst)
5107 "Return the first non-zero element of LST, which is a list of integers.
5109 If all LST elements are zeros or LST is nil, return zero."
5110 (while (and lst (zerop (car lst)))
5111 (setq lst (cdr lst)))
5112 (if lst
5113 (car lst)
5114 ;; there is no element different of zero
5118 (defun version< (v1 v2)
5119 "Return t if version V1 is lower (older) than V2.
5121 Note that version string \"1\" is equal to \"1.0\", \"1.0.0\", \"1.0.0.0\",
5122 etc. That is, the trailing \".0\"s are insignificant. Also, version
5123 string \"1\" is higher (newer) than \"1pre\", which is higher than \"1beta\",
5124 which is higher than \"1alpha\", which is higher than \"1snapshot\".
5125 Also, \"-GIT\", \"-CVS\" and \"-NNN\" are treated as snapshot versions."
5126 (version-list-< (version-to-list v1) (version-to-list v2)))
5128 (defun version<= (v1 v2)
5129 "Return t if version V1 is lower (older) than or equal to V2.
5131 Note that version string \"1\" is equal to \"1.0\", \"1.0.0\", \"1.0.0.0\",
5132 etc. That is, the trailing \".0\"s are insignificant. Also, version
5133 string \"1\" is higher (newer) than \"1pre\", which is higher than \"1beta\",
5134 which is higher than \"1alpha\", which is higher than \"1snapshot\".
5135 Also, \"-GIT\", \"-CVS\" and \"-NNN\" are treated as snapshot versions."
5136 (version-list-<= (version-to-list v1) (version-to-list v2)))
5138 (defun version= (v1 v2)
5139 "Return t if version V1 is equal to V2.
5141 Note that version string \"1\" is equal to \"1.0\", \"1.0.0\", \"1.0.0.0\",
5142 etc. That is, the trailing \".0\"s are insignificant. Also, version
5143 string \"1\" is higher (newer) than \"1pre\", which is higher than \"1beta\",
5144 which is higher than \"1alpha\", which is higher than \"1snapshot\".
5145 Also, \"-GIT\", \"-CVS\" and \"-NNN\" are treated as snapshot versions."
5146 (version-list-= (version-to-list v1) (version-to-list v2)))
5148 (defvar package--builtin-versions
5149 ;; Mostly populated by loaddefs.el via autoload-builtin-package-versions.
5150 (purecopy `((emacs . ,(version-to-list emacs-version))))
5151 "Alist giving the version of each versioned builtin package.
5152 I.e. each element of the list is of the form (NAME . VERSION) where
5153 NAME is the package name as a symbol, and VERSION is its version
5154 as a list.")
5156 (defun package--description-file (dir)
5157 (concat (let ((subdir (file-name-nondirectory
5158 (directory-file-name dir))))
5159 (if (string-match "\\([^.].*?\\)-\\([0-9]+\\(?:[.][0-9]+\\|\\(?:pre\\|beta\\|alpha\\)[0-9]+\\)*\\)" subdir)
5160 (match-string 1 subdir) subdir))
5161 "-pkg.el"))
5164 ;;; Thread support.
5166 (defmacro with-mutex (mutex &rest body)
5167 "Invoke BODY with MUTEX held, releasing MUTEX when done.
5168 This is the simplest safe way to acquire and release a mutex."
5169 (declare (indent 1) (debug t))
5170 (let ((sym (make-symbol "mutex")))
5171 `(let ((,sym ,mutex))
5172 (mutex-lock ,sym)
5173 (unwind-protect
5174 (progn ,@body)
5175 (mutex-unlock ,sym)))))
5178 ;;; Misc.
5180 (defvar definition-prefixes (make-hash-table :test 'equal)
5181 "Hash table mapping prefixes to the files in which they're used.
5182 This can be used to automatically fetch not-yet-loaded definitions.
5183 More specifically, if there is a value of the form (FILES...) for a string PREFIX
5184 it means that the FILES define variables or functions with names that start
5185 with PREFIX.
5187 Note that it does not imply that all definitions starting with PREFIX can
5188 be found in those files. E.g. if prefix is \"gnus-article-\" there might
5189 still be definitions of the form \"gnus-article-toto-titi\" in other files, which would
5190 presumably appear in this table under another prefix such as \"gnus-\"
5191 or \"gnus-article-toto-\".")
5193 (defun register-definition-prefixes (file prefixes)
5194 "Register that FILE uses PREFIXES."
5195 (dolist (prefix prefixes)
5196 (puthash prefix (cons file (gethash prefix definition-prefixes))
5197 definition-prefixes)))
5199 (defconst menu-bar-separator '("--")
5200 "Separator for menus.")
5202 ;; The following statement ought to be in print.c, but `provide' can't
5203 ;; be used there.
5204 ;; https://lists.gnu.org/r/emacs-devel/2009-08/msg00236.html
5205 (when (hash-table-p (car (read-from-string
5206 (prin1-to-string (make-hash-table)))))
5207 (provide 'hashtable-print-readable))
5209 ;; This is used in lisp/Makefile.in and in leim/Makefile.in to
5210 ;; generate file names for autoloads, custom-deps, and finder-data.
5211 (defun unmsys--file-name (file)
5212 "Produce the canonical file name for FILE from its MSYS form.
5214 On systems other than MS-Windows, just returns FILE.
5215 On MS-Windows, converts /d/foo/bar form of file names
5216 passed by MSYS Make into d:/foo/bar that Emacs can grok.
5218 This function is called from lisp/Makefile and leim/Makefile."
5219 (when (and (eq system-type 'windows-nt)
5220 (string-match "\\`/[a-zA-Z]/" file))
5221 (setq file (concat (substring file 1 2) ":" (substring file 2))))
5222 file)
5225 ;;; subr.el ends here