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