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