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