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