1 ;;; subr.el --- basic lisp subroutines for Emacs
3 ;; Copyright (C) 1985-1986, 1992, 1994-1995, 1999-2011
4 ;; Free Software Foundation, Inc.
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/>.
29 (defvar custom-declare-variable-list nil
30 "Record `defcustom' calls made before `custom.el' is loaded to handle them.
31 Each element of this list holds the arguments to one call to `defcustom'.")
33 ;; Use this, rather than defcustom, in subr.el and other files loaded
35 (defun custom-declare-variable-early (&rest arguments
)
36 (setq custom-declare-variable-list
37 (cons arguments custom-declare-variable-list
)))
39 (defmacro declare-function
(fn file
&optional arglist fileonly
)
40 "Tell the byte-compiler that function FN is defined, in FILE.
41 Optional ARGLIST is the argument list used by the function. The
42 FILE argument is not used by the byte-compiler, but by the
43 `check-declare' package, which checks that FILE contains a
44 definition for FN. ARGLIST is used by both the byte-compiler and
45 `check-declare' to check for consistency.
47 FILE can be either a Lisp file (in which case the \".el\"
48 extension is optional), or a C file. C files are expanded
49 relative to the Emacs \"src/\" directory. Lisp files are
50 searched for using `locate-library', and if that fails they are
51 expanded relative to the location of the file containing the
52 declaration. A FILE with an \"ext:\" prefix is an external file.
53 `check-declare' will check such files if they are found, and skip
54 them without error if they are not.
56 FILEONLY non-nil means that `check-declare' will only check that
57 FILE exists, not that it defines FN. This is intended for
58 function-definitions that `check-declare' does not recognize, e.g.
61 To specify a value for FILEONLY without passing an argument list,
62 set ARGLIST to t. This is necessary because nil means an
63 empty argument list, rather than an unspecified one.
65 Note that for the purposes of `check-declare', this statement
66 must be the first non-whitespace on a line.
68 For more information, see Info node `(elisp)Declaring Functions'."
69 ;; Does nothing - byte-compile-declare-function does the work.
73 ;;;; Basic Lisp macros.
77 (defmacro noreturn
(form)
78 "Evaluate FORM, expecting it not to return.
79 If FORM does return, signal an error."
81 (error "Form marked with `noreturn' did return")))
83 (defmacro 1value
(form)
84 "Evaluate FORM, expecting a constant return value.
85 This is the global do-nothing version. There is also `testcover-1value'
86 that complains if FORM ever does return differing values."
89 (defmacro def-edebug-spec
(symbol spec
)
90 "Set the `edebug-form-spec' property of SYMBOL according to SPEC.
91 Both SYMBOL and SPEC are unevaluated. The SPEC can be:
92 0 (instrument no arguments); t (instrument all arguments);
93 a symbol (naming a function with an Edebug specification); or a list.
94 The elements of the list describe the argument types; see
95 \(info \"(elisp)Specification List\") for details."
96 `(put (quote ,symbol
) 'edebug-form-spec
(quote ,spec
)))
98 (defmacro lambda
(&rest cdr
)
99 "Return a lambda expression.
100 A call of the form (lambda ARGS DOCSTRING INTERACTIVE BODY) is
101 self-quoting; the result of evaluating the lambda expression is the
102 expression itself. The lambda expression may then be treated as a
103 function, i.e., stored as the function value of a symbol, passed to
104 `funcall' or `mapcar', etc.
106 ARGS should take the same form as an argument list for a `defun'.
107 DOCSTRING is an optional documentation string.
108 If present, it should describe how to call the function.
109 But documentation strings are usually not useful in nameless functions.
110 INTERACTIVE should be a call to the function `interactive', which see.
111 It may also be omitted.
112 BODY should be a list of Lisp expressions.
114 \(fn ARGS [DOCSTRING] [INTERACTIVE] BODY)"
115 ;; Note that this definition should not use backquotes; subr.el should not
116 ;; depend on backquote.el.
117 (list 'function
(cons 'lambda cdr
)))
119 ;; Partial application of functions (similar to "currying").
120 ;; This function is here rather than in subr.el because it uses CL.
121 (defun apply-partially (fun &rest args
)
122 "Return a function that is a partial application of FUN to ARGS.
123 ARGS is a list of the first N arguments to pass to FUN.
124 The result is a new function which does the same as FUN, except that
125 the first N arguments are fixed at the values with which this function
127 `(closure () (&rest args
)
128 (apply ',fun
,@(mapcar (lambda (arg) `',arg
) args
) args
)))
130 (if (null (featurep 'cl
))
132 ;; If we reload subr.el after having loaded CL, be careful not to
133 ;; overwrite CL's extended definition of `dolist', `dotimes',
134 ;; `declare', `push' and `pop'.
135 (defmacro push
(newelt listname
)
136 "Add NEWELT to the list stored in the symbol LISTNAME.
137 This is equivalent to (setq LISTNAME (cons NEWELT LISTNAME)).
138 LISTNAME must be a symbol."
139 (declare (debug (form sexp
)))
141 (list 'cons newelt listname
)))
143 (defmacro pop
(listname)
144 "Return the first element of LISTNAME's value, and remove it from the list.
145 LISTNAME must be a symbol whose value is a list.
146 If the value is nil, `pop' returns nil but does not actually
148 (declare (debug (sexp)))
150 (list 'prog1 listname
151 (list 'setq listname
(list 'cdr listname
)))))
154 (defmacro when
(cond &rest body
)
155 "If COND yields non-nil, do BODY, else return nil.
156 When COND yields non-nil, eval BODY forms sequentially and return
157 value of last one, or nil if there are none.
160 (declare (indent 1) (debug t
))
161 (list 'if cond
(cons 'progn body
)))
163 (defmacro unless
(cond &rest body
)
164 "If COND yields nil, do BODY, else return nil.
165 When COND yields nil, eval BODY forms sequentially and return
166 value of last one, or nil if there are none.
169 (declare (indent 1) (debug t
))
170 (cons 'if
(cons cond
(cons nil body
))))
172 (if (null (featurep 'cl
))
174 ;; If we reload subr.el after having loaded CL, be careful not to
175 ;; overwrite CL's extended definition of `dolist', `dotimes',
176 ;; `declare', `push' and `pop'.
177 (defvar --dolist-tail-- nil
178 "Temporary variable used in `dolist' expansion.")
180 (defmacro dolist
(spec &rest body
)
182 Evaluate BODY with VAR bound to each car from LIST, in turn.
183 Then evaluate RESULT to get return value, default nil.
185 \(fn (VAR LIST [RESULT]) BODY...)"
186 (declare (indent 1) (debug ((symbolp form
&optional form
) body
)))
187 ;; It would be cleaner to create an uninterned symbol,
188 ;; but that uses a lot more space when many functions in many files
190 (let ((temp '--dolist-tail--
))
191 `(let ((,temp
,(nth 1 spec
))
194 (setq ,(car spec
) (car ,temp
))
196 (setq ,temp
(cdr ,temp
)))
197 ,@(if (cdr (cdr spec
))
198 `((setq ,(car spec
) nil
) ,@(cdr (cdr spec
)))))))
200 (defvar --dotimes-limit-- nil
201 "Temporary variable used in `dotimes' expansion.")
203 (defmacro dotimes
(spec &rest body
)
204 "Loop a certain number of times.
205 Evaluate BODY with VAR bound to successive integers running from 0,
206 inclusive, to COUNT, exclusive. Then evaluate RESULT to get
207 the return value (nil if RESULT is omitted).
209 \(fn (VAR COUNT [RESULT]) BODY...)"
210 (declare (indent 1) (debug dolist
))
211 ;; It would be cleaner to create an uninterned symbol,
212 ;; but that uses a lot more space when many functions in many files
214 (let ((temp '--dotimes-limit--
)
218 (,(car spec
) ,start
))
219 (while (< ,(car spec
) ,temp
)
221 (setq ,(car spec
) (1+ ,(car spec
))))
222 ,@(cdr (cdr spec
)))))
224 (defmacro declare
(&rest specs
)
225 "Do not evaluate any arguments and return nil.
226 Treated as a declaration when used at the right place in a
227 `defmacro' form. \(See Info anchor `(elisp)Definition of declare'.)"
231 (defmacro ignore-errors
(&rest body
)
232 "Execute BODY; if an error occurs, return nil.
233 Otherwise, return result of last form in BODY."
234 (declare (debug t
) (indent 0))
235 `(condition-case nil
(progn ,@body
) (error nil
)))
237 ;;;; Basic Lisp functions.
239 (defun ignore (&rest ignore
)
240 "Do nothing and return nil.
241 This function accepts any number of arguments, but ignores them."
245 ;; Signal a compile-error if the first arg is missing.
246 (defun error (&rest args
)
247 "Signal an error, making error message by passing all args to `format'.
248 In Emacs, the convention is that error messages start with a capital
249 letter but *do not* end with a period. Please follow this convention
250 for the sake of consistency."
252 (signal 'error
(list (apply 'format args
)))))
253 (set-advertised-calling-convention 'error
'(string &rest args
) "23.1")
255 ;; We put this here instead of in frame.el so that it's defined even on
256 ;; systems where frame.el isn't loaded.
257 (defun frame-configuration-p (object)
258 "Return non-nil if OBJECT seems to be a frame configuration.
259 Any list whose car is `frame-configuration' is assumed to be a frame
262 (eq (car object
) 'frame-configuration
)))
267 "Return the car of the car of X."
271 "Return the car of the cdr of X."
275 "Return the cdr of the car of X."
279 "Return the cdr of the cdr of X."
282 (defun last (list &optional n
)
283 "Return the last link of LIST. Its car is the last element.
284 If LIST is nil, return nil.
285 If N is non-nil, return the Nth-to-last link of LIST.
286 If N is bigger than the length of LIST, return LIST."
289 (let ((m (safe-length list
)))
290 (if (< n m
) (nthcdr (- m n
) list
) list
)))
292 (nthcdr (1- (safe-length list
)) list
))))
294 (defun butlast (list &optional n
)
295 "Return a copy of LIST with the last N elements removed."
296 (if (and n
(<= n
0)) list
297 (nbutlast (copy-sequence list
) n
)))
299 (defun nbutlast (list &optional n
)
300 "Modifies LIST to remove the last N elements."
301 (let ((m (length list
)))
305 (if (> n
0) (setcdr (nthcdr (- (1- m
) n
) list
) nil
))
308 (defun delete-dups (list)
309 "Destructively remove `equal' duplicates from LIST.
310 Store the result in LIST and return it. LIST must be a proper list.
311 Of several `equal' occurrences of an element in LIST, the first
315 (setcdr tail
(delete (car tail
) (cdr tail
)))
316 (setq tail
(cdr tail
))))
319 (defun number-sequence (from &optional to inc
)
320 "Return a sequence of numbers from FROM to TO (both inclusive) as a list.
321 INC is the increment used between numbers in the sequence and defaults to 1.
322 So, the Nth element of the list is \(+ FROM \(* N INC)) where N counts from
323 zero. TO is only included if there is an N for which TO = FROM + N * INC.
324 If TO is nil or numerically equal to FROM, return \(FROM).
325 If INC is positive and TO is less than FROM, or INC is negative
326 and TO is larger than FROM, return nil.
327 If INC is zero and TO is neither nil nor numerically equal to
328 FROM, signal an error.
330 This function is primarily designed for integer arguments.
331 Nevertheless, FROM, TO and INC can be integer or float. However,
332 floating point arithmetic is inexact. For instance, depending on
333 the machine, it may quite well happen that
334 \(number-sequence 0.4 0.6 0.2) returns the one element list \(0.4),
335 whereas \(number-sequence 0.4 0.8 0.2) returns a list with three
336 elements. Thus, if some of the arguments are floats and one wants
337 to make sure that TO is included, one may have to explicitly write
338 TO as \(+ FROM \(* N INC)) or use a variable whose value was
339 computed with this exact expression. Alternatively, you can,
340 of course, also replace TO with a slightly larger value
341 \(or a slightly more negative value if INC is negative)."
342 (if (or (not to
) (= from to
))
344 (or inc
(setq inc
1))
345 (when (zerop inc
) (error "The increment can not be zero"))
346 (let (seq (n 0) (next from
))
349 (setq seq
(cons next seq
)
351 next
(+ from
(* n inc
))))
353 (setq seq
(cons next seq
)
355 next
(+ from
(* n inc
)))))
358 (defun copy-tree (tree &optional vecp
)
359 "Make a copy of TREE.
360 If TREE is a cons cell, this recursively copies both its car and its cdr.
361 Contrast to `copy-sequence', which copies only along the cdrs. With second
362 argument VECP, this copies vectors as well as conses."
366 (let ((newcar (car tree
)))
367 (if (or (consp (car tree
)) (and vecp
(vectorp (car tree
))))
368 (setq newcar
(copy-tree (car tree
) vecp
)))
369 (push newcar result
))
370 (setq tree
(cdr tree
)))
371 (nconc (nreverse result
) tree
))
372 (if (and vecp
(vectorp tree
))
373 (let ((i (length (setq tree
(copy-sequence tree
)))))
374 (while (>= (setq i
(1- i
)) 0)
375 (aset tree i
(copy-tree (aref tree i
) vecp
)))
379 ;;;; Various list-search functions.
381 (defun assoc-default (key alist
&optional test default
)
382 "Find object KEY in a pseudo-alist ALIST.
383 ALIST is a list of conses or objects. Each element
384 (or the element's car, if it is a cons) is compared with KEY by
385 calling TEST, with two arguments: (i) the element or its car,
387 If that is non-nil, the element matches; then `assoc-default'
388 returns the element's cdr, if it is a cons, or DEFAULT if the
389 element is not a cons.
391 If no element matches, the value is nil.
392 If TEST is omitted or nil, `equal' is used."
393 (let (found (tail alist
) value
)
394 (while (and tail
(not found
))
395 (let ((elt (car tail
)))
396 (when (funcall (or test
'equal
) (if (consp elt
) (car elt
) elt
) key
)
397 (setq found t value
(if (consp elt
) (cdr elt
) default
))))
398 (setq tail
(cdr tail
)))
401 (make-obsolete 'assoc-ignore-case
'assoc-string
"22.1")
402 (defun assoc-ignore-case (key alist
)
403 "Like `assoc', but ignores differences in case and text representation.
404 KEY must be a string. Upper-case and lower-case letters are treated as equal.
405 Unibyte strings are converted to multibyte for comparison."
406 (assoc-string key alist t
))
408 (make-obsolete 'assoc-ignore-representation
'assoc-string
"22.1")
409 (defun assoc-ignore-representation (key alist
)
410 "Like `assoc', but ignores differences in text representation.
411 KEY must be a string.
412 Unibyte strings are converted to multibyte for comparison."
413 (assoc-string key alist nil
))
415 (defun member-ignore-case (elt list
)
416 "Like `member', but ignore differences in case and text representation.
417 ELT must be a string. Upper-case and lower-case letters are treated as equal.
418 Unibyte strings are converted to multibyte for comparison.
419 Non-strings in LIST are ignored."
421 (not (and (stringp (car list
))
422 (eq t
(compare-strings elt
0 nil
(car list
) 0 nil t
)))))
423 (setq list
(cdr list
)))
426 (defun assq-delete-all (key alist
)
427 "Delete from ALIST all elements whose car is `eq' to KEY.
428 Return the modified alist.
429 Elements of ALIST that are not conses are ignored."
430 (while (and (consp (car alist
))
431 (eq (car (car alist
)) key
))
432 (setq alist
(cdr alist
)))
433 (let ((tail alist
) tail-cdr
)
434 (while (setq tail-cdr
(cdr tail
))
435 (if (and (consp (car tail-cdr
))
436 (eq (car (car tail-cdr
)) key
))
437 (setcdr tail
(cdr tail-cdr
))
438 (setq tail tail-cdr
))))
441 (defun rassq-delete-all (value alist
)
442 "Delete from ALIST all elements whose cdr is `eq' to VALUE.
443 Return the modified alist.
444 Elements of ALIST that are not conses are ignored."
445 (while (and (consp (car alist
))
446 (eq (cdr (car alist
)) value
))
447 (setq alist
(cdr alist
)))
448 (let ((tail alist
) tail-cdr
)
449 (while (setq tail-cdr
(cdr tail
))
450 (if (and (consp (car tail-cdr
))
451 (eq (cdr (car tail-cdr
)) value
))
452 (setcdr tail
(cdr tail-cdr
))
453 (setq tail tail-cdr
))))
456 (defun remove (elt seq
)
457 "Return a copy of SEQ with all occurrences of ELT removed.
458 SEQ must be a list, vector, or string. The comparison is done with `equal'."
460 ;; If SEQ isn't a list, there's no need to copy SEQ because
461 ;; `delete' will return a new object.
463 (delete elt
(copy-sequence seq
))))
465 (defun remq (elt list
)
466 "Return LIST with all occurrences of ELT removed.
467 The comparison is done with `eq'. Contrary to `delq', this does not use
468 side-effects, and the argument LIST is not modified."
470 (delq elt
(copy-sequence list
))
476 "Convert KEYS to the internal Emacs key representation.
477 KEYS should be a string constant in the format used for
478 saving keyboard macros (see `edmacro-mode')."
479 (read-kbd-macro keys
))
482 "Beep to tell the user this binding is undefined."
486 ;; Prevent the \{...} documentation construct
487 ;; from mentioning keys that run this command.
488 (put 'undefined
'suppress-keymap t
)
490 (defun suppress-keymap (map &optional nodigits
)
491 "Make MAP override all normally self-inserting keys to be undefined.
492 Normally, as an exception, digits and minus-sign are set to make prefix args,
493 but optional second arg NODIGITS non-nil treats them like other chars."
494 (define-key map
[remap self-insert-command
] 'undefined
)
497 (define-key map
"-" 'negative-argument
)
498 ;; Make plain numbers do numeric args.
501 (define-key map
(char-to-string loop
) 'digit-argument
)
502 (setq loop
(1+ loop
))))))
504 (defun define-key-after (keymap key definition
&optional after
)
505 "Add binding in KEYMAP for KEY => DEFINITION, right after AFTER's binding.
506 This is like `define-key' except that the binding for KEY is placed
507 just after the binding for the event AFTER, instead of at the beginning
508 of the map. Note that AFTER must be an event type (like KEY), NOT a command
511 If AFTER is t or omitted, the new binding goes at the end of the keymap.
512 AFTER should be a single event type--a symbol or a character, not a sequence.
514 Bindings are always added before any inherited map.
516 The order of bindings in a keymap matters when it is used as a menu."
517 (unless after
(setq after t
))
519 (signal 'wrong-type-argument
(list 'keymapp keymap
)))
521 (if (<= (length key
) 1) (aref key
0)
522 (setq keymap
(lookup-key keymap
524 (butlast (mapcar 'identity key
)))))
525 (aref key
(1- (length key
)))))
526 (let ((tail keymap
) done inserted
)
527 (while (and (not done
) tail
)
528 ;; Delete any earlier bindings for the same key.
529 (if (eq (car-safe (car (cdr tail
))) key
)
530 (setcdr tail
(cdr (cdr tail
))))
531 ;; If we hit an included map, go down that one.
532 (if (keymapp (car tail
)) (setq tail
(car tail
)))
533 ;; When we reach AFTER's binding, insert the new binding after.
534 ;; If we reach an inherited keymap, insert just before that.
535 ;; If we reach the end of this keymap, insert at the end.
536 (if (or (and (eq (car-safe (car tail
)) after
)
538 (eq (car (cdr tail
)) 'keymap
)
541 ;; Stop the scan only if we find a parent keymap.
542 ;; Keep going past the inserted element
543 ;; so we can delete any duplications that come later.
544 (if (eq (car (cdr tail
)) 'keymap
)
546 ;; Don't insert more than once.
548 (setcdr tail
(cons (cons key definition
) (cdr tail
))))
550 (setq tail
(cdr tail
)))))
552 (defun map-keymap-sorted (function keymap
)
553 "Implement `map-keymap' with sorting.
554 Don't call this function; it is for internal use only."
556 (map-keymap (lambda (a b
) (push (cons a b
) list
))
558 (setq list
(sort list
560 (setq a
(car a
) b
(car b
))
562 (if (integerp b
) (< a b
)
565 ;; string< also accepts symbols.
568 (funcall function
(car p
) (cdr p
)))))
570 (defun keymap-canonicalize (map)
571 "Return an equivalent keymap, without inheritance."
574 (prompt (keymap-prompt map
)))
576 (setq map
(map-keymap-internal
579 ;; Treat char-ranges specially.
580 (push (cons key item
) ranges
)
581 (push (cons key item
) bindings
)))
583 (setq map
(funcall (if ranges
'make-keymap
'make-sparse-keymap
) prompt
))
584 (dolist (binding ranges
)
585 ;; Treat char-ranges specially.
586 (define-key map
(vector (car binding
)) (cdr binding
)))
587 (dolist (binding (prog1 bindings
(setq bindings
())))
588 (let* ((key (car binding
))
590 (oldbind (assq key bindings
)))
591 ;; Newer bindings override older.
592 (if oldbind
(setq bindings
(delq oldbind bindings
)))
593 (when item
;nil bindings just hide older ones.
594 (push binding bindings
))))
595 (nconc map bindings
)))
597 (put 'keyboard-translate-table
'char-table-extra-slots
0)
599 (defun keyboard-translate (from to
)
600 "Translate character FROM to TO at a low level.
601 This function creates a `keyboard-translate-table' if necessary
602 and then modifies one entry in it."
603 (or (char-table-p keyboard-translate-table
)
604 (setq keyboard-translate-table
605 (make-char-table 'keyboard-translate-table nil
)))
606 (aset keyboard-translate-table from to
))
608 ;;;; Key binding commands.
610 (defun global-set-key (key command
)
611 "Give KEY a global binding as COMMAND.
612 COMMAND is the command definition to use; usually it is
613 a symbol naming an interactively-callable function.
614 KEY is a key sequence; noninteractively, it is a string or vector
615 of characters or event types, and non-ASCII characters with codes
616 above 127 (such as ISO Latin-1) can be included if you use a vector.
618 Note that if KEY has a local binding in the current buffer,
619 that local binding will continue to shadow any global binding
620 that you make with this function."
621 (interactive "KSet key globally: \nCSet key %s to command: ")
622 (or (vectorp key
) (stringp key
)
623 (signal 'wrong-type-argument
(list 'arrayp key
)))
624 (define-key (current-global-map) key command
))
626 (defun local-set-key (key command
)
627 "Give KEY a local binding as COMMAND.
628 COMMAND is the command definition to use; usually it is
629 a symbol naming an interactively-callable function.
630 KEY is a key sequence; noninteractively, it is a string or vector
631 of characters or event types, and non-ASCII characters with codes
632 above 127 (such as ISO Latin-1) can be included if you use a vector.
634 The binding goes in the current buffer's local map,
635 which in most cases is shared with all other buffers in the same major mode."
636 (interactive "KSet key locally: \nCSet key %s locally to command: ")
637 (let ((map (current-local-map)))
639 (use-local-map (setq map
(make-sparse-keymap))))
640 (or (vectorp key
) (stringp key
)
641 (signal 'wrong-type-argument
(list 'arrayp key
)))
642 (define-key map key command
)))
644 (defun global-unset-key (key)
645 "Remove global binding of KEY.
646 KEY is a string or vector representing a sequence of keystrokes."
647 (interactive "kUnset key globally: ")
648 (global-set-key key nil
))
650 (defun local-unset-key (key)
651 "Remove local binding of KEY.
652 KEY is a string or vector representing a sequence of keystrokes."
653 (interactive "kUnset key locally: ")
654 (if (current-local-map)
655 (local-set-key key nil
))
658 ;;;; substitute-key-definition and its subroutines.
660 (defvar key-substitution-in-progress nil
661 "Used internally by `substitute-key-definition'.")
663 (defun substitute-key-definition (olddef newdef keymap
&optional oldmap prefix
)
664 "Replace OLDDEF with NEWDEF for any keys in KEYMAP now defined as OLDDEF.
665 In other words, OLDDEF is replaced with NEWDEF where ever it appears.
666 Alternatively, if optional fourth argument OLDMAP is specified, we redefine
667 in KEYMAP as NEWDEF those keys which are defined as OLDDEF in OLDMAP.
669 If you don't specify OLDMAP, you can usually get the same results
670 in a cleaner way with command remapping, like this:
671 \(define-key KEYMAP [remap OLDDEF] NEWDEF)
672 \n(fn OLDDEF NEWDEF KEYMAP &optional OLDMAP)"
673 ;; Don't document PREFIX in the doc string because we don't want to
674 ;; advertise it. It's meant for recursive calls only. Here's its
677 ;; If optional argument PREFIX is specified, it should be a key
678 ;; prefix, a string. Redefined bindings will then be bound to the
679 ;; original key, with PREFIX added at the front.
680 (or prefix
(setq prefix
""))
681 (let* ((scan (or oldmap keymap
))
682 (prefix1 (vconcat prefix
[nil]))
683 (key-substitution-in-progress
684 (cons scan key-substitution-in-progress)))
685 ;; Scan OLDMAP, finding each char or event-symbol that
686 ;; has any definition, and act on it with hack-key.
689 (aset prefix1 (length prefix) char)
690 (substitute-key-definition-key defn olddef newdef prefix1 keymap))
693 (defun substitute-key-definition-key (defn olddef newdef prefix keymap)
694 (let (inner-def skipped menu-item)
695 ;; Find the actual command name within the binding.
696 (if (eq (car-safe defn) 'menu-item)
697 (setq menu-item defn defn (nth 2 defn))
698 ;; Skip past menu-prompt.
699 (while (stringp (car-safe defn))
700 (push (pop defn) skipped))
701 ;; Skip past cached key-equivalence data for menu items.
702 (if (consp (car-safe defn))
703 (setq defn (cdr defn))))
704 (if (or (eq defn olddef)
705 ;; Compare with equal if definition is a key sequence.
706 ;; That is useful for operating on function-key-map.
707 (and (or (stringp defn) (vectorp defn))
708 (equal defn olddef)))
709 (define-key keymap prefix
711 (let ((copy (copy-sequence menu-item)))
712 (setcar (nthcdr 2 copy) newdef)
714 (nconc (nreverse skipped) newdef)))
715 ;; Look past a symbol that names a keymap.
717 (or (indirect-function defn t) defn))
718 ;; For nested keymaps, we use `inner-def' rather than `defn' so as to
719 ;; avoid autoloading a keymap. This is mostly done to preserve the
720 ;; original non-autoloading behavior of pre-map-keymap times.
721 (if (and (keymapp inner-def)
722 ;; Avoid recursively scanning
723 ;; where KEYMAP does not have a submap.
724 (let ((elt (lookup-key keymap prefix)))
725 (or (null elt) (natnump elt) (keymapp elt)))
726 ;; Avoid recursively rescanning keymap being scanned.
727 (not (memq inner-def key-substitution-in-progress)))
728 ;; If this one isn't being scanned already, scan it now.
729 (substitute-key-definition olddef newdef keymap inner-def prefix)))))
732 ;;;; The global keymap tree.
734 ;; global-map, esc-map, and ctl-x-map have their values set up in
735 ;; keymap.c; we just give them docstrings here.
737 (defvar global-map nil
738 "Default global keymap mapping Emacs keyboard input into commands.
739 The value is a keymap which is usually (but not necessarily) Emacs's
743 "Default keymap for ESC (meta) commands.
744 The normal global definition of the character ESC indirects to this keymap.")
746 (defvar ctl-x-map nil
747 "Default keymap for C-x commands.
748 The normal global definition of the character C-x indirects to this keymap.")
750 (defvar ctl-x-4-map (make-sparse-keymap)
751 "Keymap for subcommands of C-x 4.")
752 (defalias 'ctl-x-4-prefix ctl-x-4-map)
753 (define-key ctl-x-map "4" 'ctl-x-4-prefix)
755 (defvar ctl-x-5-map (make-sparse-keymap)
756 "Keymap for frame commands.")
757 (defalias 'ctl-x-5-prefix ctl-x-5-map)
758 (define-key ctl-x-map "5" 'ctl-x-5-prefix)
761 ;;;; Event manipulation functions.
763 (defconst listify-key-sequence-1 (logior 128 ?\M-\C-@))
765 (defun listify-key-sequence (key)
766 "Convert a key sequence to a list of events."
769 (mapcar (function (lambda (c)
771 (logxor c listify-key-sequence-1)
775 (defsubst eventp (obj)
776 "True if the argument is an event object."
777 (or (and (integerp obj)
778 ;; Filter out integers too large to be events.
779 ;; M is the biggest modifier.
780 (zerop (logand obj (lognot (1- (lsh ?\M-\^@ 1)))))
781 (characterp (event-basic-type obj)))
783 (get obj 'event-symbol-elements))
786 (get (car obj) 'event-symbol-elements))))
788 (defun event-modifiers (event)
789 "Return a list of symbols representing the modifier keys in event EVENT.
790 The elements of the list may include `meta', `control',
791 `shift', `hyper', `super', `alt', `click', `double', `triple', `drag',
793 EVENT may be an event or an event type. If EVENT is a symbol
794 that has never been used in an event that has been read as input
795 in the current Emacs session, then this function can return nil,
796 even when EVENT actually has modifiers."
799 (setq type (car type)))
801 ;; Don't read event-symbol-elements directly since we're not
802 ;; sure the symbol has already been parsed.
803 (cdr (internal-event-symbol-parse-modifiers type))
805 (char (logand type (lognot (logior ?\M-\^@ ?\C-\^@ ?\S-\^@
806 ?\H-\^@ ?\s-\^@ ?\A-\^@)))))
807 (if (not (zerop (logand type ?\M-\^@)))
809 (if (or (not (zerop (logand type ?\C-\^@)))
811 (push 'control list))
812 (if (or (not (zerop (logand type ?\S-\^@)))
813 (/= char (downcase char)))
815 (or (zerop (logand type ?\H-\^@))
817 (or (zerop (logand type ?\s-\^@))
819 (or (zerop (logand type ?\A-\^@))
823 (defun event-basic-type (event)
824 "Return the basic type of the given event (all modifiers removed).
825 The value is a printing character (not upper case) or a symbol.
826 EVENT may be an event or an event type. If EVENT is a symbol
827 that has never been used in an event that has been read as input
828 in the current Emacs session, then this function may return nil."
830 (setq event (car event)))
832 (car (get event 'event-symbol-elements))
833 (let* ((base (logand event (1- ?\A-\^@)))
834 (uncontrolled (if (< base 32) (logior base 64) base)))
835 ;; There are some numbers that are invalid characters and
836 ;; cause `downcase' to get an error.
838 (downcase uncontrolled)
839 (error uncontrolled)))))
841 (defsubst mouse-movement-p (object)
842 "Return non-nil if OBJECT is a mouse movement event."
843 (eq (car-safe object) 'mouse-movement))
845 (defun mouse-event-p (object)
846 "Return non-nil if OBJECT is a mouse click event."
847 ;; is this really correct? maybe remove mouse-movement?
848 (memq (event-basic-type object) '(mouse-1 mouse-2 mouse-3 mouse-movement)))
850 (defsubst event-start (event)
851 "Return the starting position of EVENT.
852 EVENT should be a click, drag, or key press event.
853 If it is a key press event, the return value has the form
854 (WINDOW POS (0 . 0) 0)
855 If it is a click or drag event, it has the form
856 (WINDOW AREA-OR-POS (X . Y) TIMESTAMP OBJECT POS (COL . ROW)
857 IMAGE (DX . DY) (WIDTH . HEIGHT))
858 The `posn-' functions access elements of such lists.
859 For more information, see Info node `(elisp)Click Events'.
861 If EVENT is a mouse or key press or a mouse click, this is the
862 position of the event. If EVENT is a drag, this is the starting
863 position of the drag."
864 (if (consp event) (nth 1 event)
865 (list (selected-window) (point) '(0 . 0) 0)))
867 (defsubst event-end (event)
868 "Return the ending location of EVENT.
869 EVENT should be a click, drag, or key press event.
870 If EVENT is a key press event, the return value has the form
871 (WINDOW POS (0 . 0) 0)
872 If EVENT is a click event, this function is the same as
873 `event-start'. For click and drag events, the return value has
875 (WINDOW AREA-OR-POS (X . Y) TIMESTAMP OBJECT POS (COL . ROW)
876 IMAGE (DX . DY) (WIDTH . HEIGHT))
877 The `posn-' functions access elements of such lists.
878 For more information, see Info node `(elisp)Click Events'.
880 If EVENT is a mouse or key press or a mouse click, this is the
881 position of the event. If EVENT is a drag, this is the starting
882 position of the drag."
883 (if (consp event) (nth (if (consp (nth 2 event)) 2 1) event)
884 (list (selected-window) (point) '(0 . 0) 0)))
886 (defsubst event-click-count (event)
887 "Return the multi-click count of EVENT, a click or drag event.
888 The return value is a positive integer."
889 (if (and (consp event) (integerp (nth 2 event))) (nth 2 event) 1))
891 ;;;; Extracting fields of the positions in an event.
893 (defsubst posn-window (position)
894 "Return the window in POSITION.
895 POSITION should be a list of the form returned by the `event-start'
896 and `event-end' functions."
899 (defsubst posn-area (position)
900 "Return the window area recorded in POSITION, or nil for the text area.
901 POSITION should be a list of the form returned by the `event-start'
902 and `event-end' functions."
903 (let ((area (if (consp (nth 1 position))
904 (car (nth 1 position))
906 (and (symbolp area) area)))
908 (defsubst posn-point (position)
909 "Return the buffer location in POSITION.
910 POSITION should be a list of the form returned by the `event-start'
911 and `event-end' functions."
913 (if (consp (nth 1 position))
914 (car (nth 1 position))
917 (defun posn-set-point (position)
918 "Move point to POSITION.
919 Select the corresponding window as well."
920 (if (not (windowp (posn-window position)))
921 (error "Position not in text area of window"))
922 (select-window (posn-window position))
923 (if (numberp (posn-point position))
924 (goto-char (posn-point position))))
926 (defsubst posn-x-y (position)
927 "Return the x and y coordinates in POSITION.
928 The return value has the form (X . Y), where X and Y are given in
929 pixels. POSITION should be a list of the form returned by
930 `event-start' and `event-end'."
933 (declare-function scroll-bar-scale "scroll-bar" (num-denom whole))
935 (defun posn-col-row (position)
936 "Return the nominal column and row in POSITION, measured in characters.
937 The column and row values are approximations calculated from the x
938 and y coordinates in POSITION and the frame's default character width
940 For a scroll-bar event, the result column is 0, and the row
941 corresponds to the vertical position of the click in the scroll bar.
942 POSITION should be a list of the form returned by the `event-start'
943 and `event-end' functions."
944 (let* ((pair (posn-x-y position))
945 (window (posn-window position))
946 (area (posn-area position)))
950 ((eq area 'vertical-scroll-bar)
951 (cons 0 (scroll-bar-scale pair (1- (window-height window)))))
952 ((eq area 'horizontal-scroll-bar)
953 (cons (scroll-bar-scale pair (window-width window)) 0))
955 (let* ((frame (if (framep window) window (window-frame window)))
956 ;; FIXME: This should take line-spacing properties on
957 ;; newlines into account.
958 (spacing (when (display-graphic-p frame)
959 (or (with-current-buffer (window-buffer window)
961 (frame-parameter frame 'line-spacing)))))
962 (cond ((floatp spacing)
963 (setq spacing (truncate (* spacing
964 (frame-char-height frame)))))
967 (cons (/ (car pair) (frame-char-width frame))
968 (- (/ (cdr pair) (+ (frame-char-height frame) spacing))
969 (if (null (with-current-buffer (window-buffer window)
973 (defun posn-actual-col-row (position)
974 "Return the actual column and row in POSITION, measured in characters.
975 These are the actual row number in the window and character number in that row.
976 Return nil if POSITION does not contain the actual position; in that case
977 `posn-col-row' can be used to get approximate values.
978 POSITION should be a list of the form returned by the `event-start'
979 and `event-end' functions."
982 (defsubst posn-timestamp (position)
983 "Return the timestamp of POSITION.
984 POSITION should be a list of the form returned by the `event-start'
985 and `event-end' functions."
988 (defsubst posn-string (position)
989 "Return the string object of POSITION.
990 Value is a cons (STRING . STRING-POS), or nil if not a string.
991 POSITION should be a list of the form returned by the `event-start'
992 and `event-end' functions."
995 (defsubst posn-image (position)
996 "Return the image object of POSITION.
997 Value is a list (image ...), or nil if not an image.
998 POSITION should be a list of the form returned by the `event-start'
999 and `event-end' functions."
1002 (defsubst posn-object (position)
1003 "Return the object (image or string) of POSITION.
1004 Value is a list (image ...) for an image object, a cons cell
1005 \(STRING . STRING-POS) for a string object, and nil for a buffer position.
1006 POSITION should be a list of the form returned by the `event-start'
1007 and `event-end' functions."
1008 (or (posn-image position) (posn-string position)))
1010 (defsubst posn-object-x-y (position)
1011 "Return the x and y coordinates relative to the object of POSITION.
1012 The return value has the form (DX . DY), where DX and DY are
1013 given in pixels. POSITION should be a list of the form returned
1014 by `event-start' and `event-end'."
1017 (defsubst posn-object-width-height (position)
1018 "Return the pixel width and height of the object of POSITION.
1019 The return value has the form (WIDTH . HEIGHT). POSITION should
1020 be a list of the form returned by `event-start' and `event-end'."
1024 ;;;; Obsolescent names for functions.
1026 (define-obsolete-function-alias 'window-dot 'window-point "22.1")
1027 (define-obsolete-function-alias 'set-window-dot 'set-window-point "22.1")
1028 (define-obsolete-function-alias 'read-input 'read-string "22.1")
1029 (define-obsolete-function-alias 'show-buffer 'set-window-buffer "22.1")
1030 (define-obsolete-function-alias 'eval-current-buffer 'eval-buffer "22.1")
1031 (define-obsolete-function-alias 'string-to-int 'string-to-number "22.1")
1033 (make-obsolete 'forward-point "use (+ (point) N) instead." "23.1")
1035 (defun insert-string (&rest args)
1036 "Mocklisp-compatibility insert function.
1037 Like the function `insert' except that any argument that is a number
1038 is converted into a string by expressing it in decimal."
1040 (insert (if (integerp el) (number-to-string el) el))))
1041 (make-obsolete 'insert-string 'insert "22.1")
1043 (defun makehash (&optional test) (make-hash-table :test (or test 'eql)))
1044 (make-obsolete 'makehash 'make-hash-table "22.1")
1046 ;; These are used by VM and some old programs
1047 (defalias 'focus-frame 'ignore "")
1048 (make-obsolete 'focus-frame "it does nothing." "22.1")
1049 (defalias 'unfocus-frame 'ignore "")
1050 (make-obsolete 'unfocus-frame "it does nothing." "22.1")
1051 (make-obsolete 'make-variable-frame-local
1052 "explicitly check for a frame-parameter instead." "22.2")
1053 (make-obsolete 'interactive-p 'called-interactively-p "23.2")
1054 (set-advertised-calling-convention 'called-interactively-p '(kind) "23.1")
1055 (set-advertised-calling-convention
1056 'all-completions '(string collection &optional predicate) "23.1")
1057 (set-advertised-calling-convention 'unintern '(name obarray) "23.3")
1059 ;;;; Obsolescence declarations for variables, and aliases.
1061 ;; Special "default-FOO" variables which contain the default value of
1062 ;; the "FOO" variable are nasty. Their implementation is brittle, and
1063 ;; slows down several unrelated variable operations; furthermore, they
1064 ;; can lead to really odd behavior if you decide to make them
1067 ;; Not used at all in Emacs, last time I checked:
1068 (make-obsolete-variable 'default-mode-line-format 'mode-line-format "23.2")
1069 (make-obsolete-variable 'default-header-line-format 'header-line-format "23.2")
1070 (make-obsolete-variable 'default-line-spacing 'line-spacing "23.2")
1071 (make-obsolete-variable 'default-abbrev-mode 'abbrev-mode "23.2")
1072 (make-obsolete-variable 'default-ctl-arrow 'ctl-arrow "23.2")
1073 (make-obsolete-variable 'default-truncate-lines 'truncate-lines "23.2")
1074 (make-obsolete-variable 'default-left-margin 'left-margin "23.2")
1075 (make-obsolete-variable 'default-tab-width 'tab-width "23.2")
1076 (make-obsolete-variable 'default-case-fold-search 'case-fold-search "23.2")
1077 (make-obsolete-variable 'default-left-margin-width 'left-margin-width "23.2")
1078 (make-obsolete-variable 'default-right-margin-width 'right-margin-width "23.2")
1079 (make-obsolete-variable 'default-left-fringe-width 'left-fringe-width "23.2")
1080 (make-obsolete-variable 'default-right-fringe-width 'right-fringe-width "23.2")
1081 (make-obsolete-variable 'default-fringes-outside-margins 'fringes-outside-margins "23.2")
1082 (make-obsolete-variable 'default-scroll-bar-width 'scroll-bar-width "23.2")
1083 (make-obsolete-variable 'default-vertical-scroll-bar 'vertical-scroll-bar "23.2")
1084 (make-obsolete-variable 'default-indicate-empty-lines 'indicate-empty-lines "23.2")
1085 (make-obsolete-variable 'default-indicate-buffer-boundaries 'indicate-buffer-boundaries "23.2")
1086 (make-obsolete-variable 'default-fringe-indicator-alist 'fringe-indicator-alist "23.2")
1087 (make-obsolete-variable 'default-fringe-cursor-alist 'fringe-cursor-alist "23.2")
1088 (make-obsolete-variable 'default-scroll-up-aggressively 'scroll-up-aggressively "23.2")
1089 (make-obsolete-variable 'default-scroll-down-aggressively 'scroll-down-aggressively "23.2")
1090 (make-obsolete-variable 'default-fill-column 'fill-column "23.2")
1091 (make-obsolete-variable 'default-cursor-type 'cursor-type "23.2")
1092 (make-obsolete-variable 'default-buffer-file-type 'buffer-file-type "23.2")
1093 (make-obsolete-variable 'default-cursor-in-non-selected-windows 'cursor-in-non-selected-windows "23.2")
1094 (make-obsolete-variable 'default-buffer-file-coding-system 'buffer-file-coding-system "23.2")
1095 (make-obsolete-variable 'default-major-mode 'major-mode "23.2")
1096 (make-obsolete-variable 'default-enable-multibyte-characters
1097 "use enable-multibyte-characters or set-buffer-multibyte instead" "23.2")
1099 (make-obsolete-variable 'define-key-rebound-commands nil "23.2")
1100 (make-obsolete-variable 'redisplay-end-trigger-functions 'jit-lock-register "23.1")
1101 (make-obsolete 'window-redisplay-end-trigger nil "23.1")
1102 (make-obsolete 'set-window-redisplay-end-trigger nil "23.1")
1104 (make-obsolete 'process-filter-multibyte-p nil "23.1")
1105 (make-obsolete 'set-process-filter-multibyte nil "23.1")
1107 (make-obsolete-variable
1108 'mode-line-inverse-video
1109 "use the appropriate faces instead."
1111 (make-obsolete-variable
1112 'unread-command-char
1113 "use `unread-command-events' instead. That variable is a list of events
1114 to reread, so it now uses nil to mean `no event', instead of -1."
1117 ;; Lisp manual only updated in 22.1.
1118 (define-obsolete-variable-alias 'executing-macro 'executing-kbd-macro
1121 (defvaralias 'x-lost-selection-hooks 'x-lost-selection-functions)
1122 (make-obsolete-variable 'x-lost-selection-hooks
1123 'x-lost-selection-functions "22.1")
1124 (defvaralias 'x-sent-selection-hooks 'x-sent-selection-functions)
1125 (make-obsolete-variable 'x-sent-selection-hooks
1126 'x-sent-selection-functions "22.1")
1128 ;; This was introduced in 21.4 for pre-unicode unification. That
1129 ;; usage was rendered obsolete in 23.1 which uses Unicode internally.
1130 ;; Other uses are possible, so this variable is not _really_ obsolete,
1131 ;; but Stefan insists to mark it so.
1132 (make-obsolete-variable 'translation-table-for-input nil "23.1")
1134 (defvaralias 'messages-buffer-max-lines 'message-log-max)
1136 ;; These aliases exist in Emacs 19.34, and probably before, but were
1137 ;; only marked as obsolete in 23.1.
1138 ;; The lisp manual (since at least Emacs 21) describes them as
1139 ;; existing "for compatibility with Emacs version 18".
1140 (define-obsolete-variable-alias 'last-input-char 'last-input-event
1142 (define-obsolete-variable-alias 'last-command-char 'last-command-event
1146 ;;;; Alternate names for functions - these are not being phased out.
1148 (defalias 'send-string 'process-send-string)
1149 (defalias 'send-region 'process-send-region)
1150 (defalias 'string= 'string-equal)
1151 (defalias 'string< 'string-lessp)
1152 (defalias 'move-marker 'set-marker)
1153 (defalias 'rplaca 'setcar)
1154 (defalias 'rplacd 'setcdr)
1155 (defalias 'beep 'ding) ;preserve lingual purity
1156 (defalias 'indent-to-column 'indent-to)
1157 (defalias 'backward-delete-char 'delete-backward-char)
1158 (defalias 'search-forward-regexp (symbol-function 're-search-forward))
1159 (defalias 'search-backward-regexp (symbol-function 're-search-backward))
1160 (defalias 'int-to-string 'number-to-string)
1161 (defalias 'store-match-data 'set-match-data)
1162 (defalias 'chmod 'set-file-modes)
1163 (defalias 'mkdir 'make-directory)
1164 ;; These are the XEmacs names:
1165 (defalias 'point-at-eol 'line-end-position)
1166 (defalias 'point-at-bol 'line-beginning-position)
1168 (defalias 'user-original-login-name 'user-login-name)
1171 ;;;; Hook manipulation functions.
1173 (defun add-hook (hook function &optional append local)
1174 "Add to the value of HOOK the function FUNCTION.
1175 FUNCTION is not added if already present.
1176 FUNCTION is added (if necessary) at the beginning of the hook list
1177 unless the optional argument APPEND is non-nil, in which case
1178 FUNCTION is added at the end.
1180 The optional fourth argument, LOCAL, if non-nil, says to modify
1181 the hook's buffer-local value rather than its default value.
1182 This makes the hook buffer-local if needed, and it makes t a member
1183 of the buffer-local value. That acts as a flag to run the hook
1184 functions in the default value as well as in the local value.
1186 HOOK should be a symbol, and FUNCTION may be any valid function. If
1187 HOOK is void, it is first set to nil. If HOOK's value is a single
1188 function, it is changed to a list of functions."
1189 (or (boundp hook) (set hook nil))
1190 (or (default-boundp hook) (set-default hook nil))
1191 (if local (unless (local-variable-if-set-p hook)
1192 (set (make-local-variable hook) (list t)))
1193 ;; Detect the case where make-local-variable was used on a hook
1194 ;; and do what we used to do.
1195 (unless (and (consp (symbol-value hook)) (memq t (symbol-value hook)))
1197 (let ((hook-value (if local (symbol-value hook) (default-value hook))))
1198 ;; If the hook value is a single function, turn it into a list.
1199 (when (or (not (listp hook-value)) (eq (car hook-value) 'lambda))
1200 (setq hook-value (list hook-value)))
1201 ;; Do the actual addition if necessary
1202 (unless (member function hook-value)
1203 (when (stringp function)
1204 (setq function (purecopy function)))
1207 (append hook-value (list function))
1208 (cons function hook-value))))
1209 ;; Set the actual variable
1212 ;; If HOOK isn't a permanent local,
1213 ;; but FUNCTION wants to survive a change of modes,
1214 ;; mark HOOK as partially permanent.
1215 (and (symbolp function)
1216 (get function 'permanent-local-hook)
1217 (not (get hook 'permanent-local))
1218 (put hook 'permanent-local 'permanent-local-hook))
1219 (set hook hook-value))
1220 (set-default hook hook-value))))
1222 (defun remove-hook (hook function &optional local)
1223 "Remove from the value of HOOK the function FUNCTION.
1224 HOOK should be a symbol, and FUNCTION may be any valid function. If
1225 FUNCTION isn't the value of HOOK, or, if FUNCTION doesn't appear in the
1226 list of hooks to run in HOOK, then nothing is done. See `add-hook'.
1228 The optional third argument, LOCAL, if non-nil, says to modify
1229 the hook's buffer-local value rather than its default value."
1230 (or (boundp hook) (set hook nil))
1231 (or (default-boundp hook) (set-default hook nil))
1232 ;; Do nothing if LOCAL is t but this hook has no local binding.
1233 (unless (and local (not (local-variable-p hook)))
1234 ;; Detect the case where make-local-variable was used on a hook
1235 ;; and do what we used to do.
1236 (when (and (local-variable-p hook)
1237 (not (and (consp (symbol-value hook))
1238 (memq t (symbol-value hook)))))
1240 (let ((hook-value (if local (symbol-value hook) (default-value hook))))
1241 ;; Remove the function, for both the list and the non-list cases.
1242 (if (or (not (listp hook-value)) (eq (car hook-value) 'lambda))
1243 (if (equal hook-value function) (setq hook-value nil))
1244 (setq hook-value (delete function (copy-sequence hook-value))))
1245 ;; If the function is on the global hook, we need to shadow it locally
1246 ;;(when (and local (member function (default-value hook))
1247 ;; (not (member (cons 'not function) hook-value)))
1248 ;; (push (cons 'not function) hook-value))
1249 ;; Set the actual variable
1251 (set-default hook hook-value)
1252 (if (equal hook-value '(t))
1253 (kill-local-variable hook)
1254 (set hook hook-value))))))
1256 (defmacro letrec (binders &rest body)
1257 "Bind variables according to BINDERS then eval BODY.
1258 The value of the last form in BODY is returned.
1259 Each element of BINDERS is a list (SYMBOL VALUEFORM) which binds
1260 SYMBOL to the value of VALUEFORM.
1261 All symbols are bound before the VALUEFORMs are evalled."
1262 ;; Only useful in lexical-binding mode.
1263 ;; As a special-form, we could implement it more efficiently (and cleanly,
1264 ;; making the vars actually unbound during evaluation of the binders).
1265 (declare (debug let) (indent 1))
1266 `(let ,(mapcar #'car binders)
1267 ,@(mapcar (lambda (binder) `(setq ,@binder)) binders)
1270 (defmacro with-wrapper-hook (var args &rest body)
1271 "Run BODY wrapped with the VAR hook.
1272 VAR is a special hook: its functions are called with a first argument
1273 which is the \"original\" code (the BODY), so the hook function can wrap
1274 the original function, or call it any number of times (including not calling
1275 it at all). This is similar to an `around' advice.
1276 VAR is normally a symbol (a variable) in which case it is treated like
1277 a hook, with a buffer-local and a global part. But it can also be an
1278 arbitrary expression.
1279 ARGS is a list of variables which will be passed as additional arguments
1280 to each function, after the initial argument, and which the first argument
1281 expects to receive when called."
1282 (declare (indent 2) (debug t))
1283 ;; We need those two gensyms because CL's lexical scoping is not available
1284 ;; for function arguments :-(
1285 (let ((funs (make-symbol "funs"))
1286 (global (make-symbol "global"))
1287 (argssym (make-symbol "args"))
1288 (runrestofhook (make-symbol "runrestofhook")))
1289 ;; Since the hook is a wrapper, the loop has to be done via
1290 ;; recursion: a given hook function will call its parameter in order to
1291 ;; continue looping.
1292 `(letrec ((,runrestofhook
1293 (lambda (,funs ,global ,argssym)
1294 ;; `funs' holds the functions left on the hook and `global'
1295 ;; holds the functions left on the global part of the hook
1296 ;; (in case the hook is local).
1298 (if (eq t (car ,funs))
1299 (funcall ,runrestofhook
1300 (append ,global (cdr ,funs)) nil ,argssym)
1303 (lambda (,funs ,global &rest ,argssym)
1304 (funcall ,runrestofhook ,funs ,global ,argssym))
1305 (cdr ,funs) ,global)
1307 ;; Once there are no more functions on the hook, run
1308 ;; the original body.
1309 (apply (lambda ,args ,@body) ,argssym)))))
1310 (funcall ,runrestofhook ,var
1311 ;; The global part of the hook, if any.
1313 `(if (local-variable-p ',var)
1314 (default-value ',var)))
1317 (defun add-to-list (list-var element &optional append compare-fn)
1318 "Add ELEMENT to the value of LIST-VAR if it isn't there yet.
1319 The test for presence of ELEMENT is done with `equal',
1320 or with COMPARE-FN if that's non-nil.
1321 If ELEMENT is added, it is added at the beginning of the list,
1322 unless the optional argument APPEND is non-nil, in which case
1323 ELEMENT is added at the end.
1325 The return value is the new value of LIST-VAR.
1327 If you want to use `add-to-list' on a variable that is not defined
1328 until a certain package is loaded, you should put the call to `add-to-list'
1329 into a hook function that will be run only after loading the package.
1330 `eval-after-load' provides one way to do this. In some cases
1331 other hooks, such as major mode hooks, can do the job."
1334 (member element (symbol-value list-var)))
1335 ((eq compare-fn 'eq)
1336 (memq element (symbol-value list-var)))
1337 ((eq compare-fn 'eql)
1338 (memql element (symbol-value list-var)))
1340 (let ((lst (symbol-value list-var)))
1342 (not (funcall compare-fn element (car lst))))
1343 (setq lst (cdr lst)))
1345 (symbol-value list-var)
1348 (append (symbol-value list-var) (list element))
1349 (cons element (symbol-value list-var))))))
1352 (defun add-to-ordered-list (list-var element &optional order)
1353 "Add ELEMENT to the value of LIST-VAR if it isn't there yet.
1354 The test for presence of ELEMENT is done with `eq'.
1356 The resulting list is reordered so that the elements are in the
1357 order given by each element's numeric list order. Elements
1358 without a numeric list order are placed at the end of the list.
1360 If the third optional argument ORDER is a number (integer or
1361 float), set the element's list order to the given value. If
1362 ORDER is nil or omitted, do not change the numeric order of
1363 ELEMENT. If ORDER has any other value, remove the numeric order
1364 of ELEMENT if it has one.
1366 The list order for each element is stored in LIST-VAR's
1367 `list-order' property.
1369 The return value is the new value of LIST-VAR."
1370 (let ((ordering (get list-var 'list-order)))
1372 (put list-var 'list-order
1373 (setq ordering (make-hash-table :weakness 'key :test 'eq))))
1375 (puthash element (and (numberp order) order) ordering))
1376 (unless (memq element (symbol-value list-var))
1377 (set list-var (cons element (symbol-value list-var))))
1378 (set list-var (sort (symbol-value list-var)
1380 (let ((oa (gethash a ordering))
1381 (ob (gethash b ordering)))
1386 (defun add-to-history (history-var newelt &optional maxelt keep-all)
1387 "Add NEWELT to the history list stored in the variable HISTORY-VAR.
1388 Return the new history list.
1389 If MAXELT is non-nil, it specifies the maximum length of the history.
1390 Otherwise, the maximum history length is the value of the `history-length'
1391 property on symbol HISTORY-VAR, if set, or the value of the `history-length'
1393 Remove duplicates of NEWELT if `history-delete-duplicates' is non-nil.
1394 If optional fourth arg KEEP-ALL is non-nil, add NEWELT to history even
1395 if it is empty or a duplicate."
1397 (setq maxelt (or (get history-var 'history-length)
1399 (let ((history (symbol-value history-var))
1401 (when (and (listp history)
1403 (not (stringp newelt))
1404 (> (length newelt) 0))
1406 (not (equal (car history) newelt))))
1407 (if history-delete-duplicates
1408 (delete newelt history))
1409 (setq history (cons newelt history))
1410 (when (integerp maxelt)
1413 (setq tail (nthcdr (1- maxelt) history))
1415 (setcdr tail nil)))))
1416 (set history-var history)))
1421 (defvar delay-mode-hooks nil
1422 "If non-nil, `run-mode-hooks' should delay running the hooks.")
1423 (defvar delayed-mode-hooks nil
1424 "List of delayed mode hooks waiting to be run.")
1425 (make-variable-buffer-local 'delayed-mode-hooks)
1426 (put 'delay-mode-hooks 'permanent-local t)
1428 (defvar after-change-major-mode-hook nil
1429 "Normal hook run at the very end of major mode functions.")
1431 (defun run-mode-hooks (&rest hooks)
1432 "Run mode hooks `delayed-mode-hooks' and HOOKS, or delay HOOKS.
1433 Execution is delayed if the variable `delay-mode-hooks' is non-nil.
1434 Otherwise, runs the mode hooks and then `after-change-major-mode-hook'.
1435 Major mode functions should use this instead of `run-hooks' when running their
1437 (if delay-mode-hooks
1439 (dolist (hook hooks)
1440 (push hook delayed-mode-hooks))
1441 ;; Normal case, just run the hook as before plus any delayed hooks.
1442 (setq hooks (nconc (nreverse delayed-mode-hooks) hooks))
1443 (setq delayed-mode-hooks nil)
1444 (apply 'run-hooks hooks)
1445 (run-hooks 'after-change-major-mode-hook)))
1447 (defmacro delay-mode-hooks (&rest body)
1448 "Execute BODY, but delay any `run-mode-hooks'.
1449 These hooks will be executed by the first following call to
1450 `run-mode-hooks' that occurs outside any `delayed-mode-hooks' form.
1451 Only affects hooks run in the current buffer."
1452 (declare (debug t) (indent 0))
1454 (make-local-variable 'delay-mode-hooks)
1455 (let ((delay-mode-hooks t))
1458 ;; PUBLIC: find if the current mode derives from another.
1460 (defun derived-mode-p (&rest modes)
1461 "Non-nil if the current major mode is derived from one of MODES.
1462 Uses the `derived-mode-parent' property of the symbol to trace backwards."
1463 (let ((parent major-mode))
1464 (while (and (not (memq parent modes))
1465 (setq parent (get parent 'derived-mode-parent))))
1470 ;; If a minor mode is not defined with define-minor-mode,
1471 ;; add it here explicitly.
1472 ;; isearch-mode is deliberately excluded, since you should
1473 ;; not call it yourself.
1474 (defvar minor-mode-list '(auto-save-mode auto-fill-mode abbrev-mode
1475 overwrite-mode view-mode
1477 "List of all minor mode functions.")
1479 (defun add-minor-mode (toggle name &optional keymap after toggle-fun)
1480 "Register a new minor mode.
1482 This is an XEmacs-compatibility function. Use `define-minor-mode' instead.
1484 TOGGLE is a symbol which is the name of a buffer-local variable that
1485 is toggled on or off to say whether the minor mode is active or not.
1487 NAME specifies what will appear in the mode line when the minor mode
1488 is active. NAME should be either a string starting with a space, or a
1489 symbol whose value is such a string.
1491 Optional KEYMAP is the keymap for the minor mode that will be added
1492 to `minor-mode-map-alist'.
1494 Optional AFTER specifies that TOGGLE should be added after AFTER
1495 in `minor-mode-alist'.
1497 Optional TOGGLE-FUN is an interactive function to toggle the mode.
1498 It defaults to (and should by convention be) TOGGLE.
1500 If TOGGLE has a non-nil `:included' property, an entry for the mode is
1501 included in the mode-line minor mode menu.
1502 If TOGGLE has a `:menu-tag', that is used for the menu item's label."
1503 (unless (memq toggle minor-mode-list)
1504 (push toggle minor-mode-list))
1506 (unless toggle-fun (setq toggle-fun toggle))
1507 (unless (eq toggle-fun toggle)
1508 (put toggle :minor-mode-function toggle-fun))
1509 ;; Add the name to the minor-mode-alist.
1511 (let ((existing (assq toggle minor-mode-alist)))
1513 (setcdr existing (list name))
1514 (let ((tail minor-mode-alist) found)
1515 (while (and tail (not found))
1516 (if (eq after (caar tail))
1518 (setq tail (cdr tail))))
1520 (let ((rest (cdr found)))
1522 (nconc found (list (list toggle name)) rest))
1523 (push (list toggle name) minor-mode-alist))))))
1524 ;; Add the toggle to the minor-modes menu if requested.
1525 (when (get toggle :included)
1526 (define-key mode-line-mode-menu
1530 (or (get toggle :menu-tag)
1531 (if (stringp name) name (symbol-name toggle)))
1532 (let ((mode-name (if (symbolp name) (symbol-value name))))
1533 (if (and (stringp mode-name) (string-match "[^ ]+" mode-name))
1534 (concat " (" (match-string 0 mode-name) ")"))))
1536 :button (cons :toggle toggle))))
1538 ;; Add the map to the minor-mode-map-alist.
1540 (let ((existing (assq toggle minor-mode-map-alist)))
1542 (setcdr existing keymap)
1543 (let ((tail minor-mode-map-alist) found)
1544 (while (and tail (not found))
1545 (if (eq after (caar tail))
1547 (setq tail (cdr tail))))
1549 (let ((rest (cdr found)))
1551 (nconc found (list (cons toggle keymap)) rest))
1552 (push (cons toggle keymap) minor-mode-map-alist)))))))
1556 (defun symbol-file (symbol &optional type)
1557 "Return the name of the file that defined SYMBOL.
1558 The value is normally an absolute file name. It can also be nil,
1559 if the definition is not associated with any file. If SYMBOL
1560 specifies an autoloaded function, the value can be a relative
1561 file name without extension.
1563 If TYPE is nil, then any kind of definition is acceptable. If
1564 TYPE is `defun', `defvar', or `defface', that specifies function
1565 definition, variable definition, or face definition only."
1566 (if (and (or (null type) (eq type 'defun))
1567 (symbolp symbol) (fboundp symbol)
1568 (eq 'autoload (car-safe (symbol-function symbol))))
1569 (nth 1 (symbol-function symbol))
1570 (let ((files load-history)
1574 (if (eq type 'defvar)
1575 ;; Variables are present just as their names.
1576 (member symbol (cdr (car files)))
1577 ;; Other types are represented as (TYPE . NAME).
1578 (member (cons type symbol) (cdr (car files))))
1579 ;; We accept all types, so look for variable def
1580 ;; and then for any other kind.
1581 (or (member symbol (cdr (car files)))
1582 (rassq symbol (cdr (car files)))))
1583 (setq file (car (car files)) files nil))
1584 (setq files (cdr files)))
1587 (defun locate-library (library &optional nosuffix path interactive-call)
1588 "Show the precise file name of Emacs library LIBRARY.
1589 LIBRARY should be a relative file name of the library, a string.
1590 It can omit the suffix (a.k.a. file-name extension) if NOSUFFIX is
1591 nil (which is the default, see below).
1592 This command searches the directories in `load-path' like `\\[load-library]'
1593 to find the file that `\\[load-library] RET LIBRARY RET' would load.
1594 Optional second arg NOSUFFIX non-nil means don't add suffixes `load-suffixes'
1595 to the specified name LIBRARY.
1597 If the optional third arg PATH is specified, that list of directories
1598 is used instead of `load-path'.
1600 When called from a program, the file name is normally returned as a
1601 string. When run interactively, the argument INTERACTIVE-CALL is t,
1602 and the file name is displayed in the echo area."
1603 (interactive (list (completing-read "Locate library: "
1605 'locate-file-completion-table
1606 load-path (get-load-suffixes)))
1609 (let ((file (locate-file library
1611 (append (unless nosuffix (get-load-suffixes))
1612 load-file-rep-suffixes))))
1613 (if interactive-call
1615 (message "Library is file %s" (abbreviate-file-name file))
1616 (message "No library %s in search path" library)))
1620 ;;;; Specifying things to do later.
1622 (defun load-history-regexp (file)
1623 "Form a regexp to find FILE in `load-history'.
1624 FILE, a string, is described in the function `eval-after-load'."
1625 (if (file-name-absolute-p file)
1626 (setq file (file-truename file)))
1627 (concat (if (file-name-absolute-p file) "\\`" "\\(\\`\\|/\\)")
1629 (if (file-name-extension file)
1631 ;; Note: regexp-opt can't be used here, since we need to call
1632 ;; this before Emacs has been fully started. 2006-05-21
1633 (concat "\\(" (mapconcat 'regexp-quote load-suffixes "\\|") "\\)?"))
1634 "\\(" (mapconcat 'regexp-quote jka-compr-load-suffixes "\\|")
1637 (defun load-history-filename-element (file-regexp)
1638 "Get the first elt of `load-history' whose car matches FILE-REGEXP.
1639 Return nil if there isn't one."
1640 (let* ((loads load-history)
1641 (load-elt (and loads (car loads))))
1644 (or (null (car load-elt))
1645 (not (string-match file-regexp (car load-elt)))))
1646 (setq loads (cdr loads)
1647 load-elt (and loads (car loads)))))
1650 (put 'eval-after-load 'lisp-indent-function 1)
1651 (defun eval-after-load (file form)
1652 "Arrange that, if FILE is ever loaded, FORM will be run at that time.
1653 If FILE is already loaded, evaluate FORM right now.
1655 If a matching file is loaded again, FORM will be evaluated again.
1657 If FILE is a string, it may be either an absolute or a relative file
1658 name, and may have an extension \(e.g. \".el\") or may lack one, and
1659 additionally may or may not have an extension denoting a compressed
1660 format \(e.g. \".gz\").
1662 When FILE is absolute, this first converts it to a true name by chasing
1663 symbolic links. Only a file of this name \(see next paragraph regarding
1664 extensions) will trigger the evaluation of FORM. When FILE is relative,
1665 a file whose absolute true name ends in FILE will trigger evaluation.
1667 When FILE lacks an extension, a file name with any extension will trigger
1668 evaluation. Otherwise, its extension must match FILE's. A further
1669 extension for a compressed format \(e.g. \".gz\") on FILE will not affect
1672 Alternatively, FILE can be a feature (i.e. a symbol), in which case FORM
1673 is evaluated at the end of any file that `provide's this feature.
1675 Usually FILE is just a library name like \"font-lock\" or a feature name
1678 This function makes or adds to an entry on `after-load-alist'."
1679 ;; Add this FORM into after-load-alist (regardless of whether we'll be
1680 ;; evaluating it now).
1681 (let* ((regexp-or-feature
1683 (setq file (purecopy (load-history-regexp file)))
1685 (elt (assoc regexp-or-feature after-load-alist)))
1687 (setq elt (list regexp-or-feature))
1688 (push elt after-load-alist))
1689 ;; Make sure `form' is evalled in the current lexical/dynamic code.
1690 (setq form `(funcall ',(eval `(lambda () ,form) lexical-binding)))
1691 (when (symbolp regexp-or-feature)
1692 ;; For features, the after-load-alist elements get run when `provide' is
1693 ;; called rather than at the end of the file. So add an indirection to
1694 ;; make sure that `form' is really run "after-load" in case the provide
1695 ;; call happens early.
1697 `(when load-file-name
1698 (let ((fun (make-symbol "eval-after-load-helper")))
1699 (fset fun `(lambda (file)
1700 (if (not (equal file ',load-file-name))
1702 (remove-hook 'after-load-functions ',fun)
1704 (add-hook 'after-load-functions fun)))))
1705 ;; Add FORM to the element unless it's already there.
1706 (unless (member form (cdr elt))
1707 (nconc elt (purecopy (list form))))
1709 ;; Is there an already loaded file whose name (or `provide' name)
1711 (if (if (stringp file)
1712 (load-history-filename-element regexp-or-feature)
1716 (defvar after-load-functions nil
1717 "Special hook run after loading a file.
1718 Each function there is called with a single argument, the absolute
1719 name of the file just loaded.")
1721 (defun do-after-load-evaluation (abs-file)
1722 "Evaluate all `eval-after-load' forms, if any, for ABS-FILE.
1723 ABS-FILE, a string, should be the absolute true name of a file just loaded.
1724 This function is called directly from the C code."
1725 ;; Run the relevant eval-after-load forms.
1726 (mapc #'(lambda (a-l-element)
1727 (when (and (stringp (car a-l-element))
1728 (string-match-p (car a-l-element) abs-file))
1729 ;; discard the file name regexp
1730 (mapc #'eval (cdr a-l-element))))
1732 ;; Complain when the user uses obsolete files.
1733 (when (string-match-p "/obsolete/[^/]*\\'" abs-file)
1734 (run-with-timer 0 nil
1736 (message "Package %s is obsolete!"
1738 (string-match "\\.elc?\\>" file))))
1739 (file-name-nondirectory abs-file)))
1740 ;; Finally, run any other hook.
1741 (run-hook-with-args 'after-load-functions abs-file))
1743 (defun eval-next-after-load (file)
1744 "Read the following input sexp, and run it whenever FILE is loaded.
1745 This makes or adds to an entry on `after-load-alist'.
1746 FILE should be the name of a library, with no directory name."
1747 (eval-after-load file (read)))
1748 (make-obsolete 'eval-next-after-load `eval-after-load "23.2")
1752 (defun process-lines (program &rest args)
1753 "Execute PROGRAM with ARGS, returning its output as a list of lines.
1754 Signal an error if the program returns with a non-zero exit status."
1756 (let ((status (apply 'call-process program nil (current-buffer) nil args)))
1757 (unless (eq status 0)
1758 (error "%s exited with status %s" program status))
1759 (goto-char (point-min))
1762 (setq lines (cons (buffer-substring-no-properties
1763 (line-beginning-position)
1764 (line-end-position))
1767 (nreverse lines)))))
1769 ;; open-network-stream is a wrapper around make-network-process.
1771 (when (featurep 'make-network-process)
1772 (defun open-network-stream (name buffer host service)
1773 "Open a TCP connection for a service to a host.
1774 Returns a subprocess-object to represent the connection.
1775 Input and output work as for subprocesses; `delete-process' closes it.
1777 NAME is the name for the process. It is modified if necessary to make
1779 BUFFER is the buffer (or buffer name) to associate with the
1780 process. Process output goes at end of that buffer. BUFFER may
1781 be nil, meaning that this process is not associated with any buffer.
1782 HOST is the name or IP address of the host to connect to.
1783 SERVICE is the name of the service desired, or an integer specifying
1784 a port number to connect to.
1786 This is a wrapper around `make-network-process', and only offers a
1787 subset of its functionality."
1788 (make-network-process :name name :buffer buffer
1789 :host host :service service)))
1794 'process-kill-without-query
1795 "use `process-query-on-exit-flag' or `set-process-query-on-exit-flag'."
1797 (defun process-kill-without-query (process &optional flag)
1798 "Say no query needed if PROCESS is running when Emacs is exited.
1799 Optional second argument if non-nil says to require a query.
1800 Value is t if a query was formerly required."
1801 (let ((old (process-query-on-exit-flag process)))
1802 (set-process-query-on-exit-flag process nil)
1805 (defun process-kill-buffer-query-function ()
1806 "Ask before killing a buffer that has a running process."
1807 (let ((process (get-buffer-process (current-buffer))))
1809 (not (memq (process-status process) '(run stop open listen)))
1810 (not (process-query-on-exit-flag process))
1811 (yes-or-no-p "Buffer has a running process; kill it? "))))
1813 (add-hook 'kill-buffer-query-functions 'process-kill-buffer-query-function)
1815 ;; process plist management
1817 (defun process-get (process propname)
1818 "Return the value of PROCESS' PROPNAME property.
1819 This is the last value stored with `(process-put PROCESS PROPNAME VALUE)'."
1820 (plist-get (process-plist process) propname))
1822 (defun process-put (process propname value)
1823 "Change PROCESS' PROPNAME property to VALUE.
1824 It can be retrieved with `(process-get PROCESS PROPNAME)'."
1825 (set-process-plist process
1826 (plist-put (process-plist process) propname value)))
1829 ;;;; Input and display facilities.
1831 (defvar read-quoted-char-radix 8
1832 "*Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
1833 Legitimate radix values are 8, 10 and 16.")
1835 (custom-declare-variable-early
1836 'read-quoted-char-radix 8
1837 "*Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
1838 Legitimate radix values are 8, 10 and 16."
1839 :type '(choice (const 8) (const 10) (const 16))
1840 :group 'editing-basics)
1842 (defconst read-key-empty-map (make-sparse-keymap))
1844 (defvar read-key-delay 0.01) ;Fast enough for 100Hz repeat rate, hopefully.
1846 (defun read-key (&optional prompt)
1847 "Read a key from the keyboard.
1848 Contrary to `read-event' this will not return a raw event but instead will
1849 obey the input decoding and translations usually done by `read-key-sequence'.
1850 So escape sequences and keyboard encoding are taken into account.
1851 When there's an ambiguity because the key looks like the prefix of
1852 some sort of escape sequence, the ambiguity is resolved via `read-key-delay'."
1853 (let ((overriding-terminal-local-map read-key-empty-map)
1854 (overriding-local-map nil)
1856 (old-global-map (current-global-map))
1857 (timer (run-with-idle-timer
1858 ;; Wait long enough that Emacs has the time to receive and
1859 ;; process all the raw events associated with the single-key.
1860 ;; But don't wait too long, or the user may find the delay
1861 ;; annoying (or keep hitting more keys which may then get
1862 ;; lost or misinterpreted).
1863 ;; This is only relevant for keys which Emacs perceives as
1864 ;; "prefixes", such as C-x (because of the C-x 8 map in
1865 ;; key-translate-table and the C-x @ map in function-key-map)
1866 ;; or ESC (because of terminal escape sequences in
1867 ;; input-decode-map).
1870 (let ((keys (this-command-keys-vector)))
1871 (unless (zerop (length keys))
1872 ;; `keys' is non-empty, so the user has hit at least
1873 ;; one key; there's no point waiting any longer, even
1874 ;; though read-key-sequence thinks we should wait
1875 ;; for more input to decide how to interpret the
1877 (throw 'read-key keys)))))))
1881 (let ((map (make-sparse-keymap)))
1882 ;; Don't hide the menu-bar and tool-bar entries.
1883 (define-key map [menu-bar] (lookup-key global-map [menu-bar]))
1884 (define-key map [tool-bar] (lookup-key global-map [tool-bar]))
1886 (aref (catch 'read-key (read-key-sequence-vector prompt nil t)) 0))
1887 (cancel-timer timer)
1888 (use-global-map old-global-map))))
1890 (defun read-quoted-char (&optional prompt)
1891 "Like `read-char', but do not allow quitting.
1892 Also, if the first character read is an octal digit,
1893 we read any number of octal digits and return the
1894 specified character code. Any nondigit terminates the sequence.
1895 If the terminator is RET, it is discarded;
1896 any other terminator is used itself as input.
1898 The optional argument PROMPT specifies a string to use to prompt the user.
1899 The variable `read-quoted-char-radix' controls which radix to use
1901 (let ((message-log-max nil) done (first t) (code 0) char translated)
1903 (let ((inhibit-quit first)
1904 ;; Don't let C-h get the help message--only help function keys.
1907 "Type the special character you want to use,
1908 or the octal character code.
1909 RET terminates the character code and is discarded;
1910 any other non-digit terminates the character code and is then used as input."))
1911 (setq char (read-event (and prompt (format "%s-" prompt)) t))
1912 (if inhibit-quit (setq quit-flag nil)))
1913 ;; Translate TAB key into control-I ASCII character, and so on.
1914 ;; Note: `read-char' does it using the `ascii-character' property.
1915 ;; We should try and use read-key instead.
1916 (let ((translation (lookup-key local-function-key-map (vector char))))
1917 (setq translated (if (arrayp translation)
1918 (aref translation 0)
1920 (if (integerp translated)
1921 (setq translated (char-resolve-modifiers translated)))
1922 (cond ((null translated))
1923 ((not (integerp translated))
1924 (setq unread-command-events (list char)
1926 ((/= (logand translated ?\M-\^@) 0)
1927 ;; Turn a meta-character into a character with the 0200 bit set.
1928 (setq code (logior (logand translated (lognot ?\M-\^@)) 128)
1930 ((and (<= ?0 translated)
1931 (< translated (+ ?0 (min 10 read-quoted-char-radix))))
1932 (setq code (+ (* code read-quoted-char-radix) (- translated ?0)))
1933 (and prompt (setq prompt (message "%s %c" prompt translated))))
1934 ((and (<= ?a (downcase translated))
1935 (< (downcase translated)
1936 (+ ?a -10 (min 36 read-quoted-char-radix))))
1937 (setq code (+ (* code read-quoted-char-radix)
1938 (+ 10 (- (downcase translated) ?a))))
1939 (and prompt (setq prompt (message "%s %c" prompt translated))))
1940 ((and (not first) (eq translated ?\C-m))
1943 (setq unread-command-events (list char)
1945 (t (setq code translated
1950 (defun read-passwd (prompt &optional confirm default)
1951 "Read a password, prompting with PROMPT, and return it.
1952 If optional CONFIRM is non-nil, read the password twice to make sure.
1953 Optional DEFAULT is a default password to use instead of empty input.
1955 This function echoes `.' for each character that the user types.
1957 The user ends with RET, LFD, or ESC. DEL or C-h rubs out.
1958 C-y yanks the current kill. C-u kills line.
1959 C-g quits; if `inhibit-quit' was non-nil around this function,
1960 then it returns nil if the user types C-g, but `quit-flag' remains set.
1962 Once the caller uses the password, it can erase the password
1963 by doing (clear-string STRING)."
1967 (while (not success)
1968 (let ((first (read-passwd prompt nil default))
1969 (second (read-passwd "Confirm password: " nil default)))
1970 (if (equal first second)
1972 (and (arrayp second) (clear-string second))
1973 (setq success first))
1974 (and (arrayp first) (clear-string first))
1975 (and (arrayp second) (clear-string second))
1976 (message "Password not repeated accurately; please start over")
1980 ;; Copy it so that add-text-properties won't modify
1981 ;; the object that was passed in by the caller.
1982 (prompt (copy-sequence prompt))
1985 (cursor-in-echo-area t)
1986 (message-log-max nil)
1987 (stop-keys (list 'return ?\r ?\n ?\e))
1988 (rubout-keys (list 'backspace ?\b ?\177)))
1989 (add-text-properties 0 (length prompt)
1990 minibuffer-prompt-properties prompt)
1991 (while (progn (message "%s%s"
1993 (make-string (length pass) ?.))
1995 (not (memq c stop-keys)))
1996 (clear-this-command-keys)
1997 (cond ((memq c rubout-keys) ; rubout
1998 (when (> (length pass) 0)
1999 (let ((new-pass (substring pass 0 -1)))
2000 (and (arrayp pass) (clear-string pass))
2001 (setq pass new-pass))))
2002 ((eq c ?\C-g) (keyboard-quit))
2004 ((= c ?\C-u) ; kill line
2005 (and (arrayp pass) (clear-string pass))
2008 (let* ((str (condition-case nil
2015 (substring-no-properties str)))
2016 (and (arrayp pass) (clear-string pass))
2018 (setq pass new-pass))))
2019 ((characterp c) ; insert char
2020 (let* ((new-char (char-to-string c))
2021 (new-pass (concat pass new-char)))
2022 (and (arrayp pass) (clear-string pass))
2023 (clear-string new-char)
2025 (setq pass new-pass)))))
2027 (or pass default "")))))
2029 ;; This should be used by `call-interactively' for `n' specs.
2030 (defun read-number (prompt &optional default)
2031 "Read a numeric value in the minibuffer, prompting with PROMPT.
2032 DEFAULT specifies a default value to return if the user just types RET.
2033 The value of DEFAULT is inserted into PROMPT."
2037 (if (string-match "\\(\\):[ \t]*\\'" prompt)
2038 (replace-match (format " (default %s)" default) t t prompt 1)
2039 (replace-regexp-in-string "[ \t]*\\'"
2040 (format " (default %s) " default)
2044 (let ((str (read-from-minibuffer prompt nil nil nil nil
2046 (number-to-string default)))))
2049 ((zerop (length str)) default)
2050 ((stringp str) (read str))))
2053 (message "Please enter a number.")
2058 (defun read-char-choice (prompt chars &optional inhibit-keyboard-quit)
2059 "Read and return one of CHARS, prompting for PROMPT.
2060 Any input that is not one of CHARS is ignored.
2062 If optional argument INHIBIT-KEYBOARD-QUIT is non-nil, ignore
2063 keyboard-quit events while waiting for a valid input."
2064 (unless (consp chars)
2065 (error "Called `read-char-choice' without valid char choices"))
2066 (let ((cursor-in-echo-area t)
2067 (executing-kbd-macro executing-kbd-macro)
2070 (unless (get-text-property 0 'face prompt)
2071 (setq prompt (propertize prompt 'face 'minibuffer-prompt)))
2072 (setq char (let ((inhibit-quit inhibit-keyboard-quit))
2075 ((not (numberp char)))
2078 ((and executing-kbd-macro (= char -1))
2079 ;; read-event returns -1 if we are in a kbd macro and
2080 ;; there are no more events in the macro. Attempt to
2081 ;; get an event interactively.
2082 (setq executing-kbd-macro nil))))
2083 ;; Display the question with the answer.
2084 (message "%s%s" prompt (char-to-string char))
2087 (defun sit-for (seconds &optional nodisp obsolete)
2088 "Perform redisplay, then wait for SECONDS seconds or until input is available.
2089 SECONDS may be a floating-point value.
2090 \(On operating systems that do not support waiting for fractions of a
2091 second, floating-point values are rounded down to the nearest integer.)
2093 If optional arg NODISP is t, don't redisplay, just wait for input.
2094 Redisplay does not happen if input is available before it starts.
2096 Value is t if waited the full time with no input arriving, and nil otherwise.
2098 An obsolete, but still supported form is
2099 \(sit-for SECONDS &optional MILLISECONDS NODISP)
2100 where the optional arg MILLISECONDS specifies an additional wait period,
2101 in milliseconds; this was useful when Emacs was built without
2102 floating point support."
2103 (if (numberp nodisp)
2104 (setq seconds (+ seconds (* 1e-3 nodisp))
2106 (if obsolete (setq nodisp obsolete)))
2114 (or nodisp (redisplay)))
2116 (or nodisp (redisplay))
2117 (let ((read (read-event nil nil seconds)))
2120 ;; If last command was a prefix arg, e.g. C-u, push this event onto
2121 ;; unread-command-events as (t . EVENT) so it will be added to
2122 ;; this-command-keys by read-key-sequence.
2123 (if (eq overriding-terminal-local-map universal-argument-map)
2124 (setq read (cons t read)))
2125 (push read unread-command-events)
2127 (set-advertised-calling-convention 'sit-for '(seconds &optional nodisp) "22.1")
2129 (defun y-or-n-p (prompt)
2130 "Ask user a \"y or n\" question. Return t if answer is \"y\".
2131 PROMPT is the string to display to ask the question. It should
2132 end in a space; `y-or-n-p' adds \"(y or n) \" to it.
2134 No confirmation of the answer is requested; a single character is enough.
2135 Also accepts Space to mean yes, or Delete to mean no. \(Actually, it uses
2136 the bindings in `query-replace-map'; see the documentation of that variable
2137 for more information. In this case, the useful bindings are `act', `skip',
2138 `recenter', and `quit'.\)
2140 Under a windowing system a dialog box will be used if `last-nonmenu-event'
2141 is nil and `use-dialog-box' is non-nil."
2142 ;; ¡Beware! when I tried to edebug this code, Emacs got into a weird state
2143 ;; where all the keys were unbound (i.e. it somehow got triggered
2144 ;; within read-key, apparently). I had to kill it.
2145 (let ((answer 'recenter))
2146 (if (and (display-popup-menus-p)
2147 (listp last-nonmenu-event)
2150 (x-popup-dialog t `(,prompt ("yes" . act) ("No" . skip))))
2151 (setq prompt (concat prompt
2152 (if (eq ?\s (aref prompt (1- (length prompt))))
2157 (let ((cursor-in-echo-area t))
2158 (when minibuffer-auto-raise
2159 (raise-frame (window-frame (minibuffer-window))))
2160 (read-key (propertize (if (eq answer 'recenter)
2162 (concat "Please answer y or n. "
2164 'face 'minibuffer-prompt)))))
2165 (setq answer (lookup-key query-replace-map (vector key) t))
2167 ((memq answer '(skip act)) nil)
2168 ((eq answer 'recenter) (recenter) t)
2169 ((memq answer '(exit-prefix quit)) (signal 'quit nil) t)
2173 (let ((ret (eq answer 'act)))
2174 (unless noninteractive
2175 (message "%s %s" prompt (if ret "y" "n")))
2179 ;;; Atomic change groups.
2181 (defmacro atomic-change-group (&rest body)
2182 "Perform BODY as an atomic change group.
2183 This means that if BODY exits abnormally,
2184 all of its changes to the current buffer are undone.
2185 This works regardless of whether undo is enabled in the buffer.
2187 This mechanism is transparent to ordinary use of undo;
2188 if undo is enabled in the buffer and BODY succeeds, the
2189 user can undo the change normally."
2190 (declare (indent 0) (debug t))
2191 (let ((handle (make-symbol "--change-group-handle--"))
2192 (success (make-symbol "--change-group-success--")))
2193 `(let ((,handle (prepare-change-group))
2194 ;; Don't truncate any undo data in the middle of this.
2195 (undo-outer-limit nil)
2196 (undo-limit most-positive-fixnum)
2197 (undo-strong-limit most-positive-fixnum)
2201 ;; This is inside the unwind-protect because
2202 ;; it enables undo if that was disabled; we need
2203 ;; to make sure that it gets disabled again.
2204 (activate-change-group ,handle)
2207 ;; Either of these functions will disable undo
2208 ;; if it was disabled before.
2210 (accept-change-group ,handle)
2211 (cancel-change-group ,handle))))))
2213 (defun prepare-change-group (&optional buffer)
2214 "Return a handle for the current buffer's state, for a change group.
2215 If you specify BUFFER, make a handle for BUFFER's state instead.
2217 Pass the handle to `activate-change-group' afterward to initiate
2218 the actual changes of the change group.
2220 To finish the change group, call either `accept-change-group' or
2221 `cancel-change-group' passing the same handle as argument. Call
2222 `accept-change-group' to accept the changes in the group as final;
2223 call `cancel-change-group' to undo them all. You should use
2224 `unwind-protect' to make sure the group is always finished. The call
2225 to `activate-change-group' should be inside the `unwind-protect'.
2226 Once you finish the group, don't use the handle again--don't try to
2227 finish the same group twice. For a simple example of correct use, see
2228 the source code of `atomic-change-group'.
2230 The handle records only the specified buffer. To make a multibuffer
2231 change group, call this function once for each buffer you want to
2232 cover, then use `nconc' to combine the returned values, like this:
2234 (nconc (prepare-change-group buffer-1)
2235 (prepare-change-group buffer-2))
2237 You can then activate that multibuffer change group with a single
2238 call to `activate-change-group' and finish it with a single call
2239 to `accept-change-group' or `cancel-change-group'."
2242 (list (cons buffer (with-current-buffer buffer buffer-undo-list)))
2243 (list (cons (current-buffer) buffer-undo-list))))
2245 (defun activate-change-group (handle)
2246 "Activate a change group made with `prepare-change-group' (which see)."
2247 (dolist (elt handle)
2248 (with-current-buffer (car elt)
2249 (if (eq buffer-undo-list t)
2250 (setq buffer-undo-list nil)))))
2252 (defun accept-change-group (handle)
2253 "Finish a change group made with `prepare-change-group' (which see).
2254 This finishes the change group by accepting its changes as final."
2255 (dolist (elt handle)
2256 (with-current-buffer (car elt)
2258 (setq buffer-undo-list t)))))
2260 (defun cancel-change-group (handle)
2261 "Finish a change group made with `prepare-change-group' (which see).
2262 This finishes the change group by reverting all of its changes."
2263 (dolist (elt handle)
2264 (with-current-buffer (car elt)
2265 (setq elt (cdr elt))
2267 ;; Widen buffer temporarily so if the buffer was narrowed within
2268 ;; the body of `atomic-change-group' all changes can be undone.
2271 (if (consp elt) (car elt)))
2273 (if (consp elt) (cdr elt))))
2274 ;; Temporarily truncate the undo log at ELT.
2276 (setcar elt nil) (setcdr elt nil))
2277 (unless (eq last-command 'undo) (undo-start))
2278 ;; Make sure there's no confusion.
2279 (when (and (consp elt) (not (eq elt (last pending-undo-list))))
2280 (error "Undoing to some unrelated state"))
2283 (while (listp pending-undo-list) (undo-more 1)))
2284 ;; Reset the modified cons cell ELT to its original content.
2286 (setcar elt old-car)
2287 (setcdr elt old-cdr))
2288 ;; Revert the undo info to what it was when we grabbed the state.
2289 (setq buffer-undo-list elt))))))
2291 ;;;; Display-related functions.
2293 ;; For compatibility.
2294 (defalias 'redraw-modeline 'force-mode-line-update)
2296 (defun force-mode-line-update (&optional all)
2297 "Force redisplay of the current buffer's mode line and header line.
2298 With optional non-nil ALL, force redisplay of all mode lines and
2299 header lines. This function also forces recomputation of the
2300 menu bar menus and the frame title."
2301 (if all (with-current-buffer (other-buffer)))
2302 (set-buffer-modified-p (buffer-modified-p)))
2304 (defun momentary-string-display (string pos &optional exit-char message)
2305 "Momentarily display STRING in the buffer at POS.
2306 Display remains until next event is input.
2307 If POS is a marker, only its position is used; its buffer is ignored.
2308 Optional third arg EXIT-CHAR can be a character, event or event
2309 description list. EXIT-CHAR defaults to SPC. If the input is
2310 EXIT-CHAR it is swallowed; otherwise it is then available as
2311 input (as a command if nothing else).
2312 Display MESSAGE (optional fourth arg) in the echo area.
2313 If MESSAGE is nil, instructions to type EXIT-CHAR are displayed there."
2314 (or exit-char (setq exit-char ?\s))
2315 (let ((ol (make-overlay pos pos))
2316 (str (copy-sequence string)))
2320 (overlay-put ol 'after-string str)
2322 ;; To avoid trouble with out-of-bounds position
2324 ;; If the string end is off screen, recenter now.
2325 (if (<= (window-end nil t) pos)
2326 (recenter (/ (window-height) 2))))
2327 (message (or message "Type %s to continue editing.")
2328 (single-key-description exit-char))
2329 (let ((event (read-event)))
2330 ;; `exit-char' can be an event, or an event description list.
2331 (or (eq event exit-char)
2332 (eq event (event-convert-list exit-char))
2333 (setq unread-command-events (list event)))))
2334 (delete-overlay ol))))
2337 ;;;; Overlay operations
2339 (defun copy-overlay (o)
2340 "Return a copy of overlay O."
2341 (let ((o1 (if (overlay-buffer o)
2342 (make-overlay (overlay-start o) (overlay-end o)
2343 ;; FIXME: there's no easy way to find the
2344 ;; insertion-type of the two markers.
2346 (let ((o1 (make-overlay (point-min) (point-min))))
2349 (props (overlay-properties o)))
2351 (overlay-put o1 (pop props) (pop props)))
2354 (defun remove-overlays (&optional beg end name val)
2355 "Clear BEG and END of overlays whose property NAME has value VAL.
2356 Overlays might be moved and/or split.
2357 BEG and END default respectively to the beginning and end of buffer."
2358 ;; This speeds up the loops over overlays.
2359 (unless beg (setq beg (point-min)))
2360 (unless end (setq end (point-max)))
2361 (overlay-recenter end)
2363 (setq beg (prog1 end (setq end beg))))
2365 (dolist (o (overlays-in beg end))
2366 (when (eq (overlay-get o name) val)
2367 ;; Either push this overlay outside beg...end
2368 ;; or split it to exclude beg...end
2369 ;; or delete it entirely (if it is contained in beg...end).
2370 (if (< (overlay-start o) beg)
2371 (if (> (overlay-end o) end)
2373 (move-overlay (copy-overlay o)
2374 (overlay-start o) beg)
2375 (move-overlay o end (overlay-end o)))
2376 (move-overlay o (overlay-start o) beg))
2377 (if (> (overlay-end o) end)
2378 (move-overlay o end (overlay-end o))
2379 (delete-overlay o)))))))
2383 (defvar suspend-hook nil
2384 "Normal hook run by `suspend-emacs', before suspending.")
2386 (defvar suspend-resume-hook nil
2387 "Normal hook run by `suspend-emacs', after Emacs is continued.")
2389 (defvar temp-buffer-show-hook nil
2390 "Normal hook run by `with-output-to-temp-buffer' after displaying the buffer.
2391 When the hook runs, the temporary buffer is current, and the window it
2392 was displayed in is selected.")
2394 (defvar temp-buffer-setup-hook nil
2395 "Normal hook run by `with-output-to-temp-buffer' at the start.
2396 When the hook runs, the temporary buffer is current.
2397 This hook is normally set up with a function to put the buffer in Help
2400 ;; Avoid compiler warnings about this variable,
2401 ;; which has a special meaning on certain system types.
2402 (defvar buffer-file-type nil
2403 "Non-nil if the visited file is a binary file.
2404 This variable is meaningful on MS-DOG and Windows NT.
2405 On those systems, it is automatically local in every buffer.
2406 On other systems, this variable is normally always nil.")
2408 ;; The `assert' macro from the cl package signals
2409 ;; `cl-assertion-failed' at runtime so always define it.
2410 (put 'cl-assertion-failed 'error-conditions '(error))
2411 (put 'cl-assertion-failed 'error-message (purecopy "Assertion failed"))
2413 (defconst user-emacs-directory
2414 (if (eq system-type 'ms-dos)
2415 ;; MS-DOS cannot have initial dot.
2418 "Directory beneath which additional per-user Emacs-specific files are placed.
2419 Various programs in Emacs store information in this directory.
2420 Note that this should end with a directory separator.
2421 See also `locate-user-emacs-file'.")
2423 (defun locate-user-emacs-file (new-name &optional old-name)
2424 "Return an absolute per-user Emacs-specific file name.
2425 If OLD-NAME is non-nil and ~/OLD-NAME exists, return ~/OLD-NAME.
2426 Else return NEW-NAME in `user-emacs-directory', creating the
2427 directory if it does not exist."
2428 (convert-standard-filename
2429 (let* ((home (concat "~" (or init-file-user "")))
2430 (at-home (and old-name (expand-file-name old-name home))))
2431 (if (and at-home (file-readable-p at-home))
2433 ;; Make sure `user-emacs-directory' exists,
2434 ;; unless we're in batch mode or dumping Emacs
2437 (file-accessible-directory-p
2438 (directory-file-name user-emacs-directory))
2439 (let ((umask (default-file-modes)))
2442 (set-default-file-modes ?\700)
2443 (make-directory user-emacs-directory))
2444 (set-default-file-modes umask))))
2445 (abbreviate-file-name
2446 (expand-file-name new-name user-emacs-directory))))))
2448 ;;;; Misc. useful functions.
2450 (defun find-tag-default ()
2451 "Determine default tag to search for, based on text at point.
2452 If there is no plausible default, return nil."
2453 (let (from to bound)
2455 ;; Look at text around `point'.
2457 (skip-syntax-backward "w_") (setq from (point)))
2459 (skip-syntax-forward "w_") (setq to (point)))
2461 ;; Look between `line-beginning-position' and `point'.
2463 (and (setq bound (line-beginning-position))
2464 (skip-syntax-backward "^w_" bound)
2465 (> (setq to (point)) bound)
2466 (skip-syntax-backward "w_")
2467 (setq from (point))))
2468 ;; Look between `point' and `line-end-position'.
2470 (and (setq bound (line-end-position))
2471 (skip-syntax-forward "^w_" bound)
2472 (< (setq from (point)) bound)
2473 (skip-syntax-forward "w_")
2474 (setq to (point)))))
2475 (buffer-substring-no-properties from to))))
2477 (defun play-sound (sound)
2478 "SOUND is a list of the form `(sound KEYWORD VALUE...)'.
2479 The following keywords are recognized:
2481 :file FILE - read sound data from FILE. If FILE isn't an
2482 absolute file name, it is searched in `data-directory'.
2484 :data DATA - read sound data from string DATA.
2486 Exactly one of :file or :data must be present.
2488 :volume VOL - set volume to VOL. VOL must an integer in the
2489 range 0..100 or a float in the range 0..1.0. If not specified,
2490 don't change the volume setting of the sound device.
2492 :device DEVICE - play sound on DEVICE. If not specified,
2493 a system-dependent default device name is used.
2495 Note: :data and :device are currently not supported on Windows."
2496 (if (fboundp 'play-sound-internal)
2497 (play-sound-internal sound)
2498 (error "This Emacs binary lacks sound support")))
2500 (declare-function w32-shell-dos-semantics "w32-fns" nil)
2502 (defun shell-quote-argument (argument)
2503 "Quote ARGUMENT for passing as argument to an inferior shell."
2504 (if (or (eq system-type 'ms-dos)
2505 (and (eq system-type 'windows-nt) (w32-shell-dos-semantics)))
2506 ;; Quote using double quotes, but escape any existing quotes in
2507 ;; the argument with backslashes.
2511 (if (or (null (string-match "[^\"]" argument))
2512 (< (match-end 0) (length argument)))
2513 (while (string-match "[\"]" argument start)
2514 (setq end (match-beginning 0)
2515 result (concat result (substring argument start end)
2516 "\\" (substring argument end (1+ end)))
2518 (concat "\"" result (substring argument start) "\""))
2519 (if (equal argument "")
2521 ;; Quote everything except POSIX filename characters.
2522 ;; This should be safe enough even for really weird shells.
2523 (replace-regexp-in-string "\n" "'\n'"
2524 (replace-regexp-in-string "[^-0-9a-zA-Z_./\n]" "\\\\\\&" argument)))))
2526 (defun string-or-null-p (object)
2527 "Return t if OBJECT is a string or nil.
2528 Otherwise, return nil."
2529 (or (stringp object) (null object)))
2531 (defun booleanp (object)
2532 "Return t if OBJECT is one of the two canonical boolean values: t or nil.
2533 Otherwise, return nil."
2534 (and (memq object '(nil t)) t))
2536 (defun field-at-pos (pos)
2537 "Return the field at position POS, taking stickiness etc into account."
2538 (let ((raw-field (get-char-property (field-beginning pos) 'field)))
2539 (if (eq raw-field 'boundary)
2540 (get-char-property (1- (field-end pos)) 'field)
2544 ;;;; Support for yanking and text properties.
2546 (defvar yank-excluded-properties)
2548 (defun remove-yank-excluded-properties (start end)
2549 "Remove `yank-excluded-properties' between START and END positions.
2550 Replaces `category' properties with their defined properties."
2551 (let ((inhibit-read-only t))
2552 ;; Replace any `category' property with the properties it stands
2553 ;; for. This is to remove `mouse-face' properties that are placed
2554 ;; on categories in *Help* buffers' buttons. See
2555 ;; http://lists.gnu.org/archive/html/emacs-devel/2002-04/msg00648.html
2557 (unless (memq yank-excluded-properties '(t nil))
2560 (while (< (point) end)
2561 (let ((cat (get-text-property (point) 'category))
2564 (next-single-property-change (point) 'category nil end))
2566 (let (run-end2 original)
2567 (remove-list-of-text-properties (point) run-end '(category))
2568 (while (< (point) run-end)
2569 (setq run-end2 (next-property-change (point) nil run-end))
2570 (setq original (text-properties-at (point)))
2571 (set-text-properties (point) run-end2 (symbol-plist cat))
2572 (add-text-properties (point) run-end2 original)
2573 (goto-char run-end2))))
2574 (goto-char run-end)))))
2575 (if (eq yank-excluded-properties t)
2576 (set-text-properties start end nil)
2577 (remove-list-of-text-properties start end yank-excluded-properties))))
2579 (defvar yank-undo-function)
2581 (defun insert-for-yank (string)
2582 "Call `insert-for-yank-1' repetitively for each `yank-handler' segment.
2584 See `insert-for-yank-1' for more details."
2586 (while (setq to (next-single-property-change 0 'yank-handler string))
2587 (insert-for-yank-1 (substring string 0 to))
2588 (setq string (substring string to))))
2589 (insert-for-yank-1 string))
2591 (defun insert-for-yank-1 (string)
2592 "Insert STRING at point, stripping some text properties.
2594 Strip text properties from the inserted text according to
2595 `yank-excluded-properties'. Otherwise just like (insert STRING).
2597 If STRING has a non-nil `yank-handler' property on the first character,
2598 the normal insert behavior is modified in various ways. The value of
2599 the yank-handler property must be a list with one to four elements
2600 with the following format: (FUNCTION PARAM NOEXCLUDE UNDO).
2601 When FUNCTION is present and non-nil, it is called instead of `insert'
2602 to insert the string. FUNCTION takes one argument--the object to insert.
2603 If PARAM is present and non-nil, it replaces STRING as the object
2604 passed to FUNCTION (or `insert'); for example, if FUNCTION is
2605 `yank-rectangle', PARAM may be a list of strings to insert as a
2607 If NOEXCLUDE is present and non-nil, the normal removal of the
2608 `yank-excluded-properties' is not performed; instead FUNCTION is
2609 responsible for removing those properties. This may be necessary
2610 if FUNCTION adjusts point before or after inserting the object.
2611 If UNDO is present and non-nil, it is a function that will be called
2612 by `yank-pop' to undo the insertion of the current object. It is
2613 called with two arguments, the start and end of the current region.
2614 FUNCTION may set `yank-undo-function' to override the UNDO value."
2615 (let* ((handler (and (stringp string)
2616 (get-text-property 0 'yank-handler string)))
2617 (param (or (nth 1 handler) string))
2619 (inhibit-read-only inhibit-read-only)
2622 (setq yank-undo-function t)
2623 (if (nth 0 handler) ;; FUNCTION
2624 (funcall (car handler) param)
2628 ;; Prevent read-only properties from interfering with the
2629 ;; following text property changes.
2630 (setq inhibit-read-only t)
2632 ;; What should we do with `font-lock-face' properties?
2633 (if font-lock-defaults
2634 ;; No, just wipe them.
2635 (remove-list-of-text-properties opoint end '(font-lock-face))
2636 ;; Convert them to `face'.
2639 (while (< (point) end)
2640 (let ((face (get-text-property (point) 'font-lock-face))
2643 (next-single-property-change (point) 'font-lock-face nil end))
2645 (remove-text-properties (point) run-end '(font-lock-face nil))
2646 (put-text-property (point) run-end 'face face))
2647 (goto-char run-end)))))
2649 (unless (nth 2 handler) ;; NOEXCLUDE
2650 (remove-yank-excluded-properties opoint (point)))
2652 ;; If last inserted char has properties, mark them as rear-nonsticky.
2653 (if (and (> end opoint)
2654 (text-properties-at (1- end)))
2655 (put-text-property (1- end) end 'rear-nonsticky t))
2657 (if (eq yank-undo-function t) ;; not set by FUNCTION
2658 (setq yank-undo-function (nth 3 handler))) ;; UNDO
2659 (if (nth 4 handler) ;; COMMAND
2660 (setq this-command (nth 4 handler)))))
2662 (defun insert-buffer-substring-no-properties (buffer &optional start end)
2663 "Insert before point a substring of BUFFER, without text properties.
2664 BUFFER may be a buffer or a buffer name.
2665 Arguments START and END are character positions specifying the substring.
2666 They default to the values of (point-min) and (point-max) in BUFFER."
2667 (let ((opoint (point)))
2668 (insert-buffer-substring buffer start end)
2669 (let ((inhibit-read-only t))
2670 (set-text-properties opoint (point) nil))))
2672 (defun insert-buffer-substring-as-yank (buffer &optional start end)
2673 "Insert before point a part of BUFFER, stripping some text properties.
2674 BUFFER may be a buffer or a buffer name.
2675 Arguments START and END are character positions specifying the substring.
2676 They default to the values of (point-min) and (point-max) in BUFFER.
2677 Strip text properties from the inserted text according to
2678 `yank-excluded-properties'."
2679 ;; Since the buffer text should not normally have yank-handler properties,
2680 ;; there is no need to handle them here.
2681 (let ((opoint (point)))
2682 (insert-buffer-substring buffer start end)
2683 (remove-yank-excluded-properties opoint (point))))
2686 ;;;; Synchronous shell commands.
2688 (defun start-process-shell-command (name buffer &rest args)
2689 "Start a program in a subprocess. Return the process object for it.
2690 NAME is name for process. It is modified if necessary to make it unique.
2691 BUFFER is the buffer (or buffer name) to associate with the process.
2692 Process output goes at end of that buffer, unless you specify
2693 an output stream or filter function to handle the output.
2694 BUFFER may be also nil, meaning that this process is not associated
2696 COMMAND is the shell command to run.
2698 An old calling convention accepted any number of arguments after COMMAND,
2699 which were just concatenated to COMMAND. This is still supported but strongly
2701 ;; We used to use `exec' to replace the shell with the command,
2702 ;; but that failed to handle (...) and semicolon, etc.
2703 (start-process name buffer shell-file-name shell-command-switch
2704 (mapconcat 'identity args " ")))
2705 (set-advertised-calling-convention 'start-process-shell-command
2706 '(name buffer command) "23.1")
2708 (defun start-file-process-shell-command (name buffer &rest args)
2709 "Start a program in a subprocess. Return the process object for it.
2710 Similar to `start-process-shell-command', but calls `start-file-process'."
2713 (if (file-remote-p default-directory) "/bin/sh" shell-file-name)
2714 (if (file-remote-p default-directory) "-c" shell-command-switch)
2715 (mapconcat 'identity args " ")))
2716 (set-advertised-calling-convention 'start-file-process-shell-command
2717 '(name buffer command) "23.1")
2719 (defun call-process-shell-command (command &optional infile buffer display
2721 "Execute the shell command COMMAND synchronously in separate process.
2722 The remaining arguments are optional.
2723 The program's input comes from file INFILE (nil means `/dev/null').
2724 Insert output in BUFFER before point; t means current buffer;
2725 nil for BUFFER means discard it; 0 means discard and don't wait.
2726 BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,
2727 REAL-BUFFER says what to do with standard output, as above,
2728 while STDERR-FILE says what to do with standard error in the child.
2729 STDERR-FILE may be nil (discard standard error output),
2730 t (mix it with ordinary output), or a file name string.
2732 Fourth arg DISPLAY non-nil means redisplay buffer as output is inserted.
2733 Remaining arguments are strings passed as additional arguments for COMMAND.
2734 Wildcards and redirection are handled as usual in the shell.
2736 If BUFFER is 0, `call-process-shell-command' returns immediately with value nil.
2737 Otherwise it waits for COMMAND to terminate and returns a numeric exit
2738 status or a signal description string.
2739 If you quit, the process is killed with SIGINT, or SIGKILL if you quit again."
2740 ;; We used to use `exec' to replace the shell with the command,
2741 ;; but that failed to handle (...) and semicolon, etc.
2742 (call-process shell-file-name
2743 infile buffer display
2744 shell-command-switch
2745 (mapconcat 'identity (cons command args) " ")))
2747 (defun process-file-shell-command (command &optional infile buffer display
2749 "Process files synchronously in a separate process.
2750 Similar to `call-process-shell-command', but calls `process-file'."
2752 (if (file-remote-p default-directory) "/bin/sh" shell-file-name)
2753 infile buffer display
2754 (if (file-remote-p default-directory) "-c" shell-command-switch)
2755 (mapconcat 'identity (cons command args) " ")))
2757 ;;;; Lisp macros to do various things temporarily.
2759 (defmacro with-current-buffer (buffer-or-name &rest body)
2760 "Execute the forms in BODY with BUFFER-OR-NAME temporarily current.
2761 BUFFER-OR-NAME must be a buffer or the name of an existing buffer.
2762 The value returned is the value of the last form in BODY. See
2763 also `with-temp-buffer'."
2764 (declare (indent 1) (debug t))
2765 `(save-current-buffer
2766 (set-buffer ,buffer-or-name)
2769 (defmacro with-selected-window (window &rest body)
2770 "Execute the forms in BODY with WINDOW as the selected window.
2771 The value returned is the value of the last form in BODY.
2773 This macro saves and restores the selected window, as well as the
2774 selected window of each frame. It does not change the order of
2775 recently selected windows. If the previously selected window of
2776 some frame is no longer live at the end of BODY, that frame's
2777 selected window is left alone. If the selected window is no
2778 longer live, then whatever window is selected at the end of BODY
2781 This macro uses `save-current-buffer' to save and restore the
2782 current buffer, since otherwise its normal operation could
2783 potentially make a different buffer current. It does not alter
2784 the buffer list ordering."
2785 (declare (indent 1) (debug t))
2786 ;; Most of this code is a copy of save-selected-window.
2787 `(let ((save-selected-window-window (selected-window))
2788 ;; It is necessary to save all of these, because calling
2789 ;; select-window changes frame-selected-window for whatever
2790 ;; frame that window is in.
2791 (save-selected-window-alist
2792 (mapcar (lambda (frame) (list frame (frame-selected-window frame)))
2794 (save-current-buffer
2796 (progn (select-window ,window 'norecord)
2798 (dolist (elt save-selected-window-alist)
2799 (and (frame-live-p (car elt))
2800 (window-live-p (cadr elt))
2801 (set-frame-selected-window (car elt) (cadr elt) 'norecord)))
2802 (when (window-live-p save-selected-window-window)
2803 (select-window save-selected-window-window 'norecord))))))
2805 (defmacro with-selected-frame (frame &rest body)
2806 "Execute the forms in BODY with FRAME as the selected frame.
2807 The value returned is the value of the last form in BODY.
2809 This macro neither changes the order of recently selected windows
2810 nor the buffer list."
2811 (declare (indent 1) (debug t))
2812 (let ((old-frame (make-symbol "old-frame"))
2813 (old-buffer (make-symbol "old-buffer")))
2814 `(let ((,old-frame (selected-frame))
2815 (,old-buffer (current-buffer)))
2817 (progn (select-frame ,frame 'norecord)
2819 (when (frame-live-p ,old-frame)
2820 (select-frame ,old-frame 'norecord))
2821 (when (buffer-live-p ,old-buffer)
2822 (set-buffer ,old-buffer))))))
2824 (defmacro save-window-excursion (&rest body)
2825 "Execute BODY, preserving window sizes and contents.
2826 Return the value of the last form in BODY.
2827 Restore which buffer appears in which window, where display starts,
2828 and the value of point and mark for each window.
2829 Also restore the choice of selected window.
2830 Also restore which buffer is current.
2831 Does not restore the value of point in current buffer.
2833 BEWARE: Most uses of this macro introduce bugs.
2834 E.g. it should not be used to try and prevent some code from opening
2835 a new window, since that window may sometimes appear in another frame,
2836 in which case `save-window-excursion' cannot help."
2837 (declare (indent 0) (debug t))
2838 (let ((c (make-symbol "wconfig")))
2839 `(let ((,c (current-window-configuration)))
2840 (unwind-protect (progn ,@body)
2841 (set-window-configuration ,c)))))
2843 (defmacro with-output-to-temp-buffer (bufname &rest body)
2844 "Bind `standard-output' to buffer BUFNAME, eval BODY, then show that buffer.
2846 This construct makes buffer BUFNAME empty before running BODY.
2847 It does not make the buffer current for BODY.
2848 Instead it binds `standard-output' to that buffer, so that output
2849 generated with `prin1' and similar functions in BODY goes into
2852 At the end of BODY, this marks buffer BUFNAME unmodifed and displays
2853 it in a window, but does not select it. The normal way to do this is
2854 by calling `display-buffer', then running `temp-buffer-show-hook'.
2855 However, if `temp-buffer-show-function' is non-nil, it calls that
2856 function instead (and does not run `temp-buffer-show-hook'). The
2857 function gets one argument, the buffer to display.
2859 The return value of `with-output-to-temp-buffer' is the value of the
2860 last form in BODY. If BODY does not finish normally, the buffer
2861 BUFNAME is not displayed.
2863 This runs the hook `temp-buffer-setup-hook' before BODY,
2864 with the buffer BUFNAME temporarily current. It runs the hook
2865 `temp-buffer-show-hook' after displaying buffer BUFNAME, with that
2866 buffer temporarily current, and the window that was used to display it
2867 temporarily selected. But it doesn't run `temp-buffer-show-hook'
2868 if it uses `temp-buffer-show-function'."
2869 (let ((old-dir (make-symbol "old-dir"))
2870 (buf (make-symbol "buf")))
2871 `(let ((,old-dir default-directory))
2872 (with-current-buffer (get-buffer-create ,bufname)
2873 (kill-all-local-variables)
2874 ;; FIXME: delete_all_overlays
2875 (setq default-directory ,old-dir)
2876 (setq buffer-read-only nil)
2877 (setq buffer-file-name nil)
2878 (setq buffer-undo-list t)
2879 (let ((,buf (current-buffer)))
2880 (let ((inhibit-read-only t)
2881 (inhibit-modification-hooks t))
2883 (run-hooks 'temp-buffer-setup-hook))
2884 (let ((standard-output ,buf))
2885 (prog1 (progn ,@body)
2886 (internal-temp-output-buffer-show ,buf))))))))
2888 (defmacro with-temp-file (file &rest body)
2889 "Create a new buffer, evaluate BODY there, and write the buffer to FILE.
2890 The value returned is the value of the last form in BODY.
2891 See also `with-temp-buffer'."
2892 (declare (indent 1) (debug t))
2893 (let ((temp-file (make-symbol "temp-file"))
2894 (temp-buffer (make-symbol "temp-buffer")))
2895 `(let ((,temp-file ,file)
2897 (get-buffer-create (generate-new-buffer-name " *temp file*"))))
2900 (with-current-buffer ,temp-buffer
2902 (with-current-buffer ,temp-buffer
2903 (write-region nil nil ,temp-file nil 0)))
2904 (and (buffer-name ,temp-buffer)
2905 (kill-buffer ,temp-buffer))))))
2907 (defmacro with-temp-message (message &rest body)
2908 "Display MESSAGE temporarily if non-nil while BODY is evaluated.
2909 The original message is restored to the echo area after BODY has finished.
2910 The value returned is the value of the last form in BODY.
2911 MESSAGE is written to the message log buffer if `message-log-max' is non-nil.
2912 If MESSAGE is nil, the echo area and message log buffer are unchanged.
2913 Use a MESSAGE of \"\" to temporarily clear the echo area."
2914 (declare (debug t) (indent 1))
2915 (let ((current-message (make-symbol "current-message"))
2916 (temp-message (make-symbol "with-temp-message")))
2917 `(let ((,temp-message ,message)
2922 (setq ,current-message (current-message))
2923 (message "%s" ,temp-message))
2926 (if ,current-message
2927 (message "%s" ,current-message)
2930 (defmacro with-temp-buffer (&rest body)
2931 "Create a temporary buffer, and evaluate BODY there like `progn'.
2932 See also `with-temp-file' and `with-output-to-string'."
2933 (declare (indent 0) (debug t))
2934 (let ((temp-buffer (make-symbol "temp-buffer")))
2935 `(let ((,temp-buffer (generate-new-buffer " *temp*")))
2936 ;; FIXME: kill-buffer can change current-buffer in some odd cases.
2937 (with-current-buffer ,temp-buffer
2940 (and (buffer-name ,temp-buffer)
2941 (kill-buffer ,temp-buffer)))))))
2943 (defmacro with-silent-modifications (&rest body)
2944 "Execute BODY, pretending it does not modify the buffer.
2945 If BODY performs real modifications to the buffer's text, other
2946 than cosmetic ones, undo data may become corrupted.
2947 Typically used around modifications of text-properties which do not really
2948 affect the buffer's content."
2949 (declare (debug t) (indent 0))
2950 (let ((modified (make-symbol "modified")))
2951 `(let* ((,modified (buffer-modified-p))
2952 (buffer-undo-list t)
2953 (inhibit-read-only t)
2954 (inhibit-modification-hooks t)
2956 ;; Avoid setting and removing file locks and checking
2957 ;; buffer's uptodate-ness w.r.t the underlying file.
2959 buffer-file-truename)
2964 (restore-buffer-modified-p nil))))))
2966 (defmacro with-output-to-string (&rest body)
2967 "Execute BODY, return the text it sent to `standard-output', as a string."
2968 (declare (indent 0) (debug t))
2969 `(let ((standard-output
2970 (get-buffer-create (generate-new-buffer-name " *string-output*"))))
2973 (let ((standard-output standard-output))
2975 (with-current-buffer standard-output
2977 (kill-buffer standard-output))))
2979 (defmacro with-local-quit (&rest body)
2980 "Execute BODY, allowing quits to terminate BODY but not escape further.
2981 When a quit terminates BODY, `with-local-quit' returns nil but
2982 requests another quit. That quit will be processed as soon as quitting
2983 is allowed once again. (Immediately, if `inhibit-quit' is nil.)"
2984 (declare (debug t) (indent 0))
2985 `(condition-case nil
2986 (let ((inhibit-quit nil))
2988 (quit (setq quit-flag t)
2989 ;; This call is to give a chance to handle quit-flag
2990 ;; in case inhibit-quit is nil.
2991 ;; Without this, it will not be handled until the next function
2992 ;; call, and that might allow it to exit thru a condition-case
2993 ;; that intends to handle the quit signal next time.
2994 (eval '(ignore nil)))))
2996 (defmacro while-no-input (&rest body)
2997 "Execute BODY only as long as there's no pending input.
2998 If input arrives, that ends the execution of BODY,
2999 and `while-no-input' returns t. Quitting makes it return nil.
3000 If BODY finishes, `while-no-input' returns whatever value BODY produced."
3001 (declare (debug t) (indent 0))
3002 (let ((catch-sym (make-symbol "input")))
3005 (let ((throw-on-input ',catch-sym))
3006 (or (input-pending-p)
3007 (progn ,@body)))))))
3009 (defmacro condition-case-no-debug (var bodyform &rest handlers)
3010 "Like `condition-case' except that it does not catch anything when debugging.
3011 More specifically if `debug-on-error' is set, then it does not catch any signal."
3012 (declare (debug condition-case) (indent 2))
3013 (let ((bodysym (make-symbol "body")))
3014 `(let ((,bodysym (lambda () ,bodyform)))
3017 (condition-case ,var
3021 (defmacro with-demoted-errors (&rest body)
3022 "Run BODY and demote any errors to simple messages.
3023 If `debug-on-error' is non-nil, run BODY without catching its errors.
3024 This is to be used around code which is not expected to signal an error
3025 but which should be robust in the unexpected case that an error is signaled."
3026 (declare (debug t) (indent 0))
3027 (let ((err (make-symbol "err")))
3028 `(condition-case-no-debug ,err
3030 (error (message "Error: %S" ,err) nil))))
3032 (defmacro combine-after-change-calls (&rest body)
3033 "Execute BODY, but don't call the after-change functions till the end.
3034 If BODY makes changes in the buffer, they are recorded
3035 and the functions on `after-change-functions' are called several times
3036 when BODY is finished.
3037 The return value is the value of the last form in BODY.
3039 If `before-change-functions' is non-nil, then calls to the after-change
3040 functions can't be deferred, so in that case this macro has no effect.
3042 Do not alter `after-change-functions' or `before-change-functions'
3044 (declare (indent 0) (debug t))
3046 (let ((combine-after-change-calls t))
3048 (combine-after-change-execute)))
3050 (defmacro with-case-table (table &rest body)
3051 "Execute the forms in BODY with TABLE as the current case table.
3052 The value returned is the value of the last form in BODY."
3053 (declare (indent 1) (debug t))
3054 (let ((old-case-table (make-symbol "table"))
3055 (old-buffer (make-symbol "buffer")))
3056 `(let ((,old-case-table (current-case-table))
3057 (,old-buffer (current-buffer)))
3059 (progn (set-case-table ,table)
3061 (with-current-buffer ,old-buffer
3062 (set-case-table ,old-case-table))))))
3064 ;;; Matching and match data.
3066 (defvar save-match-data-internal)
3068 ;; We use save-match-data-internal as the local variable because
3069 ;; that works ok in practice (people should not use that variable elsewhere).
3070 ;; We used to use an uninterned symbol; the compiler handles that properly
3071 ;; now, but it generates slower code.
3072 (defmacro save-match-data (&rest body)
3073 "Execute the BODY forms, restoring the global value of the match data.
3074 The value returned is the value of the last form in BODY."
3075 ;; It is better not to use backquote here,
3076 ;; because that makes a bootstrapping problem
3077 ;; if you need to recompile all the Lisp files using interpreted code.
3078 (declare (indent 0) (debug t))
3080 '((save-match-data-internal (match-data)))
3081 (list 'unwind-protect
3083 ;; It is safe to free (evaporate) markers immediately here,
3084 ;; as Lisp programs should not copy from save-match-data-internal.
3085 '(set-match-data save-match-data-internal 'evaporate))))
3087 (defun match-string (num &optional string)
3088 "Return string of text matched by last search.
3089 NUM specifies which parenthesized expression in the last regexp.
3090 Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
3091 Zero means the entire text matched by the whole regexp or whole string.
3092 STRING should be given if the last search was by `string-match' on STRING."
3093 (if (match-beginning num)
3095 (substring string (match-beginning num) (match-end num))
3096 (buffer-substring (match-beginning num) (match-end num)))))
3098 (defun match-string-no-properties (num &optional string)
3099 "Return string of text matched by last search, without text properties.
3100 NUM specifies which parenthesized expression in the last regexp.
3101 Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
3102 Zero means the entire text matched by the whole regexp or whole string.
3103 STRING should be given if the last search was by `string-match' on STRING."
3104 (if (match-beginning num)
3106 (substring-no-properties string (match-beginning num)
3108 (buffer-substring-no-properties (match-beginning num)
3112 (defun match-substitute-replacement (replacement
3113 &optional fixedcase literal string subexp)
3114 "Return REPLACEMENT as it will be inserted by `replace-match'.
3115 In other words, all back-references in the form `\\&' and `\\N'
3116 are substituted with actual strings matched by the last search.
3117 Optional FIXEDCASE, LITERAL, STRING and SUBEXP have the same
3118 meaning as for `replace-match'."
3119 (let ((match (match-string 0 string)))
3121 (set-match-data (mapcar (lambda (x)
3123 (- x (match-beginning 0))
3126 (replace-match replacement fixedcase literal match subexp))))
3129 (defun looking-back (regexp &optional limit greedy)
3130 "Return non-nil if text before point matches regular expression REGEXP.
3131 Like `looking-at' except matches before point, and is slower.
3132 LIMIT if non-nil speeds up the search by specifying a minimum
3133 starting position, to avoid checking matches that would start
3136 If GREEDY is non-nil, extend the match backwards as far as
3137 possible, stopping when a single additional previous character
3138 cannot be part of a match for REGEXP. When the match is
3139 extended, its starting position is allowed to occur before
3141 (let ((start (point))
3144 (and (re-search-backward (concat "\\(?:" regexp "\\)\\=") limit t)
3146 (if (and greedy pos)
3148 (narrow-to-region (point-min) start)
3149 (while (and (> pos (point-min))
3153 (looking-at (concat "\\(?:" regexp "\\)\\'"))))
3154 (setq pos (1- pos)))
3157 (looking-at (concat "\\(?:" regexp "\\)\\'")))))
3160 (defsubst looking-at-p (regexp)
3162 Same as `looking-at' except this function does not change the match data."
3163 (let ((inhibit-changing-match-data t))
3164 (looking-at regexp)))
3166 (defsubst string-match-p (regexp string &optional start)
3168 Same as `string-match' except this function does not change the match data."
3169 (let ((inhibit-changing-match-data t))
3170 (string-match regexp string start)))
3172 (defun subregexp-context-p (regexp pos &optional start)
3173 "Return non-nil if POS is in a normal subregexp context in REGEXP.
3174 A subregexp context is one where a sub-regexp can appear.
3175 A non-subregexp context is for example within brackets, or within a
3176 repetition bounds operator `\\=\\{...\\}', or right after a `\\'.
3177 If START is non-nil, it should be a position in REGEXP, smaller
3178 than POS, and known to be in a subregexp context."
3179 ;; Here's one possible implementation, with the great benefit that it
3180 ;; reuses the regexp-matcher's own parser, so it understands all the
3181 ;; details of the syntax. A disadvantage is that it needs to match the
3185 (string-match (substring regexp (or start 0) pos) "")
3188 (not (member (cadr err) '("Unmatched [ or [^"
3190 "Trailing backslash")))))
3191 ;; An alternative implementation:
3192 ;; (defconst re-context-re
3193 ;; (let* ((harmless-ch "[^\\[]")
3194 ;; (harmless-esc "\\\\[^{]")
3195 ;; (class-harmless-ch "[^][]")
3196 ;; (class-lb-harmless "[^]:]")
3197 ;; (class-lb-colon-maybe-charclass ":\\([a-z]+:]\\)?")
3198 ;; (class-lb (concat "\\[\\(" class-lb-harmless
3199 ;; "\\|" class-lb-colon-maybe-charclass "\\)"))
3201 ;; (concat "\\[^?]?"
3202 ;; "\\(" class-harmless-ch
3203 ;; "\\|" class-lb "\\)*"
3204 ;; "\\[?]")) ; special handling for bare [ at end of re
3205 ;; (braces "\\\\{[0-9,]+\\\\}"))
3206 ;; (concat "\\`\\(" harmless-ch "\\|" harmless-esc
3207 ;; "\\|" class "\\|" braces "\\)*\\'"))
3208 ;; "Matches any prefix that corresponds to a normal subregexp context.")
3209 ;; (string-match re-context-re (substring regexp (or start 0) pos))
3214 (defconst split-string-default-separators "[ \f\t\n\r\v]+"
3215 "The default value of separators for `split-string'.
3217 A regexp matching strings of whitespace. May be locale-dependent
3218 \(as yet unimplemented). Should not match non-breaking spaces.
3220 Warning: binding this to a different value and using it as default is
3221 likely to have undesired semantics.")
3223 ;; The specification says that if both SEPARATORS and OMIT-NULLS are
3224 ;; defaulted, OMIT-NULLS should be treated as t. Simplifying the logical
3225 ;; expression leads to the equivalent implementation that if SEPARATORS
3226 ;; is defaulted, OMIT-NULLS is treated as t.
3227 (defun split-string (string &optional separators omit-nulls)
3228 "Split STRING into substrings bounded by matches for SEPARATORS.
3230 The beginning and end of STRING, and each match for SEPARATORS, are
3231 splitting points. The substrings matching SEPARATORS are removed, and
3232 the substrings between the splitting points are collected as a list,
3235 If SEPARATORS is non-nil, it should be a regular expression matching text
3236 which separates, but is not part of, the substrings. If nil it defaults to
3237 `split-string-default-separators', normally \"[ \\f\\t\\n\\r\\v]+\", and
3238 OMIT-NULLS is forced to t.
3240 If OMIT-NULLS is t, zero-length substrings are omitted from the list \(so
3241 that for the default value of SEPARATORS leading and trailing whitespace
3242 are effectively trimmed). If nil, all zero-length substrings are retained,
3243 which correctly parses CSV format, for example.
3245 Note that the effect of `(split-string STRING)' is the same as
3246 `(split-string STRING split-string-default-separators t)'. In the rare
3247 case that you wish to retain zero-length substrings when splitting on
3248 whitespace, use `(split-string STRING split-string-default-separators)'.
3250 Modifies the match data; use `save-match-data' if necessary."
3251 (let ((keep-nulls (not (if separators omit-nulls t)))
3252 (rexp (or separators split-string-default-separators))
3256 (while (and (string-match rexp string
3258 (= start (match-beginning 0))
3259 (< start (length string)))
3261 (< start (length string)))
3263 (if (or keep-nulls (< start (match-beginning 0)))
3265 (cons (substring string start (match-beginning 0))
3267 (setq start (match-end 0)))
3268 (if (or keep-nulls (< start (length string)))
3270 (cons (substring string start)
3274 (defun combine-and-quote-strings (strings &optional separator)
3275 "Concatenate the STRINGS, adding the SEPARATOR (default \" \").
3276 This tries to quote the strings to avoid ambiguity such that
3277 (split-string-and-unquote (combine-and-quote-strings strs)) == strs
3278 Only some SEPARATORs will work properly."
3279 (let* ((sep (or separator " "))
3280 (re (concat "[\\\"]" "\\|" (regexp-quote sep))))
3283 (if (string-match re str)
3284 (concat "\"" (replace-regexp-in-string "[\\\"]" "\\\\\\&" str) "\"")
3288 (defun split-string-and-unquote (string &optional separator)
3289 "Split the STRING into a list of strings.
3290 It understands Emacs Lisp quoting within STRING, such that
3291 (split-string-and-unquote (combine-and-quote-strings strs)) == strs
3292 The SEPARATOR regexp defaults to \"\\s-+\"."
3293 (let ((sep (or separator "\\s-+"))
3294 (i (string-match "\"" string)))
3296 (split-string string sep t) ; no quoting: easy
3297 (append (unless (eq i 0) (split-string (substring string 0 i) sep t))
3298 (let ((rfs (read-from-string string i)))
3300 (split-string-and-unquote (substring string (cdr rfs))
3304 ;;;; Replacement in strings.
3306 (defun subst-char-in-string (fromchar tochar string &optional inplace)
3307 "Replace FROMCHAR with TOCHAR in STRING each time it occurs.
3308 Unless optional argument INPLACE is non-nil, return a new string."
3309 (let ((i (length string))
3310 (newstr (if inplace string (copy-sequence string))))
3313 (if (eq (aref newstr i) fromchar)
3314 (aset newstr i tochar)))
3317 (defun replace-regexp-in-string (regexp rep string &optional
3318 fixedcase literal subexp start)
3319 "Replace all matches for REGEXP with REP in STRING.
3321 Return a new string containing the replacements.
3323 Optional arguments FIXEDCASE, LITERAL and SUBEXP are like the
3324 arguments with the same names of function `replace-match'. If START
3325 is non-nil, start replacements at that index in STRING.
3327 REP is either a string used as the NEWTEXT arg of `replace-match' or a
3328 function. If it is a function, it is called with the actual text of each
3329 match, and its value is used as the replacement text. When REP is called,
3330 the match data are the result of matching REGEXP against a substring
3333 To replace only the first match (if any), make REGEXP match up to \\'
3334 and replace a sub-expression, e.g.
3335 (replace-regexp-in-string \"\\\\(foo\\\\).*\\\\'\" \"bar\" \" foo foo\" nil nil 1)
3339 ;; To avoid excessive consing from multiple matches in long strings,
3340 ;; don't just call `replace-match' continually. Walk down the
3341 ;; string looking for matches of REGEXP and building up a (reversed)
3342 ;; list MATCHES. This comprises segments of STRING which weren't
3343 ;; matched interspersed with replacements for segments that were.
3344 ;; [For a `large' number of replacements it's more efficient to
3345 ;; operate in a temporary buffer; we can't tell from the function's
3346 ;; args whether to choose the buffer-based implementation, though it
3347 ;; might be reasonable to do so for long enough STRING.]
3348 (let ((l (length string))
3349 (start (or start 0))
3352 (while (and (< start l) (string-match regexp string start))
3353 (setq mb (match-beginning 0)
3355 ;; If we matched the empty string, make sure we advance by one char
3356 (when (= me mb) (setq me (min l (1+ mb))))
3357 ;; Generate a replacement for the matched substring.
3358 ;; Operate only on the substring to minimize string consing.
3359 ;; Set up match data for the substring for replacement;
3360 ;; presumably this is likely to be faster than munging the
3361 ;; match data directly in Lisp.
3362 (string-match regexp (setq str (substring string mb me)))
3364 (cons (replace-match (if (stringp rep)
3366 (funcall rep (match-string 0 str)))
3367 fixedcase literal str subexp)
3368 (cons (substring string start mb) ; unmatched prefix
3371 ;; Reconstruct a string from the pieces.
3372 (setq matches (cons (substring string start l) matches)) ; leftover
3373 (apply #'concat (nreverse matches)))))
3375 (defun string-prefix-p (str1 str2 &optional ignore-case)
3376 "Return non-nil if STR1 is a prefix of STR2.
3377 If IGNORE-CASE is non-nil, the comparison is done without paying attention
3378 to case differences."
3379 (eq t (compare-strings str1 nil nil
3380 str2 0 (length str1) ignore-case)))
3382 ;;;; invisibility specs
3384 (defun add-to-invisibility-spec (element)
3385 "Add ELEMENT to `buffer-invisibility-spec'.
3386 See documentation for `buffer-invisibility-spec' for the kind of elements
3388 (if (eq buffer-invisibility-spec t)
3389 (setq buffer-invisibility-spec (list t)))
3390 (setq buffer-invisibility-spec
3391 (cons element buffer-invisibility-spec)))
3393 (defun remove-from-invisibility-spec (element)
3394 "Remove ELEMENT from `buffer-invisibility-spec'."
3395 (if (consp buffer-invisibility-spec)
3396 (setq buffer-invisibility-spec
3397 (delete element buffer-invisibility-spec))))
3401 (defmacro with-syntax-table (table &rest body)
3402 "Evaluate BODY with syntax table of current buffer set to TABLE.
3403 The syntax table of the current buffer is saved, BODY is evaluated, and the
3404 saved table is restored, even in case of an abnormal exit.
3405 Value is what BODY returns."
3406 (declare (debug t) (indent 1))
3407 (let ((old-table (make-symbol "table"))
3408 (old-buffer (make-symbol "buffer")))
3409 `(let ((,old-table (syntax-table))
3410 (,old-buffer (current-buffer)))
3413 (set-syntax-table ,table)
3415 (save-current-buffer
3416 (set-buffer ,old-buffer)
3417 (set-syntax-table ,old-table))))))
3419 (defun make-syntax-table (&optional oldtable)
3420 "Return a new syntax table.
3421 Create a syntax table which inherits from OLDTABLE (if non-nil) or
3422 from `standard-syntax-table' otherwise."
3423 (let ((table (make-char-table 'syntax-table nil)))
3424 (set-char-table-parent table (or oldtable (standard-syntax-table)))
3427 (defun syntax-after (pos)
3428 "Return the raw syntax of the char after POS.
3429 If POS is outside the buffer's accessible portion, return nil."
3430 (unless (or (< pos (point-min)) (>= pos (point-max)))
3431 (let ((st (if parse-sexp-lookup-properties
3432 (get-char-property pos 'syntax-table))))
3434 (aref (or st (syntax-table)) (char-after pos))))))
3436 (defun syntax-class (syntax)
3437 "Return the syntax class part of the syntax descriptor SYNTAX.
3438 If SYNTAX is nil, return nil."
3439 (and syntax (logand (car syntax) 65535)))
3443 (defun text-clone-maintain (ol1 after beg end &optional len)
3444 "Propagate the changes made under the overlay OL1 to the other clones.
3445 This is used on the `modification-hooks' property of text clones."
3446 (when (and after (not undo-in-progress) (overlay-start ol1))
3447 (let ((margin (if (overlay-get ol1 'text-clone-spreadp) 1 0)))
3448 (setq beg (max beg (+ (overlay-start ol1) margin)))
3449 (setq end (min end (- (overlay-end ol1) margin)))
3452 (when (overlay-get ol1 'text-clone-syntax)
3453 ;; Check content of the clone's text.
3454 (let ((cbeg (+ (overlay-start ol1) margin))
3455 (cend (- (overlay-end ol1) margin)))
3458 (if (not (re-search-forward
3459 (overlay-get ol1 'text-clone-syntax) cend t))
3460 ;; Mark the overlay for deletion.
3461 (overlay-put ol1 'text-clones nil)
3462 (when (< (match-end 0) cend)
3463 ;; Shrink the clone at its end.
3464 (setq end (min end (match-end 0)))
3465 (move-overlay ol1 (overlay-start ol1)
3466 (+ (match-end 0) margin)))
3467 (when (> (match-beginning 0) cbeg)
3468 ;; Shrink the clone at its beginning.
3469 (setq beg (max (match-beginning 0) beg))
3470 (move-overlay ol1 (- (match-beginning 0) margin)
3471 (overlay-end ol1)))))))
3472 ;; Now go ahead and update the clones.
3473 (let ((head (- beg (overlay-start ol1)))
3474 (tail (- (overlay-end ol1) end))
3475 (str (buffer-substring beg end))
3477 (inhibit-modification-hooks t))
3478 (dolist (ol2 (overlay-get ol1 'text-clones))
3479 (let ((oe (overlay-end ol2)))
3480 (unless (or (eq ol1 ol2) (null oe))
3481 (setq nothing-left nil)
3482 (let ((mod-beg (+ (overlay-start ol2) head)))
3483 ;;(overlay-put ol2 'modification-hooks nil)
3484 (goto-char (- (overlay-end ol2) tail))
3485 (unless (> mod-beg (point))
3486 (save-excursion (insert str))
3487 (delete-region mod-beg (point)))
3488 ;;(overlay-put ol2 'modification-hooks '(text-clone-maintain))
3490 (if nothing-left (delete-overlay ol1))))))))
3492 (defun text-clone-create (start end &optional spreadp syntax)
3493 "Create a text clone of START...END at point.
3494 Text clones are chunks of text that are automatically kept identical:
3495 changes done to one of the clones will be immediately propagated to the other.
3497 The buffer's content at point is assumed to be already identical to
3498 the one between START and END.
3499 If SYNTAX is provided it's a regexp that describes the possible text of
3500 the clones; the clone will be shrunk or killed if necessary to ensure that
3501 its text matches the regexp.
3502 If SPREADP is non-nil it indicates that text inserted before/after the
3503 clone should be incorporated in the clone."
3504 ;; To deal with SPREADP we can either use an overlay with `nil t' along
3505 ;; with insert-(behind|in-front-of)-hooks or use a slightly larger overlay
3506 ;; (with a one-char margin at each end) with `t nil'.
3507 ;; We opted for a larger overlay because it behaves better in the case
3508 ;; where the clone is reduced to the empty string (we want the overlay to
3509 ;; stay when the clone's content is the empty string and we want to use
3510 ;; `evaporate' to make sure those overlays get deleted when needed).
3512 (let* ((pt-end (+ (point) (- end start)))
3513 (start-margin (if (or (not spreadp) (bobp) (<= start (point-min)))
3515 (end-margin (if (or (not spreadp)
3516 (>= pt-end (point-max))
3517 (>= start (point-max)))
3519 (ol1 (make-overlay (- start start-margin) (+ end end-margin) nil t))
3520 (ol2 (make-overlay (- (point) start-margin) (+ pt-end end-margin) nil t))
3521 (dups (list ol1 ol2)))
3522 (overlay-put ol1 'modification-hooks '(text-clone-maintain))
3523 (when spreadp (overlay-put ol1 'text-clone-spreadp t))
3524 (when syntax (overlay-put ol1 'text-clone-syntax syntax))
3525 ;;(overlay-put ol1 'face 'underline)
3526 (overlay-put ol1 'evaporate t)
3527 (overlay-put ol1 'text-clones dups)
3529 (overlay-put ol2 'modification-hooks '(text-clone-maintain))
3530 (when spreadp (overlay-put ol2 'text-clone-spreadp t))
3531 (when syntax (overlay-put ol2 'text-clone-syntax syntax))
3532 ;;(overlay-put ol2 'face 'underline)
3533 (overlay-put ol2 'evaporate t)
3534 (overlay-put ol2 'text-clones dups)))
3536 ;;;; Mail user agents.
3538 ;; Here we include just enough for other packages to be able
3541 (defun define-mail-user-agent (symbol composefunc sendfunc
3542 &optional abortfunc hookvar)
3543 "Define a symbol to identify a mail-sending package for `mail-user-agent'.
3545 SYMBOL can be any Lisp symbol. Its function definition and/or
3546 value as a variable do not matter for this usage; we use only certain
3547 properties on its property list, to encode the rest of the arguments.
3549 COMPOSEFUNC is program callable function that composes an outgoing
3550 mail message buffer. This function should set up the basics of the
3551 buffer without requiring user interaction. It should populate the
3552 standard mail headers, leaving the `to:' and `subject:' headers blank
3555 COMPOSEFUNC should accept several optional arguments--the same
3556 arguments that `compose-mail' takes. See that function's documentation.
3558 SENDFUNC is the command a user would run to send the message.
3560 Optional ABORTFUNC is the command a user would run to abort the
3561 message. For mail packages that don't have a separate abort function,
3562 this can be `kill-buffer' (the equivalent of omitting this argument).
3564 Optional HOOKVAR is a hook variable that gets run before the message
3565 is actually sent. Callers that use the `mail-user-agent' may
3566 install a hook function temporarily on this hook variable.
3567 If HOOKVAR is nil, `mail-send-hook' is used.
3569 The properties used on SYMBOL are `composefunc', `sendfunc',
3570 `abortfunc', and `hookvar'."
3571 (put symbol 'composefunc composefunc)
3572 (put symbol 'sendfunc sendfunc)
3573 (put symbol 'abortfunc (or abortfunc 'kill-buffer))
3574 (put symbol 'hookvar (or hookvar 'mail-send-hook)))
3576 ;;;; Progress reporters.
3578 ;; Progress reporter has the following structure:
3580 ;; (NEXT-UPDATE-VALUE . [NEXT-UPDATE-TIME
3587 ;; This weirdeness is for optimization reasons: we want
3588 ;; `progress-reporter-update' to be as fast as possible, so
3589 ;; `(car reporter)' is better than `(aref reporter 0)'.
3591 ;; NEXT-UPDATE-TIME is a float. While `float-time' loses a couple
3592 ;; digits of precision, it doesn't really matter here. On the other
3593 ;; hand, it greatly simplifies the code.
3595 (defsubst progress-reporter-update (reporter &optional value)
3596 "Report progress of an operation in the echo area.
3597 REPORTER should be the result of a call to `make-progress-reporter'.
3599 If REPORTER is a numerical progress reporter---i.e. if it was
3600 made using non-nil MIN-VALUE and MAX-VALUE arguments to
3601 `make-progress-reporter'---then VALUE should be a number between
3602 MIN-VALUE and MAX-VALUE.
3604 If REPORTER is a non-numerical reporter, VALUE should be nil.
3606 This function is relatively inexpensive. If the change since
3607 last update is too small or insufficient time has passed, it does
3609 (when (or (not (numberp value)) ; For pulsing reporter
3610 (>= value (car reporter))) ; For numerical reporter
3611 (progress-reporter-do-update reporter value)))
3613 (defun make-progress-reporter (message &optional min-value max-value
3614 current-value min-change min-time)
3615 "Return progress reporter object for use with `progress-reporter-update'.
3617 MESSAGE is shown in the echo area, with a status indicator
3618 appended to the end. When you call `progress-reporter-done', the
3619 word \"done\" is printed after the MESSAGE. You can change the
3620 MESSAGE of an existing progress reporter by calling
3621 `progress-reporter-force-update'.
3623 MIN-VALUE and MAX-VALUE, if non-nil, are starting (0% complete)
3624 and final (100% complete) states of operation; the latter should
3625 be larger. In this case, the status message shows the percentage
3628 If MIN-VALUE and/or MAX-VALUE is omitted or nil, the status
3629 message shows a \"spinning\", non-numeric indicator.
3631 Optional CURRENT-VALUE is the initial progress; the default is
3633 Optional MIN-CHANGE is the minimal change in percents to report;
3635 CURRENT-VALUE and MIN-CHANGE do not have any effect if MIN-VALUE
3636 and/or MAX-VALUE are nil.
3638 Optional MIN-TIME specifies the minimum interval time between
3639 echo area updates (default is 0.2 seconds.) If the function
3640 `float-time' is not present, time is not tracked at all. If the
3641 OS is not capable of measuring fractions of seconds, this
3642 parameter is effectively rounded up."
3644 (setq min-time 0.2))
3646 ;; Force a call to `message' now
3647 (cons (or min-value 0)
3648 (vector (if (and (fboundp 'float-time)
3654 (if min-change (max (min min-change 50) 1) 1)
3656 (progress-reporter-update reporter (or current-value min-value))
3659 (defun progress-reporter-force-update (reporter &optional value new-message)
3660 "Report progress of an operation in the echo area unconditionally.
3662 The first two arguments are the same as in `progress-reporter-update'.
3663 NEW-MESSAGE, if non-nil, sets a new message for the reporter."
3664 (let ((parameters (cdr reporter)))
3666 (aset parameters 3 new-message))
3667 (when (aref parameters 0)
3668 (aset parameters 0 (float-time)))
3669 (progress-reporter-do-update reporter value)))
3671 (defvar progress-reporter--pulse-characters ["-" "\\" "|" "/"]
3672 "Characters to use for pulsing progress reporters.")
3674 (defun progress-reporter-do-update (reporter value)
3675 (let* ((parameters (cdr reporter))
3676 (update-time (aref parameters 0))
3677 (min-value (aref parameters 1))
3678 (max-value (aref parameters 2))
3679 (text (aref parameters 3))
3680 (current-time (float-time))
3682 ;; See if enough time has passed since the last update.
3683 (or (not update-time)
3684 (when (>= current-time update-time)
3685 ;; Calculate time for the next update
3686 (aset parameters 0 (+ update-time (aref parameters 5)))))))
3687 (cond ((and min-value max-value)
3688 ;; Numerical indicator
3689 (let* ((one-percent (/ (- max-value min-value) 100.0))
3690 (percentage (if (= max-value min-value)
3692 (truncate (/ (- value min-value)
3694 ;; Calculate NEXT-UPDATE-VALUE. If we are not printing
3695 ;; message because not enough time has passed, use 1
3696 ;; instead of MIN-CHANGE. This makes delays between echo
3697 ;; area updates closer to MIN-TIME.
3699 (min (+ min-value (* (+ percentage
3700 (if enough-time-passed
3706 (when (integerp value)
3707 (setcar reporter (ceiling (car reporter))))
3708 ;; Only print message if enough time has passed
3709 (when enough-time-passed
3710 (if (> percentage 0)
3711 (message "%s%d%%" text percentage)
3712 (message "%s" text)))))
3713 ;; Pulsing indicator
3715 (let ((index (mod (1+ (car reporter)) 4))
3716 (message-log-max nil))
3717 (setcar reporter index)
3720 (aref progress-reporter--pulse-characters
3723 (defun progress-reporter-done (reporter)
3724 "Print reporter's message followed by word \"done\" in echo area."
3725 (message "%sdone" (aref (cdr reporter) 3)))
3727 (defmacro dotimes-with-progress-reporter (spec message &rest body)
3728 "Loop a certain number of times and report progress in the echo area.
3729 Evaluate BODY with VAR bound to successive integers running from
3730 0, inclusive, to COUNT, exclusive. Then evaluate RESULT to get
3731 the return value (nil if RESULT is omitted).
3733 At each iteration MESSAGE followed by progress percentage is
3734 printed in the echo area. After the loop is finished, MESSAGE
3735 followed by word \"done\" is printed. This macro is a
3736 convenience wrapper around `make-progress-reporter' and friends.
3738 \(fn (VAR COUNT [RESULT]) MESSAGE BODY...)"
3739 (declare (indent 2) (debug ((symbolp form &optional form) form body)))
3740 (let ((temp (make-symbol "--dotimes-temp--"))
3741 (temp2 (make-symbol "--dotimes-temp2--"))
3745 (,(car spec) ,start)
3746 (,temp2 (make-progress-reporter ,message ,start ,end)))
3747 (while (< ,(car spec) ,temp)
3749 (progress-reporter-update ,temp2
3750 (setq ,(car spec) (1+ ,(car spec)))))
3751 (progress-reporter-done ,temp2)
3752 nil ,@(cdr (cdr spec)))))
3755 ;;;; Comparing version strings.
3757 (defconst version-separator "."
3758 "Specify the string used to separate the version elements.
3760 Usually the separator is \".\", but it can be any other string.")
3763 (defconst version-regexp-alist
3764 '(("^[-_+ ]?alpha$" . -3)
3765 ("^[-_+]$" . -3) ; treat "1.2.3-20050920" and "1.2-3" as alpha releases
3766 ("^[-_+ ]cvs$" . -3) ; treat "1.2.3-CVS" as alpha release
3767 ("^[-_+ ]?beta$" . -2)
3768 ("^[-_+ ]?\\(pre\\|rcc\\)$" . -1))
3769 "Specify association between non-numeric version and its priority.
3771 This association is used to handle version string like \"1.0pre2\",
3772 \"0.9alpha1\", etc. It's used by `version-to-list' (which see) to convert the
3773 non-numeric part of a version string to an integer. For example:
3775 String Version Integer List Version
3776 \"1.0pre2\" (1 0 -1 2)
3777 \"1.0PRE2\" (1 0 -1 2)
3778 \"22.8beta3\" (22 8 -2 3)
3779 \"22.8 Beta3\" (22 8 -2 3)
3780 \"0.9alpha1\" (0 9 -3 1)
3781 \"0.9AlphA1\" (0 9 -3 1)
3782 \"0.9 alpha\" (0 9 -3)
3784 Each element has the following form:
3790 REGEXP regexp used to match non-numeric part of a version string.
3791 It should begin with the `^' anchor and end with a `$' to
3792 prevent false hits. Letter-case is ignored while matching
3795 PRIORITY a negative integer specifying non-numeric priority of REGEXP.")
3798 (defun version-to-list (ver)
3799 "Convert version string VER into a list of integers.
3801 The version syntax is given by the following EBNF:
3803 VERSION ::= NUMBER ( SEPARATOR NUMBER )*.
3805 NUMBER ::= (0|1|2|3|4|5|6|7|8|9)+.
3807 SEPARATOR ::= `version-separator' (which see)
3808 | `version-regexp-alist' (which see).
3810 The NUMBER part is optional if SEPARATOR is a match for an element
3811 in `version-regexp-alist'.
3813 Examples of valid version syntax:
3815 1.0pre2 1.0.7.5 22.8beta3 0.9alpha1 6.9.30Beta
3817 Examples of invalid version syntax:
3819 1.0prepre2 1.0..7.5 22.8X3 alpha3.2 .5
3821 Examples of version conversion:
3823 Version String Version as a List of Integers
3824 \"1.0.7.5\" (1 0 7 5)
3825 \"1.0pre2\" (1 0 -1 2)
3826 \"1.0PRE2\" (1 0 -1 2)
3827 \"22.8beta3\" (22 8 -2 3)
3828 \"22.8Beta3\" (22 8 -2 3)
3829 \"0.9alpha1\" (0 9 -3 1)
3830 \"0.9AlphA1\" (0 9 -3 1)
3831 \"0.9alpha\" (0 9 -3)
3833 See documentation for `version-separator' and `version-regexp-alist'."
3834 (or (and (stringp ver) (> (length ver) 0))
3835 (error "Invalid version string: '%s'" ver))
3836 ;; Change .x.y to 0.x.y
3837 (if (and (>= (length ver) (length version-separator))
3838 (string-equal (substring ver 0 (length version-separator))
3840 (setq ver (concat "0" ver)))
3843 (case-fold-search t) ; ignore case in matching
3845 (while (and (setq s (string-match "[0-9]+" ver i))
3847 ;; handle numeric part
3848 (setq lst (cons (string-to-number (substring ver i (match-end 0)))
3851 ;; handle non-numeric part
3852 (when (and (setq s (string-match "[^0-9]+" ver i))
3854 (setq s (substring ver i (match-end 0))
3856 ;; handle alpha, beta, pre, etc. separator
3857 (unless (string= s version-separator)
3858 (setq al version-regexp-alist)
3859 (while (and al (not (string-match (caar al) s)))
3862 (push (cdar al) lst))
3863 ;; Convert 22.3a to 22.3.1, 22.3b to 22.3.2, etc.
3864 ((string-match "^[-_+ ]?\\([a-zA-Z]\\)$" s)
3865 (push (- (aref (downcase (match-string 1 s)) 0) ?a -1)
3867 (t (error "Invalid version syntax: '%s'" ver))))))
3869 (error "Invalid version syntax: '%s'" ver)
3873 (defun version-list-< (l1 l2)
3874 "Return t if L1, a list specification of a version, is lower than L2.
3876 Note that a version specified by the list (1) is equal to (1 0),
3877 \(1 0 0), (1 0 0 0), etc. That is, the trailing zeros are insignificant.
3878 Also, a version given by the list (1) is higher than (1 -1), which in
3879 turn is higher than (1 -2), which is higher than (1 -3)."
3880 (while (and l1 l2 (= (car l1) (car l2)))
3884 ;; l1 not null and l2 not null
3885 ((and l1 l2) (< (car l1) (car l2)))
3886 ;; l1 null and l2 null ==> l1 length = l2 length
3887 ((and (null l1) (null l2)) nil)
3888 ;; l1 not null and l2 null ==> l1 length > l2 length
3889 (l1 (< (version-list-not-zero l1) 0))
3890 ;; l1 null and l2 not null ==> l2 length > l1 length
3891 (t (< 0 (version-list-not-zero l2)))))
3894 (defun version-list-= (l1 l2)
3895 "Return t if L1, a list specification of a version, is equal to L2.
3897 Note that a version specified by the list (1) is equal to (1 0),
3898 \(1 0 0), (1 0 0 0), etc. That is, the trailing zeros are insignificant.
3899 Also, a version given by the list (1) is higher than (1 -1), which in
3900 turn is higher than (1 -2), which is higher than (1 -3)."
3901 (while (and l1 l2 (= (car l1) (car l2)))
3905 ;; l1 not null and l2 not null
3907 ;; l1 null and l2 null ==> l1 length = l2 length
3908 ((and (null l1) (null l2)))
3909 ;; l1 not null and l2 null ==> l1 length > l2 length
3910 (l1 (zerop (version-list-not-zero l1)))
3911 ;; l1 null and l2 not null ==> l2 length > l1 length
3912 (t (zerop (version-list-not-zero l2)))))
3915 (defun version-list-<= (l1 l2)
3916 "Return t if L1, a list specification of a version, is lower or equal to L2.
3918 Note that integer list (1) is equal to (1 0), (1 0 0), (1 0 0 0),
3919 etc. That is, the trailing zeroes are insignificant. Also, integer
3920 list (1) is greater than (1 -1) which is greater than (1 -2)
3921 which is greater than (1 -3)."
3922 (while (and l1 l2 (= (car l1) (car l2)))
3926 ;; l1 not null and l2 not null
3927 ((and l1 l2) (< (car l1) (car l2)))
3928 ;; l1 null and l2 null ==> l1 length = l2 length
3929 ((and (null l1) (null l2)))
3930 ;; l1 not null and l2 null ==> l1 length > l2 length
3931 (l1 (<= (version-list-not-zero l1) 0))
3932 ;; l1 null and l2 not null ==> l2 length > l1 length
3933 (t (<= 0 (version-list-not-zero l2)))))
3935 (defun version-list-not-zero (lst)
3936 "Return the first non-zero element of LST, which is a list of integers.
3938 If all LST elements are zeros or LST is nil, return zero."
3939 (while (and lst (zerop (car lst)))
3940 (setq lst (cdr lst)))
3943 ;; there is no element different of zero
3947 (defun version< (v1 v2)
3948 "Return t if version V1 is lower (older) than V2.
3950 Note that version string \"1\" is equal to \"1.0\", \"1.0.0\", \"1.0.0.0\",
3951 etc. That is, the trailing \".0\"s are insignificant. Also, version
3952 string \"1\" is higher (newer) than \"1pre\", which is higher than \"1beta\",
3953 which is higher than \"1alpha\"."
3954 (version-list-< (version-to-list v1) (version-to-list v2)))
3957 (defun version<= (v1 v2)
3958 "Return t if version V1 is lower (older) than or equal to V2.
3960 Note that version string \"1\" is equal to \"1.0\", \"1.0.0\", \"1.0.0.0\",
3961 etc. That is, the trailing \".0\"s are insignificant. Also, version
3962 string \"1\" is higher (newer) than \"1pre\", which is higher than \"1beta\",
3963 which is higher than \"1alpha\"."
3964 (version-list-<= (version-to-list v1) (version-to-list v2)))
3966 (defun version= (v1 v2)
3967 "Return t if version V1 is equal to V2.
3969 Note that version string \"1\" is equal to \"1.0\", \"1.0.0\", \"1.0.0.0\",
3970 etc. That is, the trailing \".0\"s are insignificant. Also, version
3971 string \"1\" is higher (newer) than \"1pre\", which is higher than \"1beta\",
3972 which is higher than \"1alpha\"."
3973 (version-list-= (version-to-list v1) (version-to-list v2)))
3977 (defconst menu-bar-separator '("--")
3978 "Separator for menus.")
3980 ;; The following statement ought to be in print.c, but `provide' can't
3982 ;; http://lists.gnu.org/archive/html/emacs-devel/2009-08/msg00236.html
3983 (when (hash-table-p (car (read-from-string
3984 (prin1-to-string (make-hash-table)))))
3985 (provide 'hashtable-print-readable))
3987 ;;; subr.el ends here