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