Add functions to gnutls.c for exporting certificate details
[emacs.git] / lisp / subr.el
blob6ce02b79a0a88d6f6389961b14ece5b4ac5bab78
1 ;;; subr.el --- basic lisp subroutines for Emacs -*- coding: utf-8; lexical-binding:t -*-
3 ;; Copyright (C) 1985-1986, 1992, 1994-1995, 1999-2014 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 'window-redisplay-end-trigger nil "23.1")
1316 (make-obsolete 'set-window-redisplay-end-trigger nil "23.1")
1318 (make-obsolete 'process-filter-multibyte-p nil "23.1")
1319 (make-obsolete 'set-process-filter-multibyte nil "23.1")
1321 ;; Lisp manual only updated in 22.1.
1322 (define-obsolete-variable-alias 'executing-macro 'executing-kbd-macro
1323 "before 19.34")
1325 (define-obsolete-variable-alias 'x-lost-selection-hooks
1326 'x-lost-selection-functions "22.1")
1327 (define-obsolete-variable-alias 'x-sent-selection-hooks
1328 'x-sent-selection-functions "22.1")
1330 ;; This was introduced in 21.4 for pre-unicode unification. That
1331 ;; usage was rendered obsolete in 23.1 which uses Unicode internally.
1332 ;; Other uses are possible, so this variable is not _really_ obsolete,
1333 ;; but Stefan insists to mark it so.
1334 (make-obsolete-variable 'translation-table-for-input nil "23.1")
1336 (defvaralias 'messages-buffer-max-lines 'message-log-max)
1338 ;;;; Alternate names for functions - these are not being phased out.
1340 (defalias 'send-string 'process-send-string)
1341 (defalias 'send-region 'process-send-region)
1342 (defalias 'string= 'string-equal)
1343 (defalias 'string< 'string-lessp)
1344 (defalias 'move-marker 'set-marker)
1345 (defalias 'rplaca 'setcar)
1346 (defalias 'rplacd 'setcdr)
1347 (defalias 'beep 'ding) ;preserve lingual purity
1348 (defalias 'indent-to-column 'indent-to)
1349 (defalias 'backward-delete-char 'delete-backward-char)
1350 (defalias 'search-forward-regexp (symbol-function 're-search-forward))
1351 (defalias 'search-backward-regexp (symbol-function 're-search-backward))
1352 (defalias 'int-to-string 'number-to-string)
1353 (defalias 'store-match-data 'set-match-data)
1354 (defalias 'chmod 'set-file-modes)
1355 (defalias 'mkdir 'make-directory)
1356 ;; These are the XEmacs names:
1357 (defalias 'point-at-eol 'line-end-position)
1358 (defalias 'point-at-bol 'line-beginning-position)
1360 (defalias 'user-original-login-name 'user-login-name)
1363 ;;;; Hook manipulation functions.
1365 (defun add-hook (hook function &optional append local)
1366 "Add to the value of HOOK the function FUNCTION.
1367 FUNCTION is not added if already present.
1368 FUNCTION is added (if necessary) at the beginning of the hook list
1369 unless the optional argument APPEND is non-nil, in which case
1370 FUNCTION is added at the end.
1372 The optional fourth argument, LOCAL, if non-nil, says to modify
1373 the hook's buffer-local value rather than its global value.
1374 This makes the hook buffer-local, and it makes t a member of the
1375 buffer-local value. That acts as a flag to run the hook
1376 functions of the global value as well as in the local value.
1378 HOOK should be a symbol, and FUNCTION may be any valid function. If
1379 HOOK is void, it is first set to nil. If HOOK's value is a single
1380 function, it is changed to a list of functions."
1381 (or (boundp hook) (set hook nil))
1382 (or (default-boundp hook) (set-default hook nil))
1383 (if local (unless (local-variable-if-set-p hook)
1384 (set (make-local-variable hook) (list t)))
1385 ;; Detect the case where make-local-variable was used on a hook
1386 ;; and do what we used to do.
1387 (unless (and (consp (symbol-value hook)) (memq t (symbol-value hook)))
1388 (setq local t)))
1389 (let ((hook-value (if local (symbol-value hook) (default-value hook))))
1390 ;; If the hook value is a single function, turn it into a list.
1391 (when (or (not (listp hook-value)) (functionp hook-value))
1392 (setq hook-value (list hook-value)))
1393 ;; Do the actual addition if necessary
1394 (unless (member function hook-value)
1395 (when (stringp function)
1396 (setq function (purecopy function)))
1397 (setq hook-value
1398 (if append
1399 (append hook-value (list function))
1400 (cons function hook-value))))
1401 ;; Set the actual variable
1402 (if local
1403 (progn
1404 ;; If HOOK isn't a permanent local,
1405 ;; but FUNCTION wants to survive a change of modes,
1406 ;; mark HOOK as partially permanent.
1407 (and (symbolp function)
1408 (get function 'permanent-local-hook)
1409 (not (get hook 'permanent-local))
1410 (put hook 'permanent-local 'permanent-local-hook))
1411 (set hook hook-value))
1412 (set-default hook hook-value))))
1414 (defun remove-hook (hook function &optional local)
1415 "Remove from the value of HOOK the function FUNCTION.
1416 HOOK should be a symbol, and FUNCTION may be any valid function. If
1417 FUNCTION isn't the value of HOOK, or, if FUNCTION doesn't appear in the
1418 list of hooks to run in HOOK, then nothing is done. See `add-hook'.
1420 The optional third argument, LOCAL, if non-nil, says to modify
1421 the hook's buffer-local value rather than its default value."
1422 (or (boundp hook) (set hook nil))
1423 (or (default-boundp hook) (set-default hook nil))
1424 ;; Do nothing if LOCAL is t but this hook has no local binding.
1425 (unless (and local (not (local-variable-p hook)))
1426 ;; Detect the case where make-local-variable was used on a hook
1427 ;; and do what we used to do.
1428 (when (and (local-variable-p hook)
1429 (not (and (consp (symbol-value hook))
1430 (memq t (symbol-value hook)))))
1431 (setq local t))
1432 (let ((hook-value (if local (symbol-value hook) (default-value hook))))
1433 ;; Remove the function, for both the list and the non-list cases.
1434 (if (or (not (listp hook-value)) (eq (car hook-value) 'lambda))
1435 (if (equal hook-value function) (setq hook-value nil))
1436 (setq hook-value (delete function (copy-sequence hook-value))))
1437 ;; If the function is on the global hook, we need to shadow it locally
1438 ;;(when (and local (member function (default-value hook))
1439 ;; (not (member (cons 'not function) hook-value)))
1440 ;; (push (cons 'not function) hook-value))
1441 ;; Set the actual variable
1442 (if (not local)
1443 (set-default hook hook-value)
1444 (if (equal hook-value '(t))
1445 (kill-local-variable hook)
1446 (set hook hook-value))))))
1448 (defmacro letrec (binders &rest body)
1449 "Bind variables according to BINDERS then eval BODY.
1450 The value of the last form in BODY is returned.
1451 Each element of BINDERS is a list (SYMBOL VALUEFORM) which binds
1452 SYMBOL to the value of VALUEFORM.
1453 All symbols are bound before the VALUEFORMs are evalled."
1454 ;; Only useful in lexical-binding mode.
1455 ;; As a special-form, we could implement it more efficiently (and cleanly,
1456 ;; making the vars actually unbound during evaluation of the binders).
1457 (declare (debug let) (indent 1))
1458 `(let ,(mapcar #'car binders)
1459 ,@(mapcar (lambda (binder) `(setq ,@binder)) binders)
1460 ,@body))
1462 (defmacro with-wrapper-hook (hook args &rest body)
1463 "Run BODY, using wrapper functions from HOOK with additional ARGS.
1464 HOOK is an abnormal hook. Each hook function in HOOK \"wraps\"
1465 around the preceding ones, like a set of nested `around' advices.
1467 Each hook function should accept an argument list consisting of a
1468 function FUN, followed by the additional arguments in ARGS.
1470 The first hook function in HOOK is passed a FUN that, if it is called
1471 with arguments ARGS, performs BODY (i.e., the default operation).
1472 The FUN passed to each successive hook function is defined based
1473 on the preceding hook functions; if called with arguments ARGS,
1474 it does what the `with-wrapper-hook' call would do if the
1475 preceding hook functions were the only ones present in HOOK.
1477 Each hook function may call its FUN argument as many times as it wishes,
1478 including never. In that case, such a hook function acts to replace
1479 the default definition altogether, and any preceding hook functions.
1480 Of course, a subsequent hook function may do the same thing.
1482 Each hook function definition is used to construct the FUN passed
1483 to the next hook function, if any. The last (or \"outermost\")
1484 FUN is then called once."
1485 (declare (indent 2) (debug (form sexp body))
1486 (obsolete "use a <foo>-function variable modified by `add-function'."
1487 "24.4"))
1488 ;; We need those two gensyms because CL's lexical scoping is not available
1489 ;; for function arguments :-(
1490 (let ((funs (make-symbol "funs"))
1491 (global (make-symbol "global"))
1492 (argssym (make-symbol "args"))
1493 (runrestofhook (make-symbol "runrestofhook")))
1494 ;; Since the hook is a wrapper, the loop has to be done via
1495 ;; recursion: a given hook function will call its parameter in order to
1496 ;; continue looping.
1497 `(letrec ((,runrestofhook
1498 (lambda (,funs ,global ,argssym)
1499 ;; `funs' holds the functions left on the hook and `global'
1500 ;; holds the functions left on the global part of the hook
1501 ;; (in case the hook is local).
1502 (if (consp ,funs)
1503 (if (eq t (car ,funs))
1504 (funcall ,runrestofhook
1505 (append ,global (cdr ,funs)) nil ,argssym)
1506 (apply (car ,funs)
1507 (apply-partially
1508 (lambda (,funs ,global &rest ,argssym)
1509 (funcall ,runrestofhook ,funs ,global ,argssym))
1510 (cdr ,funs) ,global)
1511 ,argssym))
1512 ;; Once there are no more functions on the hook, run
1513 ;; the original body.
1514 (apply (lambda ,args ,@body) ,argssym)))))
1515 (funcall ,runrestofhook ,hook
1516 ;; The global part of the hook, if any.
1517 ,(if (symbolp hook)
1518 `(if (local-variable-p ',hook)
1519 (default-value ',hook)))
1520 (list ,@args)))))
1522 (defun add-to-list (list-var element &optional append compare-fn)
1523 "Add ELEMENT to the value of LIST-VAR if it isn't there yet.
1524 The test for presence of ELEMENT is done with `equal', or with
1525 COMPARE-FN if that's non-nil.
1526 If ELEMENT is added, it is added at the beginning of the list,
1527 unless the optional argument APPEND is non-nil, in which case
1528 ELEMENT is added at the end.
1530 The return value is the new value of LIST-VAR.
1532 This is handy to add some elements to configuration variables,
1533 but please do not abuse it in Elisp code, where you are usually
1534 better off using `push' or `cl-pushnew'.
1536 If you want to use `add-to-list' on a variable that is not
1537 defined until a certain package is loaded, you should put the
1538 call to `add-to-list' into a hook function that will be run only
1539 after loading the package. `eval-after-load' provides one way to
1540 do this. In some cases other hooks, such as major mode hooks,
1541 can do the job."
1542 (declare
1543 (compiler-macro
1544 (lambda (exp)
1545 ;; FIXME: Something like this could be used for `set' as well.
1546 (if (or (not (eq 'quote (car-safe list-var)))
1547 (special-variable-p (cadr list-var))
1548 (not (macroexp-const-p append)))
1550 (let* ((sym (cadr list-var))
1551 (append (eval append))
1552 (msg (format "`add-to-list' can't use lexical var `%s'; use `push' or `cl-pushnew'"
1553 sym))
1554 ;; Big ugly hack so we only output a warning during
1555 ;; byte-compilation, and so we can use
1556 ;; byte-compile-not-lexical-var-p to silence the warning
1557 ;; when a defvar has been seen but not yet executed.
1558 (warnfun (lambda ()
1559 ;; FIXME: We should also emit a warning for let-bound
1560 ;; variables with dynamic binding.
1561 (when (assq sym byte-compile--lexical-environment)
1562 (byte-compile-log-warning msg t :error))))
1563 (code
1564 (macroexp-let2 macroexp-copyable-p x element
1565 `(if ,(if compare-fn
1566 (progn
1567 (require 'cl-lib)
1568 `(cl-member ,x ,sym :test ,compare-fn))
1569 ;; For bootstrapping reasons, don't rely on
1570 ;; cl--compiler-macro-member for the base case.
1571 `(member ,x ,sym))
1572 ,sym
1573 ,(if append
1574 `(setq ,sym (append ,sym (list ,x)))
1575 `(push ,x ,sym))))))
1576 (if (not (macroexp--compiling-p))
1577 code
1578 `(progn
1579 (macroexp--funcall-if-compiled ',warnfun)
1580 ,code)))))))
1581 (if (cond
1582 ((null compare-fn)
1583 (member element (symbol-value list-var)))
1584 ((eq compare-fn 'eq)
1585 (memq element (symbol-value list-var)))
1586 ((eq compare-fn 'eql)
1587 (memql element (symbol-value list-var)))
1589 (let ((lst (symbol-value list-var)))
1590 (while (and lst
1591 (not (funcall compare-fn element (car lst))))
1592 (setq lst (cdr lst)))
1593 lst)))
1594 (symbol-value list-var)
1595 (set list-var
1596 (if append
1597 (append (symbol-value list-var) (list element))
1598 (cons element (symbol-value list-var))))))
1601 (defun add-to-ordered-list (list-var element &optional order)
1602 "Add ELEMENT to the value of LIST-VAR if it isn't there yet.
1603 The test for presence of ELEMENT is done with `eq'.
1605 The resulting list is reordered so that the elements are in the
1606 order given by each element's numeric list order. Elements
1607 without a numeric list order are placed at the end of the list.
1609 If the third optional argument ORDER is a number (integer or
1610 float), set the element's list order to the given value. If
1611 ORDER is nil or omitted, do not change the numeric order of
1612 ELEMENT. If ORDER has any other value, remove the numeric order
1613 of ELEMENT if it has one.
1615 The list order for each element is stored in LIST-VAR's
1616 `list-order' property.
1618 The return value is the new value of LIST-VAR."
1619 (let ((ordering (get list-var 'list-order)))
1620 (unless ordering
1621 (put list-var 'list-order
1622 (setq ordering (make-hash-table :weakness 'key :test 'eq))))
1623 (when order
1624 (puthash element (and (numberp order) order) ordering))
1625 (unless (memq element (symbol-value list-var))
1626 (set list-var (cons element (symbol-value list-var))))
1627 (set list-var (sort (symbol-value list-var)
1628 (lambda (a b)
1629 (let ((oa (gethash a ordering))
1630 (ob (gethash b ordering)))
1631 (if (and oa ob)
1632 (< oa ob)
1633 oa)))))))
1635 (defun add-to-history (history-var newelt &optional maxelt keep-all)
1636 "Add NEWELT to the history list stored in the variable HISTORY-VAR.
1637 Return the new history list.
1638 If MAXELT is non-nil, it specifies the maximum length of the history.
1639 Otherwise, the maximum history length is the value of the `history-length'
1640 property on symbol HISTORY-VAR, if set, or the value of the `history-length'
1641 variable.
1642 Remove duplicates of NEWELT if `history-delete-duplicates' is non-nil.
1643 If optional fourth arg KEEP-ALL is non-nil, add NEWELT to history even
1644 if it is empty or a duplicate."
1645 (unless maxelt
1646 (setq maxelt (or (get history-var 'history-length)
1647 history-length)))
1648 (let ((history (symbol-value history-var))
1649 tail)
1650 (when (and (listp history)
1651 (or keep-all
1652 (not (stringp newelt))
1653 (> (length newelt) 0))
1654 (or keep-all
1655 (not (equal (car history) newelt))))
1656 (if history-delete-duplicates
1657 (setq history (delete newelt history)))
1658 (setq history (cons newelt history))
1659 (when (integerp maxelt)
1660 (if (= 0 maxelt)
1661 (setq history nil)
1662 (setq tail (nthcdr (1- maxelt) history))
1663 (when (consp tail)
1664 (setcdr tail nil)))))
1665 (set history-var history)))
1668 ;;;; Mode hooks.
1670 (defvar delay-mode-hooks nil
1671 "If non-nil, `run-mode-hooks' should delay running the hooks.")
1672 (defvar delayed-mode-hooks nil
1673 "List of delayed mode hooks waiting to be run.")
1674 (make-variable-buffer-local 'delayed-mode-hooks)
1675 (put 'delay-mode-hooks 'permanent-local t)
1677 (defvar change-major-mode-after-body-hook nil
1678 "Normal hook run in major mode functions, before the mode hooks.")
1680 (defvar after-change-major-mode-hook nil
1681 "Normal hook run at the very end of major mode functions.")
1683 (defun run-mode-hooks (&rest hooks)
1684 "Run mode hooks `delayed-mode-hooks' and HOOKS, or delay HOOKS.
1685 If the variable `delay-mode-hooks' is non-nil, does not run any hooks,
1686 just adds the HOOKS to the list `delayed-mode-hooks'.
1687 Otherwise, runs hooks in the sequence: `change-major-mode-after-body-hook',
1688 `delayed-mode-hooks' (in reverse order), HOOKS, and finally
1689 `after-change-major-mode-hook'. Major mode functions should use
1690 this instead of `run-hooks' when running their FOO-mode-hook."
1691 (if delay-mode-hooks
1692 ;; Delaying case.
1693 (dolist (hook hooks)
1694 (push hook delayed-mode-hooks))
1695 ;; Normal case, just run the hook as before plus any delayed hooks.
1696 (setq hooks (nconc (nreverse delayed-mode-hooks) hooks))
1697 (setq delayed-mode-hooks nil)
1698 (apply 'run-hooks (cons 'change-major-mode-after-body-hook hooks))
1699 (run-hooks 'after-change-major-mode-hook)))
1701 (defmacro delay-mode-hooks (&rest body)
1702 "Execute BODY, but delay any `run-mode-hooks'.
1703 These hooks will be executed by the first following call to
1704 `run-mode-hooks' that occurs outside any `delayed-mode-hooks' form.
1705 Only affects hooks run in the current buffer."
1706 (declare (debug t) (indent 0))
1707 `(progn
1708 (make-local-variable 'delay-mode-hooks)
1709 (let ((delay-mode-hooks t))
1710 ,@body)))
1712 ;; PUBLIC: find if the current mode derives from another.
1714 (defun derived-mode-p (&rest modes)
1715 "Non-nil if the current major mode is derived from one of MODES.
1716 Uses the `derived-mode-parent' property of the symbol to trace backwards."
1717 (let ((parent major-mode))
1718 (while (and (not (memq parent modes))
1719 (setq parent (get parent 'derived-mode-parent))))
1720 parent))
1722 ;;;; Minor modes.
1724 ;; If a minor mode is not defined with define-minor-mode,
1725 ;; add it here explicitly.
1726 ;; isearch-mode is deliberately excluded, since you should
1727 ;; not call it yourself.
1728 (defvar minor-mode-list '(auto-save-mode auto-fill-mode abbrev-mode
1729 overwrite-mode view-mode
1730 hs-minor-mode)
1731 "List of all minor mode functions.")
1733 (defun add-minor-mode (toggle name &optional keymap after toggle-fun)
1734 "Register a new minor mode.
1736 This is an XEmacs-compatibility function. Use `define-minor-mode' instead.
1738 TOGGLE is a symbol which is the name of a buffer-local variable that
1739 is toggled on or off to say whether the minor mode is active or not.
1741 NAME specifies what will appear in the mode line when the minor mode
1742 is active. NAME should be either a string starting with a space, or a
1743 symbol whose value is such a string.
1745 Optional KEYMAP is the keymap for the minor mode that will be added
1746 to `minor-mode-map-alist'.
1748 Optional AFTER specifies that TOGGLE should be added after AFTER
1749 in `minor-mode-alist'.
1751 Optional TOGGLE-FUN is an interactive function to toggle the mode.
1752 It defaults to (and should by convention be) TOGGLE.
1754 If TOGGLE has a non-nil `:included' property, an entry for the mode is
1755 included in the mode-line minor mode menu.
1756 If TOGGLE has a `:menu-tag', that is used for the menu item's label."
1757 (unless (memq toggle minor-mode-list)
1758 (push toggle minor-mode-list))
1760 (unless toggle-fun (setq toggle-fun toggle))
1761 (unless (eq toggle-fun toggle)
1762 (put toggle :minor-mode-function toggle-fun))
1763 ;; Add the name to the minor-mode-alist.
1764 (when name
1765 (let ((existing (assq toggle minor-mode-alist)))
1766 (if existing
1767 (setcdr existing (list name))
1768 (let ((tail minor-mode-alist) found)
1769 (while (and tail (not found))
1770 (if (eq after (caar tail))
1771 (setq found tail)
1772 (setq tail (cdr tail))))
1773 (if found
1774 (let ((rest (cdr found)))
1775 (setcdr found nil)
1776 (nconc found (list (list toggle name)) rest))
1777 (push (list toggle name) minor-mode-alist))))))
1778 ;; Add the toggle to the minor-modes menu if requested.
1779 (when (get toggle :included)
1780 (define-key mode-line-mode-menu
1781 (vector toggle)
1782 (list 'menu-item
1783 (concat
1784 (or (get toggle :menu-tag)
1785 (if (stringp name) name (symbol-name toggle)))
1786 (let ((mode-name (if (symbolp name) (symbol-value name))))
1787 (if (and (stringp mode-name) (string-match "[^ ]+" mode-name))
1788 (concat " (" (match-string 0 mode-name) ")"))))
1789 toggle-fun
1790 :button (cons :toggle toggle))))
1792 ;; Add the map to the minor-mode-map-alist.
1793 (when keymap
1794 (let ((existing (assq toggle minor-mode-map-alist)))
1795 (if existing
1796 (setcdr existing keymap)
1797 (let ((tail minor-mode-map-alist) found)
1798 (while (and tail (not found))
1799 (if (eq after (caar tail))
1800 (setq found tail)
1801 (setq tail (cdr tail))))
1802 (if found
1803 (let ((rest (cdr found)))
1804 (setcdr found nil)
1805 (nconc found (list (cons toggle keymap)) rest))
1806 (push (cons toggle keymap) minor-mode-map-alist)))))))
1808 ;;;; Load history
1810 (defsubst autoloadp (object)
1811 "Non-nil if OBJECT is an autoload."
1812 (eq 'autoload (car-safe object)))
1814 ;; (defun autoload-type (object)
1815 ;; "Returns the type of OBJECT or `function' or `command' if the type is nil.
1816 ;; OBJECT should be an autoload object."
1817 ;; (when (autoloadp object)
1818 ;; (let ((type (nth 3 object)))
1819 ;; (cond ((null type) (if (nth 2 object) 'command 'function))
1820 ;; ((eq 'keymap t) 'macro)
1821 ;; (type)))))
1823 ;; (defalias 'autoload-file #'cadr
1824 ;; "Return the name of the file from which AUTOLOAD will be loaded.
1825 ;; \n\(fn AUTOLOAD)")
1827 (defun symbol-file (symbol &optional type)
1828 "Return the name of the file that defined SYMBOL.
1829 The value is normally an absolute file name. It can also be nil,
1830 if the definition is not associated with any file. If SYMBOL
1831 specifies an autoloaded function, the value can be a relative
1832 file name without extension.
1834 If TYPE is nil, then any kind of definition is acceptable. If
1835 TYPE is `defun', `defvar', or `defface', that specifies function
1836 definition, variable definition, or face definition only."
1837 (if (and (or (null type) (eq type 'defun))
1838 (symbolp symbol)
1839 (autoloadp (symbol-function symbol)))
1840 (nth 1 (symbol-function symbol))
1841 (let ((files load-history)
1842 file)
1843 (while files
1844 (if (if type
1845 (if (eq type 'defvar)
1846 ;; Variables are present just as their names.
1847 (member symbol (cdr (car files)))
1848 ;; Other types are represented as (TYPE . NAME).
1849 (member (cons type symbol) (cdr (car files))))
1850 ;; We accept all types, so look for variable def
1851 ;; and then for any other kind.
1852 (or (member symbol (cdr (car files)))
1853 (rassq symbol (cdr (car files)))))
1854 (setq file (car (car files)) files nil))
1855 (setq files (cdr files)))
1856 file)))
1858 (defun locate-library (library &optional nosuffix path interactive-call)
1859 "Show the precise file name of Emacs library LIBRARY.
1860 LIBRARY should be a relative file name of the library, a string.
1861 It can omit the suffix (a.k.a. file-name extension) if NOSUFFIX is
1862 nil (which is the default, see below).
1863 This command searches the directories in `load-path' like `\\[load-library]'
1864 to find the file that `\\[load-library] RET LIBRARY RET' would load.
1865 Optional second arg NOSUFFIX non-nil means don't add suffixes `load-suffixes'
1866 to the specified name LIBRARY.
1868 If the optional third arg PATH is specified, that list of directories
1869 is used instead of `load-path'.
1871 When called from a program, the file name is normally returned as a
1872 string. When run interactively, the argument INTERACTIVE-CALL is t,
1873 and the file name is displayed in the echo area."
1874 (interactive (list (completing-read "Locate library: "
1875 (apply-partially
1876 'locate-file-completion-table
1877 load-path (get-load-suffixes)))
1878 nil nil
1880 (let ((file (locate-file library
1881 (or path load-path)
1882 (append (unless nosuffix (get-load-suffixes))
1883 load-file-rep-suffixes))))
1884 (if interactive-call
1885 (if file
1886 (message "Library is file %s" (abbreviate-file-name file))
1887 (message "No library %s in search path" library)))
1888 file))
1891 ;;;; Process stuff.
1893 (defun process-lines (program &rest args)
1894 "Execute PROGRAM with ARGS, returning its output as a list of lines.
1895 Signal an error if the program returns with a non-zero exit status."
1896 (with-temp-buffer
1897 (let ((status (apply 'call-process program nil (current-buffer) nil args)))
1898 (unless (eq status 0)
1899 (error "%s exited with status %s" program status))
1900 (goto-char (point-min))
1901 (let (lines)
1902 (while (not (eobp))
1903 (setq lines (cons (buffer-substring-no-properties
1904 (line-beginning-position)
1905 (line-end-position))
1906 lines))
1907 (forward-line 1))
1908 (nreverse lines)))))
1910 (defun process-live-p (process)
1911 "Returns non-nil if PROCESS is alive.
1912 A process is considered alive if its status is `run', `open',
1913 `listen', `connect' or `stop'. Value is nil if PROCESS is not a
1914 process."
1915 (and (processp process)
1916 (memq (process-status process)
1917 '(run open listen connect stop))))
1919 ;; compatibility
1921 (make-obsolete
1922 'process-kill-without-query
1923 "use `process-query-on-exit-flag' or `set-process-query-on-exit-flag'."
1924 "22.1")
1925 (defun process-kill-without-query (process &optional _flag)
1926 "Say no query needed if PROCESS is running when Emacs is exited.
1927 Optional second argument if non-nil says to require a query.
1928 Value is t if a query was formerly required."
1929 (let ((old (process-query-on-exit-flag process)))
1930 (set-process-query-on-exit-flag process nil)
1931 old))
1933 (defun process-kill-buffer-query-function ()
1934 "Ask before killing a buffer that has a running process."
1935 (let ((process (get-buffer-process (current-buffer))))
1936 (or (not process)
1937 (not (memq (process-status process) '(run stop open listen)))
1938 (not (process-query-on-exit-flag process))
1939 (yes-or-no-p
1940 (format "Buffer %S has a running process; kill it? "
1941 (buffer-name (current-buffer)))))))
1943 (add-hook 'kill-buffer-query-functions 'process-kill-buffer-query-function)
1945 ;; process plist management
1947 (defun process-get (process propname)
1948 "Return the value of PROCESS' PROPNAME property.
1949 This is the last value stored with `(process-put PROCESS PROPNAME VALUE)'."
1950 (plist-get (process-plist process) propname))
1952 (defun process-put (process propname value)
1953 "Change PROCESS' PROPNAME property to VALUE.
1954 It can be retrieved with `(process-get PROCESS PROPNAME)'."
1955 (set-process-plist process
1956 (plist-put (process-plist process) propname value)))
1959 ;;;; Input and display facilities.
1961 (defconst read-key-empty-map (make-sparse-keymap))
1963 (defvar read-key-delay 0.01) ;Fast enough for 100Hz repeat rate, hopefully.
1965 (defun read-key (&optional prompt)
1966 "Read a key from the keyboard.
1967 Contrary to `read-event' this will not return a raw event but instead will
1968 obey the input decoding and translations usually done by `read-key-sequence'.
1969 So escape sequences and keyboard encoding are taken into account.
1970 When there's an ambiguity because the key looks like the prefix of
1971 some sort of escape sequence, the ambiguity is resolved via `read-key-delay'."
1972 ;; This overriding-terminal-local-map binding also happens to
1973 ;; disable quail's input methods, so although read-key-sequence
1974 ;; always inherits the input method, in practice read-key does not
1975 ;; inherit the input method (at least not if it's based on quail).
1976 (let ((overriding-terminal-local-map nil)
1977 (overriding-local-map read-key-empty-map)
1978 (echo-keystrokes 0)
1979 (old-global-map (current-global-map))
1980 (timer (run-with-idle-timer
1981 ;; Wait long enough that Emacs has the time to receive and
1982 ;; process all the raw events associated with the single-key.
1983 ;; But don't wait too long, or the user may find the delay
1984 ;; annoying (or keep hitting more keys which may then get
1985 ;; lost or misinterpreted).
1986 ;; This is only relevant for keys which Emacs perceives as
1987 ;; "prefixes", such as C-x (because of the C-x 8 map in
1988 ;; key-translate-table and the C-x @ map in function-key-map)
1989 ;; or ESC (because of terminal escape sequences in
1990 ;; input-decode-map).
1991 read-key-delay t
1992 (lambda ()
1993 (let ((keys (this-command-keys-vector)))
1994 (unless (zerop (length keys))
1995 ;; `keys' is non-empty, so the user has hit at least
1996 ;; one key; there's no point waiting any longer, even
1997 ;; though read-key-sequence thinks we should wait
1998 ;; for more input to decide how to interpret the
1999 ;; current input.
2000 (throw 'read-key keys)))))))
2001 (unwind-protect
2002 (progn
2003 (use-global-map
2004 (let ((map (make-sparse-keymap)))
2005 ;; Don't hide the menu-bar and tool-bar entries.
2006 (define-key map [menu-bar] (lookup-key global-map [menu-bar]))
2007 (define-key map [tool-bar]
2008 ;; This hack avoids evaluating the :filter (Bug#9922).
2009 (or (cdr (assq 'tool-bar global-map))
2010 (lookup-key global-map [tool-bar])))
2011 map))
2012 (let* ((keys
2013 (catch 'read-key (read-key-sequence-vector prompt nil t)))
2014 (key (aref keys 0)))
2015 (if (and (> (length keys) 1)
2016 (memq key '(mode-line header-line
2017 left-fringe right-fringe)))
2018 (aref keys 1)
2019 key)))
2020 (cancel-timer timer)
2021 (use-global-map old-global-map))))
2023 (defvar read-passwd-map
2024 ;; BEWARE: `defconst' would purecopy it, breaking the sharing with
2025 ;; minibuffer-local-map along the way!
2026 (let ((map (make-sparse-keymap)))
2027 (set-keymap-parent map minibuffer-local-map)
2028 (define-key map "\C-u" #'delete-minibuffer-contents) ;bug#12570
2029 map)
2030 "Keymap used while reading passwords.")
2032 (defun read-passwd (prompt &optional confirm default)
2033 "Read a password, prompting with PROMPT, and return it.
2034 If optional CONFIRM is non-nil, read the password twice to make sure.
2035 Optional DEFAULT is a default password to use instead of empty input.
2037 This function echoes `.' for each character that the user types.
2038 You could let-bind `read-hide-char' to another hiding character, though.
2040 Once the caller uses the password, it can erase the password
2041 by doing (clear-string STRING)."
2042 (if confirm
2043 (let (success)
2044 (while (not success)
2045 (let ((first (read-passwd prompt nil default))
2046 (second (read-passwd "Confirm password: " nil default)))
2047 (if (equal first second)
2048 (progn
2049 (and (arrayp second) (clear-string second))
2050 (setq success first))
2051 (and (arrayp first) (clear-string first))
2052 (and (arrayp second) (clear-string second))
2053 (message "Password not repeated accurately; please start over")
2054 (sit-for 1))))
2055 success)
2056 (let ((hide-chars-fun
2057 (lambda (beg end _len)
2058 (clear-this-command-keys)
2059 (setq beg (min end (max (minibuffer-prompt-end)
2060 beg)))
2061 (dotimes (i (- end beg))
2062 (put-text-property (+ i beg) (+ 1 i beg)
2063 'display (string (or read-hide-char ?.))))))
2064 minibuf)
2065 (minibuffer-with-setup-hook
2066 (lambda ()
2067 (setq minibuf (current-buffer))
2068 ;; Turn off electricity.
2069 (setq-local post-self-insert-hook nil)
2070 (setq-local buffer-undo-list t)
2071 (setq-local select-active-regions nil)
2072 (use-local-map read-passwd-map)
2073 (setq-local inhibit-modification-hooks nil) ;bug#15501.
2074 (setq-local show-paren-mode nil) ;bug#16091.
2075 (add-hook 'after-change-functions hide-chars-fun nil 'local))
2076 (unwind-protect
2077 (let ((enable-recursive-minibuffers t)
2078 (read-hide-char (or read-hide-char ?.)))
2079 (read-string prompt nil t default)) ; t = "no history"
2080 (when (buffer-live-p minibuf)
2081 (with-current-buffer minibuf
2082 ;; Not sure why but it seems that there might be cases where the
2083 ;; minibuffer is not always properly reset later on, so undo
2084 ;; whatever we've done here (bug#11392).
2085 (remove-hook 'after-change-functions hide-chars-fun 'local)
2086 (kill-local-variable 'post-self-insert-hook)
2087 ;; And of course, don't keep the sensitive data around.
2088 (erase-buffer))))))))
2090 (defun read-number (prompt &optional default)
2091 "Read a numeric value in the minibuffer, prompting with PROMPT.
2092 DEFAULT specifies a default value to return if the user just types RET.
2093 The value of DEFAULT is inserted into PROMPT.
2094 This function is used by the `interactive' code letter `n'."
2095 (let ((n nil)
2096 (default1 (if (consp default) (car default) default)))
2097 (when default1
2098 (setq prompt
2099 (if (string-match "\\(\\):[ \t]*\\'" prompt)
2100 (replace-match (format " (default %s)" default1) t t prompt 1)
2101 (replace-regexp-in-string "[ \t]*\\'"
2102 (format " (default %s) " default1)
2103 prompt t t))))
2104 (while
2105 (progn
2106 (let ((str (read-from-minibuffer
2107 prompt nil nil nil nil
2108 (when default
2109 (if (consp default)
2110 (mapcar 'number-to-string (delq nil default))
2111 (number-to-string default))))))
2112 (condition-case nil
2113 (setq n (cond
2114 ((zerop (length str)) default1)
2115 ((stringp str) (read str))))
2116 (error nil)))
2117 (unless (numberp n)
2118 (message "Please enter a number.")
2119 (sit-for 1)
2120 t)))
2123 (defun read-char-choice (prompt chars &optional inhibit-keyboard-quit)
2124 "Read and return one of CHARS, prompting for PROMPT.
2125 Any input that is not one of CHARS is ignored.
2127 If optional argument INHIBIT-KEYBOARD-QUIT is non-nil, ignore
2128 keyboard-quit events while waiting for a valid input."
2129 (unless (consp chars)
2130 (error "Called `read-char-choice' without valid char choices"))
2131 (let (char done show-help (helpbuf " *Char Help*"))
2132 (let ((cursor-in-echo-area t)
2133 (executing-kbd-macro executing-kbd-macro)
2134 (esc-flag nil))
2135 (save-window-excursion ; in case we call help-form-show
2136 (while (not done)
2137 (unless (get-text-property 0 'face prompt)
2138 (setq prompt (propertize prompt 'face 'minibuffer-prompt)))
2139 (setq char (let ((inhibit-quit inhibit-keyboard-quit))
2140 (read-key prompt)))
2141 (and show-help (buffer-live-p (get-buffer helpbuf))
2142 (kill-buffer helpbuf))
2143 (cond
2144 ((not (numberp char)))
2145 ;; If caller has set help-form, that's enough.
2146 ;; They don't explicitly have to add help-char to chars.
2147 ((and help-form
2148 (eq char help-char)
2149 (setq show-help t)
2150 (help-form-show)))
2151 ((memq char chars)
2152 (setq done t))
2153 ((and executing-kbd-macro (= char -1))
2154 ;; read-event returns -1 if we are in a kbd macro and
2155 ;; there are no more events in the macro. Attempt to
2156 ;; get an event interactively.
2157 (setq executing-kbd-macro nil))
2158 ((not inhibit-keyboard-quit)
2159 (cond
2160 ((and (null esc-flag) (eq char ?\e))
2161 (setq esc-flag t))
2162 ((memq char '(?\C-g ?\e))
2163 (keyboard-quit))))))))
2164 ;; Display the question with the answer. But without cursor-in-echo-area.
2165 (message "%s%s" prompt (char-to-string char))
2166 char))
2168 (defun sit-for (seconds &optional nodisp obsolete)
2169 "Perform redisplay, then wait for SECONDS seconds or until input is available.
2170 SECONDS may be a floating-point value.
2171 \(On operating systems that do not support waiting for fractions of a
2172 second, floating-point values are rounded down to the nearest integer.)
2174 If optional arg NODISP is t, don't redisplay, just wait for input.
2175 Redisplay does not happen if input is available before it starts.
2177 Value is t if waited the full time with no input arriving, and nil otherwise.
2179 An obsolete, but still supported form is
2180 \(sit-for SECONDS &optional MILLISECONDS NODISP)
2181 where the optional arg MILLISECONDS specifies an additional wait period,
2182 in milliseconds; this was useful when Emacs was built without
2183 floating point support."
2184 (declare (advertised-calling-convention (seconds &optional nodisp) "22.1"))
2185 ;; This used to be implemented in C until the following discussion:
2186 ;; http://lists.gnu.org/archive/html/emacs-devel/2006-07/msg00401.html
2187 ;; Then it was moved to C using an implementation based on an idle timer,
2188 ;; which was then replaced by the use of read-event.
2189 (if (numberp nodisp)
2190 (setq seconds (+ seconds (* 1e-3 nodisp))
2191 nodisp obsolete)
2192 (if obsolete (setq nodisp obsolete)))
2193 (cond
2194 (noninteractive
2195 (sleep-for seconds)
2197 ((input-pending-p t)
2198 nil)
2199 ((<= seconds 0)
2200 (or nodisp (redisplay)))
2202 (or nodisp (redisplay))
2203 ;; FIXME: we should not read-event here at all, because it's much too
2204 ;; difficult to reliably "undo" a read-event by pushing it onto
2205 ;; unread-command-events.
2206 ;; For bug#14782, we need read-event to do the keyboard-coding-system
2207 ;; decoding (hence non-nil as second arg under POSIX ttys).
2208 ;; For bug#15614, we need read-event not to inherit-input-method.
2209 ;; So we temporarily suspend input-method-function.
2210 (let ((read (let ((input-method-function nil))
2211 (read-event nil t seconds))))
2212 (or (null read)
2213 (progn
2214 ;; https://lists.gnu.org/archive/html/emacs-devel/2006-10/msg00394.html
2215 ;; We want `read' appear in the next command's this-command-event
2216 ;; but not in the current one.
2217 ;; By pushing (cons t read), we indicate that `read' has not
2218 ;; yet been recorded in this-command-keys, so it will be recorded
2219 ;; next time it's read.
2220 ;; And indeed the `seconds' argument to read-event correctly
2221 ;; prevented recording this event in the current command's
2222 ;; this-command-keys.
2223 (push (cons t read) unread-command-events)
2224 nil))))))
2226 ;; Behind display-popup-menus-p test.
2227 (declare-function x-popup-dialog "menu.c" (position contents &optional header))
2229 (defun y-or-n-p (prompt)
2230 "Ask user a \"y or n\" question. Return t if answer is \"y\".
2231 PROMPT is the string to display to ask the question. It should
2232 end in a space; `y-or-n-p' adds \"(y or n) \" to it.
2234 No confirmation of the answer is requested; a single character is
2235 enough. SPC also means yes, and DEL means no.
2237 To be precise, this function translates user input into responses
2238 by consulting the bindings in `query-replace-map'; see the
2239 documentation of that variable for more information. In this
2240 case, the useful bindings are `act', `skip', `recenter',
2241 `scroll-up', `scroll-down', and `quit'.
2242 An `act' response means yes, and a `skip' response means no.
2243 A `quit' response means to invoke `keyboard-quit'.
2244 If the user enters `recenter', `scroll-up', or `scroll-down'
2245 responses, perform the requested window recentering or scrolling
2246 and ask again.
2248 Under a windowing system a dialog box will be used if `last-nonmenu-event'
2249 is nil and `use-dialog-box' is non-nil."
2250 ;; ¡Beware! when I tried to edebug this code, Emacs got into a weird state
2251 ;; where all the keys were unbound (i.e. it somehow got triggered
2252 ;; within read-key, apparently). I had to kill it.
2253 (let ((answer 'recenter)
2254 (padded (lambda (prompt &optional dialog)
2255 (let ((l (length prompt)))
2256 (concat prompt
2257 (if (or (zerop l) (eq ?\s (aref prompt (1- l))))
2258 "" " ")
2259 (if dialog "" "(y or n) "))))))
2260 (cond
2261 (noninteractive
2262 (setq prompt (funcall padded prompt))
2263 (let ((temp-prompt prompt))
2264 (while (not (memq answer '(act skip)))
2265 (let ((str (read-string temp-prompt)))
2266 (cond ((member str '("y" "Y")) (setq answer 'act))
2267 ((member str '("n" "N")) (setq answer 'skip))
2268 (t (setq temp-prompt (concat "Please answer y or n. "
2269 prompt))))))))
2270 ((and (display-popup-menus-p)
2271 (listp last-nonmenu-event)
2272 use-dialog-box)
2273 (setq prompt (funcall padded prompt t)
2274 answer (x-popup-dialog t `(,prompt ("Yes" . act) ("No" . skip)))))
2276 (setq prompt (funcall padded prompt))
2277 (while
2278 (let* ((scroll-actions '(recenter scroll-up scroll-down
2279 scroll-other-window scroll-other-window-down))
2280 (key
2281 (let ((cursor-in-echo-area t))
2282 (when minibuffer-auto-raise
2283 (raise-frame (window-frame (minibuffer-window))))
2284 (read-key (propertize (if (memq answer scroll-actions)
2285 prompt
2286 (concat "Please answer y or n. "
2287 prompt))
2288 'face 'minibuffer-prompt)))))
2289 (setq answer (lookup-key query-replace-map (vector key) t))
2290 (cond
2291 ((memq answer '(skip act)) nil)
2292 ((eq answer 'recenter)
2293 (recenter) t)
2294 ((eq answer 'scroll-up)
2295 (ignore-errors (scroll-up-command)) t)
2296 ((eq answer 'scroll-down)
2297 (ignore-errors (scroll-down-command)) t)
2298 ((eq answer 'scroll-other-window)
2299 (ignore-errors (scroll-other-window)) t)
2300 ((eq answer 'scroll-other-window-down)
2301 (ignore-errors (scroll-other-window-down)) t)
2302 ((or (memq answer '(exit-prefix quit)) (eq key ?\e))
2303 (signal 'quit nil) t)
2304 (t t)))
2305 (ding)
2306 (discard-input))))
2307 (let ((ret (eq answer 'act)))
2308 (unless noninteractive
2309 (message "%s%c" prompt (if ret ?y ?n)))
2310 ret)))
2313 ;;; Atomic change groups.
2315 (defmacro atomic-change-group (&rest body)
2316 "Perform BODY as an atomic change group.
2317 This means that if BODY exits abnormally,
2318 all of its changes to the current buffer are undone.
2319 This works regardless of whether undo is enabled in the buffer.
2321 This mechanism is transparent to ordinary use of undo;
2322 if undo is enabled in the buffer and BODY succeeds, the
2323 user can undo the change normally."
2324 (declare (indent 0) (debug t))
2325 (let ((handle (make-symbol "--change-group-handle--"))
2326 (success (make-symbol "--change-group-success--")))
2327 `(let ((,handle (prepare-change-group))
2328 ;; Don't truncate any undo data in the middle of this.
2329 (undo-outer-limit nil)
2330 (undo-limit most-positive-fixnum)
2331 (undo-strong-limit most-positive-fixnum)
2332 (,success nil))
2333 (unwind-protect
2334 (progn
2335 ;; This is inside the unwind-protect because
2336 ;; it enables undo if that was disabled; we need
2337 ;; to make sure that it gets disabled again.
2338 (activate-change-group ,handle)
2339 ,@body
2340 (setq ,success t))
2341 ;; Either of these functions will disable undo
2342 ;; if it was disabled before.
2343 (if ,success
2344 (accept-change-group ,handle)
2345 (cancel-change-group ,handle))))))
2347 (defun prepare-change-group (&optional buffer)
2348 "Return a handle for the current buffer's state, for a change group.
2349 If you specify BUFFER, make a handle for BUFFER's state instead.
2351 Pass the handle to `activate-change-group' afterward to initiate
2352 the actual changes of the change group.
2354 To finish the change group, call either `accept-change-group' or
2355 `cancel-change-group' passing the same handle as argument. Call
2356 `accept-change-group' to accept the changes in the group as final;
2357 call `cancel-change-group' to undo them all. You should use
2358 `unwind-protect' to make sure the group is always finished. The call
2359 to `activate-change-group' should be inside the `unwind-protect'.
2360 Once you finish the group, don't use the handle again--don't try to
2361 finish the same group twice. For a simple example of correct use, see
2362 the source code of `atomic-change-group'.
2364 The handle records only the specified buffer. To make a multibuffer
2365 change group, call this function once for each buffer you want to
2366 cover, then use `nconc' to combine the returned values, like this:
2368 (nconc (prepare-change-group buffer-1)
2369 (prepare-change-group buffer-2))
2371 You can then activate that multibuffer change group with a single
2372 call to `activate-change-group' and finish it with a single call
2373 to `accept-change-group' or `cancel-change-group'."
2375 (if buffer
2376 (list (cons buffer (with-current-buffer buffer buffer-undo-list)))
2377 (list (cons (current-buffer) buffer-undo-list))))
2379 (defun activate-change-group (handle)
2380 "Activate a change group made with `prepare-change-group' (which see)."
2381 (dolist (elt handle)
2382 (with-current-buffer (car elt)
2383 (if (eq buffer-undo-list t)
2384 (setq buffer-undo-list nil)))))
2386 (defun accept-change-group (handle)
2387 "Finish a change group made with `prepare-change-group' (which see).
2388 This finishes the change group by accepting its changes as final."
2389 (dolist (elt handle)
2390 (with-current-buffer (car elt)
2391 (if (eq (cdr elt) t)
2392 (setq buffer-undo-list t)))))
2394 (defun cancel-change-group (handle)
2395 "Finish a change group made with `prepare-change-group' (which see).
2396 This finishes the change group by reverting all of its changes."
2397 (dolist (elt handle)
2398 (with-current-buffer (car elt)
2399 (setq elt (cdr elt))
2400 (save-restriction
2401 ;; Widen buffer temporarily so if the buffer was narrowed within
2402 ;; the body of `atomic-change-group' all changes can be undone.
2403 (widen)
2404 (let ((old-car
2405 (if (consp elt) (car elt)))
2406 (old-cdr
2407 (if (consp elt) (cdr elt))))
2408 ;; Temporarily truncate the undo log at ELT.
2409 (when (consp elt)
2410 (setcar elt nil) (setcdr elt nil))
2411 (unless (eq last-command 'undo) (undo-start))
2412 ;; Make sure there's no confusion.
2413 (when (and (consp elt) (not (eq elt (last pending-undo-list))))
2414 (error "Undoing to some unrelated state"))
2415 ;; Undo it all.
2416 (save-excursion
2417 (while (listp pending-undo-list) (undo-more 1)))
2418 ;; Reset the modified cons cell ELT to its original content.
2419 (when (consp elt)
2420 (setcar elt old-car)
2421 (setcdr elt old-cdr))
2422 ;; Revert the undo info to what it was when we grabbed the state.
2423 (setq buffer-undo-list elt))))))
2425 ;;;; Display-related functions.
2427 ;; For compatibility.
2428 (define-obsolete-function-alias 'redraw-modeline
2429 'force-mode-line-update "24.3")
2431 (defun momentary-string-display (string pos &optional exit-char message)
2432 "Momentarily display STRING in the buffer at POS.
2433 Display remains until next event is input.
2434 If POS is a marker, only its position is used; its buffer is ignored.
2435 Optional third arg EXIT-CHAR can be a character, event or event
2436 description list. EXIT-CHAR defaults to SPC. If the input is
2437 EXIT-CHAR it is swallowed; otherwise it is then available as
2438 input (as a command if nothing else).
2439 Display MESSAGE (optional fourth arg) in the echo area.
2440 If MESSAGE is nil, instructions to type EXIT-CHAR are displayed there."
2441 (or exit-char (setq exit-char ?\s))
2442 (let ((ol (make-overlay pos pos))
2443 (str (copy-sequence string)))
2444 (unwind-protect
2445 (progn
2446 (save-excursion
2447 (overlay-put ol 'after-string str)
2448 (goto-char pos)
2449 ;; To avoid trouble with out-of-bounds position
2450 (setq pos (point))
2451 ;; If the string end is off screen, recenter now.
2452 (if (<= (window-end nil t) pos)
2453 (recenter (/ (window-height) 2))))
2454 (message (or message "Type %s to continue editing.")
2455 (single-key-description exit-char))
2456 (let ((event (read-key)))
2457 ;; `exit-char' can be an event, or an event description list.
2458 (or (eq event exit-char)
2459 (eq event (event-convert-list exit-char))
2460 (setq unread-command-events
2461 (append (this-single-command-raw-keys))))))
2462 (delete-overlay ol))))
2465 ;;;; Overlay operations
2467 (defun copy-overlay (o)
2468 "Return a copy of overlay O."
2469 (let ((o1 (if (overlay-buffer o)
2470 (make-overlay (overlay-start o) (overlay-end o)
2471 ;; FIXME: there's no easy way to find the
2472 ;; insertion-type of the two markers.
2473 (overlay-buffer o))
2474 (let ((o1 (make-overlay (point-min) (point-min))))
2475 (delete-overlay o1)
2476 o1)))
2477 (props (overlay-properties o)))
2478 (while props
2479 (overlay-put o1 (pop props) (pop props)))
2480 o1))
2482 (defun remove-overlays (&optional beg end name val)
2483 "Clear BEG and END of overlays whose property NAME has value VAL.
2484 Overlays might be moved and/or split.
2485 BEG and END default respectively to the beginning and end of buffer."
2486 ;; This speeds up the loops over overlays.
2487 (unless beg (setq beg (point-min)))
2488 (unless end (setq end (point-max)))
2489 (overlay-recenter end)
2490 (if (< end beg)
2491 (setq beg (prog1 end (setq end beg))))
2492 (save-excursion
2493 (dolist (o (overlays-in beg end))
2494 (when (eq (overlay-get o name) val)
2495 ;; Either push this overlay outside beg...end
2496 ;; or split it to exclude beg...end
2497 ;; or delete it entirely (if it is contained in beg...end).
2498 (if (< (overlay-start o) beg)
2499 (if (> (overlay-end o) end)
2500 (progn
2501 (move-overlay (copy-overlay o)
2502 (overlay-start o) beg)
2503 (move-overlay o end (overlay-end o)))
2504 (move-overlay o (overlay-start o) beg))
2505 (if (> (overlay-end o) end)
2506 (move-overlay o end (overlay-end o))
2507 (delete-overlay o)))))))
2509 ;;;; Miscellanea.
2511 (defvar suspend-hook nil
2512 "Normal hook run by `suspend-emacs', before suspending.")
2514 (defvar suspend-resume-hook nil
2515 "Normal hook run by `suspend-emacs', after Emacs is continued.")
2517 (defvar temp-buffer-show-hook nil
2518 "Normal hook run by `with-output-to-temp-buffer' after displaying the buffer.
2519 When the hook runs, the temporary buffer is current, and the window it
2520 was displayed in is selected.")
2522 (defvar temp-buffer-setup-hook nil
2523 "Normal hook run by `with-output-to-temp-buffer' at the start.
2524 When the hook runs, the temporary buffer is current.
2525 This hook is normally set up with a function to put the buffer in Help
2526 mode.")
2528 (defconst user-emacs-directory
2529 (if (eq system-type 'ms-dos)
2530 ;; MS-DOS cannot have initial dot.
2531 "~/_emacs.d/"
2532 "~/.emacs.d/")
2533 "Directory beneath which additional per-user Emacs-specific files are placed.
2534 Various programs in Emacs store information in this directory.
2535 Note that this should end with a directory separator.
2536 See also `locate-user-emacs-file'.")
2538 ;;;; Misc. useful functions.
2540 (defsubst buffer-narrowed-p ()
2541 "Return non-nil if the current buffer is narrowed."
2542 (/= (- (point-max) (point-min)) (buffer-size)))
2544 (defun find-tag-default-bounds ()
2545 "Determine the boundaries of the default tag, based on text at point.
2546 Return a cons cell with the beginning and end of the found tag.
2547 If there is no plausible default, return nil."
2548 (let (from to bound)
2549 (when (or (progn
2550 ;; Look at text around `point'.
2551 (save-excursion
2552 (skip-syntax-backward "w_") (setq from (point)))
2553 (save-excursion
2554 (skip-syntax-forward "w_") (setq to (point)))
2555 (> to from))
2556 ;; Look between `line-beginning-position' and `point'.
2557 (save-excursion
2558 (and (setq bound (line-beginning-position))
2559 (skip-syntax-backward "^w_" bound)
2560 (> (setq to (point)) bound)
2561 (skip-syntax-backward "w_")
2562 (setq from (point))))
2563 ;; Look between `point' and `line-end-position'.
2564 (save-excursion
2565 (and (setq bound (line-end-position))
2566 (skip-syntax-forward "^w_" bound)
2567 (< (setq from (point)) bound)
2568 (skip-syntax-forward "w_")
2569 (setq to (point)))))
2570 (cons from to))))
2572 (defun find-tag-default ()
2573 "Determine default tag to search for, based on text at point.
2574 If there is no plausible default, return nil."
2575 (let ((bounds (find-tag-default-bounds)))
2576 (when bounds
2577 (buffer-substring-no-properties (car bounds) (cdr bounds)))))
2579 (defun find-tag-default-as-regexp ()
2580 "Return regexp that matches the default tag at point.
2581 If there is no tag at point, return nil.
2583 When in a major mode that does not provide its own
2584 `find-tag-default-function', return a regexp that matches the
2585 symbol at point exactly."
2586 (let ((tag (funcall (or find-tag-default-function
2587 (get major-mode 'find-tag-default-function)
2588 'find-tag-default))))
2589 (if tag (regexp-quote tag))))
2591 (defun find-tag-default-as-symbol-regexp ()
2592 "Return regexp that matches the default tag at point as symbol.
2593 If there is no tag at point, return nil.
2595 When in a major mode that does not provide its own
2596 `find-tag-default-function', return a regexp that matches the
2597 symbol at point exactly."
2598 (let ((tag-regexp (find-tag-default-as-regexp)))
2599 (if (and tag-regexp
2600 (eq (or find-tag-default-function
2601 (get major-mode 'find-tag-default-function)
2602 'find-tag-default)
2603 'find-tag-default))
2604 (format "\\_<%s\\_>" tag-regexp)
2605 tag-regexp)))
2607 (defun play-sound (sound)
2608 "SOUND is a list of the form `(sound KEYWORD VALUE...)'.
2609 The following keywords are recognized:
2611 :file FILE - read sound data from FILE. If FILE isn't an
2612 absolute file name, it is searched in `data-directory'.
2614 :data DATA - read sound data from string DATA.
2616 Exactly one of :file or :data must be present.
2618 :volume VOL - set volume to VOL. VOL must an integer in the
2619 range 0..100 or a float in the range 0..1.0. If not specified,
2620 don't change the volume setting of the sound device.
2622 :device DEVICE - play sound on DEVICE. If not specified,
2623 a system-dependent default device name is used.
2625 Note: :data and :device are currently not supported on Windows."
2626 (if (fboundp 'play-sound-internal)
2627 (play-sound-internal sound)
2628 (error "This Emacs binary lacks sound support")))
2630 (declare-function w32-shell-dos-semantics "w32-fns" nil)
2632 (defun shell-quote-argument (argument)
2633 "Quote ARGUMENT for passing as argument to an inferior shell."
2634 (cond
2635 ((eq system-type 'ms-dos)
2636 ;; Quote using double quotes, but escape any existing quotes in
2637 ;; the argument with backslashes.
2638 (let ((result "")
2639 (start 0)
2640 end)
2641 (if (or (null (string-match "[^\"]" argument))
2642 (< (match-end 0) (length argument)))
2643 (while (string-match "[\"]" argument start)
2644 (setq end (match-beginning 0)
2645 result (concat result (substring argument start end)
2646 "\\" (substring argument end (1+ end)))
2647 start (1+ end))))
2648 (concat "\"" result (substring argument start) "\"")))
2650 ((and (eq system-type 'windows-nt) (w32-shell-dos-semantics))
2652 ;; First, quote argument so that CommandLineToArgvW will
2653 ;; understand it. See
2654 ;; http://msdn.microsoft.com/en-us/library/17w5ykft%28v=vs.85%29.aspx
2655 ;; After we perform that level of quoting, escape shell
2656 ;; metacharacters so that cmd won't mangle our argument. If the
2657 ;; argument contains no double quote characters, we can just
2658 ;; surround it with double quotes. Otherwise, we need to prefix
2659 ;; each shell metacharacter with a caret.
2661 (setq argument
2662 ;; escape backslashes at end of string
2663 (replace-regexp-in-string
2664 "\\(\\\\*\\)$"
2665 "\\1\\1"
2666 ;; escape backslashes and quotes in string body
2667 (replace-regexp-in-string
2668 "\\(\\\\*\\)\""
2669 "\\1\\1\\\\\""
2670 argument)))
2672 (if (string-match "[%!\"]" argument)
2673 (concat
2674 "^\""
2675 (replace-regexp-in-string
2676 "\\([%!()\"<>&|^]\\)"
2677 "^\\1"
2678 argument)
2679 "^\"")
2680 (concat "\"" argument "\"")))
2683 (if (equal argument "")
2684 "''"
2685 ;; Quote everything except POSIX filename characters.
2686 ;; This should be safe enough even for really weird shells.
2687 (replace-regexp-in-string
2688 "\n" "'\n'"
2689 (replace-regexp-in-string "[^-0-9a-zA-Z_./\n]" "\\\\\\&" argument))))
2692 (defun string-or-null-p (object)
2693 "Return t if OBJECT is a string or nil.
2694 Otherwise, return nil."
2695 (or (stringp object) (null object)))
2697 (defun booleanp (object)
2698 "Return t if OBJECT is one of the two canonical boolean values: t or nil.
2699 Otherwise, return nil."
2700 (and (memq object '(nil t)) t))
2702 (defun special-form-p (object)
2703 "Non-nil if and only if OBJECT is a special form."
2704 (if (and (symbolp object) (fboundp object))
2705 (setq object (indirect-function object t)))
2706 (and (subrp object) (eq (cdr (subr-arity object)) 'unevalled)))
2708 (defun macrop (object)
2709 "Non-nil if and only if OBJECT is a macro."
2710 (let ((def (indirect-function object t)))
2711 (when (consp def)
2712 (or (eq 'macro (car def))
2713 (and (autoloadp def) (memq (nth 4 def) '(macro t)))))))
2715 (defun field-at-pos (pos)
2716 "Return the field at position POS, taking stickiness etc into account."
2717 (let ((raw-field (get-char-property (field-beginning pos) 'field)))
2718 (if (eq raw-field 'boundary)
2719 (get-char-property (1- (field-end pos)) 'field)
2720 raw-field)))
2722 (defun sha1 (object &optional start end binary)
2723 "Return the SHA1 (Secure Hash Algorithm) of an OBJECT.
2724 OBJECT is either a string or a buffer. Optional arguments START and
2725 END are character positions specifying which portion of OBJECT for
2726 computing the hash. If BINARY is non-nil, return a string in binary
2727 form."
2728 (secure-hash 'sha1 object start end binary))
2730 (defun function-get (f prop &optional autoload)
2731 "Return the value of property PROP of function F.
2732 If AUTOLOAD is non-nil and F is autoloaded, try to autoload it
2733 in the hope that it will set PROP. If AUTOLOAD is `macro', only do it
2734 if it's an autoloaded macro."
2735 (let ((val nil))
2736 (while (and (symbolp f)
2737 (null (setq val (get f prop)))
2738 (fboundp f))
2739 (let ((fundef (symbol-function f)))
2740 (if (and autoload (autoloadp fundef)
2741 (not (equal fundef
2742 (autoload-do-load fundef f
2743 (if (eq autoload 'macro)
2744 'macro)))))
2745 nil ;Re-try `get' on the same `f'.
2746 (setq f fundef))))
2747 val))
2749 ;;;; Support for yanking and text properties.
2750 ;; Why here in subr.el rather than in simple.el? --Stef
2752 (defvar yank-handled-properties)
2753 (defvar yank-excluded-properties)
2755 (defun remove-yank-excluded-properties (start end)
2756 "Process text properties between START and END, inserted for a `yank'.
2757 Perform the handling specified by `yank-handled-properties', then
2758 remove properties specified by `yank-excluded-properties'."
2759 (let ((inhibit-read-only t))
2760 (dolist (handler yank-handled-properties)
2761 (let ((prop (car handler))
2762 (fun (cdr handler))
2763 (run-start start))
2764 (while (< run-start end)
2765 (let ((value (get-text-property run-start prop))
2766 (run-end (next-single-property-change
2767 run-start prop nil end)))
2768 (funcall fun value run-start run-end)
2769 (setq run-start run-end)))))
2770 (if (eq yank-excluded-properties t)
2771 (set-text-properties start end nil)
2772 (remove-list-of-text-properties start end yank-excluded-properties))))
2774 (defvar yank-undo-function)
2776 (defun insert-for-yank (string)
2777 "Call `insert-for-yank-1' repetitively for each `yank-handler' segment.
2779 See `insert-for-yank-1' for more details."
2780 (let (to)
2781 (while (setq to (next-single-property-change 0 'yank-handler string))
2782 (insert-for-yank-1 (substring string 0 to))
2783 (setq string (substring string to))))
2784 (insert-for-yank-1 string))
2786 (defun insert-for-yank-1 (string)
2787 "Insert STRING at point for the `yank' command.
2788 This function is like `insert', except it honors the variables
2789 `yank-handled-properties' and `yank-excluded-properties', and the
2790 `yank-handler' text property.
2792 Properties listed in `yank-handled-properties' are processed,
2793 then those listed in `yank-excluded-properties' are discarded.
2795 If STRING has a non-nil `yank-handler' property on its first
2796 character, the normal insert behavior is altered. The value of
2797 the `yank-handler' property must be a list of one to four
2798 elements, of the form (FUNCTION PARAM NOEXCLUDE UNDO).
2799 FUNCTION, if non-nil, should be a function of one argument, an
2800 object to insert; it is called instead of `insert'.
2801 PARAM, if present and non-nil, replaces STRING as the argument to
2802 FUNCTION or `insert'; e.g. if FUNCTION is `yank-rectangle', PARAM
2803 may be a list of strings to insert as a rectangle.
2804 If NOEXCLUDE is present and non-nil, the normal removal of
2805 `yank-excluded-properties' is not performed; instead FUNCTION is
2806 responsible for the removal. This may be necessary if FUNCTION
2807 adjusts point before or after inserting the object.
2808 UNDO, if present and non-nil, should be a function to be called
2809 by `yank-pop' to undo the insertion of the current object. It is
2810 given two arguments, the start and end of the region. FUNCTION
2811 may set `yank-undo-function' to override UNDO."
2812 (let* ((handler (and (stringp string)
2813 (get-text-property 0 'yank-handler string)))
2814 (param (or (nth 1 handler) string))
2815 (opoint (point))
2816 (inhibit-read-only inhibit-read-only)
2817 end)
2819 (setq yank-undo-function t)
2820 (if (nth 0 handler) ; FUNCTION
2821 (funcall (car handler) param)
2822 (insert param))
2823 (setq end (point))
2825 ;; Prevent read-only properties from interfering with the
2826 ;; following text property changes.
2827 (setq inhibit-read-only t)
2829 (unless (nth 2 handler) ; NOEXCLUDE
2830 (remove-yank-excluded-properties opoint end))
2832 ;; If last inserted char has properties, mark them as rear-nonsticky.
2833 (if (and (> end opoint)
2834 (text-properties-at (1- end)))
2835 (put-text-property (1- end) end 'rear-nonsticky t))
2837 (if (eq yank-undo-function t) ; not set by FUNCTION
2838 (setq yank-undo-function (nth 3 handler))) ; UNDO
2839 (if (nth 4 handler) ; COMMAND
2840 (setq this-command (nth 4 handler)))))
2842 (defun insert-buffer-substring-no-properties (buffer &optional start end)
2843 "Insert before point a substring of BUFFER, without text properties.
2844 BUFFER may be a buffer or a buffer name.
2845 Arguments START and END are character positions specifying the substring.
2846 They default to the values of (point-min) and (point-max) in BUFFER."
2847 (let ((opoint (point)))
2848 (insert-buffer-substring buffer start end)
2849 (let ((inhibit-read-only t))
2850 (set-text-properties opoint (point) nil))))
2852 (defun insert-buffer-substring-as-yank (buffer &optional start end)
2853 "Insert before point a part of BUFFER, stripping some text properties.
2854 BUFFER may be a buffer or a buffer name.
2855 Arguments START and END are character positions specifying the substring.
2856 They default to the values of (point-min) and (point-max) in BUFFER.
2857 Before insertion, process text properties according to
2858 `yank-handled-properties' and `yank-excluded-properties'."
2859 ;; Since the buffer text should not normally have yank-handler properties,
2860 ;; there is no need to handle them here.
2861 (let ((opoint (point)))
2862 (insert-buffer-substring buffer start end)
2863 (remove-yank-excluded-properties opoint (point))))
2865 (defun yank-handle-font-lock-face-property (face start end)
2866 "If `font-lock-defaults' is nil, apply FACE as a `face' property.
2867 START and END denote the start and end of the text to act on.
2868 Do nothing if FACE is nil."
2869 (and face
2870 (null font-lock-defaults)
2871 (put-text-property start end 'face face)))
2873 ;; This removes `mouse-face' properties in *Help* buffer buttons:
2874 ;; http://lists.gnu.org/archive/html/emacs-devel/2002-04/msg00648.html
2875 (defun yank-handle-category-property (category start end)
2876 "Apply property category CATEGORY's properties between START and END."
2877 (when category
2878 (let ((start2 start))
2879 (while (< start2 end)
2880 (let ((end2 (next-property-change start2 nil end))
2881 (original (text-properties-at start2)))
2882 (set-text-properties start2 end2 (symbol-plist category))
2883 (add-text-properties start2 end2 original)
2884 (setq start2 end2))))))
2887 ;;;; Synchronous shell commands.
2889 (defun start-process-shell-command (name buffer &rest args)
2890 "Start a program in a subprocess. Return the process object for it.
2891 NAME is name for process. It is modified if necessary to make it unique.
2892 BUFFER is the buffer (or buffer name) to associate with the process.
2893 Process output goes at end of that buffer, unless you specify
2894 an output stream or filter function to handle the output.
2895 BUFFER may be also nil, meaning that this process is not associated
2896 with any buffer
2897 COMMAND is the shell command to run.
2899 An old calling convention accepted any number of arguments after COMMAND,
2900 which were just concatenated to COMMAND. This is still supported but strongly
2901 discouraged."
2902 (declare (advertised-calling-convention (name buffer command) "23.1"))
2903 ;; We used to use `exec' to replace the shell with the command,
2904 ;; but that failed to handle (...) and semicolon, etc.
2905 (start-process name buffer shell-file-name shell-command-switch
2906 (mapconcat 'identity args " ")))
2908 (defun start-file-process-shell-command (name buffer &rest args)
2909 "Start a program in a subprocess. Return the process object for it.
2910 Similar to `start-process-shell-command', but calls `start-file-process'."
2911 (declare (advertised-calling-convention (name buffer command) "23.1"))
2912 (start-file-process
2913 name buffer
2914 (if (file-remote-p default-directory) "/bin/sh" shell-file-name)
2915 (if (file-remote-p default-directory) "-c" shell-command-switch)
2916 (mapconcat 'identity args " ")))
2918 (defun call-process-shell-command (command &optional infile buffer display
2919 &rest args)
2920 "Execute the shell command COMMAND synchronously in separate process.
2921 The remaining arguments are optional.
2922 The program's input comes from file INFILE (nil means `/dev/null').
2923 Insert output in BUFFER before point; t means current buffer;
2924 nil for BUFFER means discard it; 0 means discard and don't wait.
2925 BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,
2926 REAL-BUFFER says what to do with standard output, as above,
2927 while STDERR-FILE says what to do with standard error in the child.
2928 STDERR-FILE may be nil (discard standard error output),
2929 t (mix it with ordinary output), or a file name string.
2931 Fourth arg DISPLAY non-nil means redisplay buffer as output is inserted.
2932 Wildcards and redirection are handled as usual in the shell.
2934 If BUFFER is 0, `call-process-shell-command' returns immediately with value nil.
2935 Otherwise it waits for COMMAND to terminate and returns a numeric exit
2936 status or a signal description string.
2937 If you quit, the process is killed with SIGINT, or SIGKILL if you quit again.
2939 An old calling convention accepted any number of arguments after DISPLAY,
2940 which were just concatenated to COMMAND. This is still supported but strongly
2941 discouraged."
2942 (declare (advertised-calling-convention
2943 (command &optional infile buffer display) "24.5"))
2944 ;; We used to use `exec' to replace the shell with the command,
2945 ;; but that failed to handle (...) and semicolon, etc.
2946 (call-process shell-file-name
2947 infile buffer display
2948 shell-command-switch
2949 (mapconcat 'identity (cons command args) " ")))
2951 (defun process-file-shell-command (command &optional infile buffer display
2952 &rest args)
2953 "Process files synchronously in a separate process.
2954 Similar to `call-process-shell-command', but calls `process-file'."
2955 (declare (advertised-calling-convention
2956 (command &optional infile buffer display) "24.5"))
2957 (process-file
2958 (if (file-remote-p default-directory) "/bin/sh" shell-file-name)
2959 infile buffer display
2960 (if (file-remote-p default-directory) "-c" shell-command-switch)
2961 (mapconcat 'identity (cons command args) " ")))
2963 ;;;; Lisp macros to do various things temporarily.
2965 (defmacro track-mouse (&rest body)
2966 "Evaluate BODY with mouse movement events enabled.
2967 Within a `track-mouse' form, mouse motion generates input events that
2968 you can read with `read-event'.
2969 Normally, mouse motion is ignored."
2970 (declare (debug t) (indent 0))
2971 `(internal--track-mouse (lambda () ,@body)))
2973 (defmacro with-current-buffer (buffer-or-name &rest body)
2974 "Execute the forms in BODY with BUFFER-OR-NAME temporarily current.
2975 BUFFER-OR-NAME must be a buffer or the name of an existing buffer.
2976 The value returned is the value of the last form in BODY. See
2977 also `with-temp-buffer'."
2978 (declare (indent 1) (debug t))
2979 `(save-current-buffer
2980 (set-buffer ,buffer-or-name)
2981 ,@body))
2983 (defun internal--before-with-selected-window (window)
2984 (let ((other-frame (window-frame window)))
2985 (list window (selected-window)
2986 ;; Selecting a window on another frame also changes that
2987 ;; frame's frame-selected-window. We must save&restore it.
2988 (unless (eq (selected-frame) other-frame)
2989 (frame-selected-window other-frame))
2990 ;; Also remember the top-frame if on ttys.
2991 (unless (eq (selected-frame) other-frame)
2992 (tty-top-frame other-frame)))))
2994 (defun internal--after-with-selected-window (state)
2995 ;; First reset frame-selected-window.
2996 (when (window-live-p (nth 2 state))
2997 ;; We don't use set-frame-selected-window because it does not
2998 ;; pass the `norecord' argument to Fselect_window.
2999 (select-window (nth 2 state) 'norecord)
3000 (and (frame-live-p (nth 3 state))
3001 (not (eq (tty-top-frame) (nth 3 state)))
3002 (select-frame (nth 3 state) 'norecord)))
3003 ;; Then reset the actual selected-window.
3004 (when (window-live-p (nth 1 state))
3005 (select-window (nth 1 state) 'norecord)))
3007 (defmacro with-selected-window (window &rest body)
3008 "Execute the forms in BODY with WINDOW as the selected window.
3009 The value returned is the value of the last form in BODY.
3011 This macro saves and restores the selected window, as well as the
3012 selected window of each frame. It does not change the order of
3013 recently selected windows. If the previously selected window of
3014 some frame is no longer live at the end of BODY, that frame's
3015 selected window is left alone. If the selected window is no
3016 longer live, then whatever window is selected at the end of BODY
3017 remains selected.
3019 This macro uses `save-current-buffer' to save and restore the
3020 current buffer, since otherwise its normal operation could
3021 potentially make a different buffer current. It does not alter
3022 the buffer list ordering."
3023 (declare (indent 1) (debug t))
3024 `(let ((save-selected-window--state
3025 (internal--before-with-selected-window ,window)))
3026 (save-current-buffer
3027 (unwind-protect
3028 (progn (select-window (car save-selected-window--state) 'norecord)
3029 ,@body)
3030 (internal--after-with-selected-window save-selected-window--state)))))
3032 (defmacro with-selected-frame (frame &rest body)
3033 "Execute the forms in BODY with FRAME as the selected frame.
3034 The value returned is the value of the last form in BODY.
3036 This macro saves and restores the selected frame, and changes the
3037 order of neither the recently selected windows nor the buffers in
3038 the buffer list."
3039 (declare (indent 1) (debug t))
3040 (let ((old-frame (make-symbol "old-frame"))
3041 (old-buffer (make-symbol "old-buffer")))
3042 `(let ((,old-frame (selected-frame))
3043 (,old-buffer (current-buffer)))
3044 (unwind-protect
3045 (progn (select-frame ,frame 'norecord)
3046 ,@body)
3047 (when (frame-live-p ,old-frame)
3048 (select-frame ,old-frame 'norecord))
3049 (when (buffer-live-p ,old-buffer)
3050 (set-buffer ,old-buffer))))))
3052 (defmacro save-window-excursion (&rest body)
3053 "Execute BODY, then restore previous window configuration.
3054 This macro saves the window configuration on the selected frame,
3055 executes BODY, then calls `set-window-configuration' to restore
3056 the saved window configuration. The return value is the last
3057 form in BODY. The window configuration is also restored if BODY
3058 exits nonlocally.
3060 BEWARE: Most uses of this macro introduce bugs.
3061 E.g. it should not be used to try and prevent some code from opening
3062 a new window, since that window may sometimes appear in another frame,
3063 in which case `save-window-excursion' cannot help."
3064 (declare (indent 0) (debug t))
3065 (let ((c (make-symbol "wconfig")))
3066 `(let ((,c (current-window-configuration)))
3067 (unwind-protect (progn ,@body)
3068 (set-window-configuration ,c)))))
3070 (defun internal-temp-output-buffer-show (buffer)
3071 "Internal function for `with-output-to-temp-buffer'."
3072 (with-current-buffer buffer
3073 (set-buffer-modified-p nil)
3074 (goto-char (point-min)))
3076 (if temp-buffer-show-function
3077 (funcall temp-buffer-show-function buffer)
3078 (with-current-buffer buffer
3079 (let* ((window
3080 (let ((window-combination-limit
3081 ;; When `window-combination-limit' equals
3082 ;; `temp-buffer' or `temp-buffer-resize' and
3083 ;; `temp-buffer-resize-mode' is enabled in this
3084 ;; buffer bind it to t so resizing steals space
3085 ;; preferably from the window that was split.
3086 (if (or (eq window-combination-limit 'temp-buffer)
3087 (and (eq window-combination-limit
3088 'temp-buffer-resize)
3089 temp-buffer-resize-mode))
3091 window-combination-limit)))
3092 (display-buffer buffer)))
3093 (frame (and window (window-frame window))))
3094 (when window
3095 (unless (eq frame (selected-frame))
3096 (make-frame-visible frame))
3097 (setq minibuffer-scroll-window window)
3098 (set-window-hscroll window 0)
3099 ;; Don't try this with NOFORCE non-nil!
3100 (set-window-start window (point-min) t)
3101 ;; This should not be necessary.
3102 (set-window-point window (point-min))
3103 ;; Run `temp-buffer-show-hook', with the chosen window selected.
3104 (with-selected-window window
3105 (run-hooks 'temp-buffer-show-hook))))))
3106 ;; Return nil.
3107 nil)
3109 ;; Doc is very similar to with-temp-buffer-window.
3110 (defmacro with-output-to-temp-buffer (bufname &rest body)
3111 "Bind `standard-output' to buffer BUFNAME, eval BODY, then show that buffer.
3113 This construct makes buffer BUFNAME empty before running BODY.
3114 It does not make the buffer current for BODY.
3115 Instead it binds `standard-output' to that buffer, so that output
3116 generated with `prin1' and similar functions in BODY goes into
3117 the buffer.
3119 At the end of BODY, this marks buffer BUFNAME unmodified and displays
3120 it in a window, but does not select it. The normal way to do this is
3121 by calling `display-buffer', then running `temp-buffer-show-hook'.
3122 However, if `temp-buffer-show-function' is non-nil, it calls that
3123 function instead (and does not run `temp-buffer-show-hook'). The
3124 function gets one argument, the buffer to display.
3126 The return value of `with-output-to-temp-buffer' is the value of the
3127 last form in BODY. If BODY does not finish normally, the buffer
3128 BUFNAME is not displayed.
3130 This runs the hook `temp-buffer-setup-hook' before BODY,
3131 with the buffer BUFNAME temporarily current. It runs the hook
3132 `temp-buffer-show-hook' after displaying buffer BUFNAME, with that
3133 buffer temporarily current, and the window that was used to display it
3134 temporarily selected. But it doesn't run `temp-buffer-show-hook'
3135 if it uses `temp-buffer-show-function'.
3137 By default, the setup hook puts the buffer into Help mode before running BODY.
3138 If BODY does not change the major mode, the show hook makes the buffer
3139 read-only, and scans it for function and variable names to make them into
3140 clickable cross-references.
3142 See the related form `with-temp-buffer-window'."
3143 (declare (debug t))
3144 (let ((old-dir (make-symbol "old-dir"))
3145 (buf (make-symbol "buf")))
3146 `(let* ((,old-dir default-directory)
3147 (,buf
3148 (with-current-buffer (get-buffer-create ,bufname)
3149 (prog1 (current-buffer)
3150 (kill-all-local-variables)
3151 ;; FIXME: delete_all_overlays
3152 (setq default-directory ,old-dir)
3153 (setq buffer-read-only nil)
3154 (setq buffer-file-name nil)
3155 (setq buffer-undo-list t)
3156 (let ((inhibit-read-only t)
3157 (inhibit-modification-hooks t))
3158 (erase-buffer)
3159 (run-hooks 'temp-buffer-setup-hook)))))
3160 (standard-output ,buf))
3161 (prog1 (progn ,@body)
3162 (internal-temp-output-buffer-show ,buf)))))
3164 (defmacro with-temp-file (file &rest body)
3165 "Create a new buffer, evaluate BODY there, and write the buffer to FILE.
3166 The value returned is the value of the last form in BODY.
3167 See also `with-temp-buffer'."
3168 (declare (indent 1) (debug t))
3169 (let ((temp-file (make-symbol "temp-file"))
3170 (temp-buffer (make-symbol "temp-buffer")))
3171 `(let ((,temp-file ,file)
3172 (,temp-buffer
3173 (get-buffer-create (generate-new-buffer-name " *temp file*"))))
3174 (unwind-protect
3175 (prog1
3176 (with-current-buffer ,temp-buffer
3177 ,@body)
3178 (with-current-buffer ,temp-buffer
3179 (write-region nil nil ,temp-file nil 0)))
3180 (and (buffer-name ,temp-buffer)
3181 (kill-buffer ,temp-buffer))))))
3183 (defmacro with-temp-message (message &rest body)
3184 "Display MESSAGE temporarily if non-nil while BODY is evaluated.
3185 The original message is restored to the echo area after BODY has finished.
3186 The value returned is the value of the last form in BODY.
3187 MESSAGE is written to the message log buffer if `message-log-max' is non-nil.
3188 If MESSAGE is nil, the echo area and message log buffer are unchanged.
3189 Use a MESSAGE of \"\" to temporarily clear the echo area."
3190 (declare (debug t) (indent 1))
3191 (let ((current-message (make-symbol "current-message"))
3192 (temp-message (make-symbol "with-temp-message")))
3193 `(let ((,temp-message ,message)
3194 (,current-message))
3195 (unwind-protect
3196 (progn
3197 (when ,temp-message
3198 (setq ,current-message (current-message))
3199 (message "%s" ,temp-message))
3200 ,@body)
3201 (and ,temp-message
3202 (if ,current-message
3203 (message "%s" ,current-message)
3204 (message nil)))))))
3206 (defmacro with-temp-buffer (&rest body)
3207 "Create a temporary buffer, and evaluate BODY there like `progn'.
3208 See also `with-temp-file' and `with-output-to-string'."
3209 (declare (indent 0) (debug t))
3210 (let ((temp-buffer (make-symbol "temp-buffer")))
3211 `(let ((,temp-buffer (generate-new-buffer " *temp*")))
3212 ;; FIXME: kill-buffer can change current-buffer in some odd cases.
3213 (with-current-buffer ,temp-buffer
3214 (unwind-protect
3215 (progn ,@body)
3216 (and (buffer-name ,temp-buffer)
3217 (kill-buffer ,temp-buffer)))))))
3219 (defmacro with-silent-modifications (&rest body)
3220 "Execute BODY, pretending it does not modify the buffer.
3221 If BODY performs real modifications to the buffer's text, other
3222 than cosmetic ones, undo data may become corrupted.
3224 This macro will run BODY normally, but doesn't count its buffer
3225 modifications as being buffer modifications. This affects things
3226 like `buffer-modified-p', checking whether the file is locked by
3227 someone else, running buffer modification hooks, and other things
3228 of that nature.
3230 Typically used around modifications of text-properties which do
3231 not really affect the buffer's content."
3232 (declare (debug t) (indent 0))
3233 (let ((modified (make-symbol "modified")))
3234 `(let* ((,modified (buffer-modified-p))
3235 (buffer-undo-list t)
3236 (inhibit-read-only t)
3237 (inhibit-modification-hooks t))
3238 (unwind-protect
3239 (progn
3240 ,@body)
3241 (unless ,modified
3242 (restore-buffer-modified-p nil))))))
3244 (defmacro with-output-to-string (&rest body)
3245 "Execute BODY, return the text it sent to `standard-output', as a string."
3246 (declare (indent 0) (debug t))
3247 `(let ((standard-output
3248 (get-buffer-create (generate-new-buffer-name " *string-output*"))))
3249 (unwind-protect
3250 (progn
3251 (let ((standard-output standard-output))
3252 ,@body)
3253 (with-current-buffer standard-output
3254 (buffer-string)))
3255 (kill-buffer standard-output))))
3257 (defmacro with-local-quit (&rest body)
3258 "Execute BODY, allowing quits to terminate BODY but not escape further.
3259 When a quit terminates BODY, `with-local-quit' returns nil but
3260 requests another quit. That quit will be processed as soon as quitting
3261 is allowed once again. (Immediately, if `inhibit-quit' is nil.)"
3262 (declare (debug t) (indent 0))
3263 `(condition-case nil
3264 (let ((inhibit-quit nil))
3265 ,@body)
3266 (quit (setq quit-flag t)
3267 ;; This call is to give a chance to handle quit-flag
3268 ;; in case inhibit-quit is nil.
3269 ;; Without this, it will not be handled until the next function
3270 ;; call, and that might allow it to exit thru a condition-case
3271 ;; that intends to handle the quit signal next time.
3272 (eval '(ignore nil)))))
3274 (defmacro while-no-input (&rest body)
3275 "Execute BODY only as long as there's no pending input.
3276 If input arrives, that ends the execution of BODY,
3277 and `while-no-input' returns t. Quitting makes it return nil.
3278 If BODY finishes, `while-no-input' returns whatever value BODY produced."
3279 (declare (debug t) (indent 0))
3280 (let ((catch-sym (make-symbol "input")))
3281 `(with-local-quit
3282 (catch ',catch-sym
3283 (let ((throw-on-input ',catch-sym))
3284 (or (input-pending-p)
3285 (progn ,@body)))))))
3287 (defmacro condition-case-unless-debug (var bodyform &rest handlers)
3288 "Like `condition-case' except that it does not prevent debugging.
3289 More specifically if `debug-on-error' is set then the debugger will be invoked
3290 even if this catches the signal."
3291 (declare (debug condition-case) (indent 2))
3292 `(condition-case ,var
3293 ,bodyform
3294 ,@(mapcar (lambda (handler)
3295 `((debug ,@(if (listp (car handler)) (car handler)
3296 (list (car handler))))
3297 ,@(cdr handler)))
3298 handlers)))
3300 (define-obsolete-function-alias 'condition-case-no-debug
3301 'condition-case-unless-debug "24.1")
3303 (defmacro with-demoted-errors (format &rest body)
3304 "Run BODY and demote any errors to simple messages.
3305 FORMAT is a string passed to `message' to format any error message.
3306 It should contain a single %-sequence; e.g., \"Error: %S\".
3308 If `debug-on-error' is non-nil, run BODY without catching its errors.
3309 This is to be used around code which is not expected to signal an error
3310 but which should be robust in the unexpected case that an error is signaled.
3312 For backward compatibility, if FORMAT is not a constant string, it
3313 is assumed to be part of BODY, in which case the message format
3314 used is \"Error: %S\"."
3315 (declare (debug t) (indent 1))
3316 (let ((err (make-symbol "err"))
3317 (format (if (and (stringp format) body) format
3318 (prog1 "Error: %S"
3319 (if format (push format body))))))
3320 `(condition-case-unless-debug ,err
3321 ,(macroexp-progn body)
3322 (error (message ,format ,err) nil))))
3324 (defmacro combine-after-change-calls (&rest body)
3325 "Execute BODY, but don't call the after-change functions till the end.
3326 If BODY makes changes in the buffer, they are recorded
3327 and the functions on `after-change-functions' are called several times
3328 when BODY is finished.
3329 The return value is the value of the last form in BODY.
3331 If `before-change-functions' is non-nil, then calls to the after-change
3332 functions can't be deferred, so in that case this macro has no effect.
3334 Do not alter `after-change-functions' or `before-change-functions'
3335 in BODY."
3336 (declare (indent 0) (debug t))
3337 `(unwind-protect
3338 (let ((combine-after-change-calls t))
3339 . ,body)
3340 (combine-after-change-execute)))
3342 (defmacro with-case-table (table &rest body)
3343 "Execute the forms in BODY with TABLE as the current case table.
3344 The value returned is the value of the last form in BODY."
3345 (declare (indent 1) (debug t))
3346 (let ((old-case-table (make-symbol "table"))
3347 (old-buffer (make-symbol "buffer")))
3348 `(let ((,old-case-table (current-case-table))
3349 (,old-buffer (current-buffer)))
3350 (unwind-protect
3351 (progn (set-case-table ,table)
3352 ,@body)
3353 (with-current-buffer ,old-buffer
3354 (set-case-table ,old-case-table))))))
3356 (defmacro with-file-modes (modes &rest body)
3357 "Execute BODY with default file permissions temporarily set to MODES.
3358 MODES is as for `set-default-file-modes'."
3359 (declare (indent 1) (debug t))
3360 (let ((umask (make-symbol "umask")))
3361 `(let ((,umask (default-file-modes)))
3362 (unwind-protect
3363 (progn
3364 (set-default-file-modes ,modes)
3365 ,@body)
3366 (set-default-file-modes ,umask)))))
3369 ;;; Matching and match data.
3371 (defvar save-match-data-internal)
3373 ;; We use save-match-data-internal as the local variable because
3374 ;; that works ok in practice (people should not use that variable elsewhere).
3375 ;; We used to use an uninterned symbol; the compiler handles that properly
3376 ;; now, but it generates slower code.
3377 (defmacro save-match-data (&rest body)
3378 "Execute the BODY forms, restoring the global value of the match data.
3379 The value returned is the value of the last form in BODY."
3380 ;; It is better not to use backquote here,
3381 ;; because that makes a bootstrapping problem
3382 ;; if you need to recompile all the Lisp files using interpreted code.
3383 (declare (indent 0) (debug t))
3384 (list 'let
3385 '((save-match-data-internal (match-data)))
3386 (list 'unwind-protect
3387 (cons 'progn body)
3388 ;; It is safe to free (evaporate) markers immediately here,
3389 ;; as Lisp programs should not copy from save-match-data-internal.
3390 '(set-match-data save-match-data-internal 'evaporate))))
3392 (defun match-string (num &optional string)
3393 "Return string of text matched by last search.
3394 NUM specifies which parenthesized expression in the last regexp.
3395 Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
3396 Zero means the entire text matched by the whole regexp or whole string.
3397 STRING should be given if the last search was by `string-match' on STRING.
3398 If STRING is nil, the current buffer should be the same buffer
3399 the search/match was performed in."
3400 (if (match-beginning num)
3401 (if string
3402 (substring string (match-beginning num) (match-end num))
3403 (buffer-substring (match-beginning num) (match-end num)))))
3405 (defun match-string-no-properties (num &optional string)
3406 "Return string of text matched by last search, without text properties.
3407 NUM specifies which parenthesized expression in the last regexp.
3408 Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
3409 Zero means the entire text matched by the whole regexp or whole string.
3410 STRING should be given if the last search was by `string-match' on STRING.
3411 If STRING is nil, the current buffer should be the same buffer
3412 the search/match was performed in."
3413 (if (match-beginning num)
3414 (if string
3415 (substring-no-properties string (match-beginning num)
3416 (match-end num))
3417 (buffer-substring-no-properties (match-beginning num)
3418 (match-end num)))))
3421 (defun match-substitute-replacement (replacement
3422 &optional fixedcase literal string subexp)
3423 "Return REPLACEMENT as it will be inserted by `replace-match'.
3424 In other words, all back-references in the form `\\&' and `\\N'
3425 are substituted with actual strings matched by the last search.
3426 Optional FIXEDCASE, LITERAL, STRING and SUBEXP have the same
3427 meaning as for `replace-match'."
3428 (let ((match (match-string 0 string)))
3429 (save-match-data
3430 (set-match-data (mapcar (lambda (x)
3431 (if (numberp x)
3432 (- x (match-beginning 0))
3434 (match-data t)))
3435 (replace-match replacement fixedcase literal match subexp))))
3438 (defun looking-back (regexp &optional limit greedy)
3439 "Return non-nil if text before point matches regular expression REGEXP.
3440 Like `looking-at' except matches before point, and is slower.
3441 LIMIT if non-nil speeds up the search by specifying a minimum
3442 starting position, to avoid checking matches that would start
3443 before LIMIT.
3445 If GREEDY is non-nil, extend the match backwards as far as
3446 possible, stopping when a single additional previous character
3447 cannot be part of a match for REGEXP. When the match is
3448 extended, its starting position is allowed to occur before
3449 LIMIT.
3451 As a general recommendation, try to avoid using `looking-back'
3452 wherever possible, since it is slow."
3453 (let ((start (point))
3454 (pos
3455 (save-excursion
3456 (and (re-search-backward (concat "\\(?:" regexp "\\)\\=") limit t)
3457 (point)))))
3458 (if (and greedy pos)
3459 (save-restriction
3460 (narrow-to-region (point-min) start)
3461 (while (and (> pos (point-min))
3462 (save-excursion
3463 (goto-char pos)
3464 (backward-char 1)
3465 (looking-at (concat "\\(?:" regexp "\\)\\'"))))
3466 (setq pos (1- pos)))
3467 (save-excursion
3468 (goto-char pos)
3469 (looking-at (concat "\\(?:" regexp "\\)\\'")))))
3470 (not (null pos))))
3472 (defsubst looking-at-p (regexp)
3474 Same as `looking-at' except this function does not change the match data."
3475 (let ((inhibit-changing-match-data t))
3476 (looking-at regexp)))
3478 (defsubst string-match-p (regexp string &optional start)
3480 Same as `string-match' except this function does not change the match data."
3481 (let ((inhibit-changing-match-data t))
3482 (string-match regexp string start)))
3484 (defun subregexp-context-p (regexp pos &optional start)
3485 "Return non-nil if POS is in a normal subregexp context in REGEXP.
3486 A subregexp context is one where a sub-regexp can appear.
3487 A non-subregexp context is for example within brackets, or within a
3488 repetition bounds operator `\\=\\{...\\}', or right after a `\\'.
3489 If START is non-nil, it should be a position in REGEXP, smaller
3490 than POS, and known to be in a subregexp context."
3491 ;; Here's one possible implementation, with the great benefit that it
3492 ;; reuses the regexp-matcher's own parser, so it understands all the
3493 ;; details of the syntax. A disadvantage is that it needs to match the
3494 ;; error string.
3495 (condition-case err
3496 (progn
3497 (string-match (substring regexp (or start 0) pos) "")
3499 (invalid-regexp
3500 (not (member (cadr err) '("Unmatched [ or [^"
3501 "Unmatched \\{"
3502 "Trailing backslash")))))
3503 ;; An alternative implementation:
3504 ;; (defconst re-context-re
3505 ;; (let* ((harmless-ch "[^\\[]")
3506 ;; (harmless-esc "\\\\[^{]")
3507 ;; (class-harmless-ch "[^][]")
3508 ;; (class-lb-harmless "[^]:]")
3509 ;; (class-lb-colon-maybe-charclass ":\\([a-z]+:]\\)?")
3510 ;; (class-lb (concat "\\[\\(" class-lb-harmless
3511 ;; "\\|" class-lb-colon-maybe-charclass "\\)"))
3512 ;; (class
3513 ;; (concat "\\[^?]?"
3514 ;; "\\(" class-harmless-ch
3515 ;; "\\|" class-lb "\\)*"
3516 ;; "\\[?]")) ; special handling for bare [ at end of re
3517 ;; (braces "\\\\{[0-9,]+\\\\}"))
3518 ;; (concat "\\`\\(" harmless-ch "\\|" harmless-esc
3519 ;; "\\|" class "\\|" braces "\\)*\\'"))
3520 ;; "Matches any prefix that corresponds to a normal subregexp context.")
3521 ;; (string-match re-context-re (substring regexp (or start 0) pos))
3524 ;;;; split-string
3526 (defconst split-string-default-separators "[ \f\t\n\r\v]+"
3527 "The default value of separators for `split-string'.
3529 A regexp matching strings of whitespace. May be locale-dependent
3530 \(as yet unimplemented). Should not match non-breaking spaces.
3532 Warning: binding this to a different value and using it as default is
3533 likely to have undesired semantics.")
3535 ;; The specification says that if both SEPARATORS and OMIT-NULLS are
3536 ;; defaulted, OMIT-NULLS should be treated as t. Simplifying the logical
3537 ;; expression leads to the equivalent implementation that if SEPARATORS
3538 ;; is defaulted, OMIT-NULLS is treated as t.
3539 (defun split-string (string &optional separators omit-nulls trim)
3540 "Split STRING into substrings bounded by matches for SEPARATORS.
3542 The beginning and end of STRING, and each match for SEPARATORS, are
3543 splitting points. The substrings matching SEPARATORS are removed, and
3544 the substrings between the splitting points are collected as a list,
3545 which is returned.
3547 If SEPARATORS is non-nil, it should be a regular expression matching text
3548 which separates, but is not part of, the substrings. If nil it defaults to
3549 `split-string-default-separators', normally \"[ \\f\\t\\n\\r\\v]+\", and
3550 OMIT-NULLS is forced to t.
3552 If OMIT-NULLS is t, zero-length substrings are omitted from the list (so
3553 that for the default value of SEPARATORS leading and trailing whitespace
3554 are effectively trimmed). If nil, all zero-length substrings are retained,
3555 which correctly parses CSV format, for example.
3557 If TRIM is non-nil, it should be a regular expression to match
3558 text to trim from the beginning and end of each substring. If trimming
3559 makes the substring empty, it is treated as null.
3561 If you want to trim whitespace from the substrings, the reliably correct
3562 way is using TRIM. Making SEPARATORS match that whitespace gives incorrect
3563 results when there is whitespace at the start or end of STRING. If you
3564 see such calls to `split-string', please fix them.
3566 Note that the effect of `(split-string STRING)' is the same as
3567 `(split-string STRING split-string-default-separators t)'. In the rare
3568 case that you wish to retain zero-length substrings when splitting on
3569 whitespace, use `(split-string STRING split-string-default-separators)'.
3571 Modifies the match data; use `save-match-data' if necessary."
3572 (let* ((keep-nulls (not (if separators omit-nulls t)))
3573 (rexp (or separators split-string-default-separators))
3574 (start 0)
3575 this-start this-end
3576 notfirst
3577 (list nil)
3578 (push-one
3579 ;; Push the substring in range THIS-START to THIS-END
3580 ;; onto LIST, trimming it and perhaps discarding it.
3581 (lambda ()
3582 (when trim
3583 ;; Discard the trim from start of this substring.
3584 (let ((tem (string-match trim string this-start)))
3585 (and (eq tem this-start)
3586 (setq this-start (match-end 0)))))
3588 (when (or keep-nulls (< this-start this-end))
3589 (let ((this (substring string this-start this-end)))
3591 ;; Discard the trim from end of this substring.
3592 (when trim
3593 (let ((tem (string-match (concat trim "\\'") this 0)))
3594 (and tem (< tem (length this))
3595 (setq this (substring this 0 tem)))))
3597 ;; Trimming could make it empty; check again.
3598 (when (or keep-nulls (> (length this) 0))
3599 (push this list)))))))
3601 (while (and (string-match rexp string
3602 (if (and notfirst
3603 (= start (match-beginning 0))
3604 (< start (length string)))
3605 (1+ start) start))
3606 (< start (length string)))
3607 (setq notfirst t)
3608 (setq this-start start this-end (match-beginning 0)
3609 start (match-end 0))
3611 (funcall push-one))
3613 ;; Handle the substring at the end of STRING.
3614 (setq this-start start this-end (length string))
3615 (funcall push-one)
3617 (nreverse list)))
3619 (defun combine-and-quote-strings (strings &optional separator)
3620 "Concatenate the STRINGS, adding the SEPARATOR (default \" \").
3621 This tries to quote the strings to avoid ambiguity such that
3622 (split-string-and-unquote (combine-and-quote-strings strs)) == strs
3623 Only some SEPARATORs will work properly."
3624 (let* ((sep (or separator " "))
3625 (re (concat "[\\\"]" "\\|" (regexp-quote sep))))
3626 (mapconcat
3627 (lambda (str)
3628 (if (string-match re str)
3629 (concat "\"" (replace-regexp-in-string "[\\\"]" "\\\\\\&" str) "\"")
3630 str))
3631 strings sep)))
3633 (defun split-string-and-unquote (string &optional separator)
3634 "Split the STRING into a list of strings.
3635 It understands Emacs Lisp quoting within STRING, such that
3636 (split-string-and-unquote (combine-and-quote-strings strs)) == strs
3637 The SEPARATOR regexp defaults to \"\\s-+\"."
3638 (let ((sep (or separator "\\s-+"))
3639 (i (string-match "\"" string)))
3640 (if (null i)
3641 (split-string string sep t) ; no quoting: easy
3642 (append (unless (eq i 0) (split-string (substring string 0 i) sep t))
3643 (let ((rfs (read-from-string string i)))
3644 (cons (car rfs)
3645 (split-string-and-unquote (substring string (cdr rfs))
3646 sep)))))))
3649 ;;;; Replacement in strings.
3651 (defun subst-char-in-string (fromchar tochar string &optional inplace)
3652 "Replace FROMCHAR with TOCHAR in STRING each time it occurs.
3653 Unless optional argument INPLACE is non-nil, return a new string."
3654 (let ((i (length string))
3655 (newstr (if inplace string (copy-sequence string))))
3656 (while (> i 0)
3657 (setq i (1- i))
3658 (if (eq (aref newstr i) fromchar)
3659 (aset newstr i tochar)))
3660 newstr))
3662 (defun replace-regexp-in-string (regexp rep string &optional
3663 fixedcase literal subexp start)
3664 "Replace all matches for REGEXP with REP in STRING.
3666 Return a new string containing the replacements.
3668 Optional arguments FIXEDCASE, LITERAL and SUBEXP are like the
3669 arguments with the same names of function `replace-match'. If START
3670 is non-nil, start replacements at that index in STRING.
3672 REP is either a string used as the NEWTEXT arg of `replace-match' or a
3673 function. If it is a function, it is called with the actual text of each
3674 match, and its value is used as the replacement text. When REP is called,
3675 the match data are the result of matching REGEXP against a substring
3676 of STRING.
3678 To replace only the first match (if any), make REGEXP match up to \\'
3679 and replace a sub-expression, e.g.
3680 (replace-regexp-in-string \"\\\\(foo\\\\).*\\\\'\" \"bar\" \" foo foo\" nil nil 1)
3681 => \" bar foo\""
3683 ;; To avoid excessive consing from multiple matches in long strings,
3684 ;; don't just call `replace-match' continually. Walk down the
3685 ;; string looking for matches of REGEXP and building up a (reversed)
3686 ;; list MATCHES. This comprises segments of STRING which weren't
3687 ;; matched interspersed with replacements for segments that were.
3688 ;; [For a `large' number of replacements it's more efficient to
3689 ;; operate in a temporary buffer; we can't tell from the function's
3690 ;; args whether to choose the buffer-based implementation, though it
3691 ;; might be reasonable to do so for long enough STRING.]
3692 (let ((l (length string))
3693 (start (or start 0))
3694 matches str mb me)
3695 (save-match-data
3696 (while (and (< start l) (string-match regexp string start))
3697 (setq mb (match-beginning 0)
3698 me (match-end 0))
3699 ;; If we matched the empty string, make sure we advance by one char
3700 (when (= me mb) (setq me (min l (1+ mb))))
3701 ;; Generate a replacement for the matched substring.
3702 ;; Operate only on the substring to minimize string consing.
3703 ;; Set up match data for the substring for replacement;
3704 ;; presumably this is likely to be faster than munging the
3705 ;; match data directly in Lisp.
3706 (string-match regexp (setq str (substring string mb me)))
3707 (setq matches
3708 (cons (replace-match (if (stringp rep)
3710 (funcall rep (match-string 0 str)))
3711 fixedcase literal str subexp)
3712 (cons (substring string start mb) ; unmatched prefix
3713 matches)))
3714 (setq start me))
3715 ;; Reconstruct a string from the pieces.
3716 (setq matches (cons (substring string start l) matches)) ; leftover
3717 (apply #'concat (nreverse matches)))))
3719 (defun string-prefix-p (prefix string &optional ignore-case)
3720 "Return non-nil if PREFIX is a prefix of STRING.
3721 If IGNORE-CASE is non-nil, the comparison is done without paying attention
3722 to case differences."
3723 (let ((prefix-length (length prefix)))
3724 (if (> prefix-length (length string)) nil
3725 (eq t (compare-strings prefix 0 prefix-length string
3726 0 prefix-length ignore-case)))))
3728 (defun string-suffix-p (suffix string &optional ignore-case)
3729 "Return non-nil if SUFFIX is a suffix of STRING.
3730 If IGNORE-CASE is non-nil, the comparison is done without paying
3731 attention to case differences."
3732 (let ((start-pos (- (length string) (length suffix))))
3733 (and (>= start-pos 0)
3734 (eq t (compare-strings suffix nil nil
3735 string start-pos nil ignore-case)))))
3737 (defun bidi-string-mark-left-to-right (str)
3738 "Return a string that can be safely inserted in left-to-right text.
3740 Normally, inserting a string with right-to-left (RTL) script into
3741 a buffer may cause some subsequent text to be displayed as part
3742 of the RTL segment (usually this affects punctuation characters).
3743 This function returns a string which displays as STR but forces
3744 subsequent text to be displayed as left-to-right.
3746 If STR contains any RTL character, this function returns a string
3747 consisting of STR followed by an invisible left-to-right mark
3748 \(LRM) character. Otherwise, it returns STR."
3749 (unless (stringp str)
3750 (signal 'wrong-type-argument (list 'stringp str)))
3751 (if (string-match "\\cR" str)
3752 (concat str (propertize (string ?\x200e) 'invisible t))
3753 str))
3755 ;;;; Specifying things to do later.
3757 (defun load-history-regexp (file)
3758 "Form a regexp to find FILE in `load-history'.
3759 FILE, a string, is described in the function `eval-after-load'."
3760 (if (file-name-absolute-p file)
3761 (setq file (file-truename file)))
3762 (concat (if (file-name-absolute-p file) "\\`" "\\(\\`\\|/\\)")
3763 (regexp-quote file)
3764 (if (file-name-extension file)
3766 ;; Note: regexp-opt can't be used here, since we need to call
3767 ;; this before Emacs has been fully started. 2006-05-21
3768 (concat "\\(" (mapconcat 'regexp-quote load-suffixes "\\|") "\\)?"))
3769 "\\(" (mapconcat 'regexp-quote jka-compr-load-suffixes "\\|")
3770 "\\)?\\'"))
3772 (defun load-history-filename-element (file-regexp)
3773 "Get the first elt of `load-history' whose car matches FILE-REGEXP.
3774 Return nil if there isn't one."
3775 (let* ((loads load-history)
3776 (load-elt (and loads (car loads))))
3777 (save-match-data
3778 (while (and loads
3779 (or (null (car load-elt))
3780 (not (string-match file-regexp (car load-elt)))))
3781 (setq loads (cdr loads)
3782 load-elt (and loads (car loads)))))
3783 load-elt))
3785 (put 'eval-after-load 'lisp-indent-function 1)
3786 (defun eval-after-load (file form)
3787 "Arrange that if FILE is loaded, FORM will be run immediately afterwards.
3788 If FILE is already loaded, evaluate FORM right now.
3789 FORM can be an Elisp expression (in which case it's passed to `eval'),
3790 or a function (in which case it's passed to `funcall' with no argument).
3792 If a matching file is loaded again, FORM will be evaluated again.
3794 If FILE is a string, it may be either an absolute or a relative file
3795 name, and may have an extension (e.g. \".el\") or may lack one, and
3796 additionally may or may not have an extension denoting a compressed
3797 format (e.g. \".gz\").
3799 When FILE is absolute, this first converts it to a true name by chasing
3800 symbolic links. Only a file of this name (see next paragraph regarding
3801 extensions) will trigger the evaluation of FORM. When FILE is relative,
3802 a file whose absolute true name ends in FILE will trigger evaluation.
3804 When FILE lacks an extension, a file name with any extension will trigger
3805 evaluation. Otherwise, its extension must match FILE's. A further
3806 extension for a compressed format (e.g. \".gz\") on FILE will not affect
3807 this name matching.
3809 Alternatively, FILE can be a feature (i.e. a symbol), in which case FORM
3810 is evaluated at the end of any file that `provide's this feature.
3811 If the feature is provided when evaluating code not associated with a
3812 file, FORM is evaluated immediately after the provide statement.
3814 Usually FILE is just a library name like \"font-lock\" or a feature name
3815 like 'font-lock.
3817 This function makes or adds to an entry on `after-load-alist'."
3818 (declare (compiler-macro
3819 (lambda (whole)
3820 (if (eq 'quote (car-safe form))
3821 ;; Quote with lambda so the compiler can look inside.
3822 `(eval-after-load ,file (lambda () ,(nth 1 form)))
3823 whole))))
3824 ;; Add this FORM into after-load-alist (regardless of whether we'll be
3825 ;; evaluating it now).
3826 (let* ((regexp-or-feature
3827 (if (stringp file)
3828 (setq file (purecopy (load-history-regexp file)))
3829 file))
3830 (elt (assoc regexp-or-feature after-load-alist))
3831 (func
3832 (if (functionp form) form
3833 ;; Try to use the "current" lexical/dynamic mode for `form'.
3834 (eval `(lambda () ,form) lexical-binding))))
3835 (unless elt
3836 (setq elt (list regexp-or-feature))
3837 (push elt after-load-alist))
3838 ;; Is there an already loaded file whose name (or `provide' name)
3839 ;; matches FILE?
3840 (prog1 (if (if (stringp file)
3841 (load-history-filename-element regexp-or-feature)
3842 (featurep file))
3843 (funcall func))
3844 (let ((delayed-func
3845 (if (not (symbolp regexp-or-feature)) func
3846 ;; For features, the after-load-alist elements get run when
3847 ;; `provide' is called rather than at the end of the file.
3848 ;; So add an indirection to make sure that `func' is really run
3849 ;; "after-load" in case the provide call happens early.
3850 (lambda ()
3851 (if (not load-file-name)
3852 ;; Not being provided from a file, run func right now.
3853 (funcall func)
3854 (let ((lfn load-file-name)
3855 ;; Don't use letrec, because equal (in
3856 ;; add/remove-hook) would get trapped in a cycle.
3857 (fun (make-symbol "eval-after-load-helper")))
3858 (fset fun (lambda (file)
3859 (when (equal file lfn)
3860 (remove-hook 'after-load-functions fun)
3861 (funcall func))))
3862 (add-hook 'after-load-functions fun 'append)))))))
3863 ;; Add FORM to the element unless it's already there.
3864 (unless (member delayed-func (cdr elt))
3865 (nconc elt (list delayed-func)))))))
3867 (defmacro with-eval-after-load (file &rest body)
3868 "Execute BODY after FILE is loaded.
3869 FILE is normally a feature name, but it can also be a file name,
3870 in case that file does not provide any feature."
3871 (declare (indent 1) (debug t))
3872 `(eval-after-load ,file (lambda () ,@body)))
3874 (defvar after-load-functions nil
3875 "Special hook run after loading a file.
3876 Each function there is called with a single argument, the absolute
3877 name of the file just loaded.")
3879 (defun do-after-load-evaluation (abs-file)
3880 "Evaluate all `eval-after-load' forms, if any, for ABS-FILE.
3881 ABS-FILE, a string, should be the absolute true name of a file just loaded.
3882 This function is called directly from the C code."
3883 ;; Run the relevant eval-after-load forms.
3884 (dolist (a-l-element after-load-alist)
3885 (when (and (stringp (car a-l-element))
3886 (string-match-p (car a-l-element) abs-file))
3887 ;; discard the file name regexp
3888 (mapc #'funcall (cdr a-l-element))))
3889 ;; Complain when the user uses obsolete files.
3890 (when (save-match-data
3891 (and (string-match "/obsolete/\\([^/]*\\)\\'" abs-file)
3892 (not (equal "loaddefs.el" (match-string 1 abs-file)))))
3893 ;; Maybe we should just use display-warning? This seems yucky...
3894 (let* ((file (file-name-nondirectory abs-file))
3895 (msg (format "Package %s is obsolete!"
3896 (substring file 0
3897 (string-match "\\.elc?\\>" file)))))
3898 ;; Cribbed from cl--compiling-file.
3899 (if (and (boundp 'byte-compile--outbuffer)
3900 (bufferp (symbol-value 'byte-compile--outbuffer))
3901 (equal (buffer-name (symbol-value 'byte-compile--outbuffer))
3902 " *Compiler Output*"))
3903 ;; Don't warn about obsolete files using other obsolete files.
3904 (unless (and (stringp byte-compile-current-file)
3905 (string-match-p "/obsolete/[^/]*\\'"
3906 (expand-file-name
3907 byte-compile-current-file
3908 byte-compile-root-dir)))
3909 (byte-compile-log-warning msg))
3910 (run-with-timer 0 nil
3911 (lambda (msg)
3912 (message "%s" msg))
3913 msg))))
3915 ;; Finally, run any other hook.
3916 (run-hook-with-args 'after-load-functions abs-file))
3918 (defun eval-next-after-load (file)
3919 "Read the following input sexp, and run it whenever FILE is loaded.
3920 This makes or adds to an entry on `after-load-alist'.
3921 FILE should be the name of a library, with no directory name."
3922 (declare (obsolete eval-after-load "23.2"))
3923 (eval-after-load file (read)))
3926 (defun display-delayed-warnings ()
3927 "Display delayed warnings from `delayed-warnings-list'.
3928 Used from `delayed-warnings-hook' (which see)."
3929 (dolist (warning (nreverse delayed-warnings-list))
3930 (apply 'display-warning warning))
3931 (setq delayed-warnings-list nil))
3933 (defun collapse-delayed-warnings ()
3934 "Remove duplicates from `delayed-warnings-list'.
3935 Collapse identical adjacent warnings into one (plus count).
3936 Used from `delayed-warnings-hook' (which see)."
3937 (let ((count 1)
3938 collapsed warning)
3939 (while delayed-warnings-list
3940 (setq warning (pop delayed-warnings-list))
3941 (if (equal warning (car delayed-warnings-list))
3942 (setq count (1+ count))
3943 (when (> count 1)
3944 (setcdr warning (cons (format "%s [%d times]" (cadr warning) count)
3945 (cddr warning)))
3946 (setq count 1))
3947 (push warning collapsed)))
3948 (setq delayed-warnings-list (nreverse collapsed))))
3950 ;; At present this is only used for Emacs internals.
3951 ;; Ref http://lists.gnu.org/archive/html/emacs-devel/2012-02/msg00085.html
3952 (defvar delayed-warnings-hook '(collapse-delayed-warnings
3953 display-delayed-warnings)
3954 "Normal hook run to process and display delayed warnings.
3955 By default, this hook contains functions to consolidate the
3956 warnings listed in `delayed-warnings-list', display them, and set
3957 `delayed-warnings-list' back to nil.")
3959 (defun delay-warning (type message &optional level buffer-name)
3960 "Display a delayed warning.
3961 Aside from going through `delayed-warnings-list', this is equivalent
3962 to `display-warning'."
3963 (push (list type message level buffer-name) delayed-warnings-list))
3966 ;;;; invisibility specs
3968 (defun add-to-invisibility-spec (element)
3969 "Add ELEMENT to `buffer-invisibility-spec'.
3970 See documentation for `buffer-invisibility-spec' for the kind of elements
3971 that can be added."
3972 (if (eq buffer-invisibility-spec t)
3973 (setq buffer-invisibility-spec (list t)))
3974 (setq buffer-invisibility-spec
3975 (cons element buffer-invisibility-spec)))
3977 (defun remove-from-invisibility-spec (element)
3978 "Remove ELEMENT from `buffer-invisibility-spec'."
3979 (if (consp buffer-invisibility-spec)
3980 (setq buffer-invisibility-spec
3981 (delete element buffer-invisibility-spec))))
3983 ;;;; Syntax tables.
3985 (defmacro with-syntax-table (table &rest body)
3986 "Evaluate BODY with syntax table of current buffer set to TABLE.
3987 The syntax table of the current buffer is saved, BODY is evaluated, and the
3988 saved table is restored, even in case of an abnormal exit.
3989 Value is what BODY returns."
3990 (declare (debug t) (indent 1))
3991 (let ((old-table (make-symbol "table"))
3992 (old-buffer (make-symbol "buffer")))
3993 `(let ((,old-table (syntax-table))
3994 (,old-buffer (current-buffer)))
3995 (unwind-protect
3996 (progn
3997 (set-syntax-table ,table)
3998 ,@body)
3999 (save-current-buffer
4000 (set-buffer ,old-buffer)
4001 (set-syntax-table ,old-table))))))
4003 (defun make-syntax-table (&optional oldtable)
4004 "Return a new syntax table.
4005 Create a syntax table which inherits from OLDTABLE (if non-nil) or
4006 from `standard-syntax-table' otherwise."
4007 (let ((table (make-char-table 'syntax-table nil)))
4008 (set-char-table-parent table (or oldtable (standard-syntax-table)))
4009 table))
4011 (defun syntax-after (pos)
4012 "Return the raw syntax descriptor for the char after POS.
4013 If POS is outside the buffer's accessible portion, return nil."
4014 (unless (or (< pos (point-min)) (>= pos (point-max)))
4015 (let ((st (if parse-sexp-lookup-properties
4016 (get-char-property pos 'syntax-table))))
4017 (if (consp st) st
4018 (aref (or st (syntax-table)) (char-after pos))))))
4020 (defun syntax-class (syntax)
4021 "Return the code for the syntax class described by SYNTAX.
4023 SYNTAX should be a raw syntax descriptor; the return value is a
4024 integer which encodes the corresponding syntax class. See Info
4025 node `(elisp)Syntax Table Internals' for a list of codes.
4027 If SYNTAX is nil, return nil."
4028 (and syntax (logand (car syntax) 65535)))
4030 ;; Utility motion commands
4032 ;; Whitespace
4034 (defun forward-whitespace (arg)
4035 "Move point to the end of the next sequence of whitespace chars.
4036 Each such sequence may be a single newline, or a sequence of
4037 consecutive space and/or tab characters.
4038 With prefix argument ARG, do it ARG times if positive, or move
4039 backwards ARG times if negative."
4040 (interactive "^p")
4041 (if (natnump arg)
4042 (re-search-forward "[ \t]+\\|\n" nil 'move arg)
4043 (while (< arg 0)
4044 (if (re-search-backward "[ \t]+\\|\n" nil 'move)
4045 (or (eq (char-after (match-beginning 0)) ?\n)
4046 (skip-chars-backward " \t")))
4047 (setq arg (1+ arg)))))
4049 ;; Symbols
4051 (defun forward-symbol (arg)
4052 "Move point to the next position that is the end of a symbol.
4053 A symbol is any sequence of characters that are in either the
4054 word constituent or symbol constituent syntax class.
4055 With prefix argument ARG, do it ARG times if positive, or move
4056 backwards ARG times if negative."
4057 (interactive "^p")
4058 (if (natnump arg)
4059 (re-search-forward "\\(\\sw\\|\\s_\\)+" nil 'move arg)
4060 (while (< arg 0)
4061 (if (re-search-backward "\\(\\sw\\|\\s_\\)+" nil 'move)
4062 (skip-syntax-backward "w_"))
4063 (setq arg (1+ arg)))))
4065 ;; Syntax blocks
4067 (defun forward-same-syntax (&optional arg)
4068 "Move point past all characters with the same syntax class.
4069 With prefix argument ARG, do it ARG times if positive, or move
4070 backwards ARG times if negative."
4071 (interactive "^p")
4072 (or arg (setq arg 1))
4073 (while (< arg 0)
4074 (skip-syntax-backward
4075 (char-to-string (char-syntax (char-before))))
4076 (setq arg (1+ arg)))
4077 (while (> arg 0)
4078 (skip-syntax-forward (char-to-string (char-syntax (char-after))))
4079 (setq arg (1- arg))))
4082 ;;;; Text clones
4084 (defvar text-clone--maintaining nil)
4086 (defun text-clone--maintain (ol1 after beg end &optional _len)
4087 "Propagate the changes made under the overlay OL1 to the other clones.
4088 This is used on the `modification-hooks' property of text clones."
4089 (when (and after (not undo-in-progress)
4090 (not text-clone--maintaining)
4091 (overlay-start ol1))
4092 (let ((margin (if (overlay-get ol1 'text-clone-spreadp) 1 0)))
4093 (setq beg (max beg (+ (overlay-start ol1) margin)))
4094 (setq end (min end (- (overlay-end ol1) margin)))
4095 (when (<= beg end)
4096 (save-excursion
4097 (when (overlay-get ol1 'text-clone-syntax)
4098 ;; Check content of the clone's text.
4099 (let ((cbeg (+ (overlay-start ol1) margin))
4100 (cend (- (overlay-end ol1) margin)))
4101 (goto-char cbeg)
4102 (save-match-data
4103 (if (not (re-search-forward
4104 (overlay-get ol1 'text-clone-syntax) cend t))
4105 ;; Mark the overlay for deletion.
4106 (setq end cbeg)
4107 (when (< (match-end 0) cend)
4108 ;; Shrink the clone at its end.
4109 (setq end (min end (match-end 0)))
4110 (move-overlay ol1 (overlay-start ol1)
4111 (+ (match-end 0) margin)))
4112 (when (> (match-beginning 0) cbeg)
4113 ;; Shrink the clone at its beginning.
4114 (setq beg (max (match-beginning 0) beg))
4115 (move-overlay ol1 (- (match-beginning 0) margin)
4116 (overlay-end ol1)))))))
4117 ;; Now go ahead and update the clones.
4118 (let ((head (- beg (overlay-start ol1)))
4119 (tail (- (overlay-end ol1) end))
4120 (str (buffer-substring beg end))
4121 (nothing-left t)
4122 (text-clone--maintaining t))
4123 (dolist (ol2 (overlay-get ol1 'text-clones))
4124 (let ((oe (overlay-end ol2)))
4125 (unless (or (eq ol1 ol2) (null oe))
4126 (setq nothing-left nil)
4127 (let ((mod-beg (+ (overlay-start ol2) head)))
4128 ;;(overlay-put ol2 'modification-hooks nil)
4129 (goto-char (- (overlay-end ol2) tail))
4130 (unless (> mod-beg (point))
4131 (save-excursion (insert str))
4132 (delete-region mod-beg (point)))
4133 ;;(overlay-put ol2 'modification-hooks '(text-clone--maintain))
4134 ))))
4135 (if nothing-left (delete-overlay ol1))))))))
4137 (defun text-clone-create (start end &optional spreadp syntax)
4138 "Create a text clone of START...END at point.
4139 Text clones are chunks of text that are automatically kept identical:
4140 changes done to one of the clones will be immediately propagated to the other.
4142 The buffer's content at point is assumed to be already identical to
4143 the one between START and END.
4144 If SYNTAX is provided it's a regexp that describes the possible text of
4145 the clones; the clone will be shrunk or killed if necessary to ensure that
4146 its text matches the regexp.
4147 If SPREADP is non-nil it indicates that text inserted before/after the
4148 clone should be incorporated in the clone."
4149 ;; To deal with SPREADP we can either use an overlay with `nil t' along
4150 ;; with insert-(behind|in-front-of)-hooks or use a slightly larger overlay
4151 ;; (with a one-char margin at each end) with `t nil'.
4152 ;; We opted for a larger overlay because it behaves better in the case
4153 ;; where the clone is reduced to the empty string (we want the overlay to
4154 ;; stay when the clone's content is the empty string and we want to use
4155 ;; `evaporate' to make sure those overlays get deleted when needed).
4157 (let* ((pt-end (+ (point) (- end start)))
4158 (start-margin (if (or (not spreadp) (bobp) (<= start (point-min)))
4159 0 1))
4160 (end-margin (if (or (not spreadp)
4161 (>= pt-end (point-max))
4162 (>= start (point-max)))
4163 0 1))
4164 ;; FIXME: Reuse overlays at point to extend dups!
4165 (ol1 (make-overlay (- start start-margin) (+ end end-margin) nil t))
4166 (ol2 (make-overlay (- (point) start-margin) (+ pt-end end-margin) nil t))
4167 (dups (list ol1 ol2)))
4168 (overlay-put ol1 'modification-hooks '(text-clone--maintain))
4169 (when spreadp (overlay-put ol1 'text-clone-spreadp t))
4170 (when syntax (overlay-put ol1 'text-clone-syntax syntax))
4171 ;;(overlay-put ol1 'face 'underline)
4172 (overlay-put ol1 'evaporate t)
4173 (overlay-put ol1 'text-clones dups)
4175 (overlay-put ol2 'modification-hooks '(text-clone--maintain))
4176 (when spreadp (overlay-put ol2 'text-clone-spreadp t))
4177 (when syntax (overlay-put ol2 'text-clone-syntax syntax))
4178 ;;(overlay-put ol2 'face 'underline)
4179 (overlay-put ol2 'evaporate t)
4180 (overlay-put ol2 'text-clones dups)))
4182 ;;;; Mail user agents.
4184 ;; Here we include just enough for other packages to be able
4185 ;; to define them.
4187 (defun define-mail-user-agent (symbol composefunc sendfunc
4188 &optional abortfunc hookvar)
4189 "Define a symbol to identify a mail-sending package for `mail-user-agent'.
4191 SYMBOL can be any Lisp symbol. Its function definition and/or
4192 value as a variable do not matter for this usage; we use only certain
4193 properties on its property list, to encode the rest of the arguments.
4195 COMPOSEFUNC is program callable function that composes an outgoing
4196 mail message buffer. This function should set up the basics of the
4197 buffer without requiring user interaction. It should populate the
4198 standard mail headers, leaving the `to:' and `subject:' headers blank
4199 by default.
4201 COMPOSEFUNC should accept several optional arguments--the same
4202 arguments that `compose-mail' takes. See that function's documentation.
4204 SENDFUNC is the command a user would run to send the message.
4206 Optional ABORTFUNC is the command a user would run to abort the
4207 message. For mail packages that don't have a separate abort function,
4208 this can be `kill-buffer' (the equivalent of omitting this argument).
4210 Optional HOOKVAR is a hook variable that gets run before the message
4211 is actually sent. Callers that use the `mail-user-agent' may
4212 install a hook function temporarily on this hook variable.
4213 If HOOKVAR is nil, `mail-send-hook' is used.
4215 The properties used on SYMBOL are `composefunc', `sendfunc',
4216 `abortfunc', and `hookvar'."
4217 (put symbol 'composefunc composefunc)
4218 (put symbol 'sendfunc sendfunc)
4219 (put symbol 'abortfunc (or abortfunc 'kill-buffer))
4220 (put symbol 'hookvar (or hookvar 'mail-send-hook)))
4222 (defvar called-interactively-p-functions nil
4223 "Special hook called to skip special frames in `called-interactively-p'.
4224 The functions are called with 3 arguments: (I FRAME1 FRAME2),
4225 where FRAME1 is a \"current frame\", FRAME2 is the next frame,
4226 I is the index of the frame after FRAME2. It should return nil
4227 if those frames don't seem special and otherwise, it should return
4228 the number of frames to skip (minus 1).")
4230 (defconst internal--funcall-interactively
4231 (symbol-function 'funcall-interactively))
4233 (defun called-interactively-p (&optional kind)
4234 "Return t if the containing function was called by `call-interactively'.
4235 If KIND is `interactive', then only return t if the call was made
4236 interactively by the user, i.e. not in `noninteractive' mode nor
4237 when `executing-kbd-macro'.
4238 If KIND is `any', on the other hand, it will return t for any kind of
4239 interactive call, including being called as the binding of a key or
4240 from a keyboard macro, even in `noninteractive' mode.
4242 This function is very brittle, it may fail to return the intended result when
4243 the code is debugged, advised, or instrumented in some form. Some macros and
4244 special forms (such as `condition-case') may also sometimes wrap their bodies
4245 in a `lambda', so any call to `called-interactively-p' from those bodies will
4246 indicate whether that lambda (rather than the surrounding function) was called
4247 interactively.
4249 Instead of using this function, it is cleaner and more reliable to give your
4250 function an extra optional argument whose `interactive' spec specifies
4251 non-nil unconditionally (\"p\" is a good way to do this), or via
4252 \(not (or executing-kbd-macro noninteractive)).
4254 The only known proper use of `interactive' for KIND is in deciding
4255 whether to display a helpful message, or how to display it. If you're
4256 thinking of using it for any other purpose, it is quite likely that
4257 you're making a mistake. Think: what do you want to do when the
4258 command is called from a keyboard macro?"
4259 (declare (advertised-calling-convention (kind) "23.1"))
4260 (when (not (and (eq kind 'interactive)
4261 (or executing-kbd-macro noninteractive)))
4262 (let* ((i 1) ;; 0 is the called-interactively-p frame.
4263 frame nextframe
4264 (get-next-frame
4265 (lambda ()
4266 (setq frame nextframe)
4267 (setq nextframe (backtrace-frame i 'called-interactively-p))
4268 ;; (message "Frame %d = %S" i nextframe)
4269 (setq i (1+ i)))))
4270 (funcall get-next-frame) ;; Get the first frame.
4271 (while
4272 ;; FIXME: The edebug and advice handling should be made modular and
4273 ;; provided directly by edebug.el and nadvice.el.
4274 (progn
4275 ;; frame =(backtrace-frame i-2)
4276 ;; nextframe=(backtrace-frame i-1)
4277 (funcall get-next-frame)
4278 ;; `pcase' would be a fairly good fit here, but it sometimes moves
4279 ;; branches within local functions, which then messes up the
4280 ;; `backtrace-frame' data we get,
4282 ;; Skip special forms (from non-compiled code).
4283 (and frame (null (car frame)))
4284 ;; Skip also `interactive-p' (because we don't want to know if
4285 ;; interactive-p was called interactively but if it's caller was)
4286 ;; and `byte-code' (idem; this appears in subexpressions of things
4287 ;; like condition-case, which are wrapped in a separate bytecode
4288 ;; chunk).
4289 ;; FIXME: For lexical-binding code, this is much worse,
4290 ;; because the frames look like "byte-code -> funcall -> #[...]",
4291 ;; which is not a reliable signature.
4292 (memq (nth 1 frame) '(interactive-p 'byte-code))
4293 ;; Skip package-specific stack-frames.
4294 (let ((skip (run-hook-with-args-until-success
4295 'called-interactively-p-functions
4296 i frame nextframe)))
4297 (pcase skip
4298 (`nil nil)
4299 (`0 t)
4300 (_ (setq i (+ i skip -1)) (funcall get-next-frame)))))))
4301 ;; Now `frame' should be "the function from which we were called".
4302 (pcase (cons frame nextframe)
4303 ;; No subr calls `interactive-p', so we can rule that out.
4304 (`((,_ ,(pred (lambda (f) (subrp (indirect-function f)))) . ,_) . ,_) nil)
4305 ;; In case #<subr funcall-interactively> without going through the
4306 ;; `funcall-interactively' symbol (bug#3984).
4307 (`(,_ . (t ,(pred (lambda (f)
4308 (eq internal--funcall-interactively
4309 (indirect-function f))))
4310 . ,_))
4311 t)))))
4313 (defun interactive-p ()
4314 "Return t if the containing function was run directly by user input.
4315 This means that the function was called with `call-interactively'
4316 \(which includes being called as the binding of a key)
4317 and input is currently coming from the keyboard (not a keyboard macro),
4318 and Emacs is not running in batch mode (`noninteractive' is nil).
4320 The only known proper use of `interactive-p' is in deciding whether to
4321 display a helpful message, or how to display it. If you're thinking
4322 of using it for any other purpose, it is quite likely that you're
4323 making a mistake. Think: what do you want to do when the command is
4324 called from a keyboard macro or in batch mode?
4326 To test whether your function was called with `call-interactively',
4327 either (i) add an extra optional argument and give it an `interactive'
4328 spec that specifies non-nil unconditionally (such as \"p\"); or (ii)
4329 use `called-interactively-p'."
4330 (declare (obsolete called-interactively-p "23.2"))
4331 (called-interactively-p 'interactive))
4333 (defun internal-push-keymap (keymap symbol)
4334 (let ((map (symbol-value symbol)))
4335 (unless (memq keymap map)
4336 (unless (memq 'add-keymap-witness (symbol-value symbol))
4337 (setq map (make-composed-keymap nil (symbol-value symbol)))
4338 (push 'add-keymap-witness (cdr map))
4339 (set symbol map))
4340 (push keymap (cdr map)))))
4342 (defun internal-pop-keymap (keymap symbol)
4343 (let ((map (symbol-value symbol)))
4344 (when (memq keymap map)
4345 (setf (cdr map) (delq keymap (cdr map))))
4346 (let ((tail (cddr map)))
4347 (and (or (null tail) (keymapp tail))
4348 (eq 'add-keymap-witness (nth 1 map))
4349 (set symbol tail)))))
4351 (define-obsolete-function-alias
4352 'set-temporary-overlay-map 'set-transient-map "24.4")
4354 (defun set-transient-map (map &optional keep-pred on-exit)
4355 "Set MAP as a temporary keymap taking precedence over other keymaps.
4356 Normally, MAP is used only once, to look up the very next key.
4357 However, if the optional argument KEEP-PRED is t, MAP stays
4358 active if a key from MAP is used. KEEP-PRED can also be a
4359 function of no arguments: it is called from `pre-command-hook' and
4360 if it returns non-nil, then MAP stays active.
4362 Optional arg ON-EXIT, if non-nil, specifies a function that is
4363 called, with no arguments, after MAP is deactivated.
4365 This uses `overriding-terminal-local-map' which takes precedence over all other
4366 keymaps. As usual, if no match for a key is found in MAP, the normal key
4367 lookup sequence then continues.
4369 This returns an \"exit function\", which can be called with no argument
4370 to deactivate this transient map, regardless of KEEP-PRED."
4371 (let* ((clearfun (make-symbol "clear-transient-map"))
4372 (exitfun
4373 (lambda ()
4374 (internal-pop-keymap map 'overriding-terminal-local-map)
4375 (remove-hook 'pre-command-hook clearfun)
4376 (when on-exit (funcall on-exit)))))
4377 ;; Don't use letrec, because equal (in add/remove-hook) would get trapped
4378 ;; in a cycle.
4379 (fset clearfun
4380 (lambda ()
4381 (with-demoted-errors "set-transient-map PCH: %S"
4382 (unless (cond
4383 ((null keep-pred) nil)
4384 ((not (eq map (cadr overriding-terminal-local-map)))
4385 ;; There's presumably some other transient-map in
4386 ;; effect. Wait for that one to terminate before we
4387 ;; remove ourselves.
4388 ;; For example, if isearch and C-u both use transient
4389 ;; maps, then the lifetime of the C-u should be nested
4390 ;; within isearch's, so the pre-command-hook of
4391 ;; isearch should be suspended during the C-u one so
4392 ;; we don't exit isearch just because we hit 1 after
4393 ;; C-u and that 1 exits isearch whereas it doesn't
4394 ;; exit C-u.
4396 ((eq t keep-pred)
4397 (eq this-command
4398 (lookup-key map (this-command-keys-vector))))
4399 (t (funcall keep-pred)))
4400 (funcall exitfun)))))
4401 (add-hook 'pre-command-hook clearfun)
4402 (internal-push-keymap map 'overriding-terminal-local-map)
4403 exitfun))
4405 ;;;; Progress reporters.
4407 ;; Progress reporter has the following structure:
4409 ;; (NEXT-UPDATE-VALUE . [NEXT-UPDATE-TIME
4410 ;; MIN-VALUE
4411 ;; MAX-VALUE
4412 ;; MESSAGE
4413 ;; MIN-CHANGE
4414 ;; MIN-TIME])
4416 ;; This weirdness is for optimization reasons: we want
4417 ;; `progress-reporter-update' to be as fast as possible, so
4418 ;; `(car reporter)' is better than `(aref reporter 0)'.
4420 ;; NEXT-UPDATE-TIME is a float. While `float-time' loses a couple
4421 ;; digits of precision, it doesn't really matter here. On the other
4422 ;; hand, it greatly simplifies the code.
4424 (defsubst progress-reporter-update (reporter &optional value)
4425 "Report progress of an operation in the echo area.
4426 REPORTER should be the result of a call to `make-progress-reporter'.
4428 If REPORTER is a numerical progress reporter---i.e. if it was
4429 made using non-nil MIN-VALUE and MAX-VALUE arguments to
4430 `make-progress-reporter'---then VALUE should be a number between
4431 MIN-VALUE and MAX-VALUE.
4433 If REPORTER is a non-numerical reporter, VALUE should be nil.
4435 This function is relatively inexpensive. If the change since
4436 last update is too small or insufficient time has passed, it does
4437 nothing."
4438 (when (or (not (numberp value)) ; For pulsing reporter
4439 (>= value (car reporter))) ; For numerical reporter
4440 (progress-reporter-do-update reporter value)))
4442 (defun make-progress-reporter (message &optional min-value max-value
4443 current-value min-change min-time)
4444 "Return progress reporter object for use with `progress-reporter-update'.
4446 MESSAGE is shown in the echo area, with a status indicator
4447 appended to the end. When you call `progress-reporter-done', the
4448 word \"done\" is printed after the MESSAGE. You can change the
4449 MESSAGE of an existing progress reporter by calling
4450 `progress-reporter-force-update'.
4452 MIN-VALUE and MAX-VALUE, if non-nil, are starting (0% complete)
4453 and final (100% complete) states of operation; the latter should
4454 be larger. In this case, the status message shows the percentage
4455 progress.
4457 If MIN-VALUE and/or MAX-VALUE is omitted or nil, the status
4458 message shows a \"spinning\", non-numeric indicator.
4460 Optional CURRENT-VALUE is the initial progress; the default is
4461 MIN-VALUE.
4462 Optional MIN-CHANGE is the minimal change in percents to report;
4463 the default is 1%.
4464 CURRENT-VALUE and MIN-CHANGE do not have any effect if MIN-VALUE
4465 and/or MAX-VALUE are nil.
4467 Optional MIN-TIME specifies the minimum interval time between
4468 echo area updates (default is 0.2 seconds.) If the function
4469 `float-time' is not present, time is not tracked at all. If the
4470 OS is not capable of measuring fractions of seconds, this
4471 parameter is effectively rounded up."
4472 (when (string-match "[[:alnum:]]\\'" message)
4473 (setq message (concat message "...")))
4474 (unless min-time
4475 (setq min-time 0.2))
4476 (let ((reporter
4477 ;; Force a call to `message' now
4478 (cons (or min-value 0)
4479 (vector (if (and (fboundp 'float-time)
4480 (>= min-time 0.02))
4481 (float-time) nil)
4482 min-value
4483 max-value
4484 message
4485 (if min-change (max (min min-change 50) 1) 1)
4486 min-time))))
4487 (progress-reporter-update reporter (or current-value min-value))
4488 reporter))
4490 (defun progress-reporter-force-update (reporter &optional value new-message)
4491 "Report progress of an operation in the echo area unconditionally.
4493 The first two arguments are the same as in `progress-reporter-update'.
4494 NEW-MESSAGE, if non-nil, sets a new message for the reporter."
4495 (let ((parameters (cdr reporter)))
4496 (when new-message
4497 (aset parameters 3 new-message))
4498 (when (aref parameters 0)
4499 (aset parameters 0 (float-time)))
4500 (progress-reporter-do-update reporter value)))
4502 (defvar progress-reporter--pulse-characters ["-" "\\" "|" "/"]
4503 "Characters to use for pulsing progress reporters.")
4505 (defun progress-reporter-do-update (reporter value)
4506 (let* ((parameters (cdr reporter))
4507 (update-time (aref parameters 0))
4508 (min-value (aref parameters 1))
4509 (max-value (aref parameters 2))
4510 (text (aref parameters 3))
4511 (enough-time-passed
4512 ;; See if enough time has passed since the last update.
4513 (or (not update-time)
4514 (when (>= (float-time) update-time)
4515 ;; Calculate time for the next update
4516 (aset parameters 0 (+ update-time (aref parameters 5)))))))
4517 (cond ((and min-value max-value)
4518 ;; Numerical indicator
4519 (let* ((one-percent (/ (- max-value min-value) 100.0))
4520 (percentage (if (= max-value min-value)
4522 (truncate (/ (- value min-value)
4523 one-percent)))))
4524 ;; Calculate NEXT-UPDATE-VALUE. If we are not printing
4525 ;; message because not enough time has passed, use 1
4526 ;; instead of MIN-CHANGE. This makes delays between echo
4527 ;; area updates closer to MIN-TIME.
4528 (setcar reporter
4529 (min (+ min-value (* (+ percentage
4530 (if enough-time-passed
4531 ;; MIN-CHANGE
4532 (aref parameters 4)
4534 one-percent))
4535 max-value))
4536 (when (integerp value)
4537 (setcar reporter (ceiling (car reporter))))
4538 ;; Only print message if enough time has passed
4539 (when enough-time-passed
4540 (if (> percentage 0)
4541 (message "%s%d%%" text percentage)
4542 (message "%s" text)))))
4543 ;; Pulsing indicator
4544 (enough-time-passed
4545 (let ((index (mod (1+ (car reporter)) 4))
4546 (message-log-max nil))
4547 (setcar reporter index)
4548 (message "%s %s"
4549 text
4550 (aref progress-reporter--pulse-characters
4551 index)))))))
4553 (defun progress-reporter-done (reporter)
4554 "Print reporter's message followed by word \"done\" in echo area."
4555 (message "%sdone" (aref (cdr reporter) 3)))
4557 (defmacro dotimes-with-progress-reporter (spec message &rest body)
4558 "Loop a certain number of times and report progress in the echo area.
4559 Evaluate BODY with VAR bound to successive integers running from
4560 0, inclusive, to COUNT, exclusive. Then evaluate RESULT to get
4561 the return value (nil if RESULT is omitted).
4563 At each iteration MESSAGE followed by progress percentage is
4564 printed in the echo area. After the loop is finished, MESSAGE
4565 followed by word \"done\" is printed. This macro is a
4566 convenience wrapper around `make-progress-reporter' and friends.
4568 \(fn (VAR COUNT [RESULT]) MESSAGE BODY...)"
4569 (declare (indent 2) (debug ((symbolp form &optional form) form body)))
4570 (let ((temp (make-symbol "--dotimes-temp--"))
4571 (temp2 (make-symbol "--dotimes-temp2--"))
4572 (start 0)
4573 (end (nth 1 spec)))
4574 `(let ((,temp ,end)
4575 (,(car spec) ,start)
4576 (,temp2 (make-progress-reporter ,message ,start ,end)))
4577 (while (< ,(car spec) ,temp)
4578 ,@body
4579 (progress-reporter-update ,temp2
4580 (setq ,(car spec) (1+ ,(car spec)))))
4581 (progress-reporter-done ,temp2)
4582 nil ,@(cdr (cdr spec)))))
4585 ;;;; Comparing version strings.
4587 (defconst version-separator "."
4588 "Specify the string used to separate the version elements.
4590 Usually the separator is \".\", but it can be any other string.")
4593 (defconst version-regexp-alist
4594 '(("^[-_+ ]?snapshot$" . -4)
4595 ;; treat "1.2.3-20050920" and "1.2-3" as snapshot releases
4596 ("^[-_+]$" . -4)
4597 ;; treat "1.2.3-CVS" as snapshot release
4598 ("^[-_+ ]?\\(cvs\\|git\\|bzr\\|svn\\|hg\\|darcs\\)$" . -4)
4599 ("^[-_+ ]?alpha$" . -3)
4600 ("^[-_+ ]?beta$" . -2)
4601 ("^[-_+ ]?\\(pre\\|rc\\)$" . -1))
4602 "Specify association between non-numeric version and its priority.
4604 This association is used to handle version string like \"1.0pre2\",
4605 \"0.9alpha1\", etc. It's used by `version-to-list' (which see) to convert the
4606 non-numeric part of a version string to an integer. For example:
4608 String Version Integer List Version
4609 \"0.9snapshot\" (0 9 -4)
4610 \"1.0-git\" (1 0 -4)
4611 \"1.0pre2\" (1 0 -1 2)
4612 \"1.0PRE2\" (1 0 -1 2)
4613 \"22.8beta3\" (22 8 -2 3)
4614 \"22.8 Beta3\" (22 8 -2 3)
4615 \"0.9alpha1\" (0 9 -3 1)
4616 \"0.9AlphA1\" (0 9 -3 1)
4617 \"0.9 alpha\" (0 9 -3)
4619 Each element has the following form:
4621 (REGEXP . PRIORITY)
4623 Where:
4625 REGEXP regexp used to match non-numeric part of a version string.
4626 It should begin with the `^' anchor and end with a `$' to
4627 prevent false hits. Letter-case is ignored while matching
4628 REGEXP.
4630 PRIORITY a negative integer specifying non-numeric priority of REGEXP.")
4633 (defun version-to-list (ver)
4634 "Convert version string VER into a list of integers.
4636 The version syntax is given by the following EBNF:
4638 VERSION ::= NUMBER ( SEPARATOR NUMBER )*.
4640 NUMBER ::= (0|1|2|3|4|5|6|7|8|9)+.
4642 SEPARATOR ::= `version-separator' (which see)
4643 | `version-regexp-alist' (which see).
4645 The NUMBER part is optional if SEPARATOR is a match for an element
4646 in `version-regexp-alist'.
4648 Examples of valid version syntax:
4650 1.0pre2 1.0.7.5 22.8beta3 0.9alpha1 6.9.30Beta
4652 Examples of invalid version syntax:
4654 1.0prepre2 1.0..7.5 22.8X3 alpha3.2 .5
4656 Examples of version conversion:
4658 Version String Version as a List of Integers
4659 \"1.0.7.5\" (1 0 7 5)
4660 \"1.0pre2\" (1 0 -1 2)
4661 \"1.0PRE2\" (1 0 -1 2)
4662 \"22.8beta3\" (22 8 -2 3)
4663 \"22.8Beta3\" (22 8 -2 3)
4664 \"0.9alpha1\" (0 9 -3 1)
4665 \"0.9AlphA1\" (0 9 -3 1)
4666 \"0.9alpha\" (0 9 -3)
4667 \"0.9snapshot\" (0 9 -4)
4668 \"1.0-git\" (1 0 -4)
4670 See documentation for `version-separator' and `version-regexp-alist'."
4671 (or (and (stringp ver) (> (length ver) 0))
4672 (error "Invalid version string: '%s'" ver))
4673 ;; Change .x.y to 0.x.y
4674 (if (and (>= (length ver) (length version-separator))
4675 (string-equal (substring ver 0 (length version-separator))
4676 version-separator))
4677 (setq ver (concat "0" ver)))
4678 (save-match-data
4679 (let ((i 0)
4680 (case-fold-search t) ; ignore case in matching
4681 lst s al)
4682 (while (and (setq s (string-match "[0-9]+" ver i))
4683 (= s i))
4684 ;; handle numeric part
4685 (setq lst (cons (string-to-number (substring ver i (match-end 0)))
4686 lst)
4687 i (match-end 0))
4688 ;; handle non-numeric part
4689 (when (and (setq s (string-match "[^0-9]+" ver i))
4690 (= s i))
4691 (setq s (substring ver i (match-end 0))
4692 i (match-end 0))
4693 ;; handle alpha, beta, pre, etc. separator
4694 (unless (string= s version-separator)
4695 (setq al version-regexp-alist)
4696 (while (and al (not (string-match (caar al) s)))
4697 (setq al (cdr al)))
4698 (cond (al
4699 (push (cdar al) lst))
4700 ;; Convert 22.3a to 22.3.1, 22.3b to 22.3.2, etc.
4701 ((string-match "^[-_+ ]?\\([a-zA-Z]\\)$" s)
4702 (push (- (aref (downcase (match-string 1 s)) 0) ?a -1)
4703 lst))
4704 (t (error "Invalid version syntax: '%s'" ver))))))
4705 (if (null lst)
4706 (error "Invalid version syntax: '%s'" ver)
4707 (nreverse lst)))))
4710 (defun version-list-< (l1 l2)
4711 "Return t if L1, a list specification of a version, is lower than L2.
4713 Note that a version specified by the list (1) is equal to (1 0),
4714 \(1 0 0), (1 0 0 0), etc. That is, the trailing zeros are insignificant.
4715 Also, a version given by the list (1) is higher than (1 -1), which in
4716 turn is higher than (1 -2), which is higher than (1 -3)."
4717 (while (and l1 l2 (= (car l1) (car l2)))
4718 (setq l1 (cdr l1)
4719 l2 (cdr l2)))
4720 (cond
4721 ;; l1 not null and l2 not null
4722 ((and l1 l2) (< (car l1) (car l2)))
4723 ;; l1 null and l2 null ==> l1 length = l2 length
4724 ((and (null l1) (null l2)) nil)
4725 ;; l1 not null and l2 null ==> l1 length > l2 length
4726 (l1 (< (version-list-not-zero l1) 0))
4727 ;; l1 null and l2 not null ==> l2 length > l1 length
4728 (t (< 0 (version-list-not-zero l2)))))
4731 (defun version-list-= (l1 l2)
4732 "Return t if L1, a list specification of a version, is equal to L2.
4734 Note that a version specified by the list (1) is equal to (1 0),
4735 \(1 0 0), (1 0 0 0), etc. That is, the trailing zeros are insignificant.
4736 Also, a version given by the list (1) is higher than (1 -1), which in
4737 turn is higher than (1 -2), which is higher than (1 -3)."
4738 (while (and l1 l2 (= (car l1) (car l2)))
4739 (setq l1 (cdr l1)
4740 l2 (cdr l2)))
4741 (cond
4742 ;; l1 not null and l2 not null
4743 ((and l1 l2) nil)
4744 ;; l1 null and l2 null ==> l1 length = l2 length
4745 ((and (null l1) (null l2)))
4746 ;; l1 not null and l2 null ==> l1 length > l2 length
4747 (l1 (zerop (version-list-not-zero l1)))
4748 ;; l1 null and l2 not null ==> l2 length > l1 length
4749 (t (zerop (version-list-not-zero l2)))))
4752 (defun version-list-<= (l1 l2)
4753 "Return t if L1, a list specification of a version, is lower or equal to L2.
4755 Note that integer list (1) is equal to (1 0), (1 0 0), (1 0 0 0),
4756 etc. That is, the trailing zeroes are insignificant. Also, integer
4757 list (1) is greater than (1 -1) which is greater than (1 -2)
4758 which is greater than (1 -3)."
4759 (while (and l1 l2 (= (car l1) (car l2)))
4760 (setq l1 (cdr l1)
4761 l2 (cdr l2)))
4762 (cond
4763 ;; l1 not null and l2 not null
4764 ((and l1 l2) (< (car l1) (car l2)))
4765 ;; l1 null and l2 null ==> l1 length = l2 length
4766 ((and (null l1) (null l2)))
4767 ;; l1 not null and l2 null ==> l1 length > l2 length
4768 (l1 (<= (version-list-not-zero l1) 0))
4769 ;; l1 null and l2 not null ==> l2 length > l1 length
4770 (t (<= 0 (version-list-not-zero l2)))))
4772 (defun version-list-not-zero (lst)
4773 "Return the first non-zero element of LST, which is a list of integers.
4775 If all LST elements are zeros or LST is nil, return zero."
4776 (while (and lst (zerop (car lst)))
4777 (setq lst (cdr lst)))
4778 (if lst
4779 (car lst)
4780 ;; there is no element different of zero
4784 (defun version< (v1 v2)
4785 "Return t if version V1 is lower (older) than V2.
4787 Note that version string \"1\" is equal to \"1.0\", \"1.0.0\", \"1.0.0.0\",
4788 etc. That is, the trailing \".0\"s are insignificant. Also, version
4789 string \"1\" is higher (newer) than \"1pre\", which is higher than \"1beta\",
4790 which is higher than \"1alpha\", which is higher than \"1snapshot\".
4791 Also, \"-GIT\", \"-CVS\" and \"-NNN\" are treated as snapshot versions."
4792 (version-list-< (version-to-list v1) (version-to-list v2)))
4794 (defun version<= (v1 v2)
4795 "Return t if version V1 is lower (older) than or equal to V2.
4797 Note that version string \"1\" is equal to \"1.0\", \"1.0.0\", \"1.0.0.0\",
4798 etc. That is, the trailing \".0\"s are insignificant. Also, version
4799 string \"1\" is higher (newer) than \"1pre\", which is higher than \"1beta\",
4800 which is higher than \"1alpha\", which is higher than \"1snapshot\".
4801 Also, \"-GIT\", \"-CVS\" and \"-NNN\" are treated as snapshot versions."
4802 (version-list-<= (version-to-list v1) (version-to-list v2)))
4804 (defun version= (v1 v2)
4805 "Return t if version V1 is equal to V2.
4807 Note that version string \"1\" is equal to \"1.0\", \"1.0.0\", \"1.0.0.0\",
4808 etc. That is, the trailing \".0\"s are insignificant. Also, version
4809 string \"1\" is higher (newer) than \"1pre\", which is higher than \"1beta\",
4810 which is higher than \"1alpha\", which is higher than \"1snapshot\".
4811 Also, \"-GIT\", \"-CVS\" and \"-NNN\" are treated as snapshot versions."
4812 (version-list-= (version-to-list v1) (version-to-list v2)))
4814 (defvar package--builtin-versions
4815 ;; Mostly populated by loaddefs.el via autoload-builtin-package-versions.
4816 (purecopy `((emacs . ,(version-to-list emacs-version))))
4817 "Alist giving the version of each versioned builtin package.
4818 I.e. each element of the list is of the form (NAME . VERSION) where
4819 NAME is the package name as a symbol, and VERSION is its version
4820 as a list.")
4822 (defun package--description-file (dir)
4823 (concat (let ((subdir (file-name-nondirectory
4824 (directory-file-name dir))))
4825 (if (string-match "\\([^.].*?\\)-\\([0-9]+\\(?:[.][0-9]+\\|\\(?:pre\\|beta\\|alpha\\)[0-9]+\\)*\\)" subdir)
4826 (match-string 1 subdir) subdir))
4827 "-pkg.el"))
4830 ;;; Misc.
4831 (defconst menu-bar-separator '("--")
4832 "Separator for menus.")
4834 ;; The following statement ought to be in print.c, but `provide' can't
4835 ;; be used there.
4836 ;; http://lists.gnu.org/archive/html/emacs-devel/2009-08/msg00236.html
4837 (when (hash-table-p (car (read-from-string
4838 (prin1-to-string (make-hash-table)))))
4839 (provide 'hashtable-print-readable))
4841 ;; This is used in lisp/Makefile.in and in leim/Makefile.in to
4842 ;; generate file names for autoloads, custom-deps, and finder-data.
4843 (defun unmsys--file-name (file)
4844 "Produce the canonical file name for FILE from its MSYS form.
4846 On systems other than MS-Windows, just returns FILE.
4847 On MS-Windows, converts /d/foo/bar form of file names
4848 passed by MSYS Make into d:/foo/bar that Emacs can grok.
4850 This function is called from lisp/Makefile and leim/Makefile."
4851 (when (and (eq system-type 'windows-nt)
4852 (string-match "\\`/[a-zA-Z]/" file))
4853 (setq file (concat (substring file 1 2) ":" (substring file 2))))
4854 file)
4857 ;;; subr.el ends here