]> code.delx.au - gnu-emacs/blob - lisp/subr.el
Switch to recommended form of GPLv3 permissions notice.
[gnu-emacs] / lisp / subr.el
1 ;;; subr.el --- basic lisp subroutines for Emacs
2
3 ;; Copyright (C) 1985, 1986, 1992, 1994, 1995, 1999, 2000, 2001, 2002, 2003,
4 ;; 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
5
6 ;; Maintainer: FSF
7 ;; Keywords: internal
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23
24 ;;; Commentary:
25
26 ;;; Code:
27 (defvar custom-declare-variable-list nil
28 "Record `defcustom' calls made before `custom.el' is loaded to handle them.
29 Each element of this list holds the arguments to one call to `defcustom'.")
30
31 ;; Use this, rather than defcustom, in subr.el and other files loaded
32 ;; before custom.el.
33 (defun custom-declare-variable-early (&rest arguments)
34 (setq custom-declare-variable-list
35 (cons arguments custom-declare-variable-list)))
36
37 (defmacro declare-function (fn file &optional arglist fileonly)
38 "Tell the byte-compiler that function FN is defined, in FILE.
39 Optional ARGLIST is the argument list used by the function. The
40 FILE argument is not used by the byte-compiler, but by the
41 `check-declare' package, which checks that FILE contains a
42 definition for FN. ARGLIST is used by both the byte-compiler and
43 `check-declare' to check for consistency.
44
45 FILE can be either a Lisp file (in which case the \".el\"
46 extension is optional), or a C file. C files are expanded
47 relative to the Emacs \"src/\" directory. Lisp files are
48 searched for using `locate-library', and if that fails they are
49 expanded relative to the location of the file containing the
50 declaration. A FILE with an \"ext:\" prefix is an external file.
51 `check-declare' will check such files if they are found, and skip
52 them without error if they are not.
53
54 FILEONLY non-nil means that `check-declare' will only check that
55 FILE exists, not that it defines FN. This is intended for
56 function-definitions that `check-declare' does not recognize, e.g.
57 `defstruct'.
58
59 To specify a value for FILEONLY without passing an argument list,
60 set ARGLIST to `t'. This is necessary because `nil' means an
61 empty argument list, rather than an unspecified one.
62
63 Note that for the purposes of `check-declare', this statement
64 must be the first non-whitespace on a line, and everything up to
65 the end of FILE must be all on the same line. For example:
66
67 \(declare-function c-end-of-defun \"progmodes/cc-cmds.el\"
68 \(&optional arg))
69
70 For more information, see Info node `elisp(Declaring Functions)'."
71 ;; Does nothing - byte-compile-declare-function does the work.
72 nil)
73 \f
74 ;;;; Basic Lisp macros.
75
76 (defalias 'not 'null)
77
78 (defmacro noreturn (form)
79 "Evaluate FORM, expecting it not to return.
80 If FORM does return, signal an error."
81 `(prog1 ,form
82 (error "Form marked with `noreturn' did return")))
83
84 (defmacro 1value (form)
85 "Evaluate FORM, expecting a constant return value.
86 This is the global do-nothing version. There is also `testcover-1value'
87 that complains if FORM ever does return differing values."
88 form)
89
90 (defmacro def-edebug-spec (symbol spec)
91 "Set the `edebug-form-spec' property of SYMBOL according to SPEC.
92 Both SYMBOL and SPEC are unevaluated. The SPEC can be 0, t, a symbol
93 \(naming a function), or a list."
94 `(put (quote ,symbol) 'edebug-form-spec (quote ,spec)))
95
96 (defmacro lambda (&rest cdr)
97 "Return a lambda expression.
98 A call of the form (lambda ARGS DOCSTRING INTERACTIVE BODY) is
99 self-quoting; the result of evaluating the lambda expression is the
100 expression itself. The lambda expression may then be treated as a
101 function, i.e., stored as the function value of a symbol, passed to
102 `funcall' or `mapcar', etc.
103
104 ARGS should take the same form as an argument list for a `defun'.
105 DOCSTRING is an optional documentation string.
106 If present, it should describe how to call the function.
107 But documentation strings are usually not useful in nameless functions.
108 INTERACTIVE should be a call to the function `interactive', which see.
109 It may also be omitted.
110 BODY should be a list of Lisp expressions.
111
112 \(fn ARGS [DOCSTRING] [INTERACTIVE] 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 push (newelt listname)
118 "Add NEWELT to the list stored in the symbol LISTNAME.
119 This is equivalent to (setq LISTNAME (cons NEWELT LISTNAME)).
120 LISTNAME must be a symbol."
121 (declare (debug (form sexp)))
122 (list 'setq listname
123 (list 'cons newelt listname)))
124
125 (defmacro pop (listname)
126 "Return the first element of LISTNAME's value, and remove it from the list.
127 LISTNAME must be a symbol whose value is a list.
128 If the value is nil, `pop' returns nil but does not actually
129 change the list."
130 (declare (debug (sexp)))
131 (list 'car
132 (list 'prog1 listname
133 (list 'setq listname (list 'cdr listname)))))
134
135 (defmacro when (cond &rest body)
136 "If COND yields non-nil, do BODY, else return nil.
137 When COND yields non-nil, eval BODY forms sequentially and return
138 value of last one, or nil if there are none.
139
140 \(fn COND BODY...)"
141 (declare (indent 1) (debug t))
142 (list 'if cond (cons 'progn body)))
143
144 (defmacro unless (cond &rest body)
145 "If COND yields nil, do BODY, else return nil.
146 When COND yields nil, eval BODY forms sequentially and return
147 value of last one, or nil if there are none.
148
149 \(fn COND BODY...)"
150 (declare (indent 1) (debug t))
151 (cons 'if (cons cond (cons nil body))))
152
153 (defvar --dolist-tail-- nil
154 "Temporary variable used in `dolist' expansion.")
155
156 (defmacro dolist (spec &rest body)
157 "Loop over a list.
158 Evaluate BODY with VAR bound to each car from LIST, in turn.
159 Then evaluate RESULT to get return value, default nil.
160
161 \(fn (VAR LIST [RESULT]) BODY...)"
162 (declare (indent 1) (debug ((symbolp form &optional form) body)))
163 ;; It would be cleaner to create an uninterned symbol,
164 ;; but that uses a lot more space when many functions in many files
165 ;; use dolist.
166 (let ((temp '--dolist-tail--))
167 `(let ((,temp ,(nth 1 spec))
168 ,(car spec))
169 (while ,temp
170 (setq ,(car spec) (car ,temp))
171 ,@body
172 (setq ,temp (cdr ,temp)))
173 ,@(if (cdr (cdr spec))
174 `((setq ,(car spec) nil) ,@(cdr (cdr spec)))))))
175
176 (defvar --dotimes-limit-- nil
177 "Temporary variable used in `dotimes' expansion.")
178
179 (defmacro dotimes (spec &rest body)
180 "Loop a certain number of times.
181 Evaluate BODY with VAR bound to successive integers running from 0,
182 inclusive, to COUNT, exclusive. Then evaluate RESULT to get
183 the return value (nil if RESULT is omitted).
184
185 \(fn (VAR COUNT [RESULT]) BODY...)"
186 (declare (indent 1) (debug dolist))
187 ;; It would be cleaner to create an uninterned symbol,
188 ;; but that uses a lot more space when many functions in many files
189 ;; use dotimes.
190 (let ((temp '--dotimes-limit--)
191 (start 0)
192 (end (nth 1 spec)))
193 `(let ((,temp ,end)
194 (,(car spec) ,start))
195 (while (< ,(car spec) ,temp)
196 ,@body
197 (setq ,(car spec) (1+ ,(car spec))))
198 ,@(cdr (cdr spec)))))
199
200 (defmacro declare (&rest specs)
201 "Do not evaluate any arguments and return nil.
202 Treated as a declaration when used at the right place in a
203 `defmacro' form. \(See Info anchor `(elisp)Definition of declare'.)"
204 nil)
205 \f
206 ;;;; Basic Lisp functions.
207
208 (defun ignore (&rest ignore)
209 "Do nothing and return nil.
210 This function accepts any number of arguments, but ignores them."
211 (interactive)
212 nil)
213
214 (defun error (&rest args)
215 "Signal an error, making error message by passing all args to `format'.
216 In Emacs, the convention is that error messages start with a capital
217 letter but *do not* end with a period. Please follow this convention
218 for the sake of consistency."
219 (while t
220 (signal 'error (list (apply 'format args)))))
221
222 ;; We put this here instead of in frame.el so that it's defined even on
223 ;; systems where frame.el isn't loaded.
224 (defun frame-configuration-p (object)
225 "Return non-nil if OBJECT seems to be a frame configuration.
226 Any list whose car is `frame-configuration' is assumed to be a frame
227 configuration."
228 (and (consp object)
229 (eq (car object) 'frame-configuration)))
230
231 (defun functionp (object)
232 "Non-nil if OBJECT is a function."
233 (or (and (symbolp object) (fboundp object)
234 (condition-case nil
235 (setq object (indirect-function object))
236 (error nil))
237 (eq (car-safe object) 'autoload)
238 (not (car-safe (cdr-safe (cdr-safe (cdr-safe (cdr-safe object)))))))
239 (and (subrp object)
240 ;; Filter out special forms.
241 (not (eq 'unevalled (cdr (subr-arity object)))))
242 (byte-code-function-p object)
243 (eq (car-safe object) 'lambda)))
244 \f
245 ;;;; List functions.
246
247 (defsubst caar (x)
248 "Return the car of the car of X."
249 (car (car x)))
250
251 (defsubst cadr (x)
252 "Return the car of the cdr of X."
253 (car (cdr x)))
254
255 (defsubst cdar (x)
256 "Return the cdr of the car of X."
257 (cdr (car x)))
258
259 (defsubst cddr (x)
260 "Return the cdr of the cdr of X."
261 (cdr (cdr x)))
262
263 (defun last (list &optional n)
264 "Return the last link of LIST. Its car is the last element.
265 If LIST is nil, return nil.
266 If N is non-nil, return the Nth-to-last link of LIST.
267 If N is bigger than the length of LIST, return LIST."
268 (if n
269 (let ((m 0) (p list))
270 (while (consp p)
271 (setq m (1+ m) p (cdr p)))
272 (if (<= n 0) p
273 (if (< n m) (nthcdr (- m n) list) list)))
274 (while (consp (cdr list))
275 (setq list (cdr list)))
276 list))
277
278 (defun butlast (list &optional n)
279 "Return a copy of LIST with the last N elements removed."
280 (if (and n (<= n 0)) list
281 (nbutlast (copy-sequence list) n)))
282
283 (defun nbutlast (list &optional n)
284 "Modifies LIST to remove the last N elements."
285 (let ((m (length list)))
286 (or n (setq n 1))
287 (and (< n m)
288 (progn
289 (if (> n 0) (setcdr (nthcdr (- (1- m) n) list) nil))
290 list))))
291
292 (defun delete-dups (list)
293 "Destructively remove `equal' duplicates from LIST.
294 Store the result in LIST and return it. LIST must be a proper list.
295 Of several `equal' occurrences of an element in LIST, the first
296 one is kept."
297 (let ((tail list))
298 (while tail
299 (setcdr tail (delete (car tail) (cdr tail)))
300 (setq tail (cdr tail))))
301 list)
302
303 (defun number-sequence (from &optional to inc)
304 "Return a sequence of numbers from FROM to TO (both inclusive) as a list.
305 INC is the increment used between numbers in the sequence and defaults to 1.
306 So, the Nth element of the list is \(+ FROM \(* N INC)) where N counts from
307 zero. TO is only included if there is an N for which TO = FROM + N * INC.
308 If TO is nil or numerically equal to FROM, return \(FROM).
309 If INC is positive and TO is less than FROM, or INC is negative
310 and TO is larger than FROM, return nil.
311 If INC is zero and TO is neither nil nor numerically equal to
312 FROM, signal an error.
313
314 This function is primarily designed for integer arguments.
315 Nevertheless, FROM, TO and INC can be integer or float. However,
316 floating point arithmetic is inexact. For instance, depending on
317 the machine, it may quite well happen that
318 \(number-sequence 0.4 0.6 0.2) returns the one element list \(0.4),
319 whereas \(number-sequence 0.4 0.8 0.2) returns a list with three
320 elements. Thus, if some of the arguments are floats and one wants
321 to make sure that TO is included, one may have to explicitly write
322 TO as \(+ FROM \(* N INC)) or use a variable whose value was
323 computed with this exact expression. Alternatively, you can,
324 of course, also replace TO with a slightly larger value
325 \(or a slightly more negative value if INC is negative)."
326 (if (or (not to) (= from to))
327 (list from)
328 (or inc (setq inc 1))
329 (when (zerop inc) (error "The increment can not be zero"))
330 (let (seq (n 0) (next from))
331 (if (> inc 0)
332 (while (<= next to)
333 (setq seq (cons next seq)
334 n (1+ n)
335 next (+ from (* n inc))))
336 (while (>= next to)
337 (setq seq (cons next seq)
338 n (1+ n)
339 next (+ from (* n inc)))))
340 (nreverse seq))))
341
342 (defun copy-tree (tree &optional vecp)
343 "Make a copy of TREE.
344 If TREE is a cons cell, this recursively copies both its car and its cdr.
345 Contrast to `copy-sequence', which copies only along the cdrs. With second
346 argument VECP, this copies vectors as well as conses."
347 (if (consp tree)
348 (let (result)
349 (while (consp tree)
350 (let ((newcar (car tree)))
351 (if (or (consp (car tree)) (and vecp (vectorp (car tree))))
352 (setq newcar (copy-tree (car tree) vecp)))
353 (push newcar result))
354 (setq tree (cdr tree)))
355 (nconc (nreverse result) tree))
356 (if (and vecp (vectorp tree))
357 (let ((i (length (setq tree (copy-sequence tree)))))
358 (while (>= (setq i (1- i)) 0)
359 (aset tree i (copy-tree (aref tree i) vecp)))
360 tree)
361 tree)))
362 \f
363 ;;;; Various list-search functions.
364
365 (defun assoc-default (key alist &optional test default)
366 "Find object KEY in a pseudo-alist ALIST.
367 ALIST is a list of conses or objects. Each element (or the element's car,
368 if it is a cons) is compared with KEY by evaluating (TEST (car elt) KEY).
369 If that is non-nil, the element matches;
370 then `assoc-default' returns the element's cdr, if it is a cons,
371 or DEFAULT if the element is not a cons.
372
373 If no element matches, the value is nil.
374 If TEST is omitted or nil, `equal' is used."
375 (let (found (tail alist) value)
376 (while (and tail (not found))
377 (let ((elt (car tail)))
378 (when (funcall (or test 'equal) (if (consp elt) (car elt) elt) key)
379 (setq found t value (if (consp elt) (cdr elt) default))))
380 (setq tail (cdr tail)))
381 value))
382
383 (make-obsolete 'assoc-ignore-case 'assoc-string "22.1")
384 (defun assoc-ignore-case (key alist)
385 "Like `assoc', but ignores differences in case and text representation.
386 KEY must be a string. Upper-case and lower-case letters are treated as equal.
387 Unibyte strings are converted to multibyte for comparison."
388 (assoc-string key alist t))
389
390 (make-obsolete 'assoc-ignore-representation 'assoc-string "22.1")
391 (defun assoc-ignore-representation (key alist)
392 "Like `assoc', but ignores differences in text representation.
393 KEY must be a string.
394 Unibyte strings are converted to multibyte for comparison."
395 (assoc-string key alist nil))
396
397 (defun member-ignore-case (elt list)
398 "Like `member', but ignores differences in case and text representation.
399 ELT must be a string. Upper-case and lower-case letters are treated as equal.
400 Unibyte strings are converted to multibyte for comparison.
401 Non-strings in LIST are ignored."
402 (while (and list
403 (not (and (stringp (car list))
404 (eq t (compare-strings elt 0 nil (car list) 0 nil t)))))
405 (setq list (cdr list)))
406 list)
407
408 (defun assq-delete-all (key alist)
409 "Delete from ALIST all elements whose car is `eq' to KEY.
410 Return the modified alist.
411 Elements of ALIST that are not conses are ignored."
412 (while (and (consp (car alist))
413 (eq (car (car alist)) key))
414 (setq alist (cdr alist)))
415 (let ((tail alist) tail-cdr)
416 (while (setq tail-cdr (cdr tail))
417 (if (and (consp (car tail-cdr))
418 (eq (car (car tail-cdr)) key))
419 (setcdr tail (cdr tail-cdr))
420 (setq tail tail-cdr))))
421 alist)
422
423 (defun rassq-delete-all (value alist)
424 "Delete from ALIST all elements whose cdr is `eq' to VALUE.
425 Return the modified alist.
426 Elements of ALIST that are not conses are ignored."
427 (while (and (consp (car alist))
428 (eq (cdr (car alist)) value))
429 (setq alist (cdr alist)))
430 (let ((tail alist) tail-cdr)
431 (while (setq tail-cdr (cdr tail))
432 (if (and (consp (car tail-cdr))
433 (eq (cdr (car tail-cdr)) value))
434 (setcdr tail (cdr tail-cdr))
435 (setq tail tail-cdr))))
436 alist)
437
438 (defun remove (elt seq)
439 "Return a copy of SEQ with all occurrences of ELT removed.
440 SEQ must be a list, vector, or string. The comparison is done with `equal'."
441 (if (nlistp seq)
442 ;; If SEQ isn't a list, there's no need to copy SEQ because
443 ;; `delete' will return a new object.
444 (delete elt seq)
445 (delete elt (copy-sequence seq))))
446
447 (defun remq (elt list)
448 "Return LIST with all occurrences of ELT removed.
449 The comparison is done with `eq'. Contrary to `delq', this does not use
450 side-effects, and the argument LIST is not modified."
451 (if (memq elt list)
452 (delq elt (copy-sequence list))
453 list))
454 \f
455 ;;;; Keymap support.
456
457 (defmacro kbd (keys)
458 "Convert KEYS to the internal Emacs key representation.
459 KEYS should be a string constant in the format used for
460 saving keyboard macros (see `edmacro-mode')."
461 (read-kbd-macro keys))
462
463 (defun undefined ()
464 (interactive)
465 (ding))
466
467 ;; Prevent the \{...} documentation construct
468 ;; from mentioning keys that run this command.
469 (put 'undefined 'suppress-keymap t)
470
471 (defun suppress-keymap (map &optional nodigits)
472 "Make MAP override all normally self-inserting keys to be undefined.
473 Normally, as an exception, digits and minus-sign are set to make prefix args,
474 but optional second arg NODIGITS non-nil treats them like other chars."
475 (define-key map [remap self-insert-command] 'undefined)
476 (or nodigits
477 (let (loop)
478 (define-key map "-" 'negative-argument)
479 ;; Make plain numbers do numeric args.
480 (setq loop ?0)
481 (while (<= loop ?9)
482 (define-key map (char-to-string loop) 'digit-argument)
483 (setq loop (1+ loop))))))
484
485 (defun define-key-after (keymap key definition &optional after)
486 "Add binding in KEYMAP for KEY => DEFINITION, right after AFTER's binding.
487 This is like `define-key' except that the binding for KEY is placed
488 just after the binding for the event AFTER, instead of at the beginning
489 of the map. Note that AFTER must be an event type (like KEY), NOT a command
490 \(like DEFINITION).
491
492 If AFTER is t or omitted, the new binding goes at the end of the keymap.
493 AFTER should be a single event type--a symbol or a character, not a sequence.
494
495 Bindings are always added before any inherited map.
496
497 The order of bindings in a keymap matters when it is used as a menu."
498 (unless after (setq after t))
499 (or (keymapp keymap)
500 (signal 'wrong-type-argument (list 'keymapp keymap)))
501 (setq key
502 (if (<= (length key) 1) (aref key 0)
503 (setq keymap (lookup-key keymap
504 (apply 'vector
505 (butlast (mapcar 'identity key)))))
506 (aref key (1- (length key)))))
507 (let ((tail keymap) done inserted)
508 (while (and (not done) tail)
509 ;; Delete any earlier bindings for the same key.
510 (if (eq (car-safe (car (cdr tail))) key)
511 (setcdr tail (cdr (cdr tail))))
512 ;; If we hit an included map, go down that one.
513 (if (keymapp (car tail)) (setq tail (car tail)))
514 ;; When we reach AFTER's binding, insert the new binding after.
515 ;; If we reach an inherited keymap, insert just before that.
516 ;; If we reach the end of this keymap, insert at the end.
517 (if (or (and (eq (car-safe (car tail)) after)
518 (not (eq after t)))
519 (eq (car (cdr tail)) 'keymap)
520 (null (cdr tail)))
521 (progn
522 ;; Stop the scan only if we find a parent keymap.
523 ;; Keep going past the inserted element
524 ;; so we can delete any duplications that come later.
525 (if (eq (car (cdr tail)) 'keymap)
526 (setq done t))
527 ;; Don't insert more than once.
528 (or inserted
529 (setcdr tail (cons (cons key definition) (cdr tail))))
530 (setq inserted t)))
531 (setq tail (cdr tail)))))
532
533 (defun map-keymap-sorted (function keymap)
534 "Implement `map-keymap' with sorting.
535 Don't call this function; it is for internal use only."
536 (let (list)
537 (map-keymap (lambda (a b) (push (cons a b) list))
538 keymap)
539 (setq list (sort list
540 (lambda (a b)
541 (setq a (car a) b (car b))
542 (if (integerp a)
543 (if (integerp b) (< a b)
544 t)
545 (if (integerp b) t
546 ;; string< also accepts symbols.
547 (string< a b))))))
548 (dolist (p list)
549 (funcall function (car p) (cdr p)))))
550
551 (defun keymap-canonicalize (map)
552 "Return an equivalent keymap, without inheritance."
553 (let ((bindings ())
554 (ranges ()))
555 (while (keymapp map)
556 (setq map (map-keymap-internal
557 (lambda (key item)
558 (if (consp key)
559 ;; Treat char-ranges specially.
560 (push (cons key item) ranges)
561 (push (cons key item) bindings)))
562 map)))
563 (setq map (funcall (if ranges 'make-keymap 'make-sparse-keymap)
564 (keymap-prompt map)))
565 (dolist (binding ranges)
566 ;; Treat char-ranges specially.
567 (define-key map (vector (car binding)) (cdr binding)))
568 (dolist (binding (prog1 bindings (setq bindings ())))
569 (let* ((key (car binding))
570 (item (cdr binding))
571 (oldbind (assq key bindings)))
572 ;; Newer bindings override older.
573 (if oldbind (setq bindings (delq oldbind bindings)))
574 (when item ;nil bindings just hide older ones.
575 (push binding bindings))))
576 (nconc map bindings)))
577
578 (put 'keyboard-translate-table 'char-table-extra-slots 0)
579
580 (defun keyboard-translate (from to)
581 "Translate character FROM to TO at a low level.
582 This function creates a `keyboard-translate-table' if necessary
583 and then modifies one entry in it."
584 (or (char-table-p keyboard-translate-table)
585 (setq keyboard-translate-table
586 (make-char-table 'keyboard-translate-table nil)))
587 (aset keyboard-translate-table from to))
588 \f
589 ;;;; Key binding commands.
590
591 (defun global-set-key (key command)
592 "Give KEY a global binding as COMMAND.
593 COMMAND is the command definition to use; usually it is
594 a symbol naming an interactively-callable function.
595 KEY is a key sequence; noninteractively, it is a string or vector
596 of characters or event types, and non-ASCII characters with codes
597 above 127 (such as ISO Latin-1) can be included if you use a vector.
598
599 Note that if KEY has a local binding in the current buffer,
600 that local binding will continue to shadow any global binding
601 that you make with this function."
602 (interactive "KSet key globally: \nCSet key %s to command: ")
603 (or (vectorp key) (stringp key)
604 (signal 'wrong-type-argument (list 'arrayp key)))
605 (define-key (current-global-map) key command))
606
607 (defun local-set-key (key command)
608 "Give KEY a local binding as COMMAND.
609 COMMAND is the command definition to use; usually it is
610 a symbol naming an interactively-callable function.
611 KEY is a key sequence; noninteractively, it is a string or vector
612 of characters or event types, and non-ASCII characters with codes
613 above 127 (such as ISO Latin-1) can be included if you use a vector.
614
615 The binding goes in the current buffer's local map,
616 which in most cases is shared with all other buffers in the same major mode."
617 (interactive "KSet key locally: \nCSet key %s locally to command: ")
618 (let ((map (current-local-map)))
619 (or map
620 (use-local-map (setq map (make-sparse-keymap))))
621 (or (vectorp key) (stringp key)
622 (signal 'wrong-type-argument (list 'arrayp key)))
623 (define-key map key command)))
624
625 (defun global-unset-key (key)
626 "Remove global binding of KEY.
627 KEY is a string or vector representing a sequence of keystrokes."
628 (interactive "kUnset key globally: ")
629 (global-set-key key nil))
630
631 (defun local-unset-key (key)
632 "Remove local binding of KEY.
633 KEY is a string or vector representing a sequence of keystrokes."
634 (interactive "kUnset key locally: ")
635 (if (current-local-map)
636 (local-set-key key nil))
637 nil)
638 \f
639 ;;;; substitute-key-definition and its subroutines.
640
641 (defvar key-substitution-in-progress nil
642 "Used internally by `substitute-key-definition'.")
643
644 (defun substitute-key-definition (olddef newdef keymap &optional oldmap prefix)
645 "Replace OLDDEF with NEWDEF for any keys in KEYMAP now defined as OLDDEF.
646 In other words, OLDDEF is replaced with NEWDEF where ever it appears.
647 Alternatively, if optional fourth argument OLDMAP is specified, we redefine
648 in KEYMAP as NEWDEF those keys which are defined as OLDDEF in OLDMAP.
649
650 If you don't specify OLDMAP, you can usually get the same results
651 in a cleaner way with command remapping, like this:
652 \(define-key KEYMAP [remap OLDDEF] NEWDEF)
653 \n(fn OLDDEF NEWDEF KEYMAP &optional OLDMAP)"
654 ;; Don't document PREFIX in the doc string because we don't want to
655 ;; advertise it. It's meant for recursive calls only. Here's its
656 ;; meaning
657
658 ;; If optional argument PREFIX is specified, it should be a key
659 ;; prefix, a string. Redefined bindings will then be bound to the
660 ;; original key, with PREFIX added at the front.
661 (or prefix (setq prefix ""))
662 (let* ((scan (or oldmap keymap))
663 (prefix1 (vconcat prefix [nil]))
664 (key-substitution-in-progress
665 (cons scan key-substitution-in-progress)))
666 ;; Scan OLDMAP, finding each char or event-symbol that
667 ;; has any definition, and act on it with hack-key.
668 (map-keymap
669 (lambda (char defn)
670 (aset prefix1 (length prefix) char)
671 (substitute-key-definition-key defn olddef newdef prefix1 keymap))
672 scan)))
673
674 (defun substitute-key-definition-key (defn olddef newdef prefix keymap)
675 (let (inner-def skipped menu-item)
676 ;; Find the actual command name within the binding.
677 (if (eq (car-safe defn) 'menu-item)
678 (setq menu-item defn defn (nth 2 defn))
679 ;; Skip past menu-prompt.
680 (while (stringp (car-safe defn))
681 (push (pop defn) skipped))
682 ;; Skip past cached key-equivalence data for menu items.
683 (if (consp (car-safe defn))
684 (setq defn (cdr defn))))
685 (if (or (eq defn olddef)
686 ;; Compare with equal if definition is a key sequence.
687 ;; That is useful for operating on function-key-map.
688 (and (or (stringp defn) (vectorp defn))
689 (equal defn olddef)))
690 (define-key keymap prefix
691 (if menu-item
692 (let ((copy (copy-sequence menu-item)))
693 (setcar (nthcdr 2 copy) newdef)
694 copy)
695 (nconc (nreverse skipped) newdef)))
696 ;; Look past a symbol that names a keymap.
697 (setq inner-def
698 (or (indirect-function defn t) defn))
699 ;; For nested keymaps, we use `inner-def' rather than `defn' so as to
700 ;; avoid autoloading a keymap. This is mostly done to preserve the
701 ;; original non-autoloading behavior of pre-map-keymap times.
702 (if (and (keymapp inner-def)
703 ;; Avoid recursively scanning
704 ;; where KEYMAP does not have a submap.
705 (let ((elt (lookup-key keymap prefix)))
706 (or (null elt) (natnump elt) (keymapp elt)))
707 ;; Avoid recursively rescanning keymap being scanned.
708 (not (memq inner-def key-substitution-in-progress)))
709 ;; If this one isn't being scanned already, scan it now.
710 (substitute-key-definition olddef newdef keymap inner-def prefix)))))
711
712 \f
713 ;;;; The global keymap tree.
714
715 ;;; global-map, esc-map, and ctl-x-map have their values set up in
716 ;;; keymap.c; we just give them docstrings here.
717
718 (defvar global-map nil
719 "Default global keymap mapping Emacs keyboard input into commands.
720 The value is a keymap which is usually (but not necessarily) Emacs's
721 global map.")
722
723 (defvar esc-map nil
724 "Default keymap for ESC (meta) commands.
725 The normal global definition of the character ESC indirects to this keymap.")
726
727 (defvar ctl-x-map nil
728 "Default keymap for C-x commands.
729 The normal global definition of the character C-x indirects to this keymap.")
730
731 (defvar ctl-x-4-map (make-sparse-keymap)
732 "Keymap for subcommands of C-x 4.")
733 (defalias 'ctl-x-4-prefix ctl-x-4-map)
734 (define-key ctl-x-map "4" 'ctl-x-4-prefix)
735
736 (defvar ctl-x-5-map (make-sparse-keymap)
737 "Keymap for frame commands.")
738 (defalias 'ctl-x-5-prefix ctl-x-5-map)
739 (define-key ctl-x-map "5" 'ctl-x-5-prefix)
740
741 \f
742 ;;;; Event manipulation functions.
743
744 ;; The call to `read' is to ensure that the value is computed at load time
745 ;; and not compiled into the .elc file. The value is negative on most
746 ;; machines, but not on all!
747 (defconst listify-key-sequence-1 (logior 128 (read "?\\M-\\^@")))
748
749 (defun listify-key-sequence (key)
750 "Convert a key sequence to a list of events."
751 (if (vectorp key)
752 (append key nil)
753 (mapcar (function (lambda (c)
754 (if (> c 127)
755 (logxor c listify-key-sequence-1)
756 c)))
757 key)))
758
759 (defsubst eventp (obj)
760 "True if the argument is an event object."
761 (or (and (integerp obj)
762 ;; Filter out integers too large to be events.
763 ;; M is the biggest modifier.
764 (zerop (logand obj (lognot (1- (lsh ?\M-\^@ 1)))))
765 (characterp (event-basic-type obj)))
766 (and (symbolp obj)
767 (get obj 'event-symbol-elements))
768 (and (consp obj)
769 (symbolp (car obj))
770 (get (car obj) 'event-symbol-elements))))
771
772 (defun event-modifiers (event)
773 "Return a list of symbols representing the modifier keys in event EVENT.
774 The elements of the list may include `meta', `control',
775 `shift', `hyper', `super', `alt', `click', `double', `triple', `drag',
776 and `down'.
777 EVENT may be an event or an event type. If EVENT is a symbol
778 that has never been used in an event that has been read as input
779 in the current Emacs session, then this function can return nil,
780 even when EVENT actually has modifiers."
781 (let ((type event))
782 (if (listp type)
783 (setq type (car type)))
784 (if (symbolp type)
785 ;; Don't read event-symbol-elements directly since we're not
786 ;; sure the symbol has already been parsed.
787 (cdr (internal-event-symbol-parse-modifiers type))
788 (let ((list nil)
789 (char (logand type (lognot (logior ?\M-\^@ ?\C-\^@ ?\S-\^@
790 ?\H-\^@ ?\s-\^@ ?\A-\^@)))))
791 (if (not (zerop (logand type ?\M-\^@)))
792 (push 'meta list))
793 (if (or (not (zerop (logand type ?\C-\^@)))
794 (< char 32))
795 (push 'control list))
796 (if (or (not (zerop (logand type ?\S-\^@)))
797 (/= char (downcase char)))
798 (push 'shift list))
799 (or (zerop (logand type ?\H-\^@))
800 (push 'hyper list))
801 (or (zerop (logand type ?\s-\^@))
802 (push 'super list))
803 (or (zerop (logand type ?\A-\^@))
804 (push 'alt list))
805 list))))
806
807 (defun event-basic-type (event)
808 "Return the basic type of the given event (all modifiers removed).
809 The value is a printing character (not upper case) or a symbol.
810 EVENT may be an event or an event type. If EVENT is a symbol
811 that has never been used in an event that has been read as input
812 in the current Emacs session, then this function may return nil."
813 (if (consp event)
814 (setq event (car event)))
815 (if (symbolp event)
816 (car (get event 'event-symbol-elements))
817 (let* ((base (logand event (1- ?\A-\^@)))
818 (uncontrolled (if (< base 32) (logior base 64) base)))
819 ;; There are some numbers that are invalid characters and
820 ;; cause `downcase' to get an error.
821 (condition-case ()
822 (downcase uncontrolled)
823 (error uncontrolled)))))
824
825 (defsubst mouse-movement-p (object)
826 "Return non-nil if OBJECT is a mouse movement event."
827 (eq (car-safe object) 'mouse-movement))
828
829 (defun mouse-event-p (object)
830 "Return non-nil if OBJECT is a mouse click event."
831 ;; is this really correct? maybe remove mouse-movement?
832 (memq (event-basic-type object) '(mouse-1 mouse-2 mouse-3 mouse-movement)))
833
834 (defsubst event-start (event)
835 "Return the starting position of EVENT.
836 If EVENT is a mouse or key press or a mouse click, this returns the location
837 of the event.
838 If EVENT is a drag, this returns the drag's starting position.
839 The return value is of the form
840 (WINDOW AREA-OR-POS (X . Y) TIMESTAMP OBJECT POS (COL . ROW)
841 IMAGE (DX . DY) (WIDTH . HEIGHT))
842 The `posn-' functions access elements of such lists."
843 (if (consp event) (nth 1 event)
844 (list (selected-window) (point) '(0 . 0) 0)))
845
846 (defsubst event-end (event)
847 "Return the ending location of EVENT.
848 EVENT should be a click, drag, or key press event.
849 If EVENT is a click event, this function is the same as `event-start'.
850 The return value is of the form
851 (WINDOW AREA-OR-POS (X . Y) TIMESTAMP OBJECT POS (COL . ROW)
852 IMAGE (DX . DY) (WIDTH . HEIGHT))
853 The `posn-' functions access elements of such lists."
854 (if (consp event) (nth (if (consp (nth 2 event)) 2 1) event)
855 (list (selected-window) (point) '(0 . 0) 0)))
856
857 (defsubst event-click-count (event)
858 "Return the multi-click count of EVENT, a click or drag event.
859 The return value is a positive integer."
860 (if (and (consp event) (integerp (nth 2 event))) (nth 2 event) 1))
861 \f
862 ;;;; Extracting fields of the positions in an event.
863
864 (defsubst posn-window (position)
865 "Return the window in POSITION.
866 POSITION should be a list of the form returned by the `event-start'
867 and `event-end' functions."
868 (nth 0 position))
869
870 (defsubst posn-area (position)
871 "Return the window area recorded in POSITION, or nil for the text area.
872 POSITION should be a list of the form returned by the `event-start'
873 and `event-end' functions."
874 (let ((area (if (consp (nth 1 position))
875 (car (nth 1 position))
876 (nth 1 position))))
877 (and (symbolp area) area)))
878
879 (defsubst posn-point (position)
880 "Return the buffer location in POSITION.
881 POSITION should be a list of the form returned by the `event-start'
882 and `event-end' functions."
883 (or (nth 5 position)
884 (if (consp (nth 1 position))
885 (car (nth 1 position))
886 (nth 1 position))))
887
888 (defun posn-set-point (position)
889 "Move point to POSITION.
890 Select the corresponding window as well."
891 (if (not (windowp (posn-window position)))
892 (error "Position not in text area of window"))
893 (select-window (posn-window position))
894 (if (numberp (posn-point position))
895 (goto-char (posn-point position))))
896
897 (defsubst posn-x-y (position)
898 "Return the x and y coordinates in POSITION.
899 POSITION should be a list of the form returned by the `event-start'
900 and `event-end' functions."
901 (nth 2 position))
902
903 (defun posn-col-row (position)
904 "Return the nominal column and row in POSITION, measured in characters.
905 The column and row values are approximations calculated from the x
906 and y coordinates in POSITION and the frame's default character width
907 and height.
908 For a scroll-bar event, the result column is 0, and the row
909 corresponds to the vertical position of the click in the scroll bar.
910 POSITION should be a list of the form returned by the `event-start'
911 and `event-end' functions."
912 (let* ((pair (posn-x-y position))
913 (window (posn-window position))
914 (area (posn-area position)))
915 (cond
916 ((null window)
917 '(0 . 0))
918 ((eq area 'vertical-scroll-bar)
919 (cons 0 (scroll-bar-scale pair (1- (window-height window)))))
920 ((eq area 'horizontal-scroll-bar)
921 (cons (scroll-bar-scale pair (window-width window)) 0))
922 (t
923 (let* ((frame (if (framep window) window (window-frame window)))
924 (x (/ (car pair) (frame-char-width frame)))
925 (y (/ (cdr pair) (+ (frame-char-height frame)
926 (or (frame-parameter frame 'line-spacing)
927 ;; FIXME: Why the `default'?
928 (default-value 'line-spacing)
929 0)))))
930 (cons x y))))))
931
932 (defun posn-actual-col-row (position)
933 "Return the actual column and row in POSITION, measured in characters.
934 These are the actual row number in the window and character number in that row.
935 Return nil if POSITION does not contain the actual position; in that case
936 `posn-col-row' can be used to get approximate values.
937 POSITION should be a list of the form returned by the `event-start'
938 and `event-end' functions."
939 (nth 6 position))
940
941 (defsubst posn-timestamp (position)
942 "Return the timestamp of POSITION.
943 POSITION should be a list of the form returned by the `event-start'
944 and `event-end' functions."
945 (nth 3 position))
946
947 (defsubst posn-string (position)
948 "Return the string object of POSITION.
949 Value is a cons (STRING . STRING-POS), or nil if not a string.
950 POSITION should be a list of the form returned by the `event-start'
951 and `event-end' functions."
952 (nth 4 position))
953
954 (defsubst posn-image (position)
955 "Return the image object of POSITION.
956 Value is a list (image ...), or nil if not an image.
957 POSITION should be a list of the form returned by the `event-start'
958 and `event-end' functions."
959 (nth 7 position))
960
961 (defsubst posn-object (position)
962 "Return the object (image or string) of POSITION.
963 Value is a list (image ...) for an image object, a cons cell
964 \(STRING . STRING-POS) for a string object, and nil for a buffer position.
965 POSITION should be a list of the form returned by the `event-start'
966 and `event-end' functions."
967 (or (posn-image position) (posn-string position)))
968
969 (defsubst posn-object-x-y (position)
970 "Return the x and y coordinates relative to the object of POSITION.
971 POSITION should be a list of the form returned by the `event-start'
972 and `event-end' functions."
973 (nth 8 position))
974
975 (defsubst posn-object-width-height (position)
976 "Return the pixel width and height of the object of POSITION.
977 POSITION should be a list of the form returned by the `event-start'
978 and `event-end' functions."
979 (nth 9 position))
980
981 \f
982 ;;;; Obsolescent names for functions.
983
984 (define-obsolete-function-alias 'window-dot 'window-point "22.1")
985 (define-obsolete-function-alias 'set-window-dot 'set-window-point "22.1")
986 (define-obsolete-function-alias 'read-input 'read-string "22.1")
987 (define-obsolete-function-alias 'show-buffer 'set-window-buffer "22.1")
988 (define-obsolete-function-alias 'eval-current-buffer 'eval-buffer "22.1")
989 (define-obsolete-function-alias 'string-to-int 'string-to-number "22.1")
990
991 (make-obsolete 'char-bytes "now always returns 1." "20.4")
992
993 (defun insert-string (&rest args)
994 "Mocklisp-compatibility insert function.
995 Like the function `insert' except that any argument that is a number
996 is converted into a string by expressing it in decimal."
997 (dolist (el args)
998 (insert (if (integerp el) (number-to-string el) el))))
999 (make-obsolete 'insert-string 'insert "22.1")
1000
1001 (defun makehash (&optional test) (make-hash-table :test (or test 'eql)))
1002 (make-obsolete 'makehash 'make-hash-table "22.1")
1003
1004 ;; Some programs still use this as a function.
1005 (defun baud-rate ()
1006 "Return the value of the `baud-rate' variable."
1007 baud-rate)
1008 (make-obsolete 'baud-rate "use the `baud-rate' variable instead." "before 19.15")
1009
1010 ;; These are used by VM and some old programs
1011 (defalias 'focus-frame 'ignore "")
1012 (make-obsolete 'focus-frame "it does nothing." "22.1")
1013 (defalias 'unfocus-frame 'ignore "")
1014 (make-obsolete 'unfocus-frame "it does nothing." "22.1")
1015 (make-obsolete 'make-variable-frame-local "use a frame-parameter instead." "22.2")
1016 \f
1017 ;;;; Obsolescence declarations for variables, and aliases.
1018
1019 (make-obsolete-variable 'redisplay-end-trigger-functions 'jit-lock-register "23.1")
1020 (make-obsolete 'window-redisplay-end-trigger nil "23.1")
1021 (make-obsolete 'set-window-redisplay-end-trigger nil "23.1")
1022
1023 (make-obsolete 'process-filter-multibyte-p nil "23.1")
1024 (make-obsolete 'set-process-filter-multibyte nil "23.1")
1025
1026 (make-obsolete-variable 'directory-sep-char "do not use it." "21.1")
1027 (make-obsolete-variable
1028 'mode-line-inverse-video
1029 "use the appropriate faces instead."
1030 "21.1")
1031 (make-obsolete-variable
1032 'unread-command-char
1033 "use `unread-command-events' instead. That variable is a list of events
1034 to reread, so it now uses nil to mean `no event', instead of -1."
1035 "before 19.15")
1036
1037 ;; Lisp manual only updated in 22.1.
1038 (define-obsolete-variable-alias 'executing-macro 'executing-kbd-macro
1039 "before 19.34")
1040
1041 (defvaralias 'x-lost-selection-hooks 'x-lost-selection-functions)
1042 (make-obsolete-variable 'x-lost-selection-hooks
1043 'x-lost-selection-functions "22.1")
1044 (defvaralias 'x-sent-selection-hooks 'x-sent-selection-functions)
1045 (make-obsolete-variable 'x-sent-selection-hooks
1046 'x-sent-selection-functions "22.1")
1047 ;; This was introduced in 21.4 for pre-unicode unification and was rendered
1048 ;; obsolete by the use of Unicode internally in 23.1.
1049 (make-obsolete-variable 'translation-table-for-input nil "23.1")
1050
1051 (defvaralias 'messages-buffer-max-lines 'message-log-max)
1052 \f
1053 ;;;; Alternate names for functions - these are not being phased out.
1054
1055 (defalias 'send-string 'process-send-string)
1056 (defalias 'send-region 'process-send-region)
1057 (defalias 'string= 'string-equal)
1058 (defalias 'string< 'string-lessp)
1059 (defalias 'move-marker 'set-marker)
1060 (defalias 'rplaca 'setcar)
1061 (defalias 'rplacd 'setcdr)
1062 (defalias 'beep 'ding) ;preserve lingual purity
1063 (defalias 'indent-to-column 'indent-to)
1064 (defalias 'backward-delete-char 'delete-backward-char)
1065 (defalias 'search-forward-regexp (symbol-function 're-search-forward))
1066 (defalias 'search-backward-regexp (symbol-function 're-search-backward))
1067 (defalias 'int-to-string 'number-to-string)
1068 (defalias 'store-match-data 'set-match-data)
1069 ;; These are the XEmacs names:
1070 (defalias 'point-at-eol 'line-end-position)
1071 (defalias 'point-at-bol 'line-beginning-position)
1072
1073 (defalias 'user-original-login-name 'user-login-name)
1074
1075 \f
1076 ;;;; Hook manipulation functions.
1077
1078 (defun make-local-hook (hook)
1079 "Make the hook HOOK local to the current buffer.
1080 The return value is HOOK.
1081
1082 You never need to call this function now that `add-hook' does it for you
1083 if its LOCAL argument is non-nil.
1084
1085 When a hook is local, its local and global values
1086 work in concert: running the hook actually runs all the hook
1087 functions listed in *either* the local value *or* the global value
1088 of the hook variable.
1089
1090 This function works by making t a member of the buffer-local value,
1091 which acts as a flag to run the hook functions in the default value as
1092 well. This works for all normal hooks, but does not work for most
1093 non-normal hooks yet. We will be changing the callers of non-normal
1094 hooks so that they can handle localness; this has to be done one by
1095 one.
1096
1097 This function does nothing if HOOK is already local in the current
1098 buffer.
1099
1100 Do not use `make-local-variable' to make a hook variable buffer-local."
1101 (if (local-variable-p hook)
1102 nil
1103 (or (boundp hook) (set hook nil))
1104 (make-local-variable hook)
1105 (set hook (list t)))
1106 hook)
1107 (make-obsolete 'make-local-hook "not necessary any more." "21.1")
1108
1109 (defun add-hook (hook function &optional append local)
1110 "Add to the value of HOOK the function FUNCTION.
1111 FUNCTION is not added if already present.
1112 FUNCTION is added (if necessary) at the beginning of the hook list
1113 unless the optional argument APPEND is non-nil, in which case
1114 FUNCTION is added at the end.
1115
1116 The optional fourth argument, LOCAL, if non-nil, says to modify
1117 the hook's buffer-local value rather than its default value.
1118 This makes the hook buffer-local if needed, and it makes t a member
1119 of the buffer-local value. That acts as a flag to run the hook
1120 functions in the default value as well as in the local value.
1121
1122 HOOK should be a symbol, and FUNCTION may be any valid function. If
1123 HOOK is void, it is first set to nil. If HOOK's value is a single
1124 function, it is changed to a list of functions."
1125 (or (boundp hook) (set hook nil))
1126 (or (default-boundp hook) (set-default hook nil))
1127 (if local (unless (local-variable-if-set-p hook)
1128 (set (make-local-variable hook) (list t)))
1129 ;; Detect the case where make-local-variable was used on a hook
1130 ;; and do what we used to do.
1131 (unless (and (consp (symbol-value hook)) (memq t (symbol-value hook)))
1132 (setq local t)))
1133 (let ((hook-value (if local (symbol-value hook) (default-value hook))))
1134 ;; If the hook value is a single function, turn it into a list.
1135 (when (or (not (listp hook-value)) (eq (car hook-value) 'lambda))
1136 (setq hook-value (list hook-value)))
1137 ;; Do the actual addition if necessary
1138 (unless (member function hook-value)
1139 (setq hook-value
1140 (if append
1141 (append hook-value (list function))
1142 (cons function hook-value))))
1143 ;; Set the actual variable
1144 (if local
1145 (progn
1146 ;; If HOOK isn't a permanent local,
1147 ;; but FUNCTION wants to survive a change of modes,
1148 ;; mark HOOK as partially permanent.
1149 (and (symbolp function)
1150 (get function 'permanent-local-hook)
1151 (not (get hook 'permanent-local))
1152 (put hook 'permanent-local 'permanent-local-hook))
1153 (set hook hook-value))
1154 (set-default hook hook-value))))
1155
1156 (defun remove-hook (hook function &optional local)
1157 "Remove from the value of HOOK the function FUNCTION.
1158 HOOK should be a symbol, and FUNCTION may be any valid function. If
1159 FUNCTION isn't the value of HOOK, or, if FUNCTION doesn't appear in the
1160 list of hooks to run in HOOK, then nothing is done. See `add-hook'.
1161
1162 The optional third argument, LOCAL, if non-nil, says to modify
1163 the hook's buffer-local value rather than its default value."
1164 (or (boundp hook) (set hook nil))
1165 (or (default-boundp hook) (set-default hook nil))
1166 ;; Do nothing if LOCAL is t but this hook has no local binding.
1167 (unless (and local (not (local-variable-p hook)))
1168 ;; Detect the case where make-local-variable was used on a hook
1169 ;; and do what we used to do.
1170 (when (and (local-variable-p hook)
1171 (not (and (consp (symbol-value hook))
1172 (memq t (symbol-value hook)))))
1173 (setq local t))
1174 (let ((hook-value (if local (symbol-value hook) (default-value hook))))
1175 ;; Remove the function, for both the list and the non-list cases.
1176 (if (or (not (listp hook-value)) (eq (car hook-value) 'lambda))
1177 (if (equal hook-value function) (setq hook-value nil))
1178 (setq hook-value (delete function (copy-sequence hook-value))))
1179 ;; If the function is on the global hook, we need to shadow it locally
1180 ;;(when (and local (member function (default-value hook))
1181 ;; (not (member (cons 'not function) hook-value)))
1182 ;; (push (cons 'not function) hook-value))
1183 ;; Set the actual variable
1184 (if (not local)
1185 (set-default hook hook-value)
1186 (if (equal hook-value '(t))
1187 (kill-local-variable hook)
1188 (set hook hook-value))))))
1189
1190 (defun add-to-list (list-var element &optional append compare-fn)
1191 "Add ELEMENT to the value of LIST-VAR if it isn't there yet.
1192 The test for presence of ELEMENT is done with `equal',
1193 or with COMPARE-FN if that's non-nil.
1194 If ELEMENT is added, it is added at the beginning of the list,
1195 unless the optional argument APPEND is non-nil, in which case
1196 ELEMENT is added at the end.
1197
1198 The return value is the new value of LIST-VAR.
1199
1200 If you want to use `add-to-list' on a variable that is not defined
1201 until a certain package is loaded, you should put the call to `add-to-list'
1202 into a hook function that will be run only after loading the package.
1203 `eval-after-load' provides one way to do this. In some cases
1204 other hooks, such as major mode hooks, can do the job."
1205 (if (cond
1206 ((null compare-fn)
1207 (member element (symbol-value list-var)))
1208 ((eq compare-fn 'eq)
1209 (memq element (symbol-value list-var)))
1210 ((eq compare-fn 'eql)
1211 (memql element (symbol-value list-var)))
1212 (t
1213 (let ((lst (symbol-value list-var)))
1214 (while (and lst
1215 (not (funcall compare-fn element (car lst))))
1216 (setq lst (cdr lst)))
1217 lst)))
1218 (symbol-value list-var)
1219 (set list-var
1220 (if append
1221 (append (symbol-value list-var) (list element))
1222 (cons element (symbol-value list-var))))))
1223
1224
1225 (defun add-to-ordered-list (list-var element &optional order)
1226 "Add ELEMENT to the value of LIST-VAR if it isn't there yet.
1227 The test for presence of ELEMENT is done with `eq'.
1228
1229 The resulting list is reordered so that the elements are in the
1230 order given by each element's numeric list order. Elements
1231 without a numeric list order are placed at the end of the list.
1232
1233 If the third optional argument ORDER is a number (integer or
1234 float), set the element's list order to the given value. If
1235 ORDER is nil or omitted, do not change the numeric order of
1236 ELEMENT. If ORDER has any other value, remove the numeric order
1237 of ELEMENT if it has one.
1238
1239 The list order for each element is stored in LIST-VAR's
1240 `list-order' property.
1241
1242 The return value is the new value of LIST-VAR."
1243 (let ((ordering (get list-var 'list-order)))
1244 (unless ordering
1245 (put list-var 'list-order
1246 (setq ordering (make-hash-table :weakness 'key :test 'eq))))
1247 (when order
1248 (puthash element (and (numberp order) order) ordering))
1249 (unless (memq element (symbol-value list-var))
1250 (set list-var (cons element (symbol-value list-var))))
1251 (set list-var (sort (symbol-value list-var)
1252 (lambda (a b)
1253 (let ((oa (gethash a ordering))
1254 (ob (gethash b ordering)))
1255 (if (and oa ob)
1256 (< oa ob)
1257 oa)))))))
1258
1259 (defun add-to-history (history-var newelt &optional maxelt keep-all)
1260 "Add NEWELT to the history list stored in the variable HISTORY-VAR.
1261 Return the new history list.
1262 If MAXELT is non-nil, it specifies the maximum length of the history.
1263 Otherwise, the maximum history length is the value of the `history-length'
1264 property on symbol HISTORY-VAR, if set, or the value of the `history-length'
1265 variable.
1266 Remove duplicates of NEWELT if `history-delete-duplicates' is non-nil.
1267 If optional fourth arg KEEP-ALL is non-nil, add NEWELT to history even
1268 if it is empty or a duplicate."
1269 (unless maxelt
1270 (setq maxelt (or (get history-var 'history-length)
1271 history-length)))
1272 (let ((history (symbol-value history-var))
1273 tail)
1274 (when (and (listp history)
1275 (or keep-all
1276 (not (stringp newelt))
1277 (> (length newelt) 0))
1278 (or keep-all
1279 (not (equal (car history) newelt))))
1280 (if history-delete-duplicates
1281 (delete newelt history))
1282 (setq history (cons newelt history))
1283 (when (integerp maxelt)
1284 (if (= 0 maxelt)
1285 (setq history nil)
1286 (setq tail (nthcdr (1- maxelt) history))
1287 (when (consp tail)
1288 (setcdr tail nil)))))
1289 (set history-var history)))
1290
1291 \f
1292 ;;;; Mode hooks.
1293
1294 (defvar delay-mode-hooks nil
1295 "If non-nil, `run-mode-hooks' should delay running the hooks.")
1296 (defvar delayed-mode-hooks nil
1297 "List of delayed mode hooks waiting to be run.")
1298 (make-variable-buffer-local 'delayed-mode-hooks)
1299 (put 'delay-mode-hooks 'permanent-local t)
1300
1301 (defvar after-change-major-mode-hook nil
1302 "Normal hook run at the very end of major mode functions.")
1303
1304 (defun run-mode-hooks (&rest hooks)
1305 "Run mode hooks `delayed-mode-hooks' and HOOKS, or delay HOOKS.
1306 Execution is delayed if `delay-mode-hooks' is non-nil.
1307 If `delay-mode-hooks' is nil, run `after-change-major-mode-hook'
1308 after running the mode hooks.
1309 Major mode functions should use this instead of `run-hooks' when running their
1310 FOO-mode-hook."
1311 (if delay-mode-hooks
1312 ;; Delaying case.
1313 (dolist (hook hooks)
1314 (push hook delayed-mode-hooks))
1315 ;; Normal case, just run the hook as before plus any delayed hooks.
1316 (setq hooks (nconc (nreverse delayed-mode-hooks) hooks))
1317 (setq delayed-mode-hooks nil)
1318 (apply 'run-hooks hooks)
1319 (run-hooks 'after-change-major-mode-hook)))
1320
1321 (defmacro delay-mode-hooks (&rest body)
1322 "Execute BODY, but delay any `run-mode-hooks'.
1323 These hooks will be executed by the first following call to
1324 `run-mode-hooks' that occurs outside any `delayed-mode-hooks' form.
1325 Only affects hooks run in the current buffer."
1326 (declare (debug t) (indent 0))
1327 `(progn
1328 (make-local-variable 'delay-mode-hooks)
1329 (let ((delay-mode-hooks t))
1330 ,@body)))
1331
1332 ;; PUBLIC: find if the current mode derives from another.
1333
1334 (defun derived-mode-p (&rest modes)
1335 "Non-nil if the current major mode is derived from one of MODES.
1336 Uses the `derived-mode-parent' property of the symbol to trace backwards."
1337 (let ((parent major-mode))
1338 (while (and (not (memq parent modes))
1339 (setq parent (get parent 'derived-mode-parent))))
1340 parent))
1341 \f
1342 ;;;; Minor modes.
1343
1344 ;; If a minor mode is not defined with define-minor-mode,
1345 ;; add it here explicitly.
1346 ;; isearch-mode is deliberately excluded, since you should
1347 ;; not call it yourself.
1348 (defvar minor-mode-list '(auto-save-mode auto-fill-mode abbrev-mode
1349 overwrite-mode view-mode
1350 hs-minor-mode)
1351 "List of all minor mode functions.")
1352
1353 (defun add-minor-mode (toggle name &optional keymap after toggle-fun)
1354 "Register a new minor mode.
1355
1356 This is an XEmacs-compatibility function. Use `define-minor-mode' instead.
1357
1358 TOGGLE is a symbol which is the name of a buffer-local variable that
1359 is toggled on or off to say whether the minor mode is active or not.
1360
1361 NAME specifies what will appear in the mode line when the minor mode
1362 is active. NAME should be either a string starting with a space, or a
1363 symbol whose value is such a string.
1364
1365 Optional KEYMAP is the keymap for the minor mode that will be added
1366 to `minor-mode-map-alist'.
1367
1368 Optional AFTER specifies that TOGGLE should be added after AFTER
1369 in `minor-mode-alist'.
1370
1371 Optional TOGGLE-FUN is an interactive function to toggle the mode.
1372 It defaults to (and should by convention be) TOGGLE.
1373
1374 If TOGGLE has a non-nil `:included' property, an entry for the mode is
1375 included in the mode-line minor mode menu.
1376 If TOGGLE has a `:menu-tag', that is used for the menu item's label."
1377 (unless (memq toggle minor-mode-list)
1378 (push toggle minor-mode-list))
1379
1380 (unless toggle-fun (setq toggle-fun toggle))
1381 (unless (eq toggle-fun toggle)
1382 (put toggle :minor-mode-function toggle-fun))
1383 ;; Add the name to the minor-mode-alist.
1384 (when name
1385 (let ((existing (assq toggle minor-mode-alist)))
1386 (if existing
1387 (setcdr existing (list name))
1388 (let ((tail minor-mode-alist) found)
1389 (while (and tail (not found))
1390 (if (eq after (caar tail))
1391 (setq found tail)
1392 (setq tail (cdr tail))))
1393 (if found
1394 (let ((rest (cdr found)))
1395 (setcdr found nil)
1396 (nconc found (list (list toggle name)) rest))
1397 (setq minor-mode-alist (cons (list toggle name)
1398 minor-mode-alist)))))))
1399 ;; Add the toggle to the minor-modes menu if requested.
1400 (when (get toggle :included)
1401 (define-key mode-line-mode-menu
1402 (vector toggle)
1403 (list 'menu-item
1404 (concat
1405 (or (get toggle :menu-tag)
1406 (if (stringp name) name (symbol-name toggle)))
1407 (let ((mode-name (if (symbolp name) (symbol-value name))))
1408 (if (and (stringp mode-name) (string-match "[^ ]+" mode-name))
1409 (concat " (" (match-string 0 mode-name) ")"))))
1410 toggle-fun
1411 :button (cons :toggle toggle))))
1412
1413 ;; Add the map to the minor-mode-map-alist.
1414 (when keymap
1415 (let ((existing (assq toggle minor-mode-map-alist)))
1416 (if existing
1417 (setcdr existing keymap)
1418 (let ((tail minor-mode-map-alist) found)
1419 (while (and tail (not found))
1420 (if (eq after (caar tail))
1421 (setq found tail)
1422 (setq tail (cdr tail))))
1423 (if found
1424 (let ((rest (cdr found)))
1425 (setcdr found nil)
1426 (nconc found (list (cons toggle keymap)) rest))
1427 (setq minor-mode-map-alist (cons (cons toggle keymap)
1428 minor-mode-map-alist))))))))
1429 \f
1430 ;;; Load history
1431
1432 ;; (defvar symbol-file-load-history-loaded nil
1433 ;; "Non-nil means we have loaded the file `fns-VERSION.el' in `exec-directory'.
1434 ;; That file records the part of `load-history' for preloaded files,
1435 ;; which is cleared out before dumping to make Emacs smaller.")
1436
1437 ;; (defun load-symbol-file-load-history ()
1438 ;; "Load the file `fns-VERSION.el' in `exec-directory' if not already done.
1439 ;; That file records the part of `load-history' for preloaded files,
1440 ;; which is cleared out before dumping to make Emacs smaller."
1441 ;; (unless symbol-file-load-history-loaded
1442 ;; (load (expand-file-name
1443 ;; ;; fns-XX.YY.ZZ.el does not work on DOS filesystem.
1444 ;; (if (eq system-type 'ms-dos)
1445 ;; "fns.el"
1446 ;; (format "fns-%s.el" emacs-version))
1447 ;; exec-directory)
1448 ;; ;; The file name fns-%s.el already has a .el extension.
1449 ;; nil nil t)
1450 ;; (setq symbol-file-load-history-loaded t)))
1451
1452 (defun symbol-file (symbol &optional type)
1453 "Return the input source in which SYMBOL was defined.
1454 The value is an absolute file name.
1455 It can also be nil, if the definition is not associated with any file.
1456
1457 If TYPE is nil, then any kind of definition is acceptable.
1458 If TYPE is `defun' or `defvar', that specifies function
1459 definition only or variable definition only.
1460 `defface' specifies a face definition only."
1461 (if (and (or (null type) (eq type 'defun))
1462 (symbolp symbol) (fboundp symbol)
1463 (eq 'autoload (car-safe (symbol-function symbol))))
1464 (nth 1 (symbol-function symbol))
1465 (let ((files load-history)
1466 file)
1467 (while files
1468 (if (if type
1469 (if (eq type 'defvar)
1470 ;; Variables are present just as their names.
1471 (member symbol (cdr (car files)))
1472 ;; Other types are represented as (TYPE . NAME).
1473 (member (cons type symbol) (cdr (car files))))
1474 ;; We accept all types, so look for variable def
1475 ;; and then for any other kind.
1476 (or (member symbol (cdr (car files)))
1477 (rassq symbol (cdr (car files)))))
1478 (setq file (car (car files)) files nil))
1479 (setq files (cdr files)))
1480 file)))
1481
1482 (defun locate-library (library &optional nosuffix path interactive-call)
1483 "Show the precise file name of Emacs library LIBRARY.
1484 This command searches the directories in `load-path' like `\\[load-library]'
1485 to find the file that `\\[load-library] RET LIBRARY RET' would load.
1486 Optional second arg NOSUFFIX non-nil means don't add suffixes `load-suffixes'
1487 to the specified name LIBRARY.
1488
1489 If the optional third arg PATH is specified, that list of directories
1490 is used instead of `load-path'.
1491
1492 When called from a program, the file name is normaly returned as a
1493 string. When run interactively, the argument INTERACTIVE-CALL is t,
1494 and the file name is displayed in the echo area."
1495 (interactive (list (completing-read "Locate library: "
1496 (apply-partially
1497 'locate-file-completion-table
1498 load-path (get-load-suffixes)))
1499 nil nil
1500 t))
1501 (let ((file (locate-file library
1502 (or path load-path)
1503 (append (unless nosuffix (get-load-suffixes))
1504 load-file-rep-suffixes))))
1505 (if interactive-call
1506 (if file
1507 (message "Library is file %s" (abbreviate-file-name file))
1508 (message "No library %s in search path" library)))
1509 file))
1510
1511 \f
1512 ;;;; Specifying things to do later.
1513
1514 (defmacro eval-at-startup (&rest body)
1515 "Make arrangements to evaluate BODY when Emacs starts up.
1516 If this is run after Emacs startup, evaluate BODY immediately.
1517 Always returns nil.
1518
1519 This works by adding a function to `before-init-hook'.
1520 That function's doc string says which file created it."
1521 `(progn
1522 (if command-line-processed
1523 (progn . ,body)
1524 (add-hook 'before-init-hook
1525 '(lambda () ,(concat "From " (or load-file-name "no file"))
1526 . ,body)
1527 t))
1528 nil))
1529
1530 (defun load-history-regexp (file)
1531 "Form a regexp to find FILE in `load-history'.
1532 FILE, a string, is described in the function `eval-after-load'."
1533 (if (file-name-absolute-p file)
1534 (setq file (file-truename file)))
1535 (concat (if (file-name-absolute-p file) "\\`" "\\(\\`\\|/\\)")
1536 (regexp-quote file)
1537 (if (file-name-extension file)
1538 ""
1539 ;; Note: regexp-opt can't be used here, since we need to call
1540 ;; this before Emacs has been fully started. 2006-05-21
1541 (concat "\\(" (mapconcat 'regexp-quote load-suffixes "\\|") "\\)?"))
1542 "\\(" (mapconcat 'regexp-quote jka-compr-load-suffixes "\\|")
1543 "\\)?\\'"))
1544
1545 (defun load-history-filename-element (file-regexp)
1546 "Get the first elt of `load-history' whose car matches FILE-REGEXP.
1547 Return nil if there isn't one."
1548 (let* ((loads load-history)
1549 (load-elt (and loads (car loads))))
1550 (save-match-data
1551 (while (and loads
1552 (or (null (car load-elt))
1553 (not (string-match file-regexp (car load-elt)))))
1554 (setq loads (cdr loads)
1555 load-elt (and loads (car loads)))))
1556 load-elt))
1557
1558 (defun eval-after-load (file form)
1559 "Arrange that, if FILE is ever loaded, FORM will be run at that time.
1560 If FILE is already loaded, evaluate FORM right now.
1561
1562 If a matching file is loaded again, FORM will be evaluated again.
1563
1564 If FILE is a string, it may be either an absolute or a relative file
1565 name, and may have an extension \(e.g. \".el\") or may lack one, and
1566 additionally may or may not have an extension denoting a compressed
1567 format \(e.g. \".gz\").
1568
1569 When FILE is absolute, this first converts it to a true name by chasing
1570 symbolic links. Only a file of this name \(see next paragraph regarding
1571 extensions) will trigger the evaluation of FORM. When FILE is relative,
1572 a file whose absolute true name ends in FILE will trigger evaluation.
1573
1574 When FILE lacks an extension, a file name with any extension will trigger
1575 evaluation. Otherwise, its extension must match FILE's. A further
1576 extension for a compressed format \(e.g. \".gz\") on FILE will not affect
1577 this name matching.
1578
1579 Alternatively, FILE can be a feature (i.e. a symbol), in which case FORM
1580 is evaluated whenever that feature is `provide'd.
1581
1582 Usually FILE is just a library name like \"font-lock\" or a feature name
1583 like 'font-lock.
1584
1585 This function makes or adds to an entry on `after-load-alist'."
1586 ;; Add this FORM into after-load-alist (regardless of whether we'll be
1587 ;; evaluating it now).
1588 (let* ((regexp-or-feature
1589 (if (stringp file) (load-history-regexp file) file))
1590 (elt (assoc regexp-or-feature after-load-alist)))
1591 (unless elt
1592 (setq elt (list regexp-or-feature))
1593 (push elt after-load-alist))
1594 ;; Add FORM to the element unless it's already there.
1595 (unless (member form (cdr elt))
1596 (nconc elt (list form)))
1597
1598 ;; Is there an already loaded file whose name (or `provide' name)
1599 ;; matches FILE?
1600 (if (if (stringp file)
1601 (load-history-filename-element regexp-or-feature)
1602 (featurep file))
1603 (eval form))))
1604
1605 (defun do-after-load-evaluation (abs-file)
1606 "Evaluate all `eval-after-load' forms, if any, for ABS-FILE.
1607 ABS-FILE, a string, should be the absolute true name of a file just loaded."
1608 (let ((after-load-elts after-load-alist)
1609 a-l-element file-elements file-element form)
1610 (while after-load-elts
1611 (setq a-l-element (car after-load-elts)
1612 after-load-elts (cdr after-load-elts))
1613 (when (and (stringp (car a-l-element))
1614 (string-match (car a-l-element) abs-file))
1615 (while (setq a-l-element (cdr a-l-element)) ; discard the file name
1616 (setq form (car a-l-element))
1617 (eval form))))))
1618
1619 (defun eval-next-after-load (file)
1620 "Read the following input sexp, and run it whenever FILE is loaded.
1621 This makes or adds to an entry on `after-load-alist'.
1622 FILE should be the name of a library, with no directory name."
1623 (eval-after-load file (read)))
1624 \f
1625 ;;;; Process stuff.
1626
1627 (defun process-lines (program &rest args)
1628 "Execute PROGRAM with ARGS, returning its output as a list of lines.
1629 Signal an error if the program returns with a non-zero exit status."
1630 (with-temp-buffer
1631 (let ((status (apply 'call-process program nil (current-buffer) nil args)))
1632 (unless (eq status 0)
1633 (error "%s exited with status %s" program status))
1634 (goto-char (point-min))
1635 (let (lines)
1636 (while (not (eobp))
1637 (setq lines (cons (buffer-substring-no-properties
1638 (line-beginning-position)
1639 (line-end-position))
1640 lines))
1641 (forward-line 1))
1642 (nreverse lines)))))
1643
1644 ;; open-network-stream is a wrapper around make-network-process.
1645
1646 (when (featurep 'make-network-process)
1647 (defun open-network-stream (name buffer host service)
1648 "Open a TCP connection for a service to a host.
1649 Returns a subprocess-object to represent the connection.
1650 Input and output work as for subprocesses; `delete-process' closes it.
1651
1652 Args are NAME BUFFER HOST SERVICE.
1653 NAME is name for process. It is modified if necessary to make it unique.
1654 BUFFER is the buffer (or buffer name) to associate with the process.
1655 Process output goes at end of that buffer, unless you specify
1656 an output stream or filter function to handle the output.
1657 BUFFER may be also nil, meaning that this process is not associated
1658 with any buffer.
1659 HOST is name of the host to connect to, or its IP address.
1660 SERVICE is name of the service desired, or an integer specifying
1661 a port number to connect to."
1662 (make-network-process :name name :buffer buffer
1663 :host host :service service)))
1664
1665 ;; compatibility
1666
1667 (make-obsolete
1668 'process-kill-without-query
1669 "use `process-query-on-exit-flag' or `set-process-query-on-exit-flag'."
1670 "22.1")
1671 (defun process-kill-without-query (process &optional flag)
1672 "Say no query needed if PROCESS is running when Emacs is exited.
1673 Optional second argument if non-nil says to require a query.
1674 Value is t if a query was formerly required."
1675 (let ((old (process-query-on-exit-flag process)))
1676 (set-process-query-on-exit-flag process nil)
1677 old))
1678
1679 ;; process plist management
1680
1681 (defun process-get (process propname)
1682 "Return the value of PROCESS' PROPNAME property.
1683 This is the last value stored with `(process-put PROCESS PROPNAME VALUE)'."
1684 (plist-get (process-plist process) propname))
1685
1686 (defun process-put (process propname value)
1687 "Change PROCESS' PROPNAME property to VALUE.
1688 It can be retrieved with `(process-get PROCESS PROPNAME)'."
1689 (set-process-plist process
1690 (plist-put (process-plist process) propname value)))
1691
1692 \f
1693 ;;;; Input and display facilities.
1694
1695 (defvar read-quoted-char-radix 8
1696 "*Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
1697 Legitimate radix values are 8, 10 and 16.")
1698
1699 (custom-declare-variable-early
1700 'read-quoted-char-radix 8
1701 "*Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
1702 Legitimate radix values are 8, 10 and 16."
1703 :type '(choice (const 8) (const 10) (const 16))
1704 :group 'editing-basics)
1705
1706 (defun read-quoted-char (&optional prompt)
1707 "Like `read-char', but do not allow quitting.
1708 Also, if the first character read is an octal digit,
1709 we read any number of octal digits and return the
1710 specified character code. Any nondigit terminates the sequence.
1711 If the terminator is RET, it is discarded;
1712 any other terminator is used itself as input.
1713
1714 The optional argument PROMPT specifies a string to use to prompt the user.
1715 The variable `read-quoted-char-radix' controls which radix to use
1716 for numeric input."
1717 (let ((message-log-max nil) done (first t) (code 0) char translated)
1718 (while (not done)
1719 (let ((inhibit-quit first)
1720 ;; Don't let C-h get the help message--only help function keys.
1721 (help-char nil)
1722 (help-form
1723 "Type the special character you want to use,
1724 or the octal character code.
1725 RET terminates the character code and is discarded;
1726 any other non-digit terminates the character code and is then used as input."))
1727 (setq char (read-event (and prompt (format "%s-" prompt)) t))
1728 (if inhibit-quit (setq quit-flag nil)))
1729 ;; Translate TAB key into control-I ASCII character, and so on.
1730 ;; Note: `read-char' does it using the `ascii-character' property.
1731 ;; We could try and use read-key-sequence instead, but then C-q ESC
1732 ;; or C-q C-x might not return immediately since ESC or C-x might be
1733 ;; bound to some prefix in function-key-map or key-translation-map.
1734 (setq translated
1735 (if (integerp char)
1736 (char-resolve-modifers char)
1737 char))
1738 (let ((translation (lookup-key local-function-key-map (vector char))))
1739 (if (arrayp translation)
1740 (setq translated (aref translation 0))))
1741 (cond ((null translated))
1742 ((not (integerp translated))
1743 (setq unread-command-events (list char)
1744 done t))
1745 ((/= (logand translated ?\M-\^@) 0)
1746 ;; Turn a meta-character into a character with the 0200 bit set.
1747 (setq code (logior (logand translated (lognot ?\M-\^@)) 128)
1748 done t))
1749 ((and (<= ?0 translated) (< translated (+ ?0 (min 10 read-quoted-char-radix))))
1750 (setq code (+ (* code read-quoted-char-radix) (- translated ?0)))
1751 (and prompt (setq prompt (message "%s %c" prompt translated))))
1752 ((and (<= ?a (downcase translated))
1753 (< (downcase translated) (+ ?a -10 (min 36 read-quoted-char-radix))))
1754 (setq code (+ (* code read-quoted-char-radix)
1755 (+ 10 (- (downcase translated) ?a))))
1756 (and prompt (setq prompt (message "%s %c" prompt translated))))
1757 ((and (not first) (eq translated ?\C-m))
1758 (setq done t))
1759 ((not first)
1760 (setq unread-command-events (list char)
1761 done t))
1762 (t (setq code translated
1763 done t)))
1764 (setq first nil))
1765 code))
1766
1767 (defun read-passwd (prompt &optional confirm default)
1768 "Read a password, prompting with PROMPT, and return it.
1769 If optional CONFIRM is non-nil, read the password twice to make sure.
1770 Optional DEFAULT is a default password to use instead of empty input.
1771
1772 This function echoes `.' for each character that the user types.
1773 The user ends with RET, LFD, or ESC. DEL or C-h rubs out. C-u kills line.
1774 C-g quits; if `inhibit-quit' was non-nil around this function,
1775 then it returns nil if the user types C-g, but quit-flag remains set.
1776
1777 Once the caller uses the password, it can erase the password
1778 by doing (clear-string STRING)."
1779 (with-local-quit
1780 (if confirm
1781 (let (success)
1782 (while (not success)
1783 (let ((first (read-passwd prompt nil default))
1784 (second (read-passwd "Confirm password: " nil default)))
1785 (if (equal first second)
1786 (progn
1787 (and (arrayp second) (clear-string second))
1788 (setq success first))
1789 (and (arrayp first) (clear-string first))
1790 (and (arrayp second) (clear-string second))
1791 (message "Password not repeated accurately; please start over")
1792 (sit-for 1))))
1793 success)
1794 (let ((pass nil)
1795 ;; Copy it so that add-text-properties won't modify
1796 ;; the object that was passed in by the caller.
1797 (prompt (copy-sequence prompt))
1798 (c 0)
1799 (echo-keystrokes 0)
1800 (cursor-in-echo-area t)
1801 (message-log-max nil))
1802 (add-text-properties 0 (length prompt)
1803 minibuffer-prompt-properties prompt)
1804 (while (progn (message "%s%s"
1805 prompt
1806 (make-string (length pass) ?.))
1807 (setq c (read-char-exclusive nil t))
1808 (and (/= c ?\r) (/= c ?\n) (/= c ?\e)))
1809 (clear-this-command-keys)
1810 (if (= c ?\C-u)
1811 (progn
1812 (and (arrayp pass) (clear-string pass))
1813 (setq pass ""))
1814 (if (and (/= c ?\b) (/= c ?\177))
1815 (let* ((new-char (char-to-string c))
1816 (new-pass (concat pass new-char)))
1817 (and (arrayp pass) (clear-string pass))
1818 (clear-string new-char)
1819 (setq c ?\0)
1820 (setq pass new-pass))
1821 (if (> (length pass) 0)
1822 (let ((new-pass (substring pass 0 -1)))
1823 (and (arrayp pass) (clear-string pass))
1824 (setq pass new-pass))))))
1825 (message nil)
1826 (or pass default "")))))
1827
1828 ;; This should be used by `call-interactively' for `n' specs.
1829 (defun read-number (prompt &optional default)
1830 "Read a numeric value in the minibuffer, prompting with PROMPT.
1831 DEFAULT specifies a default value to return if the user just types RET.
1832 The value of DEFAULT is inserted into PROMPT."
1833 (let ((n nil))
1834 (when default
1835 (setq prompt
1836 (if (string-match "\\(\\):[ \t]*\\'" prompt)
1837 (replace-match (format " (default %s)" default) t t prompt 1)
1838 (replace-regexp-in-string "[ \t]*\\'"
1839 (format " (default %s) " default)
1840 prompt t t))))
1841 (while
1842 (progn
1843 (let ((str (read-from-minibuffer prompt nil nil nil nil
1844 (and default
1845 (number-to-string default)))))
1846 (condition-case nil
1847 (setq n (cond
1848 ((zerop (length str)) default)
1849 ((stringp str) (read str))))
1850 (error nil)))
1851 (unless (numberp n)
1852 (message "Please enter a number.")
1853 (sit-for 1)
1854 t)))
1855 n))
1856
1857 (defun sit-for (seconds &optional nodisp obsolete)
1858 "Perform redisplay, then wait for SECONDS seconds or until input is available.
1859 SECONDS may be a floating-point value.
1860 \(On operating systems that do not support waiting for fractions of a
1861 second, floating-point values are rounded down to the nearest integer.)
1862
1863 If optional arg NODISP is t, don't redisplay, just wait for input.
1864 Redisplay does not happen if input is available before it starts.
1865
1866 Value is t if waited the full time with no input arriving, and nil otherwise.
1867
1868 An obsolete, but still supported form is
1869 \(sit-for SECONDS &optional MILLISECONDS NODISP)
1870 where the optional arg MILLISECONDS specifies an additional wait period,
1871 in milliseconds; this was useful when Emacs was built without
1872 floating point support.
1873
1874 \(fn SECONDS &optional NODISP)"
1875 (if (numberp nodisp)
1876 (setq seconds (+ seconds (* 1e-3 nodisp))
1877 nodisp obsolete)
1878 (if obsolete (setq nodisp obsolete)))
1879 (cond
1880 (noninteractive
1881 (sleep-for seconds)
1882 t)
1883 ((input-pending-p)
1884 nil)
1885 ((<= seconds 0)
1886 (or nodisp (redisplay)))
1887 (t
1888 (or nodisp (redisplay))
1889 (let ((read (read-event nil nil seconds)))
1890 (or (null read)
1891 (progn
1892 ;; If last command was a prefix arg, e.g. C-u, push this event onto
1893 ;; unread-command-events as (t . EVENT) so it will be added to
1894 ;; this-command-keys by read-key-sequence.
1895 (if (eq overriding-terminal-local-map universal-argument-map)
1896 (setq read (cons t read)))
1897 (push read unread-command-events)
1898 nil))))))
1899 \f
1900 ;;; Atomic change groups.
1901
1902 (defmacro atomic-change-group (&rest body)
1903 "Perform BODY as an atomic change group.
1904 This means that if BODY exits abnormally,
1905 all of its changes to the current buffer are undone.
1906 This works regardless of whether undo is enabled in the buffer.
1907
1908 This mechanism is transparent to ordinary use of undo;
1909 if undo is enabled in the buffer and BODY succeeds, the
1910 user can undo the change normally."
1911 (declare (indent 0) (debug t))
1912 (let ((handle (make-symbol "--change-group-handle--"))
1913 (success (make-symbol "--change-group-success--")))
1914 `(let ((,handle (prepare-change-group))
1915 ;; Don't truncate any undo data in the middle of this.
1916 (undo-outer-limit nil)
1917 (undo-limit most-positive-fixnum)
1918 (undo-strong-limit most-positive-fixnum)
1919 (,success nil))
1920 (unwind-protect
1921 (progn
1922 ;; This is inside the unwind-protect because
1923 ;; it enables undo if that was disabled; we need
1924 ;; to make sure that it gets disabled again.
1925 (activate-change-group ,handle)
1926 ,@body
1927 (setq ,success t))
1928 ;; Either of these functions will disable undo
1929 ;; if it was disabled before.
1930 (if ,success
1931 (accept-change-group ,handle)
1932 (cancel-change-group ,handle))))))
1933
1934 (defun prepare-change-group (&optional buffer)
1935 "Return a handle for the current buffer's state, for a change group.
1936 If you specify BUFFER, make a handle for BUFFER's state instead.
1937
1938 Pass the handle to `activate-change-group' afterward to initiate
1939 the actual changes of the change group.
1940
1941 To finish the change group, call either `accept-change-group' or
1942 `cancel-change-group' passing the same handle as argument. Call
1943 `accept-change-group' to accept the changes in the group as final;
1944 call `cancel-change-group' to undo them all. You should use
1945 `unwind-protect' to make sure the group is always finished. The call
1946 to `activate-change-group' should be inside the `unwind-protect'.
1947 Once you finish the group, don't use the handle again--don't try to
1948 finish the same group twice. For a simple example of correct use, see
1949 the source code of `atomic-change-group'.
1950
1951 The handle records only the specified buffer. To make a multibuffer
1952 change group, call this function once for each buffer you want to
1953 cover, then use `nconc' to combine the returned values, like this:
1954
1955 (nconc (prepare-change-group buffer-1)
1956 (prepare-change-group buffer-2))
1957
1958 You can then activate that multibuffer change group with a single
1959 call to `activate-change-group' and finish it with a single call
1960 to `accept-change-group' or `cancel-change-group'."
1961
1962 (if buffer
1963 (list (cons buffer (with-current-buffer buffer buffer-undo-list)))
1964 (list (cons (current-buffer) buffer-undo-list))))
1965
1966 (defun activate-change-group (handle)
1967 "Activate a change group made with `prepare-change-group' (which see)."
1968 (dolist (elt handle)
1969 (with-current-buffer (car elt)
1970 (if (eq buffer-undo-list t)
1971 (setq buffer-undo-list nil)))))
1972
1973 (defun accept-change-group (handle)
1974 "Finish a change group made with `prepare-change-group' (which see).
1975 This finishes the change group by accepting its changes as final."
1976 (dolist (elt handle)
1977 (with-current-buffer (car elt)
1978 (if (eq elt t)
1979 (setq buffer-undo-list t)))))
1980
1981 (defun cancel-change-group (handle)
1982 "Finish a change group made with `prepare-change-group' (which see).
1983 This finishes the change group by reverting all of its changes."
1984 (dolist (elt handle)
1985 (with-current-buffer (car elt)
1986 (setq elt (cdr elt))
1987 (let ((old-car
1988 (if (consp elt) (car elt)))
1989 (old-cdr
1990 (if (consp elt) (cdr elt))))
1991 ;; Temporarily truncate the undo log at ELT.
1992 (when (consp elt)
1993 (setcar elt nil) (setcdr elt nil))
1994 (unless (eq last-command 'undo) (undo-start))
1995 ;; Make sure there's no confusion.
1996 (when (and (consp elt) (not (eq elt (last pending-undo-list))))
1997 (error "Undoing to some unrelated state"))
1998 ;; Undo it all.
1999 (save-excursion
2000 (while (listp pending-undo-list) (undo-more 1)))
2001 ;; Reset the modified cons cell ELT to its original content.
2002 (when (consp elt)
2003 (setcar elt old-car)
2004 (setcdr elt old-cdr))
2005 ;; Revert the undo info to what it was when we grabbed the state.
2006 (setq buffer-undo-list elt)))))
2007 \f
2008 ;;;; Display-related functions.
2009
2010 ;; For compatibility.
2011 (defalias 'redraw-modeline 'force-mode-line-update)
2012
2013 (defun force-mode-line-update (&optional all)
2014 "Force redisplay of the current buffer's mode line and header line.
2015 With optional non-nil ALL, force redisplay of all mode lines and
2016 header lines. This function also forces recomputation of the
2017 menu bar menus and the frame title."
2018 (if all (save-excursion (set-buffer (other-buffer))))
2019 (set-buffer-modified-p (buffer-modified-p)))
2020
2021 (defun momentary-string-display (string pos &optional exit-char message)
2022 "Momentarily display STRING in the buffer at POS.
2023 Display remains until next event is input.
2024 If POS is a marker, only its position is used; its buffer is ignored.
2025 Optional third arg EXIT-CHAR can be a character, event or event
2026 description list. EXIT-CHAR defaults to SPC. If the input is
2027 EXIT-CHAR it is swallowed; otherwise it is then available as
2028 input (as a command if nothing else).
2029 Display MESSAGE (optional fourth arg) in the echo area.
2030 If MESSAGE is nil, instructions to type EXIT-CHAR are displayed there."
2031 (or exit-char (setq exit-char ?\s))
2032 (let ((inhibit-read-only t)
2033 ;; Don't modify the undo list at all.
2034 (buffer-undo-list t)
2035 (modified (buffer-modified-p))
2036 (name buffer-file-name)
2037 insert-end)
2038 (unwind-protect
2039 (progn
2040 (save-excursion
2041 (goto-char pos)
2042 ;; To avoid trouble with out-of-bounds position
2043 (setq pos (point))
2044 ;; defeat file locking... don't try this at home, kids!
2045 (setq buffer-file-name nil)
2046 (insert-before-markers string)
2047 (setq insert-end (point))
2048 ;; If the message end is off screen, recenter now.
2049 (if (< (window-end nil t) insert-end)
2050 (recenter (/ (window-height) 2)))
2051 ;; If that pushed message start off the screen,
2052 ;; scroll to start it at the top of the screen.
2053 (move-to-window-line 0)
2054 (if (> (point) pos)
2055 (progn
2056 (goto-char pos)
2057 (recenter 0))))
2058 (message (or message "Type %s to continue editing.")
2059 (single-key-description exit-char))
2060 (let (char)
2061 (if (integerp exit-char)
2062 (condition-case nil
2063 (progn
2064 (setq char (read-char))
2065 (or (eq char exit-char)
2066 (setq unread-command-events (list char))))
2067 (error
2068 ;; `exit-char' is a character, hence it differs
2069 ;; from char, which is an event.
2070 (setq unread-command-events (list char))))
2071 ;; `exit-char' can be an event, or an event description
2072 ;; list.
2073 (setq char (read-event))
2074 (or (eq char exit-char)
2075 (eq char (event-convert-list exit-char))
2076 (setq unread-command-events (list char))))))
2077 (if insert-end
2078 (save-excursion
2079 (delete-region pos insert-end)))
2080 (setq buffer-file-name name)
2081 (set-buffer-modified-p modified))))
2082
2083 \f
2084 ;;;; Overlay operations
2085
2086 (defun copy-overlay (o)
2087 "Return a copy of overlay O."
2088 (let ((o1 (make-overlay (overlay-start o) (overlay-end o)
2089 ;; FIXME: there's no easy way to find the
2090 ;; insertion-type of the two markers.
2091 (overlay-buffer o)))
2092 (props (overlay-properties o)))
2093 (while props
2094 (overlay-put o1 (pop props) (pop props)))
2095 o1))
2096
2097 (defun remove-overlays (&optional beg end name val)
2098 "Clear BEG and END of overlays whose property NAME has value VAL.
2099 Overlays might be moved and/or split.
2100 BEG and END default respectively to the beginning and end of buffer."
2101 ;; This speeds up the loops over overlays.
2102 (unless beg (setq beg (point-min)))
2103 (unless end (setq end (point-max)))
2104 (overlay-recenter end)
2105 (if (< end beg)
2106 (setq beg (prog1 end (setq end beg))))
2107 (save-excursion
2108 (dolist (o (overlays-in beg end))
2109 (when (eq (overlay-get o name) val)
2110 ;; Either push this overlay outside beg...end
2111 ;; or split it to exclude beg...end
2112 ;; or delete it entirely (if it is contained in beg...end).
2113 (if (< (overlay-start o) beg)
2114 (if (> (overlay-end o) end)
2115 (progn
2116 (move-overlay (copy-overlay o)
2117 (overlay-start o) beg)
2118 (move-overlay o end (overlay-end o)))
2119 (move-overlay o (overlay-start o) beg))
2120 (if (> (overlay-end o) end)
2121 (move-overlay o end (overlay-end o))
2122 (delete-overlay o)))))))
2123 \f
2124 ;;;; Miscellanea.
2125
2126 (defvar suspend-hook nil
2127 "Normal hook run by `suspend-emacs', before suspending.")
2128
2129 (defvar suspend-resume-hook nil
2130 "Normal hook run by `suspend-emacs', after Emacs is continued.")
2131
2132 (defvar temp-buffer-show-hook nil
2133 "Normal hook run by `with-output-to-temp-buffer' after displaying the buffer.
2134 When the hook runs, the temporary buffer is current, and the window it
2135 was displayed in is selected. This hook is normally set up with a
2136 function to make the buffer read only, and find function names and
2137 variable names in it, provided the major mode is still Help mode.")
2138
2139 (defvar temp-buffer-setup-hook nil
2140 "Normal hook run by `with-output-to-temp-buffer' at the start.
2141 When the hook runs, the temporary buffer is current.
2142 This hook is normally set up with a function to put the buffer in Help
2143 mode.")
2144
2145 ;; Avoid compiler warnings about this variable,
2146 ;; which has a special meaning on certain system types.
2147 (defvar buffer-file-type nil
2148 "Non-nil if the visited file is a binary file.
2149 This variable is meaningful on MS-DOG and Windows NT.
2150 On those systems, it is automatically local in every buffer.
2151 On other systems, this variable is normally always nil.")
2152
2153 ;; The `assert' macro from the cl package signals
2154 ;; `cl-assertion-failed' at runtime so always define it.
2155 (put 'cl-assertion-failed 'error-conditions '(error))
2156 (put 'cl-assertion-failed 'error-message "Assertion failed")
2157
2158 (defconst user-emacs-directory
2159 (if (eq system-type 'ms-dos)
2160 ;; MS-DOS cannot have initial dot.
2161 "~/_emacs.d/"
2162 "~/.emacs.d/")
2163 "Directory beneath which additional per-user Emacs-specific files are placed.
2164 Various programs in Emacs store information in this directory.
2165 Note that this should end with a directory separator.")
2166
2167 \f
2168 ;;;; Misc. useful functions.
2169
2170 (defun find-tag-default ()
2171 "Determine default tag to search for, based on text at point.
2172 If there is no plausible default, return nil."
2173 (let (from to bound)
2174 (when (or (progn
2175 ;; Look at text around `point'.
2176 (save-excursion
2177 (skip-syntax-backward "w_") (setq from (point)))
2178 (save-excursion
2179 (skip-syntax-forward "w_") (setq to (point)))
2180 (> to from))
2181 ;; Look between `line-beginning-position' and `point'.
2182 (save-excursion
2183 (and (setq bound (line-beginning-position))
2184 (skip-syntax-backward "^w_" bound)
2185 (> (setq to (point)) bound)
2186 (skip-syntax-backward "w_")
2187 (setq from (point))))
2188 ;; Look between `point' and `line-end-position'.
2189 (save-excursion
2190 (and (setq bound (line-end-position))
2191 (skip-syntax-forward "^w_" bound)
2192 (< (setq from (point)) bound)
2193 (skip-syntax-forward "w_")
2194 (setq to (point)))))
2195 (buffer-substring-no-properties from to))))
2196
2197 (defun play-sound (sound)
2198 "SOUND is a list of the form `(sound KEYWORD VALUE...)'.
2199 The following keywords are recognized:
2200
2201 :file FILE - read sound data from FILE. If FILE isn't an
2202 absolute file name, it is searched in `data-directory'.
2203
2204 :data DATA - read sound data from string DATA.
2205
2206 Exactly one of :file or :data must be present.
2207
2208 :volume VOL - set volume to VOL. VOL must an integer in the
2209 range 0..100 or a float in the range 0..1.0. If not specified,
2210 don't change the volume setting of the sound device.
2211
2212 :device DEVICE - play sound on DEVICE. If not specified,
2213 a system-dependent default device name is used."
2214 (if (fboundp 'play-sound-internal)
2215 (play-sound-internal sound)
2216 (error "This Emacs binary lacks sound support")))
2217
2218 (declare-function w32-shell-dos-semantics "w32-fns" nil)
2219
2220 (defun shell-quote-argument (argument)
2221 "Quote an argument for passing as argument to an inferior shell."
2222 (if (or (eq system-type 'ms-dos)
2223 (and (eq system-type 'windows-nt) (w32-shell-dos-semantics)))
2224 ;; Quote using double quotes, but escape any existing quotes in
2225 ;; the argument with backslashes.
2226 (let ((result "")
2227 (start 0)
2228 end)
2229 (if (or (null (string-match "[^\"]" argument))
2230 (< (match-end 0) (length argument)))
2231 (while (string-match "[\"]" argument start)
2232 (setq end (match-beginning 0)
2233 result (concat result (substring argument start end)
2234 "\\" (substring argument end (1+ end)))
2235 start (1+ end))))
2236 (concat "\"" result (substring argument start) "\""))
2237 (if (equal argument "")
2238 "''"
2239 ;; Quote everything except POSIX filename characters.
2240 ;; This should be safe enough even for really weird shells.
2241 (let ((result "") (start 0) end)
2242 (while (string-match "[^-0-9a-zA-Z_./]" argument start)
2243 (setq end (match-beginning 0)
2244 result (concat result (substring argument start end)
2245 "\\" (substring argument end (1+ end)))
2246 start (1+ end)))
2247 (concat result (substring argument start))))))
2248
2249 (defun string-or-null-p (object)
2250 "Return t if OBJECT is a string or nil.
2251 Otherwise, return nil."
2252 (or (stringp object) (null object)))
2253
2254 (defun booleanp (object)
2255 "Return non-nil if OBJECT is one of the two canonical boolean values: t or nil."
2256 (memq object '(nil t)))
2257
2258 (defun field-at-pos (pos)
2259 "Return the field at position POS, taking stickiness etc into account"
2260 (let ((raw-field (get-char-property (field-beginning pos) 'field)))
2261 (if (eq raw-field 'boundary)
2262 (get-char-property (1- (field-end pos)) 'field)
2263 raw-field)))
2264
2265 \f
2266 ;;;; Support for yanking and text properties.
2267
2268 (defvar yank-excluded-properties)
2269
2270 (defun remove-yank-excluded-properties (start end)
2271 "Remove `yank-excluded-properties' between START and END positions.
2272 Replaces `category' properties with their defined properties."
2273 (let ((inhibit-read-only t))
2274 ;; Replace any `category' property with the properties it stands for.
2275 (unless (memq yank-excluded-properties '(t nil))
2276 (save-excursion
2277 (goto-char start)
2278 (while (< (point) end)
2279 (let ((cat (get-text-property (point) 'category))
2280 run-end)
2281 (setq run-end
2282 (next-single-property-change (point) 'category nil end))
2283 (when cat
2284 (let (run-end2 original)
2285 (remove-list-of-text-properties (point) run-end '(category))
2286 (while (< (point) run-end)
2287 (setq run-end2 (next-property-change (point) nil run-end))
2288 (setq original (text-properties-at (point)))
2289 (set-text-properties (point) run-end2 (symbol-plist cat))
2290 (add-text-properties (point) run-end2 original)
2291 (goto-char run-end2))))
2292 (goto-char run-end)))))
2293 (if (eq yank-excluded-properties t)
2294 (set-text-properties start end nil)
2295 (remove-list-of-text-properties start end yank-excluded-properties))))
2296
2297 (defvar yank-undo-function)
2298
2299 (defun insert-for-yank (string)
2300 "Calls `insert-for-yank-1' repetitively for each `yank-handler' segment.
2301
2302 See `insert-for-yank-1' for more details."
2303 (let (to)
2304 (while (setq to (next-single-property-change 0 'yank-handler string))
2305 (insert-for-yank-1 (substring string 0 to))
2306 (setq string (substring string to))))
2307 (insert-for-yank-1 string))
2308
2309 (defun insert-for-yank-1 (string)
2310 "Insert STRING at point, stripping some text properties.
2311
2312 Strip text properties from the inserted text according to
2313 `yank-excluded-properties'. Otherwise just like (insert STRING).
2314
2315 If STRING has a non-nil `yank-handler' property on the first character,
2316 the normal insert behavior is modified in various ways. The value of
2317 the yank-handler property must be a list with one to four elements
2318 with the following format: (FUNCTION PARAM NOEXCLUDE UNDO).
2319 When FUNCTION is present and non-nil, it is called instead of `insert'
2320 to insert the string. FUNCTION takes one argument--the object to insert.
2321 If PARAM is present and non-nil, it replaces STRING as the object
2322 passed to FUNCTION (or `insert'); for example, if FUNCTION is
2323 `yank-rectangle', PARAM may be a list of strings to insert as a
2324 rectangle.
2325 If NOEXCLUDE is present and non-nil, the normal removal of the
2326 yank-excluded-properties is not performed; instead FUNCTION is
2327 responsible for removing those properties. This may be necessary
2328 if FUNCTION adjusts point before or after inserting the object.
2329 If UNDO is present and non-nil, it is a function that will be called
2330 by `yank-pop' to undo the insertion of the current object. It is
2331 called with two arguments, the start and end of the current region.
2332 FUNCTION may set `yank-undo-function' to override the UNDO value."
2333 (let* ((handler (and (stringp string)
2334 (get-text-property 0 'yank-handler string)))
2335 (param (or (nth 1 handler) string))
2336 (opoint (point))
2337 (inhibit-read-only inhibit-read-only)
2338 end)
2339
2340 (setq yank-undo-function t)
2341 (if (nth 0 handler) ;; FUNCTION
2342 (funcall (car handler) param)
2343 (insert param))
2344 (setq end (point))
2345
2346 ;; Prevent read-only properties from interfering with the
2347 ;; following text property changes.
2348 (setq inhibit-read-only t)
2349
2350 ;; What should we do with `font-lock-face' properties?
2351 (if font-lock-defaults
2352 ;; No, just wipe them.
2353 (remove-list-of-text-properties opoint end '(font-lock-face))
2354 ;; Convert them to `face'.
2355 (save-excursion
2356 (goto-char opoint)
2357 (while (< (point) end)
2358 (let ((face (get-text-property (point) 'font-lock-face))
2359 run-end)
2360 (setq run-end
2361 (next-single-property-change (point) 'font-lock-face nil end))
2362 (when face
2363 (remove-text-properties (point) run-end '(font-lock-face nil))
2364 (put-text-property (point) run-end 'face face))
2365 (goto-char run-end)))))
2366
2367 (unless (nth 2 handler) ;; NOEXCLUDE
2368 (remove-yank-excluded-properties opoint (point)))
2369
2370 ;; If last inserted char has properties, mark them as rear-nonsticky.
2371 (if (and (> end opoint)
2372 (text-properties-at (1- end)))
2373 (put-text-property (1- end) end 'rear-nonsticky t))
2374
2375 (if (eq yank-undo-function t) ;; not set by FUNCTION
2376 (setq yank-undo-function (nth 3 handler))) ;; UNDO
2377 (if (nth 4 handler) ;; COMMAND
2378 (setq this-command (nth 4 handler)))))
2379
2380 (defun insert-buffer-substring-no-properties (buffer &optional start end)
2381 "Insert before point a substring of BUFFER, without text properties.
2382 BUFFER may be a buffer or a buffer name.
2383 Arguments START and END are character positions specifying the substring.
2384 They default to the values of (point-min) and (point-max) in BUFFER."
2385 (let ((opoint (point)))
2386 (insert-buffer-substring buffer start end)
2387 (let ((inhibit-read-only t))
2388 (set-text-properties opoint (point) nil))))
2389
2390 (defun insert-buffer-substring-as-yank (buffer &optional start end)
2391 "Insert before point a part of BUFFER, stripping some text properties.
2392 BUFFER may be a buffer or a buffer name.
2393 Arguments START and END are character positions specifying the substring.
2394 They default to the values of (point-min) and (point-max) in BUFFER.
2395 Strip text properties from the inserted text according to
2396 `yank-excluded-properties'."
2397 ;; Since the buffer text should not normally have yank-handler properties,
2398 ;; there is no need to handle them here.
2399 (let ((opoint (point)))
2400 (insert-buffer-substring buffer start end)
2401 (remove-yank-excluded-properties opoint (point))))
2402
2403 \f
2404 ;;;; Synchronous shell commands.
2405
2406 (defun start-process-shell-command (name buffer &rest args)
2407 "Start a program in a subprocess. Return the process object for it.
2408 NAME is name for process. It is modified if necessary to make it unique.
2409 BUFFER is the buffer (or buffer name) to associate with the process.
2410 Process output goes at end of that buffer, unless you specify
2411 an output stream or filter function to handle the output.
2412 BUFFER may be also nil, meaning that this process is not associated
2413 with any buffer
2414 COMMAND is the name of a shell command.
2415 Remaining arguments are the arguments for the command; they are all
2416 spliced together with blanks separating between each two of them, before
2417 passing the command to the shell.
2418 Wildcards and redirection are handled as usual in the shell.
2419
2420 \(fn NAME BUFFER COMMAND &rest COMMAND-ARGS)"
2421 (cond
2422 ((eq system-type 'vax-vms)
2423 (apply 'start-process name buffer args))
2424 ;; We used to use `exec' to replace the shell with the command,
2425 ;; but that failed to handle (...) and semicolon, etc.
2426 (t
2427 (start-process name buffer shell-file-name shell-command-switch
2428 (mapconcat 'identity args " ")))))
2429
2430 (defun start-file-process-shell-command (name buffer &rest args)
2431 "Start a program in a subprocess. Return the process object for it.
2432 Similar to `start-process-shell-command', but calls `start-file-process'."
2433 (start-file-process
2434 name buffer
2435 (if (file-remote-p default-directory) "/bin/sh" shell-file-name)
2436 (if (file-remote-p default-directory) "-c" shell-command-switch)
2437 (mapconcat 'identity args " ")))
2438
2439 (defun call-process-shell-command (command &optional infile buffer display
2440 &rest args)
2441 "Execute the shell command COMMAND synchronously in separate process.
2442 The remaining arguments are optional.
2443 The program's input comes from file INFILE (nil means `/dev/null').
2444 Insert output in BUFFER before point; t means current buffer;
2445 nil for BUFFER means discard it; 0 means discard and don't wait.
2446 BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,
2447 REAL-BUFFER says what to do with standard output, as above,
2448 while STDERR-FILE says what to do with standard error in the child.
2449 STDERR-FILE may be nil (discard standard error output),
2450 t (mix it with ordinary output), or a file name string.
2451
2452 Fourth arg DISPLAY non-nil means redisplay buffer as output is inserted.
2453 Remaining arguments are strings passed as additional arguments for COMMAND.
2454 Wildcards and redirection are handled as usual in the shell.
2455
2456 If BUFFER is 0, `call-process-shell-command' returns immediately with value nil.
2457 Otherwise it waits for COMMAND to terminate and returns a numeric exit
2458 status or a signal description string.
2459 If you quit, the process is killed with SIGINT, or SIGKILL if you quit again."
2460 (cond
2461 ((eq system-type 'vax-vms)
2462 (apply 'call-process command infile buffer display args))
2463 ;; We used to use `exec' to replace the shell with the command,
2464 ;; but that failed to handle (...) and semicolon, etc.
2465 (t
2466 (call-process shell-file-name
2467 infile buffer display
2468 shell-command-switch
2469 (mapconcat 'identity (cons command args) " ")))))
2470
2471 (defun process-file-shell-command (command &optional infile buffer display
2472 &rest args)
2473 "Process files synchronously in a separate process.
2474 Similar to `call-process-shell-command', but calls `process-file'."
2475 (process-file
2476 (if (file-remote-p default-directory) "/bin/sh" shell-file-name)
2477 infile buffer display
2478 (if (file-remote-p default-directory) "-c" shell-command-switch)
2479 (mapconcat 'identity (cons command args) " ")))
2480 \f
2481 ;;;; Lisp macros to do various things temporarily.
2482
2483 (defmacro with-current-buffer (buffer &rest body)
2484 "Execute the forms in BODY with BUFFER temporarily current.
2485 BUFFER can be a buffer or a buffer name.
2486 The value returned is the value of the last form in BODY.
2487 See also `with-temp-buffer'."
2488 (declare (indent 1) (debug t))
2489 `(save-current-buffer
2490 (set-buffer ,buffer)
2491 ,@body))
2492
2493 (defmacro with-selected-window (window &rest body)
2494 "Execute the forms in BODY with WINDOW as the selected window.
2495 The value returned is the value of the last form in BODY.
2496
2497 This macro saves and restores the current buffer, since otherwise
2498 its normal operation could potentially make a different
2499 buffer current. It does not alter the buffer list ordering.
2500
2501 This macro saves and restores the selected window, as well as
2502 the selected window in each frame. If the previously selected
2503 window of some frame is no longer live at the end of BODY, that
2504 frame's selected window is left alone. If the selected window is
2505 no longer live, then whatever window is selected at the end of
2506 BODY remains selected.
2507 See also `with-temp-buffer'."
2508 (declare (indent 1) (debug t))
2509 ;; Most of this code is a copy of save-selected-window.
2510 `(let ((save-selected-window-window (selected-window))
2511 ;; It is necessary to save all of these, because calling
2512 ;; select-window changes frame-selected-window for whatever
2513 ;; frame that window is in.
2514 (save-selected-window-alist
2515 (mapcar (lambda (frame) (list frame (frame-selected-window frame)))
2516 (frame-list))))
2517 (save-current-buffer
2518 (unwind-protect
2519 (progn (select-window ,window 'norecord)
2520 ,@body)
2521 (dolist (elt save-selected-window-alist)
2522 (and (frame-live-p (car elt))
2523 (window-live-p (cadr elt))
2524 (set-frame-selected-window (car elt) (cadr elt))))
2525 (if (window-live-p save-selected-window-window)
2526 (select-window save-selected-window-window 'norecord))))))
2527
2528 (defmacro with-selected-frame (frame &rest body)
2529 "Execute the forms in BODY with FRAME as the selected frame.
2530 The value returned is the value of the last form in BODY.
2531 See also `with-temp-buffer'."
2532 (declare (indent 1) (debug t))
2533 (let ((old-frame (make-symbol "old-frame"))
2534 (old-buffer (make-symbol "old-buffer")))
2535 `(let ((,old-frame (selected-frame))
2536 (,old-buffer (current-buffer)))
2537 (unwind-protect
2538 (progn (select-frame ,frame)
2539 ,@body)
2540 (if (frame-live-p ,old-frame)
2541 (select-frame ,old-frame))
2542 (if (buffer-live-p ,old-buffer)
2543 (set-buffer ,old-buffer))))))
2544
2545 (defmacro with-temp-file (file &rest body)
2546 "Create a new buffer, evaluate BODY there, and write the buffer to FILE.
2547 The value returned is the value of the last form in BODY.
2548 See also `with-temp-buffer'."
2549 (declare (debug t))
2550 (let ((temp-file (make-symbol "temp-file"))
2551 (temp-buffer (make-symbol "temp-buffer")))
2552 `(let ((,temp-file ,file)
2553 (,temp-buffer
2554 (get-buffer-create (generate-new-buffer-name " *temp file*"))))
2555 (unwind-protect
2556 (prog1
2557 (with-current-buffer ,temp-buffer
2558 ,@body)
2559 (with-current-buffer ,temp-buffer
2560 (widen)
2561 (write-region (point-min) (point-max) ,temp-file nil 0)))
2562 (and (buffer-name ,temp-buffer)
2563 (kill-buffer ,temp-buffer))))))
2564
2565 (defmacro with-temp-message (message &rest body)
2566 "Display MESSAGE temporarily if non-nil while BODY is evaluated.
2567 The original message is restored to the echo area after BODY has finished.
2568 The value returned is the value of the last form in BODY.
2569 MESSAGE is written to the message log buffer if `message-log-max' is non-nil.
2570 If MESSAGE is nil, the echo area and message log buffer are unchanged.
2571 Use a MESSAGE of \"\" to temporarily clear the echo area."
2572 (declare (debug t))
2573 (let ((current-message (make-symbol "current-message"))
2574 (temp-message (make-symbol "with-temp-message")))
2575 `(let ((,temp-message ,message)
2576 (,current-message))
2577 (unwind-protect
2578 (progn
2579 (when ,temp-message
2580 (setq ,current-message (current-message))
2581 (message "%s" ,temp-message))
2582 ,@body)
2583 (and ,temp-message
2584 (if ,current-message
2585 (message "%s" ,current-message)
2586 (message nil)))))))
2587
2588 (defmacro with-temp-buffer (&rest body)
2589 "Create a temporary buffer, and evaluate BODY there like `progn'.
2590 See also `with-temp-file' and `with-output-to-string'."
2591 (declare (indent 0) (debug t))
2592 (let ((temp-buffer (make-symbol "temp-buffer")))
2593 `(let ((,temp-buffer (generate-new-buffer " *temp*")))
2594 ;; FIXME: kill-buffer can change current-buffer in some odd cases.
2595 (with-current-buffer ,temp-buffer
2596 (unwind-protect
2597 (progn ,@body)
2598 (and (buffer-name ,temp-buffer)
2599 (kill-buffer ,temp-buffer)))))))
2600
2601 (defmacro with-output-to-string (&rest body)
2602 "Execute BODY, return the text it sent to `standard-output', as a string."
2603 (declare (indent 0) (debug t))
2604 `(let ((standard-output
2605 (get-buffer-create (generate-new-buffer-name " *string-output*"))))
2606 (let ((standard-output standard-output))
2607 ,@body)
2608 (with-current-buffer standard-output
2609 (prog1
2610 (buffer-string)
2611 (kill-buffer nil)))))
2612
2613 (defmacro with-local-quit (&rest body)
2614 "Execute BODY, allowing quits to terminate BODY but not escape further.
2615 When a quit terminates BODY, `with-local-quit' returns nil but
2616 requests another quit. That quit will be processed as soon as quitting
2617 is allowed once again. (Immediately, if `inhibit-quit' is nil.)"
2618 (declare (debug t) (indent 0))
2619 `(condition-case nil
2620 (let ((inhibit-quit nil))
2621 ,@body)
2622 (quit (setq quit-flag t)
2623 ;; This call is to give a chance to handle quit-flag
2624 ;; in case inhibit-quit is nil.
2625 ;; Without this, it will not be handled until the next function
2626 ;; call, and that might allow it to exit thru a condition-case
2627 ;; that intends to handle the quit signal next time.
2628 (eval '(ignore nil)))))
2629
2630 (defmacro while-no-input (&rest body)
2631 "Execute BODY only as long as there's no pending input.
2632 If input arrives, that ends the execution of BODY,
2633 and `while-no-input' returns t. Quitting makes it return nil.
2634 If BODY finishes, `while-no-input' returns whatever value BODY produced."
2635 (declare (debug t) (indent 0))
2636 (let ((catch-sym (make-symbol "input")))
2637 `(with-local-quit
2638 (catch ',catch-sym
2639 (let ((throw-on-input ',catch-sym))
2640 (or (input-pending-p)
2641 (progn ,@body)))))))
2642
2643 (defmacro condition-case-no-debug (var bodyform &rest handlers)
2644 "Like `condition-case' except that it does not catch anything when debugging.
2645 More specifically if `debug-on-error' is set, then it does not catch any signal."
2646 (declare (debug condition-case) (indent 2))
2647 (let ((bodysym (make-symbol "body")))
2648 `(let ((,bodysym (lambda () ,bodyform)))
2649 (if debug-on-error
2650 (funcall ,bodysym)
2651 (condition-case ,var
2652 (funcall ,bodysym)
2653 ,@handlers)))))
2654
2655 (defmacro with-demoted-errors (&rest body)
2656 "Run BODY and demote any errors to simple messages.
2657 If `debug-on-error' is non-nil, run BODY without catching its errors.
2658 This is to be used around code which is not expected to signal an error
2659 but which should be robust in the unexpected case that an error is signalled."
2660 (declare (debug t) (indent 0))
2661 (let ((err (make-symbol "err")))
2662 `(condition-case-no-debug ,err
2663 (progn ,@body)
2664 (error (message "Error: %s" ,err) nil))))
2665
2666 (defmacro combine-after-change-calls (&rest body)
2667 "Execute BODY, but don't call the after-change functions till the end.
2668 If BODY makes changes in the buffer, they are recorded
2669 and the functions on `after-change-functions' are called several times
2670 when BODY is finished.
2671 The return value is the value of the last form in BODY.
2672
2673 If `before-change-functions' is non-nil, then calls to the after-change
2674 functions can't be deferred, so in that case this macro has no effect.
2675
2676 Do not alter `after-change-functions' or `before-change-functions'
2677 in BODY."
2678 (declare (indent 0) (debug t))
2679 `(unwind-protect
2680 (let ((combine-after-change-calls t))
2681 . ,body)
2682 (combine-after-change-execute)))
2683
2684 (defmacro with-case-table (table &rest body)
2685 "Execute the forms in BODY with TABLE as the current case table.
2686 The value returned is the value of the last form in BODY."
2687 (declare (indent 1) (debug t))
2688 (let ((old-case-table (make-symbol "table"))
2689 (old-buffer (make-symbol "buffer")))
2690 `(let ((,old-case-table (current-case-table))
2691 (,old-buffer (current-buffer)))
2692 (unwind-protect
2693 (progn (set-case-table ,table)
2694 ,@body)
2695 (with-current-buffer ,old-buffer
2696 (set-case-table ,old-case-table))))))
2697 \f
2698 ;;; Matching and match data.
2699
2700 (defvar save-match-data-internal)
2701
2702 ;; We use save-match-data-internal as the local variable because
2703 ;; that works ok in practice (people should not use that variable elsewhere).
2704 ;; We used to use an uninterned symbol; the compiler handles that properly
2705 ;; now, but it generates slower code.
2706 (defmacro save-match-data (&rest body)
2707 "Execute the BODY forms, restoring the global value of the match data.
2708 The value returned is the value of the last form in BODY."
2709 ;; It is better not to use backquote here,
2710 ;; because that makes a bootstrapping problem
2711 ;; if you need to recompile all the Lisp files using interpreted code.
2712 (declare (indent 0) (debug t))
2713 (list 'let
2714 '((save-match-data-internal (match-data)))
2715 (list 'unwind-protect
2716 (cons 'progn body)
2717 ;; It is safe to free (evaporate) markers immediately here,
2718 ;; as Lisp programs should not copy from save-match-data-internal.
2719 '(set-match-data save-match-data-internal 'evaporate))))
2720
2721 (defun match-string (num &optional string)
2722 "Return string of text matched by last search.
2723 NUM specifies which parenthesized expression in the last regexp.
2724 Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
2725 Zero means the entire text matched by the whole regexp or whole string.
2726 STRING should be given if the last search was by `string-match' on STRING."
2727 (if (match-beginning num)
2728 (if string
2729 (substring string (match-beginning num) (match-end num))
2730 (buffer-substring (match-beginning num) (match-end num)))))
2731
2732 (defun match-string-no-properties (num &optional string)
2733 "Return string of text matched by last search, without text properties.
2734 NUM specifies which parenthesized expression in the last regexp.
2735 Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
2736 Zero means the entire text matched by the whole regexp or whole string.
2737 STRING should be given if the last search was by `string-match' on STRING."
2738 (if (match-beginning num)
2739 (if string
2740 (substring-no-properties string (match-beginning num)
2741 (match-end num))
2742 (buffer-substring-no-properties (match-beginning num)
2743 (match-end num)))))
2744
2745
2746 (defun match-substitute-replacement (replacement
2747 &optional fixedcase literal string subexp)
2748 "Return REPLACEMENT as it will be inserted by `replace-match'.
2749 In other words, all back-references in the form `\\&' and `\\N'
2750 are substituted with actual strings matched by the last search.
2751 Optional FIXEDCASE, LITERAL, STRING and SUBEXP have the same
2752 meaning as for `replace-match'."
2753 (let ((match (match-string 0 string)))
2754 (save-match-data
2755 (set-match-data (mapcar (lambda (x)
2756 (if (numberp x)
2757 (- x (match-beginning 0))
2758 x))
2759 (match-data t)))
2760 (replace-match replacement fixedcase literal match subexp))))
2761
2762
2763 (defun looking-back (regexp &optional limit greedy)
2764 "Return non-nil if text before point matches regular expression REGEXP.
2765 Like `looking-at' except matches before point, and is slower.
2766 LIMIT if non-nil speeds up the search by specifying a minimum
2767 starting position, to avoid checking matches that would start
2768 before LIMIT.
2769
2770 If GREEDY is non-nil, extend the match backwards as far as possible,
2771 stopping when a single additional previous character cannot be part
2772 of a match for REGEXP."
2773 (let ((start (point))
2774 (pos
2775 (save-excursion
2776 (and (re-search-backward (concat "\\(?:" regexp "\\)\\=") limit t)
2777 (point)))))
2778 (if (and greedy pos)
2779 (save-restriction
2780 (narrow-to-region (point-min) start)
2781 (while (and (> pos (point-min))
2782 (save-excursion
2783 (goto-char pos)
2784 (backward-char 1)
2785 (looking-at (concat "\\(?:" regexp "\\)\\'"))))
2786 (setq pos (1- pos)))
2787 (save-excursion
2788 (goto-char pos)
2789 (looking-at (concat "\\(?:" regexp "\\)\\'")))))
2790 (not (null pos))))
2791
2792 (defsubst looking-at-p (regexp)
2793 "\
2794 Same as `looking-at' except this function does not change the match data."
2795 (let ((inhibit-changing-match-data t))
2796 (looking-at regexp)))
2797
2798 (defsubst string-match-p (regexp string &optional start)
2799 "\
2800 Same as `string-match' except this function does not change the match data."
2801 (let ((inhibit-changing-match-data t))
2802 (string-match regexp string start)))
2803
2804 (defun subregexp-context-p (regexp pos &optional start)
2805 "Return non-nil if POS is in a normal subregexp context in REGEXP.
2806 A subregexp context is one where a sub-regexp can appear.
2807 A non-subregexp context is for example within brackets, or within a
2808 repetition bounds operator `\\=\\{...\\}', or right after a `\\'.
2809 If START is non-nil, it should be a position in REGEXP, smaller
2810 than POS, and known to be in a subregexp context."
2811 ;; Here's one possible implementation, with the great benefit that it
2812 ;; reuses the regexp-matcher's own parser, so it understands all the
2813 ;; details of the syntax. A disadvantage is that it needs to match the
2814 ;; error string.
2815 (condition-case err
2816 (progn
2817 (string-match (substring regexp (or start 0) pos) "")
2818 t)
2819 (invalid-regexp
2820 (not (member (cadr err) '("Unmatched [ or [^"
2821 "Unmatched \\{"
2822 "Trailing backslash")))))
2823 ;; An alternative implementation:
2824 ;; (defconst re-context-re
2825 ;; (let* ((harmless-ch "[^\\[]")
2826 ;; (harmless-esc "\\\\[^{]")
2827 ;; (class-harmless-ch "[^][]")
2828 ;; (class-lb-harmless "[^]:]")
2829 ;; (class-lb-colon-maybe-charclass ":\\([a-z]+:]\\)?")
2830 ;; (class-lb (concat "\\[\\(" class-lb-harmless
2831 ;; "\\|" class-lb-colon-maybe-charclass "\\)"))
2832 ;; (class
2833 ;; (concat "\\[^?]?"
2834 ;; "\\(" class-harmless-ch
2835 ;; "\\|" class-lb "\\)*"
2836 ;; "\\[?]")) ; special handling for bare [ at end of re
2837 ;; (braces "\\\\{[0-9,]+\\\\}"))
2838 ;; (concat "\\`\\(" harmless-ch "\\|" harmless-esc
2839 ;; "\\|" class "\\|" braces "\\)*\\'"))
2840 ;; "Matches any prefix that corresponds to a normal subregexp context.")
2841 ;; (string-match re-context-re (substring regexp (or start 0) pos))
2842 )
2843 \f
2844 ;;;; split-string
2845
2846 (defconst split-string-default-separators "[ \f\t\n\r\v]+"
2847 "The default value of separators for `split-string'.
2848
2849 A regexp matching strings of whitespace. May be locale-dependent
2850 \(as yet unimplemented). Should not match non-breaking spaces.
2851
2852 Warning: binding this to a different value and using it as default is
2853 likely to have undesired semantics.")
2854
2855 ;; The specification says that if both SEPARATORS and OMIT-NULLS are
2856 ;; defaulted, OMIT-NULLS should be treated as t. Simplifying the logical
2857 ;; expression leads to the equivalent implementation that if SEPARATORS
2858 ;; is defaulted, OMIT-NULLS is treated as t.
2859 (defun split-string (string &optional separators omit-nulls)
2860 "Split STRING into substrings bounded by matches for SEPARATORS.
2861
2862 The beginning and end of STRING, and each match for SEPARATORS, are
2863 splitting points. The substrings matching SEPARATORS are removed, and
2864 the substrings between the splitting points are collected as a list,
2865 which is returned.
2866
2867 If SEPARATORS is non-nil, it should be a regular expression matching text
2868 which separates, but is not part of, the substrings. If nil it defaults to
2869 `split-string-default-separators', normally \"[ \\f\\t\\n\\r\\v]+\", and
2870 OMIT-NULLS is forced to t.
2871
2872 If OMIT-NULLS is t, zero-length substrings are omitted from the list \(so
2873 that for the default value of SEPARATORS leading and trailing whitespace
2874 are effectively trimmed). If nil, all zero-length substrings are retained,
2875 which correctly parses CSV format, for example.
2876
2877 Note that the effect of `(split-string STRING)' is the same as
2878 `(split-string STRING split-string-default-separators t)'. In the rare
2879 case that you wish to retain zero-length substrings when splitting on
2880 whitespace, use `(split-string STRING split-string-default-separators)'.
2881
2882 Modifies the match data; use `save-match-data' if necessary."
2883 (let ((keep-nulls (not (if separators omit-nulls t)))
2884 (rexp (or separators split-string-default-separators))
2885 (start 0)
2886 notfirst
2887 (list nil))
2888 (while (and (string-match rexp string
2889 (if (and notfirst
2890 (= start (match-beginning 0))
2891 (< start (length string)))
2892 (1+ start) start))
2893 (< start (length string)))
2894 (setq notfirst t)
2895 (if (or keep-nulls (< start (match-beginning 0)))
2896 (setq list
2897 (cons (substring string start (match-beginning 0))
2898 list)))
2899 (setq start (match-end 0)))
2900 (if (or keep-nulls (< start (length string)))
2901 (setq list
2902 (cons (substring string start)
2903 list)))
2904 (nreverse list)))
2905
2906 (defun combine-and-quote-strings (strings &optional separator)
2907 "Concatenate the STRINGS, adding the SEPARATOR (default \" \").
2908 This tries to quote the strings to avoid ambiguity such that
2909 (split-string-and-unquote (combine-and-quote-strings strs)) == strs
2910 Only some SEPARATORs will work properly."
2911 (let* ((sep (or separator " "))
2912 (re (concat "[\\\"]" "\\|" (regexp-quote sep))))
2913 (mapconcat
2914 (lambda (str)
2915 (if (string-match re str)
2916 (concat "\"" (replace-regexp-in-string "[\\\"]" "\\\\\\&" str) "\"")
2917 str))
2918 strings sep)))
2919
2920 (defun split-string-and-unquote (string &optional separator)
2921 "Split the STRING into a list of strings.
2922 It understands Emacs Lisp quoting within STRING, such that
2923 (split-string-and-unquote (combine-and-quote-strings strs)) == strs
2924 The SEPARATOR regexp defaults to \"\\s-+\"."
2925 (let ((sep (or separator "\\s-+"))
2926 (i (string-match "[\"]" string)))
2927 (if (null i)
2928 (split-string string sep t) ; no quoting: easy
2929 (append (unless (eq i 0) (split-string (substring string 0 i) sep t))
2930 (let ((rfs (read-from-string string i)))
2931 (cons (car rfs)
2932 (split-string-and-unquote (substring string (cdr rfs))
2933 sep)))))))
2934
2935 \f
2936 ;;;; Replacement in strings.
2937
2938 (defun subst-char-in-string (fromchar tochar string &optional inplace)
2939 "Replace FROMCHAR with TOCHAR in STRING each time it occurs.
2940 Unless optional argument INPLACE is non-nil, return a new string."
2941 (let ((i (length string))
2942 (newstr (if inplace string (copy-sequence string))))
2943 (while (> i 0)
2944 (setq i (1- i))
2945 (if (eq (aref newstr i) fromchar)
2946 (aset newstr i tochar)))
2947 newstr))
2948
2949 (defun replace-regexp-in-string (regexp rep string &optional
2950 fixedcase literal subexp start)
2951 "Replace all matches for REGEXP with REP in STRING.
2952
2953 Return a new string containing the replacements.
2954
2955 Optional arguments FIXEDCASE, LITERAL and SUBEXP are like the
2956 arguments with the same names of function `replace-match'. If START
2957 is non-nil, start replacements at that index in STRING.
2958
2959 REP is either a string used as the NEWTEXT arg of `replace-match' or a
2960 function. If it is a function, it is called with the actual text of each
2961 match, and its value is used as the replacement text. When REP is called,
2962 the match-data are the result of matching REGEXP against a substring
2963 of STRING.
2964
2965 To replace only the first match (if any), make REGEXP match up to \\'
2966 and replace a sub-expression, e.g.
2967 (replace-regexp-in-string \"\\\\(foo\\\\).*\\\\'\" \"bar\" \" foo foo\" nil nil 1)
2968 => \" bar foo\"
2969 "
2970
2971 ;; To avoid excessive consing from multiple matches in long strings,
2972 ;; don't just call `replace-match' continually. Walk down the
2973 ;; string looking for matches of REGEXP and building up a (reversed)
2974 ;; list MATCHES. This comprises segments of STRING which weren't
2975 ;; matched interspersed with replacements for segments that were.
2976 ;; [For a `large' number of replacements it's more efficient to
2977 ;; operate in a temporary buffer; we can't tell from the function's
2978 ;; args whether to choose the buffer-based implementation, though it
2979 ;; might be reasonable to do so for long enough STRING.]
2980 (let ((l (length string))
2981 (start (or start 0))
2982 matches str mb me)
2983 (save-match-data
2984 (while (and (< start l) (string-match regexp string start))
2985 (setq mb (match-beginning 0)
2986 me (match-end 0))
2987 ;; If we matched the empty string, make sure we advance by one char
2988 (when (= me mb) (setq me (min l (1+ mb))))
2989 ;; Generate a replacement for the matched substring.
2990 ;; Operate only on the substring to minimize string consing.
2991 ;; Set up match data for the substring for replacement;
2992 ;; presumably this is likely to be faster than munging the
2993 ;; match data directly in Lisp.
2994 (string-match regexp (setq str (substring string mb me)))
2995 (setq matches
2996 (cons (replace-match (if (stringp rep)
2997 rep
2998 (funcall rep (match-string 0 str)))
2999 fixedcase literal str subexp)
3000 (cons (substring string start mb) ; unmatched prefix
3001 matches)))
3002 (setq start me))
3003 ;; Reconstruct a string from the pieces.
3004 (setq matches (cons (substring string start l) matches)) ; leftover
3005 (apply #'concat (nreverse matches)))))
3006 \f
3007 ;;;; invisibility specs
3008
3009 (defun add-to-invisibility-spec (element)
3010 "Add ELEMENT to `buffer-invisibility-spec'.
3011 See documentation for `buffer-invisibility-spec' for the kind of elements
3012 that can be added."
3013 (if (eq buffer-invisibility-spec t)
3014 (setq buffer-invisibility-spec (list t)))
3015 (setq buffer-invisibility-spec
3016 (cons element buffer-invisibility-spec)))
3017
3018 (defun remove-from-invisibility-spec (element)
3019 "Remove ELEMENT from `buffer-invisibility-spec'."
3020 (if (consp buffer-invisibility-spec)
3021 (setq buffer-invisibility-spec
3022 (delete element buffer-invisibility-spec))))
3023 \f
3024 ;;;; Syntax tables.
3025
3026 (defmacro with-syntax-table (table &rest body)
3027 "Evaluate BODY with syntax table of current buffer set to TABLE.
3028 The syntax table of the current buffer is saved, BODY is evaluated, and the
3029 saved table is restored, even in case of an abnormal exit.
3030 Value is what BODY returns."
3031 (declare (debug t))
3032 (let ((old-table (make-symbol "table"))
3033 (old-buffer (make-symbol "buffer")))
3034 `(let ((,old-table (syntax-table))
3035 (,old-buffer (current-buffer)))
3036 (unwind-protect
3037 (progn
3038 (set-syntax-table ,table)
3039 ,@body)
3040 (save-current-buffer
3041 (set-buffer ,old-buffer)
3042 (set-syntax-table ,old-table))))))
3043
3044 (defun make-syntax-table (&optional oldtable)
3045 "Return a new syntax table.
3046 Create a syntax table which inherits from OLDTABLE (if non-nil) or
3047 from `standard-syntax-table' otherwise."
3048 (let ((table (make-char-table 'syntax-table nil)))
3049 (set-char-table-parent table (or oldtable (standard-syntax-table)))
3050 table))
3051
3052 (defun syntax-after (pos)
3053 "Return the raw syntax of the char after POS.
3054 If POS is outside the buffer's accessible portion, return nil."
3055 (unless (or (< pos (point-min)) (>= pos (point-max)))
3056 (let ((st (if parse-sexp-lookup-properties
3057 (get-char-property pos 'syntax-table))))
3058 (if (consp st) st
3059 (aref (or st (syntax-table)) (char-after pos))))))
3060
3061 (defun syntax-class (syntax)
3062 "Return the syntax class part of the syntax descriptor SYNTAX.
3063 If SYNTAX is nil, return nil."
3064 (and syntax (logand (car syntax) 65535)))
3065 \f
3066 ;;;; Text clones
3067
3068 (defun text-clone-maintain (ol1 after beg end &optional len)
3069 "Propagate the changes made under the overlay OL1 to the other clones.
3070 This is used on the `modification-hooks' property of text clones."
3071 (when (and after (not undo-in-progress) (overlay-start ol1))
3072 (let ((margin (if (overlay-get ol1 'text-clone-spreadp) 1 0)))
3073 (setq beg (max beg (+ (overlay-start ol1) margin)))
3074 (setq end (min end (- (overlay-end ol1) margin)))
3075 (when (<= beg end)
3076 (save-excursion
3077 (when (overlay-get ol1 'text-clone-syntax)
3078 ;; Check content of the clone's text.
3079 (let ((cbeg (+ (overlay-start ol1) margin))
3080 (cend (- (overlay-end ol1) margin)))
3081 (goto-char cbeg)
3082 (save-match-data
3083 (if (not (re-search-forward
3084 (overlay-get ol1 'text-clone-syntax) cend t))
3085 ;; Mark the overlay for deletion.
3086 (overlay-put ol1 'text-clones nil)
3087 (when (< (match-end 0) cend)
3088 ;; Shrink the clone at its end.
3089 (setq end (min end (match-end 0)))
3090 (move-overlay ol1 (overlay-start ol1)
3091 (+ (match-end 0) margin)))
3092 (when (> (match-beginning 0) cbeg)
3093 ;; Shrink the clone at its beginning.
3094 (setq beg (max (match-beginning 0) beg))
3095 (move-overlay ol1 (- (match-beginning 0) margin)
3096 (overlay-end ol1)))))))
3097 ;; Now go ahead and update the clones.
3098 (let ((head (- beg (overlay-start ol1)))
3099 (tail (- (overlay-end ol1) end))
3100 (str (buffer-substring beg end))
3101 (nothing-left t)
3102 (inhibit-modification-hooks t))
3103 (dolist (ol2 (overlay-get ol1 'text-clones))
3104 (let ((oe (overlay-end ol2)))
3105 (unless (or (eq ol1 ol2) (null oe))
3106 (setq nothing-left nil)
3107 (let ((mod-beg (+ (overlay-start ol2) head)))
3108 ;;(overlay-put ol2 'modification-hooks nil)
3109 (goto-char (- (overlay-end ol2) tail))
3110 (unless (> mod-beg (point))
3111 (save-excursion (insert str))
3112 (delete-region mod-beg (point)))
3113 ;;(overlay-put ol2 'modification-hooks '(text-clone-maintain))
3114 ))))
3115 (if nothing-left (delete-overlay ol1))))))))
3116
3117 (defun text-clone-create (start end &optional spreadp syntax)
3118 "Create a text clone of START...END at point.
3119 Text clones are chunks of text that are automatically kept identical:
3120 changes done to one of the clones will be immediately propagated to the other.
3121
3122 The buffer's content at point is assumed to be already identical to
3123 the one between START and END.
3124 If SYNTAX is provided it's a regexp that describes the possible text of
3125 the clones; the clone will be shrunk or killed if necessary to ensure that
3126 its text matches the regexp.
3127 If SPREADP is non-nil it indicates that text inserted before/after the
3128 clone should be incorporated in the clone."
3129 ;; To deal with SPREADP we can either use an overlay with `nil t' along
3130 ;; with insert-(behind|in-front-of)-hooks or use a slightly larger overlay
3131 ;; (with a one-char margin at each end) with `t nil'.
3132 ;; We opted for a larger overlay because it behaves better in the case
3133 ;; where the clone is reduced to the empty string (we want the overlay to
3134 ;; stay when the clone's content is the empty string and we want to use
3135 ;; `evaporate' to make sure those overlays get deleted when needed).
3136 ;;
3137 (let* ((pt-end (+ (point) (- end start)))
3138 (start-margin (if (or (not spreadp) (bobp) (<= start (point-min)))
3139 0 1))
3140 (end-margin (if (or (not spreadp)
3141 (>= pt-end (point-max))
3142 (>= start (point-max)))
3143 0 1))
3144 (ol1 (make-overlay (- start start-margin) (+ end end-margin) nil t))
3145 (ol2 (make-overlay (- (point) start-margin) (+ pt-end end-margin) nil t))
3146 (dups (list ol1 ol2)))
3147 (overlay-put ol1 'modification-hooks '(text-clone-maintain))
3148 (when spreadp (overlay-put ol1 'text-clone-spreadp t))
3149 (when syntax (overlay-put ol1 'text-clone-syntax syntax))
3150 ;;(overlay-put ol1 'face 'underline)
3151 (overlay-put ol1 'evaporate t)
3152 (overlay-put ol1 'text-clones dups)
3153 ;;
3154 (overlay-put ol2 'modification-hooks '(text-clone-maintain))
3155 (when spreadp (overlay-put ol2 'text-clone-spreadp t))
3156 (when syntax (overlay-put ol2 'text-clone-syntax syntax))
3157 ;;(overlay-put ol2 'face 'underline)
3158 (overlay-put ol2 'evaporate t)
3159 (overlay-put ol2 'text-clones dups)))
3160 \f
3161 ;;;; Mail user agents.
3162
3163 ;; Here we include just enough for other packages to be able
3164 ;; to define them.
3165
3166 (defun define-mail-user-agent (symbol composefunc sendfunc
3167 &optional abortfunc hookvar)
3168 "Define a symbol to identify a mail-sending package for `mail-user-agent'.
3169
3170 SYMBOL can be any Lisp symbol. Its function definition and/or
3171 value as a variable do not matter for this usage; we use only certain
3172 properties on its property list, to encode the rest of the arguments.
3173
3174 COMPOSEFUNC is program callable function that composes an outgoing
3175 mail message buffer. This function should set up the basics of the
3176 buffer without requiring user interaction. It should populate the
3177 standard mail headers, leaving the `to:' and `subject:' headers blank
3178 by default.
3179
3180 COMPOSEFUNC should accept several optional arguments--the same
3181 arguments that `compose-mail' takes. See that function's documentation.
3182
3183 SENDFUNC is the command a user would run to send the message.
3184
3185 Optional ABORTFUNC is the command a user would run to abort the
3186 message. For mail packages that don't have a separate abort function,
3187 this can be `kill-buffer' (the equivalent of omitting this argument).
3188
3189 Optional HOOKVAR is a hook variable that gets run before the message
3190 is actually sent. Callers that use the `mail-user-agent' may
3191 install a hook function temporarily on this hook variable.
3192 If HOOKVAR is nil, `mail-send-hook' is used.
3193
3194 The properties used on SYMBOL are `composefunc', `sendfunc',
3195 `abortfunc', and `hookvar'."
3196 (put symbol 'composefunc composefunc)
3197 (put symbol 'sendfunc sendfunc)
3198 (put symbol 'abortfunc (or abortfunc 'kill-buffer))
3199 (put symbol 'hookvar (or hookvar 'mail-send-hook)))
3200 \f
3201 ;;;; Progress reporters.
3202
3203 ;; Progress reporter has the following structure:
3204 ;;
3205 ;; (NEXT-UPDATE-VALUE . [NEXT-UPDATE-TIME
3206 ;; MIN-VALUE
3207 ;; MAX-VALUE
3208 ;; MESSAGE
3209 ;; MIN-CHANGE
3210 ;; MIN-TIME])
3211 ;;
3212 ;; This weirdeness is for optimization reasons: we want
3213 ;; `progress-reporter-update' to be as fast as possible, so
3214 ;; `(car reporter)' is better than `(aref reporter 0)'.
3215 ;;
3216 ;; NEXT-UPDATE-TIME is a float. While `float-time' loses a couple
3217 ;; digits of precision, it doesn't really matter here. On the other
3218 ;; hand, it greatly simplifies the code.
3219
3220 (defsubst progress-reporter-update (reporter value)
3221 "Report progress of an operation in the echo area.
3222 However, if the change since last echo area update is too small
3223 or not enough time has passed, then do nothing (see
3224 `make-progress-reporter' for details).
3225
3226 First parameter, REPORTER, should be the result of a call to
3227 `make-progress-reporter'. Second, VALUE, determines the actual
3228 progress of operation; it must be between MIN-VALUE and MAX-VALUE
3229 as passed to `make-progress-reporter'.
3230
3231 This function is very inexpensive, you may not bother how often
3232 you call it."
3233 (when (>= value (car reporter))
3234 (progress-reporter-do-update reporter value)))
3235
3236 (defun make-progress-reporter (message min-value max-value
3237 &optional current-value
3238 min-change min-time)
3239 "Return progress reporter object to be used with `progress-reporter-update'.
3240
3241 MESSAGE is shown in the echo area. When at least 1% of operation
3242 is complete, the exact percentage will be appended to the
3243 MESSAGE. When you call `progress-reporter-done', word \"done\"
3244 is printed after the MESSAGE. You can change MESSAGE of an
3245 existing progress reporter with `progress-reporter-force-update'.
3246
3247 MIN-VALUE and MAX-VALUE designate starting (0% complete) and
3248 final (100% complete) states of operation. The latter should be
3249 larger; if this is not the case, then simply negate all values.
3250 Optional CURRENT-VALUE specifies the progress by the moment you
3251 call this function. You should omit it or set it to nil in most
3252 cases since it defaults to MIN-VALUE.
3253
3254 Optional MIN-CHANGE determines the minimal change in percents to
3255 report (default is 1%.) Optional MIN-TIME specifies the minimal
3256 time before echo area updates (default is 0.2 seconds.) If
3257 `float-time' function is not present, then time is not tracked
3258 at all. If OS is not capable of measuring fractions of seconds,
3259 then this parameter is effectively rounded up."
3260
3261 (unless min-time
3262 (setq min-time 0.2))
3263 (let ((reporter
3264 (cons min-value ;; Force a call to `message' now
3265 (vector (if (and (fboundp 'float-time)
3266 (>= min-time 0.02))
3267 (float-time) nil)
3268 min-value
3269 max-value
3270 message
3271 (if min-change (max (min min-change 50) 1) 1)
3272 min-time))))
3273 (progress-reporter-update reporter (or current-value min-value))
3274 reporter))
3275
3276 (defun progress-reporter-force-update (reporter value &optional new-message)
3277 "Report progress of an operation in the echo area unconditionally.
3278
3279 First two parameters are the same as for
3280 `progress-reporter-update'. Optional NEW-MESSAGE allows you to
3281 change the displayed message."
3282 (let ((parameters (cdr reporter)))
3283 (when new-message
3284 (aset parameters 3 new-message))
3285 (when (aref parameters 0)
3286 (aset parameters 0 (float-time)))
3287 (progress-reporter-do-update reporter value)))
3288
3289 (defun progress-reporter-do-update (reporter value)
3290 (let* ((parameters (cdr reporter))
3291 (min-value (aref parameters 1))
3292 (max-value (aref parameters 2))
3293 (one-percent (/ (- max-value min-value) 100.0))
3294 (percentage (if (= max-value min-value)
3295 0
3296 (truncate (/ (- value min-value) one-percent))))
3297 (update-time (aref parameters 0))
3298 (current-time (float-time))
3299 (enough-time-passed
3300 ;; See if enough time has passed since the last update.
3301 (or (not update-time)
3302 (when (>= current-time update-time)
3303 ;; Calculate time for the next update
3304 (aset parameters 0 (+ update-time (aref parameters 5)))))))
3305 ;;
3306 ;; Calculate NEXT-UPDATE-VALUE. If we are not going to print
3307 ;; message this time because not enough time has passed, then use
3308 ;; 1 instead of MIN-CHANGE. This makes delays between echo area
3309 ;; updates closer to MIN-TIME.
3310 (setcar reporter
3311 (min (+ min-value (* (+ percentage
3312 (if enough-time-passed
3313 (aref parameters 4) ;; MIN-CHANGE
3314 1))
3315 one-percent))
3316 max-value))
3317 (when (integerp value)
3318 (setcar reporter (ceiling (car reporter))))
3319 ;;
3320 ;; Only print message if enough time has passed
3321 (when enough-time-passed
3322 (if (> percentage 0)
3323 (message "%s%d%%" (aref parameters 3) percentage)
3324 (message "%s" (aref parameters 3))))))
3325
3326 (defun progress-reporter-done (reporter)
3327 "Print reporter's message followed by word \"done\" in echo area."
3328 (message "%sdone" (aref (cdr reporter) 3)))
3329
3330 (defmacro dotimes-with-progress-reporter (spec message &rest body)
3331 "Loop a certain number of times and report progress in the echo area.
3332 Evaluate BODY with VAR bound to successive integers running from
3333 0, inclusive, to COUNT, exclusive. Then evaluate RESULT to get
3334 the return value (nil if RESULT is omitted).
3335
3336 At each iteration MESSAGE followed by progress percentage is
3337 printed in the echo area. After the loop is finished, MESSAGE
3338 followed by word \"done\" is printed. This macro is a
3339 convenience wrapper around `make-progress-reporter' and friends.
3340
3341 \(fn (VAR COUNT [RESULT]) MESSAGE BODY...)"
3342 (declare (indent 2) (debug ((symbolp form &optional form) form body)))
3343 (let ((temp (make-symbol "--dotimes-temp--"))
3344 (temp2 (make-symbol "--dotimes-temp2--"))
3345 (start 0)
3346 (end (nth 1 spec)))
3347 `(let ((,temp ,end)
3348 (,(car spec) ,start)
3349 (,temp2 (make-progress-reporter ,message ,start ,end)))
3350 (while (< ,(car spec) ,temp)
3351 ,@body
3352 (progress-reporter-update ,temp2
3353 (setq ,(car spec) (1+ ,(car spec)))))
3354 (progress-reporter-done ,temp2)
3355 nil ,@(cdr (cdr spec)))))
3356
3357 \f
3358 ;;;; Comparing version strings.
3359
3360 (defvar version-separator "."
3361 "*Specify the string used to separate the version elements.
3362
3363 Usually the separator is \".\", but it can be any other string.")
3364
3365
3366 (defvar version-regexp-alist
3367 '(("^[-_+ ]?a\\(lpha\\)?$" . -3)
3368 ("^[-_+]$" . -3) ; treat "1.2.3-20050920" and "1.2-3" as alpha releases
3369 ("^[-_+ ]cvs$" . -3) ; treat "1.2.3-CVS" as alpha release
3370 ("^[-_+ ]?b\\(eta\\)?$" . -2)
3371 ("^[-_+ ]?\\(pre\\|rc\\)$" . -1))
3372 "*Specify association between non-numeric version part and a priority.
3373
3374 This association is used to handle version string like \"1.0pre2\",
3375 \"0.9alpha1\", etc. It's used by `version-to-list' (which see) to convert the
3376 non-numeric part to an integer. For example:
3377
3378 String Version Integer List Version
3379 \"1.0pre2\" (1 0 -1 2)
3380 \"1.0PRE2\" (1 0 -1 2)
3381 \"22.8beta3\" (22 8 -2 3)
3382 \"22.8 Beta3\" (22 8 -2 3)
3383 \"0.9alpha1\" (0 9 -3 1)
3384 \"0.9AlphA1\" (0 9 -3 1)
3385 \"0.9 alpha\" (0 9 -3)
3386
3387 Each element has the following form:
3388
3389 (REGEXP . PRIORITY)
3390
3391 Where:
3392
3393 REGEXP regexp used to match non-numeric part of a version string.
3394 It should begin with a `^' anchor and end with a `$' to
3395 prevent false hits. Letter-case is ignored while matching
3396 REGEXP.
3397
3398 PRIORITY negative integer which indicate the non-numeric priority.")
3399
3400
3401 (defun version-to-list (ver)
3402 "Convert version string VER into an integer list.
3403
3404 The version syntax is given by the following EBNF:
3405
3406 VERSION ::= NUMBER ( SEPARATOR NUMBER )*.
3407
3408 NUMBER ::= (0|1|2|3|4|5|6|7|8|9)+.
3409
3410 SEPARATOR ::= `version-separator' (which see)
3411 | `version-regexp-alist' (which see).
3412
3413 The NUMBER part is optional if SEPARATOR is a match for an element
3414 in `version-regexp-alist'.
3415
3416 As an example of valid version syntax:
3417
3418 1.0pre2 1.0.7.5 22.8beta3 0.9alpha1 6.9.30Beta
3419
3420 As an example of invalid version syntax:
3421
3422 1.0prepre2 1.0..7.5 22.8X3 alpha3.2 .5
3423
3424 As an example of version convertion:
3425
3426 String Version Integer List Version
3427 \"1.0.7.5\" (1 0 7 5)
3428 \"1.0pre2\" (1 0 -1 2)
3429 \"1.0PRE2\" (1 0 -1 2)
3430 \"22.8beta3\" (22 8 -2 3)
3431 \"22.8Beta3\" (22 8 -2 3)
3432 \"0.9alpha1\" (0 9 -3 1)
3433 \"0.9AlphA1\" (0 9 -3 1)
3434 \"0.9alpha\" (0 9 -3)
3435
3436 See documentation for `version-separator' and `version-regexp-alist'."
3437 (or (and (stringp ver) (> (length ver) 0))
3438 (error "Invalid version string: '%s'" ver))
3439 ;; Change .x.y to 0.x.y
3440 (if (and (>= (length ver) (length version-separator))
3441 (string-equal (substring ver 0 (length version-separator))
3442 version-separator))
3443 (setq ver (concat "0" ver)))
3444 (save-match-data
3445 (let ((i 0)
3446 (case-fold-search t) ; ignore case in matching
3447 lst s al)
3448 (while (and (setq s (string-match "[0-9]+" ver i))
3449 (= s i))
3450 ;; handle numeric part
3451 (setq lst (cons (string-to-number (substring ver i (match-end 0)))
3452 lst)
3453 i (match-end 0))
3454 ;; handle non-numeric part
3455 (when (and (setq s (string-match "[^0-9]+" ver i))
3456 (= s i))
3457 (setq s (substring ver i (match-end 0))
3458 i (match-end 0))
3459 ;; handle alpha, beta, pre, etc. separator
3460 (unless (string= s version-separator)
3461 (setq al version-regexp-alist)
3462 (while (and al (not (string-match (caar al) s)))
3463 (setq al (cdr al)))
3464 (or al (error "Invalid version syntax: '%s'" ver))
3465 (setq lst (cons (cdar al) lst)))))
3466 (if (null lst)
3467 (error "Invalid version syntax: '%s'" ver)
3468 (nreverse lst)))))
3469
3470
3471 (defun version-list-< (l1 l2)
3472 "Return t if integer list L1 is lesser than L2.
3473
3474 Note that integer list (1) is equal to (1 0), (1 0 0), (1 0 0 0),
3475 etc. That is, the trailing zeroes are irrelevant. Also, integer
3476 list (1) is greater than (1 -1) which is greater than (1 -2)
3477 which is greater than (1 -3)."
3478 (while (and l1 l2 (= (car l1) (car l2)))
3479 (setq l1 (cdr l1)
3480 l2 (cdr l2)))
3481 (cond
3482 ;; l1 not null and l2 not null
3483 ((and l1 l2) (< (car l1) (car l2)))
3484 ;; l1 null and l2 null ==> l1 length = l2 length
3485 ((and (null l1) (null l2)) nil)
3486 ;; l1 not null and l2 null ==> l1 length > l2 length
3487 (l1 (< (version-list-not-zero l1) 0))
3488 ;; l1 null and l2 not null ==> l2 length > l1 length
3489 (t (< 0 (version-list-not-zero l2)))))
3490
3491
3492 (defun version-list-= (l1 l2)
3493 "Return t if integer list L1 is equal to L2.
3494
3495 Note that integer list (1) is equal to (1 0), (1 0 0), (1 0 0 0),
3496 etc. That is, the trailing zeroes are irrelevant. Also, integer
3497 list (1) is greater than (1 -1) which is greater than (1 -2)
3498 which is greater than (1 -3)."
3499 (while (and l1 l2 (= (car l1) (car l2)))
3500 (setq l1 (cdr l1)
3501 l2 (cdr l2)))
3502 (cond
3503 ;; l1 not null and l2 not null
3504 ((and l1 l2) nil)
3505 ;; l1 null and l2 null ==> l1 length = l2 length
3506 ((and (null l1) (null l2)))
3507 ;; l1 not null and l2 null ==> l1 length > l2 length
3508 (l1 (zerop (version-list-not-zero l1)))
3509 ;; l1 null and l2 not null ==> l2 length > l1 length
3510 (t (zerop (version-list-not-zero l2)))))
3511
3512
3513 (defun version-list-<= (l1 l2)
3514 "Return t if integer list L1 is lesser than or equal to L2.
3515
3516 Note that integer list (1) is equal to (1 0), (1 0 0), (1 0 0 0),
3517 etc. That is, the trailing zeroes are irrelevant. Also, integer
3518 list (1) is greater than (1 -1) which is greater than (1 -2)
3519 which is greater than (1 -3)."
3520 (while (and l1 l2 (= (car l1) (car l2)))
3521 (setq l1 (cdr l1)
3522 l2 (cdr l2)))
3523 (cond
3524 ;; l1 not null and l2 not null
3525 ((and l1 l2) (< (car l1) (car l2)))
3526 ;; l1 null and l2 null ==> l1 length = l2 length
3527 ((and (null l1) (null l2)))
3528 ;; l1 not null and l2 null ==> l1 length > l2 length
3529 (l1 (<= (version-list-not-zero l1) 0))
3530 ;; l1 null and l2 not null ==> l2 length > l1 length
3531 (t (<= 0 (version-list-not-zero l2)))))
3532
3533 (defun version-list-not-zero (lst)
3534 "Return the first non-zero element of integer list LST.
3535
3536 If all LST elements are zeroes or LST is nil, return zero."
3537 (while (and lst (zerop (car lst)))
3538 (setq lst (cdr lst)))
3539 (if lst
3540 (car lst)
3541 ;; there is no element different of zero
3542 0))
3543
3544
3545 (defun version< (v1 v2)
3546 "Return t if version V1 is lesser than V2.
3547
3548 Note that version string \"1\" is equal to \"1.0\", \"1.0.0\", \"1.0.0.0\",
3549 etc. That is, the trailing \".0\"s are irrelevant. Also, version string \"1\"
3550 is greater than \"1pre\" which is greater than \"1beta\" which is greater than
3551 \"1alpha\"."
3552 (version-list-< (version-to-list v1) (version-to-list v2)))
3553
3554
3555 (defun version<= (v1 v2)
3556 "Return t if version V1 is lesser than or equal to V2.
3557
3558 Note that version string \"1\" is equal to \"1.0\", \"1.0.0\", \"1.0.0.0\",
3559 etc. That is, the trailing \".0\"s are irrelevant. Also, version string \"1\"
3560 is greater than \"1pre\" which is greater than \"1beta\" which is greater than
3561 \"1alpha\"."
3562 (version-list-<= (version-to-list v1) (version-to-list v2)))
3563
3564 (defun version= (v1 v2)
3565 "Return t if version V1 is equal to V2.
3566
3567 Note that version string \"1\" is equal to \"1.0\", \"1.0.0\", \"1.0.0.0\",
3568 etc. That is, the trailing \".0\"s are irrelevant. Also, version string \"1\"
3569 is greater than \"1pre\" which is greater than \"1beta\" which is greater than
3570 \"1alpha\"."
3571 (version-list-= (version-to-list v1) (version-to-list v2)))
3572
3573
3574
3575 ;; arch-tag: f7e0e6e5-70aa-4897-ae72-7a3511ec40bc
3576 ;;; subr.el ends here