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