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