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