(number-sequence): New function.
[bpt/emacs.git] / lisp / subr.el
CommitLineData
c88ab9ce 1;;; subr.el --- basic lisp subroutines for Emacs
630cc463 2
2308acda 3;; Copyright (C) 1985, 86, 92, 94, 95, 99, 2000, 2001, 2002, 2003
fe10cef0 4;; 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
492878e4 13;; the Free Software Foundation; either version 2, 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
EN
22;; along with GNU Emacs; see the file COPYING. If not, write to the
23;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
24;; Boston, MA 02111-1307, 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
GM
38
39\f
40(defun macro-declaration-function (macro decl)
41 "Process a declaration found in a macro definition.
42This is set as the value of the variable `macro-declaration-function'.
43MACRO is the name of the macro being defined.
44DECL is a list `(declare ...)' containing the declarations.
45The return value of this function is not used."
46 (dolist (d (cdr decl))
47 (cond ((and (consp d) (eq (car d) 'indent))
48 (put macro 'lisp-indent-function (cadr d)))
49 ((and (consp d) (eq (car d) 'debug))
50 (put macro 'edebug-form-spec (cadr d)))
51 (t
52 (message "Unknown declaration %s" d)))))
53
54(setq macro-declaration-function 'macro-declaration-function)
55
9a5336ae
JB
56\f
57;;;; Lisp language features.
58
0764e16f
SM
59(defalias 'not 'null)
60
9a5336ae
JB
61(defmacro lambda (&rest cdr)
62 "Return a lambda expression.
63A call of the form (lambda ARGS DOCSTRING INTERACTIVE BODY) is
64self-quoting; the result of evaluating the lambda expression is the
65expression itself. The lambda expression may then be treated as a
bec0d7f9
RS
66function, i.e., stored as the function value of a symbol, passed to
67funcall or mapcar, etc.
68
9a5336ae 69ARGS should take the same form as an argument list for a `defun'.
8fd68088
RS
70DOCSTRING is an optional documentation string.
71 If present, it should describe how to call the function.
72 But documentation strings are usually not useful in nameless functions.
9a5336ae
JB
73INTERACTIVE should be a call to the function `interactive', which see.
74It may also be omitted.
374d3fe7 75BODY should be a list of Lisp expressions."
9a5336ae
JB
76 ;; Note that this definition should not use backquotes; subr.el should not
77 ;; depend on backquote.el.
78 (list 'function (cons 'lambda cdr)))
79
1be152fc 80(defmacro push (newelt listname)
fa65505b 81 "Add NEWELT to the list stored in the symbol LISTNAME.
1be152fc 82This is equivalent to (setq LISTNAME (cons NEWELT LISTNAME)).
d270117a 83LISTNAME must be a symbol."
22d85d00
DL
84 (list 'setq listname
85 (list 'cons newelt listname)))
d270117a
RS
86
87(defmacro pop (listname)
88 "Return the first element of LISTNAME's value, and remove it from the list.
89LISTNAME must be a symbol whose value is a list.
90If the value is nil, `pop' returns nil but does not actually
91change the list."
54993fa4
MB
92 (list 'car
93 (list 'prog1 listname
94 (list 'setq listname (list 'cdr listname)))))
d270117a 95
debff3c3 96(defmacro when (cond &rest body)
b021ef18 97 "If COND yields non-nil, do BODY, else return nil."
debff3c3 98 (list 'if cond (cons 'progn body)))
9a5336ae 99
debff3c3 100(defmacro unless (cond &rest body)
b021ef18 101 "If COND yields nil, do BODY, else return nil."
debff3c3 102 (cons 'if (cons cond (cons nil body))))
d370591d 103
a0b0756a
RS
104(defmacro dolist (spec &rest body)
105 "(dolist (VAR LIST [RESULT]) BODY...): loop over a list.
106Evaluate BODY with VAR bound to each car from LIST, in turn.
107Then evaluate RESULT to get return value, default nil."
e4295aa1
RS
108 (let ((temp (make-symbol "--dolist-temp--")))
109 (list 'let (list (list temp (nth 1 spec)) (car spec))
110 (list 'while temp
111 (list 'setq (car spec) (list 'car temp))
112 (cons 'progn
113 (append body
114 (list (list 'setq temp (list 'cdr temp))))))
115 (if (cdr (cdr spec))
116 (cons 'progn
117 (cons (list 'setq (car spec) nil) (cdr (cdr spec))))))))
a0b0756a
RS
118
119(defmacro dotimes (spec &rest body)
120 "(dotimes (VAR COUNT [RESULT]) BODY...): loop a certain number of times.
121Evaluate BODY with VAR bound to successive integers running from 0,
122inclusive, to COUNT, exclusive. Then evaluate RESULT to get
123the return value (nil if RESULT is omitted)."
e4295aa1
RS
124 (let ((temp (make-symbol "--dotimes-temp--")))
125 (list 'let (list (list temp (nth 1 spec)) (list (car spec) 0))
126 (list 'while (list '< (car spec) temp)
127 (cons 'progn
128 (append body (list (list 'setq (car spec)
129 (list '1+ (car spec)))))))
130 (if (cdr (cdr spec))
131 (car (cdr (cdr spec)))
132 nil))))
a0b0756a 133
d370591d
RS
134(defsubst caar (x)
135 "Return the car of the car of X."
136 (car (car x)))
137
138(defsubst cadr (x)
139 "Return the car of the cdr of X."
140 (car (cdr x)))
141
142(defsubst cdar (x)
143 "Return the cdr of the car of X."
144 (cdr (car x)))
145
146(defsubst cddr (x)
147 "Return the cdr of the cdr of X."
148 (cdr (cdr x)))
e8c32c99 149
369fba5f
RS
150(defun last (x &optional n)
151 "Return the last link of the list X. Its car is the last element.
152If X is nil, return nil.
153If N is non-nil, return the Nth-to-last link of X.
154If N is bigger than the length of X, return X."
155 (if n
156 (let ((m 0) (p x))
157 (while (consp p)
158 (setq m (1+ m) p (cdr p)))
159 (if (<= n 0) p
160 (if (< n m) (nthcdr (- m n) x) x)))
6bfdc2e2 161 (while (consp (cdr x))
369fba5f
RS
162 (setq x (cdr x)))
163 x))
526d204e 164
1c1c65de
KH
165(defun butlast (x &optional n)
166 "Returns a copy of LIST with the last N elements removed."
167 (if (and n (<= n 0)) x
168 (nbutlast (copy-sequence x) n)))
169
170(defun nbutlast (x &optional n)
171 "Modifies LIST to remove the last N elements."
172 (let ((m (length x)))
173 (or n (setq n 1))
174 (and (< n m)
175 (progn
176 (if (> n 0) (setcdr (nthcdr (- (1- m) n) x) nil))
177 x))))
178
abd9177a
KH
179(defun number-sequence (from &optional to)
180 "Return a sequence of numbers from FROM to TO (both inclusive) as a list.
181The Nth element of the list is (+ FROM N) where N counts from zero.
182If TO is nil, it defaults to FROM.
183If TO is less than FROM, the value is nil."
184 (if to
185 (if (< to from)
186 (setq to (1- from)))
187 (setq to from))
188 (let* ((list (make-list (- (1+ to) from) from))
189 (tail (cdr list)))
190 (while tail
191 (setcar tail (setq from (1+ from)))
192 (setq tail (cdr tail)))
193 list))
194
13157efc 195(defun remove (elt seq)
963f49a2 196 "Return a copy of SEQ with all occurrences of ELT removed.
13157efc
GM
197SEQ must be a list, vector, or string. The comparison is done with `equal'."
198 (if (nlistp seq)
199 ;; If SEQ isn't a list, there's no need to copy SEQ because
200 ;; `delete' will return a new object.
201 (delete elt seq)
202 (delete elt (copy-sequence seq))))
203
204(defun remq (elt list)
264ef586 205 "Return a copy of LIST with all occurrences of ELT removed.
13157efc
GM
206The comparison is done with `eq'."
207 (if (memq elt list)
208 (delq elt (copy-sequence list))
209 list))
210
a176c9eb
CW
211(defun copy-tree (tree &optional vecp)
212 "Make a copy of TREE.
213If TREE is a cons cell, this recursively copies both its car and its cdr.
cfebd4db 214Contrast to `copy-sequence', which copies only along the cdrs. With second
a176c9eb
CW
215argument VECP, this copies vectors as well as conses."
216 (if (consp tree)
cfebd4db
RS
217 (let (result)
218 (while (consp tree)
219 (let ((newcar (car tree)))
220 (if (or (consp (car tree)) (and vecp (vectorp (car tree))))
221 (setq newcar (copy-tree (car tree) vecp)))
222 (push newcar result))
223 (setq tree (cdr tree)))
68b08950 224 (nconc (nreverse result) tree))
a176c9eb
CW
225 (if (and vecp (vectorp tree))
226 (let ((i (length (setq tree (copy-sequence tree)))))
227 (while (>= (setq i (1- i)) 0)
cfebd4db
RS
228 (aset tree i (copy-tree (aref tree i) vecp)))
229 tree)
230 tree)))
a176c9eb 231
8a288450
RS
232(defun assoc-default (key alist &optional test default)
233 "Find object KEY in a pseudo-alist ALIST.
234ALIST is a list of conses or objects. Each element (or the element's car,
235if it is a cons) is compared with KEY by evaluating (TEST (car elt) KEY).
236If that is non-nil, the element matches;
237then `assoc-default' returns the element's cdr, if it is a cons,
526d204e 238or DEFAULT if the element is not a cons.
8a288450
RS
239
240If no element matches, the value is nil.
241If TEST is omitted or nil, `equal' is used."
242 (let (found (tail alist) value)
243 (while (and tail (not found))
244 (let ((elt (car tail)))
245 (when (funcall (or test 'equal) (if (consp elt) (car elt) elt) key)
246 (setq found t value (if (consp elt) (cdr elt) default))))
247 (setq tail (cdr tail)))
248 value))
98aae5f6
KH
249
250(defun assoc-ignore-case (key alist)
251 "Like `assoc', but ignores differences in case and text representation.
252KEY must be a string. Upper-case and lower-case letters are treated as equal.
253Unibyte strings are converted to multibyte for comparison."
254 (let (element)
255 (while (and alist (not element))
256 (if (eq t (compare-strings key 0 nil (car (car alist)) 0 nil t))
257 (setq element (car alist)))
258 (setq alist (cdr alist)))
259 element))
260
261(defun assoc-ignore-representation (key alist)
262 "Like `assoc', but ignores differences in text representation.
264ef586 263KEY must be a string.
98aae5f6
KH
264Unibyte strings are converted to multibyte for comparison."
265 (let (element)
266 (while (and alist (not element))
267 (if (eq t (compare-strings key 0 nil (car (car alist)) 0 nil))
268 (setq element (car alist)))
269 (setq alist (cdr alist)))
270 element))
cbbc3205
GM
271
272(defun member-ignore-case (elt list)
273 "Like `member', but ignores differences in case and text representation.
274ELT must be a string. Upper-case and lower-case letters are treated as equal.
d86a3084
RS
275Unibyte strings are converted to multibyte for comparison.
276Non-strings in LIST are ignored."
277 (while (and list
278 (not (and (stringp (car list))
279 (eq t (compare-strings elt 0 nil (car list) 0 nil t)))))
242c13e8
MB
280 (setq list (cdr list)))
281 list)
cbbc3205 282
9a5336ae 283\f
9a5336ae 284;;;; Keymap support.
be9b65ac
DL
285
286(defun undefined ()
287 (interactive)
288 (ding))
289
290;Prevent the \{...} documentation construct
291;from mentioning keys that run this command.
292(put 'undefined 'suppress-keymap t)
293
294(defun suppress-keymap (map &optional nodigits)
295 "Make MAP override all normally self-inserting keys to be undefined.
296Normally, as an exception, digits and minus-sign are set to make prefix args,
297but optional second arg NODIGITS non-nil treats them like other chars."
098ba983 298 (define-key map [remap self-insert-command] 'undefined)
be9b65ac
DL
299 (or nodigits
300 (let (loop)
301 (define-key map "-" 'negative-argument)
302 ;; Make plain numbers do numeric args.
303 (setq loop ?0)
304 (while (<= loop ?9)
305 (define-key map (char-to-string loop) 'digit-argument)
306 (setq loop (1+ loop))))))
307
be9b65ac
DL
308;Moved to keymap.c
309;(defun copy-keymap (keymap)
264ef586 310; "Return a copy of KEYMAP"
be9b65ac
DL
311; (while (not (keymapp keymap))
312; (setq keymap (signal 'wrong-type-argument (list 'keymapp keymap))))
313; (if (vectorp keymap)
314; (copy-sequence keymap)
315; (copy-alist keymap)))
316
f14dbba7
KH
317(defvar key-substitution-in-progress nil
318 "Used internally by substitute-key-definition.")
319
7f2c2edd 320(defun substitute-key-definition (olddef newdef keymap &optional oldmap prefix)
be9b65ac
DL
321 "Replace OLDDEF with NEWDEF for any keys in KEYMAP now defined as OLDDEF.
322In other words, OLDDEF is replaced with NEWDEF where ever it appears.
4656b314 323Alternatively, if optional fourth argument OLDMAP is specified, we redefine
ff77cf40 324in KEYMAP as NEWDEF those keys which are defined as OLDDEF in OLDMAP."
739f2672
GM
325 ;; Don't document PREFIX in the doc string because we don't want to
326 ;; advertise it. It's meant for recursive calls only. Here's its
327 ;; meaning
264ef586 328
739f2672
GM
329 ;; If optional argument PREFIX is specified, it should be a key
330 ;; prefix, a string. Redefined bindings will then be bound to the
331 ;; original key, with PREFIX added at the front.
7f2c2edd
RS
332 (or prefix (setq prefix ""))
333 (let* ((scan (or oldmap keymap))
334 (vec1 (vector nil))
f14dbba7
KH
335 (prefix1 (vconcat prefix vec1))
336 (key-substitution-in-progress
337 (cons scan key-substitution-in-progress)))
7f2c2edd
RS
338 ;; Scan OLDMAP, finding each char or event-symbol that
339 ;; has any definition, and act on it with hack-key.
340 (while (consp scan)
341 (if (consp (car scan))
342 (let ((char (car (car scan)))
343 (defn (cdr (car scan))))
344 ;; The inside of this let duplicates exactly
345 ;; the inside of the following let that handles array elements.
346 (aset vec1 0 char)
347 (aset prefix1 (length prefix) char)
44d798af 348 (let (inner-def skipped)
7f2c2edd
RS
349 ;; Skip past menu-prompt.
350 (while (stringp (car-safe defn))
44d798af 351 (setq skipped (cons (car defn) skipped))
7f2c2edd 352 (setq defn (cdr defn)))
e025dddf
RS
353 ;; Skip past cached key-equivalence data for menu items.
354 (and (consp defn) (consp (car defn))
355 (setq defn (cdr defn)))
7f2c2edd 356 (setq inner-def defn)
e025dddf 357 ;; Look past a symbol that names a keymap.
7f2c2edd
RS
358 (while (and (symbolp inner-def)
359 (fboundp inner-def))
360 (setq inner-def (symbol-function inner-def)))
328a37ec
RS
361 (if (or (eq defn olddef)
362 ;; Compare with equal if definition is a key sequence.
363 ;; That is useful for operating on function-key-map.
364 (and (or (stringp defn) (vectorp defn))
365 (equal defn olddef)))
44d798af 366 (define-key keymap prefix1 (nconc (nreverse skipped) newdef))
f14dbba7 367 (if (and (keymapp defn)
350b7567
RS
368 ;; Avoid recursively scanning
369 ;; where KEYMAP does not have a submap.
afd9831b
RS
370 (let ((elt (lookup-key keymap prefix1)))
371 (or (null elt)
372 (keymapp elt)))
350b7567 373 ;; Avoid recursively rescanning keymap being scanned.
f14dbba7
KH
374 (not (memq inner-def
375 key-substitution-in-progress)))
e025dddf
RS
376 ;; If this one isn't being scanned already,
377 ;; scan it now.
7f2c2edd
RS
378 (substitute-key-definition olddef newdef keymap
379 inner-def
380 prefix1)))))
916cc49f 381 (if (vectorp (car scan))
7f2c2edd
RS
382 (let* ((array (car scan))
383 (len (length array))
384 (i 0))
385 (while (< i len)
386 (let ((char i) (defn (aref array i)))
387 ;; The inside of this let duplicates exactly
388 ;; the inside of the previous let.
389 (aset vec1 0 char)
390 (aset prefix1 (length prefix) char)
44d798af 391 (let (inner-def skipped)
7f2c2edd
RS
392 ;; Skip past menu-prompt.
393 (while (stringp (car-safe defn))
44d798af 394 (setq skipped (cons (car defn) skipped))
7f2c2edd 395 (setq defn (cdr defn)))
e025dddf
RS
396 (and (consp defn) (consp (car defn))
397 (setq defn (cdr defn)))
7f2c2edd
RS
398 (setq inner-def defn)
399 (while (and (symbolp inner-def)
400 (fboundp inner-def))
401 (setq inner-def (symbol-function inner-def)))
328a37ec
RS
402 (if (or (eq defn olddef)
403 (and (or (stringp defn) (vectorp defn))
404 (equal defn olddef)))
44d798af
RS
405 (define-key keymap prefix1
406 (nconc (nreverse skipped) newdef))
f14dbba7 407 (if (and (keymapp defn)
afd9831b
RS
408 (let ((elt (lookup-key keymap prefix1)))
409 (or (null elt)
410 (keymapp elt)))
f14dbba7
KH
411 (not (memq inner-def
412 key-substitution-in-progress)))
7f2c2edd
RS
413 (substitute-key-definition olddef newdef keymap
414 inner-def
415 prefix1)))))
97fd9abf
RS
416 (setq i (1+ i))))
417 (if (char-table-p (car scan))
418 (map-char-table
419 (function (lambda (char defn)
420 (let ()
421 ;; The inside of this let duplicates exactly
422 ;; the inside of the previous let,
423 ;; except that it uses set-char-table-range
424 ;; instead of define-key.
425 (aset vec1 0 char)
426 (aset prefix1 (length prefix) char)
427 (let (inner-def skipped)
428 ;; Skip past menu-prompt.
429 (while (stringp (car-safe defn))
430 (setq skipped (cons (car defn) skipped))
431 (setq defn (cdr defn)))
432 (and (consp defn) (consp (car defn))
433 (setq defn (cdr defn)))
434 (setq inner-def defn)
435 (while (and (symbolp inner-def)
436 (fboundp inner-def))
437 (setq inner-def (symbol-function inner-def)))
438 (if (or (eq defn olddef)
439 (and (or (stringp defn) (vectorp defn))
440 (equal defn olddef)))
9a5114ac
RS
441 (define-key keymap prefix1
442 (nconc (nreverse skipped) newdef))
97fd9abf
RS
443 (if (and (keymapp defn)
444 (let ((elt (lookup-key keymap prefix1)))
445 (or (null elt)
446 (keymapp elt)))
447 (not (memq inner-def
448 key-substitution-in-progress)))
449 (substitute-key-definition olddef newdef keymap
450 inner-def
451 prefix1)))))))
452 (car scan)))))
7f2c2edd 453 (setq scan (cdr scan)))))
9a5336ae 454
4ced66fd 455(defun define-key-after (keymap key definition &optional after)
4434d61b
RS
456 "Add binding in KEYMAP for KEY => DEFINITION, right after AFTER's binding.
457This is like `define-key' except that the binding for KEY is placed
458just after the binding for the event AFTER, instead of at the beginning
c34a9d34
RS
459of the map. Note that AFTER must be an event type (like KEY), NOT a command
460\(like DEFINITION).
461
4ced66fd 462If AFTER is t or omitted, the new binding goes at the end of the keymap.
08b1f8a1 463AFTER should be a single event type--a symbol or a character, not a sequence.
c34a9d34 464
4ced66fd 465Bindings are always added before any inherited map.
c34a9d34 466
4ced66fd
DL
467The order of bindings in a keymap matters when it is used as a menu."
468 (unless after (setq after t))
4434d61b
RS
469 (or (keymapp keymap)
470 (signal 'wrong-type-argument (list 'keymapp keymap)))
08b1f8a1
GM
471 (setq key
472 (if (<= (length key) 1) (aref key 0)
473 (setq keymap (lookup-key keymap
474 (apply 'vector
475 (butlast (mapcar 'identity key)))))
476 (aref key (1- (length key)))))
477 (let ((tail keymap) done inserted)
4434d61b
RS
478 (while (and (not done) tail)
479 ;; Delete any earlier bindings for the same key.
08b1f8a1 480 (if (eq (car-safe (car (cdr tail))) key)
4434d61b 481 (setcdr tail (cdr (cdr tail))))
08b1f8a1
GM
482 ;; If we hit an included map, go down that one.
483 (if (keymapp (car tail)) (setq tail (car tail)))
4434d61b
RS
484 ;; When we reach AFTER's binding, insert the new binding after.
485 ;; If we reach an inherited keymap, insert just before that.
113d28a8 486 ;; If we reach the end of this keymap, insert at the end.
c34a9d34
RS
487 (if (or (and (eq (car-safe (car tail)) after)
488 (not (eq after t)))
113d28a8
RS
489 (eq (car (cdr tail)) 'keymap)
490 (null (cdr tail)))
4434d61b 491 (progn
113d28a8
RS
492 ;; Stop the scan only if we find a parent keymap.
493 ;; Keep going past the inserted element
494 ;; so we can delete any duplications that come later.
495 (if (eq (car (cdr tail)) 'keymap)
496 (setq done t))
497 ;; Don't insert more than once.
498 (or inserted
08b1f8a1 499 (setcdr tail (cons (cons key definition) (cdr tail))))
113d28a8 500 (setq inserted t)))
4434d61b
RS
501 (setq tail (cdr tail)))))
502
51fa3961 503
d128fe85
RS
504(defmacro kbd (keys)
505 "Convert KEYS to the internal Emacs key representation.
506KEYS should be a string constant in the format used for
507saving keyboard macros (see `insert-kbd-macro')."
508 (read-kbd-macro keys))
509
8bed5e3d
RS
510(put 'keyboard-translate-table 'char-table-extra-slots 0)
511
9a5336ae
JB
512(defun keyboard-translate (from to)
513 "Translate character FROM to TO at a low level.
514This function creates a `keyboard-translate-table' if necessary
515and then modifies one entry in it."
8bed5e3d
RS
516 (or (char-table-p keyboard-translate-table)
517 (setq keyboard-translate-table
518 (make-char-table 'keyboard-translate-table nil)))
9a5336ae
JB
519 (aset keyboard-translate-table from to))
520
521\f
264ef586 522;;;; The global keymap tree.
9a5336ae
JB
523
524;;; global-map, esc-map, and ctl-x-map have their values set up in
525;;; keymap.c; we just give them docstrings here.
526
527(defvar global-map nil
528 "Default global keymap mapping Emacs keyboard input into commands.
529The value is a keymap which is usually (but not necessarily) Emacs's
530global map.")
531
532(defvar esc-map nil
533 "Default keymap for ESC (meta) commands.
534The normal global definition of the character ESC indirects to this keymap.")
535
536(defvar ctl-x-map nil
537 "Default keymap for C-x commands.
538The normal global definition of the character C-x indirects to this keymap.")
539
540(defvar ctl-x-4-map (make-sparse-keymap)
03eeb110 541 "Keymap for subcommands of C-x 4.")
059184dd 542(defalias 'ctl-x-4-prefix ctl-x-4-map)
9a5336ae
JB
543(define-key ctl-x-map "4" 'ctl-x-4-prefix)
544
545(defvar ctl-x-5-map (make-sparse-keymap)
546 "Keymap for frame commands.")
059184dd 547(defalias 'ctl-x-5-prefix ctl-x-5-map)
9a5336ae
JB
548(define-key ctl-x-map "5" 'ctl-x-5-prefix)
549
0f03054a 550\f
9a5336ae
JB
551;;;; Event manipulation functions.
552
da16e648
KH
553;; The call to `read' is to ensure that the value is computed at load time
554;; and not compiled into the .elc file. The value is negative on most
555;; machines, but not on all!
556(defconst listify-key-sequence-1 (logior 128 (read "?\\M-\\^@")))
114137b8 557
cde6d7e3
RS
558(defun listify-key-sequence (key)
559 "Convert a key sequence to a list of events."
560 (if (vectorp key)
561 (append key nil)
562 (mapcar (function (lambda (c)
563 (if (> c 127)
114137b8 564 (logxor c listify-key-sequence-1)
cde6d7e3
RS
565 c)))
566 (append key nil))))
567
53e5a4e8
RS
568(defsubst eventp (obj)
569 "True if the argument is an event object."
570 (or (integerp obj)
571 (and (symbolp obj)
572 (get obj 'event-symbol-elements))
573 (and (consp obj)
574 (symbolp (car obj))
575 (get (car obj) 'event-symbol-elements))))
576
577(defun event-modifiers (event)
578 "Returns a list of symbols representing the modifier keys in event EVENT.
579The elements of the list may include `meta', `control',
32295976
RS
580`shift', `hyper', `super', `alt', `click', `double', `triple', `drag',
581and `down'."
53e5a4e8
RS
582 (let ((type event))
583 (if (listp type)
584 (setq type (car type)))
585 (if (symbolp type)
586 (cdr (get type 'event-symbol-elements))
587 (let ((list nil))
da16e648 588 (or (zerop (logand type ?\M-\^@))
53e5a4e8 589 (setq list (cons 'meta list)))
da16e648 590 (or (and (zerop (logand type ?\C-\^@))
53e5a4e8
RS
591 (>= (logand type 127) 32))
592 (setq list (cons 'control list)))
da16e648 593 (or (and (zerop (logand type ?\S-\^@))
53e5a4e8
RS
594 (= (logand type 255) (downcase (logand type 255))))
595 (setq list (cons 'shift list)))
da16e648 596 (or (zerop (logand type ?\H-\^@))
53e5a4e8 597 (setq list (cons 'hyper list)))
da16e648 598 (or (zerop (logand type ?\s-\^@))
53e5a4e8 599 (setq list (cons 'super list)))
da16e648 600 (or (zerop (logand type ?\A-\^@))
53e5a4e8
RS
601 (setq list (cons 'alt list)))
602 list))))
603
d63de416
RS
604(defun event-basic-type (event)
605 "Returns the basic type of the given event (all modifiers removed).
7a0485b2 606The value is a printing character (not upper case) or a symbol."
2b0f4ba5
JB
607 (if (consp event)
608 (setq event (car event)))
d63de416
RS
609 (if (symbolp event)
610 (car (get event 'event-symbol-elements))
611 (let ((base (logand event (1- (lsh 1 18)))))
612 (downcase (if (< base 32) (logior base 64) base)))))
613
0f03054a
RS
614(defsubst mouse-movement-p (object)
615 "Return non-nil if OBJECT is a mouse movement event."
616 (and (consp object)
617 (eq (car object) 'mouse-movement)))
618
619(defsubst event-start (event)
620 "Return the starting position of EVENT.
621If EVENT is a mouse press or a mouse click, this returns the location
622of the event.
623If EVENT is a drag, this returns the drag's starting position.
624The return value is of the form
e55c21be 625 (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
0f03054a 626The `posn-' functions access elements of such lists."
5ef6a86d
SM
627 (if (consp event) (nth 1 event)
628 (list (selected-window) (point) '(0 . 0) 0)))
0f03054a
RS
629
630(defsubst event-end (event)
631 "Return the ending location of EVENT. EVENT should be a click or drag event.
632If EVENT is a click event, this function is the same as `event-start'.
633The return value is of the form
e55c21be 634 (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
0f03054a 635The `posn-' functions access elements of such lists."
5ef6a86d
SM
636 (if (consp event) (nth (if (consp (nth 2 event)) 2 1) event)
637 (list (selected-window) (point) '(0 . 0) 0)))
0f03054a 638
32295976
RS
639(defsubst event-click-count (event)
640 "Return the multi-click count of EVENT, a click or drag event.
641The return value is a positive integer."
5ef6a86d 642 (if (and (consp event) (integerp (nth 2 event))) (nth 2 event) 1))
32295976 643
0f03054a
RS
644(defsubst posn-window (position)
645 "Return the window in POSITION.
646POSITION should be a list of the form
e55c21be 647 (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
0f03054a
RS
648as returned by the `event-start' and `event-end' functions."
649 (nth 0 position))
650
651(defsubst posn-point (position)
652 "Return the buffer location in POSITION.
653POSITION should be a list of the form
e55c21be 654 (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
0f03054a 655as returned by the `event-start' and `event-end' functions."
15db4e0e
JB
656 (if (consp (nth 1 position))
657 (car (nth 1 position))
658 (nth 1 position)))
0f03054a 659
e55c21be
RS
660(defsubst posn-x-y (position)
661 "Return the x and y coordinates in POSITION.
0f03054a 662POSITION should be a list of the form
e55c21be 663 (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
0f03054a
RS
664as returned by the `event-start' and `event-end' functions."
665 (nth 2 position))
666
ed627e08 667(defun posn-col-row (position)
dbbcac56 668 "Return the column and row in POSITION, measured in characters.
e55c21be
RS
669POSITION should be a list of the form
670 (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
ed627e08
RS
671as returned by the `event-start' and `event-end' functions.
672For a scroll-bar event, the result column is 0, and the row
673corresponds to the vertical position of the click in the scroll bar."
3a24cce0 674 (let* ((pair (nth 2 position))
194600a8 675 (window (posn-window position)))
dbbcac56
KH
676 (if (eq (if (consp (nth 1 position))
677 (car (nth 1 position))
678 (nth 1 position))
ed627e08
RS
679 'vertical-scroll-bar)
680 (cons 0 (scroll-bar-scale pair (1- (window-height window))))
dbbcac56
KH
681 (if (eq (if (consp (nth 1 position))
682 (car (nth 1 position))
683 (nth 1 position))
ed627e08
RS
684 'horizontal-scroll-bar)
685 (cons (scroll-bar-scale pair (window-width window)) 0)
9ba60df9
RS
686 (let* ((frame (if (framep window) window (window-frame window)))
687 (x (/ (car pair) (frame-char-width frame)))
ee24a852 688 (y (/ (cdr pair) (+ (frame-char-height frame)
194600a8
JPW
689 (or (frame-parameter frame 'line-spacing)
690 default-line-spacing
691 0)))))
ed627e08 692 (cons x y))))))
e55c21be 693
0f03054a
RS
694(defsubst posn-timestamp (position)
695 "Return the timestamp of POSITION.
696POSITION should be a list of the form
e55c21be 697 (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
f415c00c 698as returned by the `event-start' and `event-end' functions."
0f03054a 699 (nth 3 position))
9a5336ae 700
0f03054a 701\f
9a5336ae
JB
702;;;; Obsolescent names for functions.
703
059184dd
ER
704(defalias 'dot 'point)
705(defalias 'dot-marker 'point-marker)
706(defalias 'dot-min 'point-min)
707(defalias 'dot-max 'point-max)
708(defalias 'window-dot 'window-point)
709(defalias 'set-window-dot 'set-window-point)
710(defalias 'read-input 'read-string)
711(defalias 'send-string 'process-send-string)
712(defalias 'send-region 'process-send-region)
713(defalias 'show-buffer 'set-window-buffer)
714(defalias 'buffer-flush-undo 'buffer-disable-undo)
715(defalias 'eval-current-buffer 'eval-buffer)
716(defalias 'compiled-function-p 'byte-code-function-p)
ae1cc031 717(defalias 'define-function 'defalias)
be9b65ac 718
0cba3a0f 719(defalias 'sref 'aref)
2598a293 720(make-obsolete 'sref 'aref "20.4")
1c12af5c 721(make-obsolete 'char-bytes "now always returns 1." "20.4")
9af6aa14 722(make-obsolete 'chars-in-region "use (abs (- BEG END))." "20.3")
b4591b37
JB
723(make-obsolete 'dot 'point "before 19.15")
724(make-obsolete 'dot-max 'point-max "before 19.15")
725(make-obsolete 'dot-min 'point-min "before 19.15")
726(make-obsolete 'dot-marker 'point-marker "before 19.15")
727(make-obsolete 'buffer-flush-undo 'buffer-disable-undo "before 19.15")
728(make-obsolete 'baud-rate "use the baud-rate variable instead." "before 19.15")
729(make-obsolete 'compiled-function-p 'byte-code-function-p "before 19.15")
730(make-obsolete 'define-function 'defalias "20.1")
6bb762b3 731
676927b7
PJ
732(defun insert-string (&rest args)
733 "Mocklisp-compatibility insert function.
734Like the function `insert' except that any argument that is a number
735is converted into a string by expressing it in decimal."
736 (dolist (el args)
737 (insert (if (integerp el) (number-to-string el) el))))
9e028368
SM
738(make-obsolete 'insert-string 'insert "21.4")
739(defun makehash (&optional test) (make-hash-table :test (or test 'eql)))
740(make-obsolete 'makehash 'make-hash-table "21.4")
676927b7 741
9a5336ae
JB
742;; Some programs still use this as a function.
743(defun baud-rate ()
8eb93953 744 "Return the value of the `baud-rate' variable."
9a5336ae
JB
745 baud-rate)
746
0a5c0893
MB
747(defalias 'focus-frame 'ignore)
748(defalias 'unfocus-frame 'ignore)
bd292357
JB
749
750\f
751;;;; Obsolescence declarations for variables.
752
753(make-obsolete-variable 'directory-sep-char "do not use it." "21.1")
754(make-obsolete-variable 'mode-line-inverse-video "use the appropriate faces instead." "21.1")
755(make-obsolete-variable 'unread-command-char
756 "use `unread-command-events' instead. That variable is a list of events to reread, so it now uses nil to mean `no event', instead of -1."
757 "before 19.15")
758(make-obsolete-variable 'executing-macro 'executing-kbd-macro "before 19.34")
759(make-obsolete-variable 'post-command-idle-hook
760 "use timers instead, with `run-with-idle-timer'." "before 19.34")
761(make-obsolete-variable 'post-command-idle-delay
762 "use timers instead, with `run-with-idle-timer'." "before 19.34")
763
9a5336ae
JB
764\f
765;;;; Alternate names for functions - these are not being phased out.
766
059184dd
ER
767(defalias 'string= 'string-equal)
768(defalias 'string< 'string-lessp)
769(defalias 'move-marker 'set-marker)
059184dd
ER
770(defalias 'rplaca 'setcar)
771(defalias 'rplacd 'setcdr)
eb8c3be9 772(defalias 'beep 'ding) ;preserve lingual purity
059184dd
ER
773(defalias 'indent-to-column 'indent-to)
774(defalias 'backward-delete-char 'delete-backward-char)
775(defalias 'search-forward-regexp (symbol-function 're-search-forward))
776(defalias 'search-backward-regexp (symbol-function 're-search-backward))
777(defalias 'int-to-string 'number-to-string)
024ae2c6 778(defalias 'store-match-data 'set-match-data)
112f332f 779(defalias 'make-variable-frame-localizable 'make-variable-frame-local)
d6c22d46 780;; These are the XEmacs names:
475fb2fb
KH
781(defalias 'point-at-eol 'line-end-position)
782(defalias 'point-at-bol 'line-beginning-position)
37f6661a
JB
783
784;;; Should this be an obsolete name? If you decide it should, you get
785;;; to go through all the sources and change them.
059184dd 786(defalias 'string-to-int 'string-to-number)
be9b65ac 787\f
9a5336ae 788;;;; Hook manipulation functions.
be9b65ac 789
0e4d378b
RS
790(defun make-local-hook (hook)
791 "Make the hook HOOK local to the current buffer.
71c78f01
RS
792The return value is HOOK.
793
c344cf32
SM
794You never need to call this function now that `add-hook' does it for you
795if its LOCAL argument is non-nil.
796
0e4d378b
RS
797When a hook is local, its local and global values
798work in concert: running the hook actually runs all the hook
799functions listed in *either* the local value *or* the global value
800of the hook variable.
801
08b1f8a1 802This function works by making t a member of the buffer-local value,
7dd1926e
RS
803which acts as a flag to run the hook functions in the default value as
804well. This works for all normal hooks, but does not work for most
805non-normal hooks yet. We will be changing the callers of non-normal
806hooks so that they can handle localness; this has to be done one by
807one.
808
809This function does nothing if HOOK is already local in the current
810buffer.
0e4d378b
RS
811
812Do not use `make-local-variable' to make a hook variable buffer-local."
813 (if (local-variable-p hook)
814 nil
815 (or (boundp hook) (set hook nil))
816 (make-local-variable hook)
71c78f01
RS
817 (set hook (list t)))
818 hook)
8eb93953 819(make-obsolete 'make-local-hook "not necessary any more." "21.1")
0e4d378b
RS
820
821(defun add-hook (hook function &optional append local)
32295976
RS
822 "Add to the value of HOOK the function FUNCTION.
823FUNCTION is not added if already present.
824FUNCTION is added (if necessary) at the beginning of the hook list
825unless the optional argument APPEND is non-nil, in which case
826FUNCTION is added at the end.
827
0e4d378b
RS
828The optional fourth argument, LOCAL, if non-nil, says to modify
829the hook's buffer-local value rather than its default value.
61a3d8c4
RS
830This makes the hook buffer-local if needed, and it makes t a member
831of the buffer-local value. That acts as a flag to run the hook
832functions in the default value as well as in the local value.
0e4d378b 833
32295976
RS
834HOOK should be a symbol, and FUNCTION may be any valid function. If
835HOOK is void, it is first set to nil. If HOOK's value is a single
aa09b5ca 836function, it is changed to a list of functions."
be9b65ac 837 (or (boundp hook) (set hook nil))
0e4d378b 838 (or (default-boundp hook) (set-default hook nil))
08b1f8a1
GM
839 (if local (unless (local-variable-if-set-p hook)
840 (set (make-local-variable hook) (list t)))
8947a5e2
SM
841 ;; Detect the case where make-local-variable was used on a hook
842 ;; and do what we used to do.
843 (unless (and (consp (symbol-value hook)) (memq t (symbol-value hook)))
844 (setq local t)))
845 (let ((hook-value (if local (symbol-value hook) (default-value hook))))
846 ;; If the hook value is a single function, turn it into a list.
847 (when (or (not (listp hook-value)) (eq (car hook-value) 'lambda))
2248c40d 848 (setq hook-value (list hook-value)))
8947a5e2
SM
849 ;; Do the actual addition if necessary
850 (unless (member function hook-value)
851 (setq hook-value
852 (if append
853 (append hook-value (list function))
854 (cons function hook-value))))
855 ;; Set the actual variable
856 (if local (set hook hook-value) (set-default hook hook-value))))
0e4d378b
RS
857
858(defun remove-hook (hook function &optional local)
24980d16
RS
859 "Remove from the value of HOOK the function FUNCTION.
860HOOK should be a symbol, and FUNCTION may be any valid function. If
861FUNCTION isn't the value of HOOK, or, if FUNCTION doesn't appear in the
0e4d378b
RS
862list of hooks to run in HOOK, then nothing is done. See `add-hook'.
863
864The optional third argument, LOCAL, if non-nil, says to modify
865the hook's buffer-local value rather than its default value.
08b1f8a1 866This makes the hook buffer-local if needed."
8947a5e2
SM
867 (or (boundp hook) (set hook nil))
868 (or (default-boundp hook) (set-default hook nil))
08b1f8a1
GM
869 (if local (unless (local-variable-if-set-p hook)
870 (set (make-local-variable hook) (list t)))
8947a5e2
SM
871 ;; Detect the case where make-local-variable was used on a hook
872 ;; and do what we used to do.
873 (unless (and (consp (symbol-value hook)) (memq t (symbol-value hook)))
874 (setq local t)))
875 (let ((hook-value (if local (symbol-value hook) (default-value hook))))
e4da9c1c
SM
876 ;; Remove the function, for both the list and the non-list cases.
877 (if (or (not (listp hook-value)) (eq (car hook-value) 'lambda))
878 (if (equal hook-value function) (setq hook-value nil))
879 (setq hook-value (delete function (copy-sequence hook-value))))
8947a5e2
SM
880 ;; If the function is on the global hook, we need to shadow it locally
881 ;;(when (and local (member function (default-value hook))
882 ;; (not (member (cons 'not function) hook-value)))
883 ;; (push (cons 'not function) hook-value))
884 ;; Set the actual variable
1087f3e6
RS
885 (if (not local)
886 (set-default hook hook-value)
887 (if (equal hook-value '(t))
888 (kill-local-variable hook)
889 (set hook hook-value)))))
6e3af630 890
c8bfa689 891(defun add-to-list (list-var element &optional append)
8851c1f0 892 "Add to the value of LIST-VAR the element ELEMENT if it isn't there yet.
9f0b1f09 893The test for presence of ELEMENT is done with `equal'.
c8bfa689
MB
894If ELEMENT is added, it is added at the beginning of the list,
895unless the optional argument APPEND is non-nil, in which case
896ELEMENT is added at the end.
508bcbca 897
daebae3d
PJ
898The return value is the new value of LIST-VAR.
899
8851c1f0
RS
900If you want to use `add-to-list' on a variable that is not defined
901until a certain package is loaded, you should put the call to `add-to-list'
902into a hook function that will be run only after loading the package.
903`eval-after-load' provides one way to do this. In some cases
904other hooks, such as major mode hooks, can do the job."
15171a06
KH
905 (if (member element (symbol-value list-var))
906 (symbol-value list-var)
c8bfa689
MB
907 (set list-var
908 (if append
909 (append (symbol-value list-var) (list element))
910 (cons element (symbol-value list-var))))))
448a0170
MB
911
912\f
913;;; Load history
914
a2c4ae01
RS
915;;; (defvar symbol-file-load-history-loaded nil
916;;; "Non-nil means we have loaded the file `fns-VERSION.el' in `exec-directory'.
917;;; That file records the part of `load-history' for preloaded files,
918;;; which is cleared out before dumping to make Emacs smaller.")
919
920;;; (defun load-symbol-file-load-history ()
921;;; "Load the file `fns-VERSION.el' in `exec-directory' if not already done.
922;;; That file records the part of `load-history' for preloaded files,
923;;; which is cleared out before dumping to make Emacs smaller."
924;;; (unless symbol-file-load-history-loaded
925;;; (load (expand-file-name
926;;; ;; fns-XX.YY.ZZ.el does not work on DOS filesystem.
927;;; (if (eq system-type 'ms-dos)
928;;; "fns.el"
929;;; (format "fns-%s.el" emacs-version))
930;;; exec-directory)
931;;; ;; The file name fns-%s.el already has a .el extension.
932;;; nil nil t)
933;;; (setq symbol-file-load-history-loaded t)))
448a0170
MB
934
935(defun symbol-file (function)
936 "Return the input source from which FUNCTION was loaded.
937The value is normally a string that was passed to `load':
938either an absolute file name, or a library name
939\(with no directory name and no `.el' or `.elc' at the end).
940It can also be nil, if the definition is not associated with any file."
e9f13a95
SM
941 (if (and (symbolp function) (fboundp function)
942 (eq 'autoload (car-safe (symbol-function function))))
943 (nth 1 (symbol-function function))
944 (let ((files load-history)
cb21744e 945 file)
e9f13a95 946 (while files
12320833 947 (if (member function (cdr (car files)))
e9f13a95
SM
948 (setq file (car (car files)) files nil))
949 (setq files (cdr files)))
950 file)))
448a0170 951
be9b65ac 952\f
9a5336ae
JB
953;;;; Specifying things to do after certain files are loaded.
954
955(defun eval-after-load (file form)
956 "Arrange that, if FILE is ever loaded, FORM will be run at that time.
957This makes or adds to an entry on `after-load-alist'.
90914938 958If FILE is already loaded, evaluate FORM right now.
12c7071c 959It does nothing if FORM is already on the list for FILE.
19594307
DL
960FILE must match exactly. Normally FILE is the name of a library,
961with no directory or extension specified, since that is how `load'
a2d7836f
SM
962is normally called.
963FILE can also be a feature (i.e. a symbol), in which case FORM is
964evaluated whenever that feature is `provide'd."
12c7071c 965 (let ((elt (assoc file after-load-alist)))
a2d7836f
SM
966 ;; Make sure there is an element for FILE.
967 (unless elt (setq elt (list file)) (push elt after-load-alist))
968 ;; Add FORM to the element if it isn't there.
969 (unless (member form (cdr elt))
970 (nconc elt (list form))
971 ;; If the file has been loaded already, run FORM right away.
972 (if (if (symbolp file)
973 (featurep file)
974 ;; Make sure `load-history' contains the files dumped with
975 ;; Emacs for the case that FILE is one of them.
e9f13a95 976 ;; (load-symbol-file-load-history)
a2d7836f
SM
977 (assoc file load-history))
978 (eval form))))
9a5336ae
JB
979 form)
980
981(defun eval-next-after-load (file)
982 "Read the following input sexp, and run it whenever FILE is loaded.
983This makes or adds to an entry on `after-load-alist'.
984FILE should be the name of a library, with no directory name."
985 (eval-after-load file (read)))
7aaacaff
RS
986\f
987;;; make-network-process wrappers
988
989(if (featurep 'make-network-process)
990 (progn
991
992(defun open-network-stream (name buffer host service)
993 "Open a TCP connection for a service to a host.
994Returns a subprocess-object to represent the connection.
995Input and output work as for subprocesses; `delete-process' closes it.
996Args are NAME BUFFER HOST SERVICE.
997NAME is name for process. It is modified if necessary to make it unique.
998BUFFER is the buffer (or buffer-name) to associate with the process.
999 Process output goes at end of that buffer, unless you specify
1000 an output stream or filter function to handle the output.
1001 BUFFER may be also nil, meaning that this process is not associated
1002 with any buffer
1003Third arg is name of the host to connect to, or its IP address.
1004Fourth arg SERVICE is name of the service desired, or an integer
1005specifying a port number to connect to."
1006 (make-network-process :name name :buffer buffer
1007 :host host :service service))
1008
1009(defun open-network-stream-nowait (name buffer host service &optional sentinel filter)
1010 "Initiate connection to a TCP connection for a service to a host.
1011It returns nil if non-blocking connects are not supported; otherwise,
1012it returns a subprocess-object to represent the connection.
1013
1014This function is similar to `open-network-stream', except that this
1015function returns before the connection is established. When the
1016connection is completed, the sentinel function will be called with
1017second arg matching `open' (if successful) or `failed' (on error).
1018
1019Args are NAME BUFFER HOST SERVICE SENTINEL FILTER.
1020NAME, BUFFER, HOST, and SERVICE are as for `open-network-stream'.
1021Optional args, SENTINEL and FILTER specifies the sentinel and filter
1022functions to be used for this network stream."
1023 (if (featurep 'make-network-process '(:nowait t))
1024 (make-network-process :name name :buffer buffer :nowait t
1025 :host host :service service
1026 :filter filter :sentinel sentinel)))
1027
1028(defun open-network-stream-server (name buffer service &optional sentinel filter)
1029 "Create a network server process for a TCP service.
1030It returns nil if server processes are not supported; otherwise,
1031it returns a subprocess-object to represent the server.
1032
1033When a client connects to the specified service, a new subprocess
1034is created to handle the new connection, and the sentinel function
1035is called for the new process.
1036
1037Args are NAME BUFFER SERVICE SENTINEL FILTER.
1038NAME is name for the server process. Client processes are named by
1039appending the ip-address and port number of the client to NAME.
1040BUFFER is the buffer (or buffer-name) to associate with the server
1041process. Client processes will not get a buffer if a process filter
1042is specified or BUFFER is nil; otherwise, a new buffer is created for
1043the client process. The name is similar to the process name.
1044Third arg SERVICE is name of the service desired, or an integer
1045specifying a port number to connect to. It may also be t to selected
1046an unused port number for the server.
1047Optional args, SENTINEL and FILTER specifies the sentinel and filter
1048functions to be used for the client processes; the server process
1049does not use these function."
1050 (if (featurep 'make-network-process '(:server t))
1051 (make-network-process :name name :buffer buffer
1052 :service service :server t :noquery t
1053 :sentinel sentinel :filter filter)))
1054
1055)) ;; (featurep 'make-network-process)
1056
1057
1058;; compatibility
1059
1060(defun process-kill-without-query (process &optional flag)
1061 "Say no query needed if PROCESS is running when Emacs is exited.
1062Optional second argument if non-nil says to require a query.
264ef586 1063Value is t if a query was formerly required.
7aaacaff
RS
1064New code should not use this function; use `process-query-on-exit-flag'
1065or `set-process-query-on-exit-flag' instead."
1066 (let ((old (process-query-on-exit-flag process)))
1067 (set-process-query-on-exit-flag process nil)
1068 old))
9a5336ae 1069
34368d12
KS
1070;; process plist management
1071
1072(defun process-get (process propname)
1073 "Return the value of PROCESS' PROPNAME property.
1074This is the last value stored with `(process-put PROCESS PROPNAME VALUE)'."
1075 (plist-get (process-plist process) propname))
1076
1077(defun process-put (process propname value)
1078 "Change PROCESS' PROPNAME property to VALUE.
1079It can be retrieved with `(process-get PROCESS PROPNAME)'."
f1180544 1080 (set-process-plist process
34368d12
KS
1081 (plist-put (process-plist process) propname value)))
1082
9a5336ae
JB
1083\f
1084;;;; Input and display facilities.
1085
77a5664f 1086(defvar read-quoted-char-radix 8
1ba764de 1087 "*Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
77a5664f
RS
1088Legitimate radix values are 8, 10 and 16.")
1089
1090(custom-declare-variable-early
264ef586 1091 'read-quoted-char-radix 8
77a5664f 1092 "*Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
1ba764de
RS
1093Legitimate radix values are 8, 10 and 16."
1094 :type '(choice (const 8) (const 10) (const 16))
1095 :group 'editing-basics)
1096
9a5336ae 1097(defun read-quoted-char (&optional prompt)
2444730b
RS
1098 "Like `read-char', but do not allow quitting.
1099Also, if the first character read is an octal digit,
1100we read any number of octal digits and return the
569b03f2 1101specified character code. Any nondigit terminates the sequence.
1ba764de 1102If the terminator is RET, it is discarded;
2444730b
RS
1103any other terminator is used itself as input.
1104
569b03f2
RS
1105The optional argument PROMPT specifies a string to use to prompt the user.
1106The variable `read-quoted-char-radix' controls which radix to use
1107for numeric input."
2444730b
RS
1108 (let ((message-log-max nil) done (first t) (code 0) char)
1109 (while (not done)
1110 (let ((inhibit-quit first)
42e636f0
KH
1111 ;; Don't let C-h get the help message--only help function keys.
1112 (help-char nil)
1113 (help-form
1114 "Type the special character you want to use,
2444730b 1115or the octal character code.
1ba764de 1116RET terminates the character code and is discarded;
2444730b 1117any other non-digit terminates the character code and is then used as input."))
3f0161d0 1118 (setq char (read-event (and prompt (format "%s-" prompt)) t))
9a5336ae 1119 (if inhibit-quit (setq quit-flag nil)))
3f0161d0
SM
1120 ;; Translate TAB key into control-I ASCII character, and so on.
1121 ;; Note: `read-char' does it using the `ascii-character' property.
1122 ;; We could try and use read-key-sequence instead, but then C-q ESC
1123 ;; or C-q C-x might not return immediately since ESC or C-x might be
1124 ;; bound to some prefix in function-key-map or key-translation-map.
1125 (and char
1126 (let ((translated (lookup-key function-key-map (vector char))))
1127 (if (arrayp translated)
1128 (setq char (aref translated 0)))))
9a5336ae 1129 (cond ((null char))
1ba764de 1130 ((not (integerp char))
177aef40 1131 (setq unread-command-events (listify-key-sequence (this-single-command-raw-keys))
1ba764de 1132 done t))
bf896a1b
RS
1133 ((/= (logand char ?\M-\^@) 0)
1134 ;; Turn a meta-character into a character with the 0200 bit set.
1135 (setq code (logior (logand char (lognot ?\M-\^@)) 128)
1136 done t))
1ba764de
RS
1137 ((and (<= ?0 char) (< char (+ ?0 (min 10 read-quoted-char-radix))))
1138 (setq code (+ (* code read-quoted-char-radix) (- char ?0)))
1139 (and prompt (setq prompt (message "%s %c" prompt char))))
1140 ((and (<= ?a (downcase char))
1141 (< (downcase char) (+ ?a -10 (min 26 read-quoted-char-radix))))
92304bc8
RS
1142 (setq code (+ (* code read-quoted-char-radix)
1143 (+ 10 (- (downcase char) ?a))))
91a6acc3 1144 (and prompt (setq prompt (message "%s %c" prompt char))))
1ba764de 1145 ((and (not first) (eq char ?\C-m))
2444730b
RS
1146 (setq done t))
1147 ((not first)
177aef40 1148 (setq unread-command-events (listify-key-sequence (this-single-command-raw-keys))
2444730b
RS
1149 done t))
1150 (t (setq code char
1151 done t)))
1152 (setq first nil))
bf896a1b 1153 code))
9a5336ae 1154
44071d6b
RS
1155(defun read-passwd (prompt &optional confirm default)
1156 "Read a password, prompting with PROMPT. Echo `.' for each character typed.
e0e4cb7a 1157End with RET, LFD, or ESC. DEL or C-h rubs out. C-u kills line.
44071d6b
RS
1158Optional argument CONFIRM, if non-nil, then read it twice to make sure.
1159Optional DEFAULT is a default password to use instead of empty input."
1160 (if confirm
1161 (let (success)
1162 (while (not success)
1163 (let ((first (read-passwd prompt nil default))
1164 (second (read-passwd "Confirm password: " nil default)))
1165 (if (equal first second)
fe10cef0
GM
1166 (progn
1167 (and (arrayp second) (fillarray second ?\0))
1168 (setq success first))
1169 (and (arrayp first) (fillarray first ?\0))
1170 (and (arrayp second) (fillarray second ?\0))
44071d6b
RS
1171 (message "Password not repeated accurately; please start over")
1172 (sit-for 1))))
1173 success)
1174 (let ((pass nil)
1175 (c 0)
1176 (echo-keystrokes 0)
1177 (cursor-in-echo-area t))
1178 (while (progn (message "%s%s"
1179 prompt
1180 (make-string (length pass) ?.))
42ccb7c8 1181 (setq c (read-char-exclusive nil t))
44071d6b 1182 (and (/= c ?\r) (/= c ?\n) (/= c ?\e)))
719349f6 1183 (clear-this-command-keys)
44071d6b 1184 (if (= c ?\C-u)
fe10cef0
GM
1185 (progn
1186 (and (arrayp pass) (fillarray pass ?\0))
1187 (setq pass ""))
44071d6b 1188 (if (and (/= c ?\b) (/= c ?\177))
fe10cef0
GM
1189 (let* ((new-char (char-to-string c))
1190 (new-pass (concat pass new-char)))
1191 (and (arrayp pass) (fillarray pass ?\0))
1192 (fillarray new-char ?\0)
1193 (setq c ?\0)
1194 (setq pass new-pass))
44071d6b 1195 (if (> (length pass) 0)
fe10cef0
GM
1196 (let ((new-pass (substring pass 0 -1)))
1197 (and (arrayp pass) (fillarray pass ?\0))
1198 (setq pass new-pass))))))
44071d6b
RS
1199 (message nil)
1200 (or pass default ""))))
e0e4cb7a 1201\f
2493767e
RS
1202;;; Atomic change groups.
1203
69cae2d4
RS
1204(defmacro atomic-change-group (&rest body)
1205 "Perform BODY as an atomic change group.
1206This means that if BODY exits abnormally,
1207all of its changes to the current buffer are undone.
b9ab4064 1208This works regardless of whether undo is enabled in the buffer.
69cae2d4
RS
1209
1210This mechanism is transparent to ordinary use of undo;
1211if undo is enabled in the buffer and BODY succeeds, the
1212user can undo the change normally."
1213 (let ((handle (make-symbol "--change-group-handle--"))
1214 (success (make-symbol "--change-group-success--")))
1215 `(let ((,handle (prepare-change-group))
1216 (,success nil))
1217 (unwind-protect
1218 (progn
1219 ;; This is inside the unwind-protect because
1220 ;; it enables undo if that was disabled; we need
1221 ;; to make sure that it gets disabled again.
1222 (activate-change-group ,handle)
1223 ,@body
1224 (setq ,success t))
1225 ;; Either of these functions will disable undo
1226 ;; if it was disabled before.
1227 (if ,success
1228 (accept-change-group ,handle)
1229 (cancel-change-group ,handle))))))
1230
1231(defun prepare-change-group (&optional buffer)
1232 "Return a handle for the current buffer's state, for a change group.
1233If you specify BUFFER, make a handle for BUFFER's state instead.
1234
1235Pass the handle to `activate-change-group' afterward to initiate
1236the actual changes of the change group.
1237
1238To finish the change group, call either `accept-change-group' or
1239`cancel-change-group' passing the same handle as argument. Call
1240`accept-change-group' to accept the changes in the group as final;
1241call `cancel-change-group' to undo them all. You should use
1242`unwind-protect' to make sure the group is always finished. The call
1243to `activate-change-group' should be inside the `unwind-protect'.
1244Once you finish the group, don't use the handle again--don't try to
1245finish the same group twice. For a simple example of correct use, see
1246the source code of `atomic-change-group'.
1247
1248The handle records only the specified buffer. To make a multibuffer
1249change group, call this function once for each buffer you want to
1250cover, then use `nconc' to combine the returned values, like this:
1251
1252 (nconc (prepare-change-group buffer-1)
1253 (prepare-change-group buffer-2))
1254
1255You can then activate that multibuffer change group with a single
1256call to `activate-change-group' and finish it with a single call
1257to `accept-change-group' or `cancel-change-group'."
1258
1259 (list (cons (current-buffer) buffer-undo-list)))
1260
1261(defun activate-change-group (handle)
1262 "Activate a change group made with `prepare-change-group' (which see)."
1263 (dolist (elt handle)
1264 (with-current-buffer (car elt)
1265 (if (eq buffer-undo-list t)
1266 (setq buffer-undo-list nil)))))
1267
1268(defun accept-change-group (handle)
1269 "Finish a change group made with `prepare-change-group' (which see).
1270This finishes the change group by accepting its changes as final."
1271 (dolist (elt handle)
1272 (with-current-buffer (car elt)
1273 (if (eq elt t)
1274 (setq buffer-undo-list t)))))
1275
1276(defun cancel-change-group (handle)
1277 "Finish a change group made with `prepare-change-group' (which see).
1278This finishes the change group by reverting all of its changes."
1279 (dolist (elt handle)
1280 (with-current-buffer (car elt)
1281 (setq elt (cdr elt))
264ef586 1282 (let ((old-car
69cae2d4
RS
1283 (if (consp elt) (car elt)))
1284 (old-cdr
1285 (if (consp elt) (cdr elt))))
1286 ;; Temporarily truncate the undo log at ELT.
1287 (when (consp elt)
1288 (setcar elt nil) (setcdr elt nil))
1289 (unless (eq last-command 'undo) (undo-start))
1290 ;; Make sure there's no confusion.
1291 (when (and (consp elt) (not (eq elt (last pending-undo-list))))
1292 (error "Undoing to some unrelated state"))
1293 ;; Undo it all.
1294 (while pending-undo-list (undo-more 1))
1295 ;; Reset the modified cons cell ELT to its original content.
1296 (when (consp elt)
1297 (setcar elt old-car)
1298 (setcdr elt old-cdr))
1299 ;; Revert the undo info to what it was when we grabbed the state.
1300 (setq buffer-undo-list elt)))))
1301\f
a9d956be
RS
1302;; For compatibility.
1303(defalias 'redraw-modeline 'force-mode-line-update)
1304
9a5336ae 1305(defun force-mode-line-update (&optional all)
dc756612
RS
1306 "Force the mode line of the current buffer to be redisplayed.
1307With optional non-nil ALL, force redisplay of all mode lines."
9a5336ae
JB
1308 (if all (save-excursion (set-buffer (other-buffer))))
1309 (set-buffer-modified-p (buffer-modified-p)))
1310
aa3b4ded 1311(defun momentary-string-display (string pos &optional exit-char message)
be9b65ac
DL
1312 "Momentarily display STRING in the buffer at POS.
1313Display remains until next character is typed.
1314If the char is EXIT-CHAR (optional third arg, default is SPC) it is swallowed;
1315otherwise it is then available as input (as a command if nothing else).
1316Display MESSAGE (optional fourth arg) in the echo area.
1317If MESSAGE is nil, instructions to type EXIT-CHAR are displayed there."
1318 (or exit-char (setq exit-char ?\ ))
c306e0e0 1319 (let ((inhibit-read-only t)
ca2ec1c5
RS
1320 ;; Don't modify the undo list at all.
1321 (buffer-undo-list t)
be9b65ac
DL
1322 (modified (buffer-modified-p))
1323 (name buffer-file-name)
1324 insert-end)
1325 (unwind-protect
1326 (progn
1327 (save-excursion
1328 (goto-char pos)
1329 ;; defeat file locking... don't try this at home, kids!
1330 (setq buffer-file-name nil)
1331 (insert-before-markers string)
3eec84bf
RS
1332 (setq insert-end (point))
1333 ;; If the message end is off screen, recenter now.
024ae2c6 1334 (if (< (window-end nil t) insert-end)
3eec84bf
RS
1335 (recenter (/ (window-height) 2)))
1336 ;; If that pushed message start off the screen,
1337 ;; scroll to start it at the top of the screen.
1338 (move-to-window-line 0)
1339 (if (> (point) pos)
1340 (progn
1341 (goto-char pos)
1342 (recenter 0))))
be9b65ac
DL
1343 (message (or message "Type %s to continue editing.")
1344 (single-key-description exit-char))
3547c855 1345 (let ((char (read-event)))
be9b65ac 1346 (or (eq char exit-char)
dbc4e1c1 1347 (setq unread-command-events (list char)))))
be9b65ac
DL
1348 (if insert-end
1349 (save-excursion
1350 (delete-region pos insert-end)))
1351 (setq buffer-file-name name)
1352 (set-buffer-modified-p modified))))
1353
9a5336ae 1354\f
aa3b4ded
SM
1355;;;; Overlay operations
1356
1357(defun copy-overlay (o)
1358 "Return a copy of overlay O."
1359 (let ((o1 (make-overlay (overlay-start o) (overlay-end o)
1360 ;; FIXME: there's no easy way to find the
1361 ;; insertion-type of the two markers.
1362 (overlay-buffer o)))
1363 (props (overlay-properties o)))
1364 (while props
1365 (overlay-put o1 (pop props) (pop props)))
1366 o1))
1367
1368(defun remove-overlays (beg end name val)
1369 "Clear BEG and END of overlays whose property NAME has value VAL.
1370Overlays might be moved and or split."
1371 (if (< end beg)
1372 (setq beg (prog1 end (setq end beg))))
1373 (save-excursion
1374 (dolist (o (overlays-in beg end))
1375 (when (eq (overlay-get o name) val)
1376 ;; Either push this overlay outside beg...end
1377 ;; or split it to exclude beg...end
1378 ;; or delete it entirely (if it is contained in beg...end).
1379 (if (< (overlay-start o) beg)
1380 (if (> (overlay-end o) end)
1381 (progn
1382 (move-overlay (copy-overlay o)
1383 (overlay-start o) beg)
1384 (move-overlay o end (overlay-end o)))
1385 (move-overlay o (overlay-start o) beg))
1386 (if (> (overlay-end o) end)
1387 (move-overlay o end (overlay-end o))
1388 (delete-overlay o)))))))
c5802acf 1389\f
9a5336ae
JB
1390;;;; Miscellanea.
1391
448b61c9
RS
1392;; A number of major modes set this locally.
1393;; Give it a global value to avoid compiler warnings.
1394(defvar font-lock-defaults nil)
1395
4fb17037
RS
1396(defvar suspend-hook nil
1397 "Normal hook run by `suspend-emacs', before suspending.")
1398
1399(defvar suspend-resume-hook nil
1400 "Normal hook run by `suspend-emacs', after Emacs is continued.")
1401
784bc7cd
RS
1402(defvar temp-buffer-show-hook nil
1403 "Normal hook run by `with-output-to-temp-buffer' after displaying the buffer.
1404When the hook runs, the temporary buffer is current, and the window it
1405was displayed in is selected. This hook is normally set up with a
1406function to make the buffer read only, and find function names and
1407variable names in it, provided the major mode is still Help mode.")
1408
1409(defvar temp-buffer-setup-hook nil
1410 "Normal hook run by `with-output-to-temp-buffer' at the start.
1411When the hook runs, the temporary buffer is current.
1412This hook is normally set up with a function to put the buffer in Help
1413mode.")
1414
448b61c9
RS
1415;; Avoid compiler warnings about this variable,
1416;; which has a special meaning on certain system types.
1417(defvar buffer-file-type nil
1418 "Non-nil if the visited file is a binary file.
1419This variable is meaningful on MS-DOG and Windows NT.
1420On those systems, it is automatically local in every buffer.
1421On other systems, this variable is normally always nil.")
1422
a860d25f 1423;; This should probably be written in C (i.e., without using `walk-windows').
63503b24 1424(defun get-buffer-window-list (buffer &optional minibuf frame)
a860d25f 1425 "Return windows currently displaying BUFFER, or nil if none.
63503b24 1426See `walk-windows' for the meaning of MINIBUF and FRAME."
43c5ac8c 1427 (let ((buffer (if (bufferp buffer) buffer (get-buffer buffer))) windows)
a860d25f
SM
1428 (walk-windows (function (lambda (window)
1429 (if (eq (window-buffer window) buffer)
1430 (setq windows (cons window windows)))))
63503b24 1431 minibuf frame)
a860d25f
SM
1432 windows))
1433
f9269e19
RS
1434(defun ignore (&rest ignore)
1435 "Do nothing and return nil.
1436This function accepts any number of arguments, but ignores them."
c0f1a4f6 1437 (interactive)
9a5336ae
JB
1438 nil)
1439
1440(defun error (&rest args)
aa308ce2
RS
1441 "Signal an error, making error message by passing all args to `format'.
1442In Emacs, the convention is that error messages start with a capital
1443letter but *do not* end with a period. Please follow this convention
1444for the sake of consistency."
9a5336ae
JB
1445 (while t
1446 (signal 'error (list (apply 'format args)))))
1447
cef7ae6e 1448(defalias 'user-original-login-name 'user-login-name)
9a5336ae 1449
2493767e
RS
1450(defvar yank-excluded-properties)
1451
8ed59ad5
KS
1452(defun remove-yank-excluded-properties (start end)
1453 "Remove `yank-excluded-properties' between START and END positions.
1454Replaces `category' properties with their defined properties."
1455 (let ((inhibit-read-only t))
1456 ;; Replace any `category' property with the properties it stands for.
1457 (unless (memq yank-excluded-properties '(t nil))
1458 (save-excursion
1459 (goto-char start)
1460 (while (< (point) end)
1461 (let ((cat (get-text-property (point) 'category))
1462 run-end)
8ed59ad5
KS
1463 (setq run-end
1464 (next-single-property-change (point) 'category nil end))
ebaa3349
RS
1465 (when cat
1466 (let (run-end2 original)
1467 (remove-list-of-text-properties (point) run-end '(category))
1468 (while (< (point) run-end)
1469 (setq run-end2 (next-property-change (point) nil run-end))
1470 (setq original (text-properties-at (point)))
1471 (set-text-properties (point) run-end2 (symbol-plist cat))
1472 (add-text-properties (point) run-end2 original)
1473 (goto-char run-end2))))
1474 (goto-char run-end)))))
8ed59ad5
KS
1475 (if (eq yank-excluded-properties t)
1476 (set-text-properties start end nil)
ebaa3349 1477 (remove-list-of-text-properties start end yank-excluded-properties))))
8ed59ad5 1478
e0e80ec9
KS
1479(defvar yank-undo-function)
1480
1481(defun insert-for-yank (string)
1482 "Insert STRING at point, stripping some text properties.
1483Strip text properties from the inserted text according to
1484`yank-excluded-properties'. Otherwise just like (insert STRING).
1485
374d3fe7 1486If STRING has a non-nil `yank-handler' property on the first character,
e0e80ec9
KS
1487the normal insert behaviour is modified in various ways. The value of
1488the yank-handler property must be a list with one to five elements
9dd10e25 1489with the following format: (FUNCTION PARAM NOEXCLUDE UNDO).
e0e80ec9
KS
1490When FUNCTION is present and non-nil, it is called instead of `insert'
1491 to insert the string. FUNCTION takes one argument--the object to insert.
1492If PARAM is present and non-nil, it replaces STRING as the object
1493 passed to FUNCTION (or `insert'); for example, if FUNCTION is
1494 `yank-rectangle', PARAM may be a list of strings to insert as a
1495 rectangle.
1496If NOEXCLUDE is present and non-nil, the normal removal of the
1497 yank-excluded-properties is not performed; instead FUNCTION is
1498 responsible for removing those properties. This may be necessary
1499 if FUNCTION adjusts point before or after inserting the object.
1500If UNDO is present and non-nil, it is a function that will be called
1501 by `yank-pop' to undo the insertion of the current object. It is
f1180544 1502 called with two arguments, the start and end of the current region.
9dd10e25 1503 FUNCTION may set `yank-undo-function' to override the UNDO value."
57596fb6
KS
1504 (let* ((handler (and (stringp string)
1505 (get-text-property 0 'yank-handler string)))
1506 (param (or (nth 1 handler) string))
e0e80ec9 1507 (opoint (point)))
57596fb6
KS
1508 (setq yank-undo-function t)
1509 (if (nth 0 handler) ;; FUNCTION
1510 (funcall (car handler) param)
e0e80ec9 1511 (insert param))
57596fb6 1512 (unless (nth 2 handler) ;; NOEXCLUDE
e0e80ec9 1513 (remove-yank-excluded-properties opoint (point)))
57596fb6
KS
1514 (if (eq yank-undo-function t) ;; not set by FUNCTION
1515 (setq yank-undo-function (nth 3 handler))) ;; UNDO
1516 (if (nth 4 handler) ;; COMMAND
1517 (setq this-command (nth 4 handler)))))
f1180544 1518
3b8690f6
KS
1519(defun insert-buffer-substring-no-properties (buf &optional start end)
1520 "Insert before point a substring of buffer BUFFER, without text properties.
1521BUFFER may be a buffer or a buffer name.
1522Arguments START and END are character numbers specifying the substring.
1523They default to the beginning and the end of BUFFER."
1524 (let ((opoint (point)))
1525 (insert-buffer-substring buf start end)
1526 (let ((inhibit-read-only t))
1527 (set-text-properties opoint (point) nil))))
1528
1529(defun insert-buffer-substring-as-yank (buf &optional start end)
1530 "Insert before point a part of buffer BUFFER, stripping some text properties.
1531BUFFER may be a buffer or a buffer name. Arguments START and END are
1532character numbers specifying the substring. They default to the
1533beginning and the end of BUFFER. Strip text properties from the
1534inserted text according to `yank-excluded-properties'."
1535 (let ((opoint (point)))
1536 (insert-buffer-substring buf start end)
8ed59ad5 1537 (remove-yank-excluded-properties opoint (point))))
3b8690f6 1538
2493767e
RS
1539\f
1540;; Synchronous shell commands.
1541
be9b65ac
DL
1542(defun start-process-shell-command (name buffer &rest args)
1543 "Start a program in a subprocess. Return the process object for it.
1544Args are NAME BUFFER COMMAND &rest COMMAND-ARGS.
1545NAME is name for process. It is modified if necessary to make it unique.
1546BUFFER is the buffer or (buffer-name) to associate with the process.
1547 Process output goes at end of that buffer, unless you specify
1548 an output stream or filter function to handle the output.
1549 BUFFER may be also nil, meaning that this process is not associated
1550 with any buffer
1551Third arg is command name, the name of a shell command.
1552Remaining arguments are the arguments for the command.
4f1d6310 1553Wildcards and redirection are handled as usual in the shell."
a247bf21
KH
1554 (cond
1555 ((eq system-type 'vax-vms)
1556 (apply 'start-process name buffer args))
b59f6d7a
RS
1557 ;; We used to use `exec' to replace the shell with the command,
1558 ;; but that failed to handle (...) and semicolon, etc.
a247bf21
KH
1559 (t
1560 (start-process name buffer shell-file-name shell-command-switch
b59f6d7a 1561 (mapconcat 'identity args " ")))))
93aca633
MB
1562
1563(defun call-process-shell-command (command &optional infile buffer display
1564 &rest args)
1565 "Execute the shell command COMMAND synchronously in separate process.
1566The remaining arguments are optional.
1567The program's input comes from file INFILE (nil means `/dev/null').
1568Insert output in BUFFER before point; t means current buffer;
1569 nil for BUFFER means discard it; 0 means discard and don't wait.
1570BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,
1571REAL-BUFFER says what to do with standard output, as above,
1572while STDERR-FILE says what to do with standard error in the child.
1573STDERR-FILE may be nil (discard standard error output),
1574t (mix it with ordinary output), or a file name string.
1575
1576Fourth arg DISPLAY non-nil means redisplay buffer as output is inserted.
1577Remaining arguments are strings passed as additional arguments for COMMAND.
1578Wildcards and redirection are handled as usual in the shell.
1579
1580If BUFFER is 0, `call-process-shell-command' returns immediately with value nil.
1581Otherwise it waits for COMMAND to terminate and returns a numeric exit
1582status or a signal description string.
1583If you quit, the process is killed with SIGINT, or SIGKILL if you quit again."
1584 (cond
1585 ((eq system-type 'vax-vms)
1586 (apply 'call-process command infile buffer display args))
1587 ;; We used to use `exec' to replace the shell with the command,
1588 ;; but that failed to handle (...) and semicolon, etc.
1589 (t
1590 (call-process shell-file-name
1591 infile buffer display
1592 shell-command-switch
1593 (mapconcat 'identity (cons command args) " ")))))
a7ed4c2a 1594\f
a7f284ec
RS
1595(defmacro with-current-buffer (buffer &rest body)
1596 "Execute the forms in BODY with BUFFER as the current buffer.
a2fdb55c
EN
1597The value returned is the value of the last form in BODY.
1598See also `with-temp-buffer'."
ce87039d
SM
1599 (cons 'save-current-buffer
1600 (cons (list 'set-buffer buffer)
1601 body)))
a7f284ec 1602
e5bb8a8c
SM
1603(defmacro with-temp-file (file &rest body)
1604 "Create a new buffer, evaluate BODY there, and write the buffer to FILE.
1605The value returned is the value of the last form in BODY.
a2fdb55c 1606See also `with-temp-buffer'."
a7ed4c2a 1607 (let ((temp-file (make-symbol "temp-file"))
a2fdb55c
EN
1608 (temp-buffer (make-symbol "temp-buffer")))
1609 `(let ((,temp-file ,file)
1610 (,temp-buffer
1611 (get-buffer-create (generate-new-buffer-name " *temp file*"))))
1612 (unwind-protect
1613 (prog1
1614 (with-current-buffer ,temp-buffer
e5bb8a8c 1615 ,@body)
a2fdb55c
EN
1616 (with-current-buffer ,temp-buffer
1617 (widen)
1618 (write-region (point-min) (point-max) ,temp-file nil 0)))
1619 (and (buffer-name ,temp-buffer)
1620 (kill-buffer ,temp-buffer))))))
1621
e5bb8a8c 1622(defmacro with-temp-message (message &rest body)
a600effe 1623 "Display MESSAGE temporarily if non-nil while BODY is evaluated.
e5bb8a8c
SM
1624The original message is restored to the echo area after BODY has finished.
1625The value returned is the value of the last form in BODY.
a600effe
SM
1626MESSAGE is written to the message log buffer if `message-log-max' is non-nil.
1627If MESSAGE is nil, the echo area and message log buffer are unchanged.
1628Use a MESSAGE of \"\" to temporarily clear the echo area."
110201c8
SM
1629 (let ((current-message (make-symbol "current-message"))
1630 (temp-message (make-symbol "with-temp-message")))
1631 `(let ((,temp-message ,message)
1632 (,current-message))
e5bb8a8c
SM
1633 (unwind-protect
1634 (progn
110201c8
SM
1635 (when ,temp-message
1636 (setq ,current-message (current-message))
aadf7ff3 1637 (message "%s" ,temp-message))
e5bb8a8c 1638 ,@body)
cad84646
RS
1639 (and ,temp-message
1640 (if ,current-message
1641 (message "%s" ,current-message)
1642 (message nil)))))))
e5bb8a8c
SM
1643
1644(defmacro with-temp-buffer (&rest body)
1645 "Create a temporary buffer, and evaluate BODY there like `progn'.
a2fdb55c
EN
1646See also `with-temp-file' and `with-output-to-string'."
1647 (let ((temp-buffer (make-symbol "temp-buffer")))
1648 `(let ((,temp-buffer
1649 (get-buffer-create (generate-new-buffer-name " *temp*"))))
1650 (unwind-protect
1651 (with-current-buffer ,temp-buffer
e5bb8a8c 1652 ,@body)
a2fdb55c
EN
1653 (and (buffer-name ,temp-buffer)
1654 (kill-buffer ,temp-buffer))))))
1655
5db7925d
RS
1656(defmacro with-output-to-string (&rest body)
1657 "Execute BODY, return the text it sent to `standard-output', as a string."
a2fdb55c
EN
1658 `(let ((standard-output
1659 (get-buffer-create (generate-new-buffer-name " *string-output*"))))
5db7925d
RS
1660 (let ((standard-output standard-output))
1661 ,@body)
a2fdb55c
EN
1662 (with-current-buffer standard-output
1663 (prog1
1664 (buffer-string)
1665 (kill-buffer nil)))))
2ec9c94e 1666
0764e16f
SM
1667(defmacro with-local-quit (&rest body)
1668 "Execute BODY with `inhibit-quit' temporarily bound to nil."
12320833 1669 (declare (debug t) (indent 0))
0764e16f
SM
1670 `(condition-case nil
1671 (let ((inhibit-quit nil))
1672 ,@body)
1673 (quit (setq quit-flag t))))
1674
2ec9c94e
RS
1675(defmacro combine-after-change-calls (&rest body)
1676 "Execute BODY, but don't call the after-change functions till the end.
1677If BODY makes changes in the buffer, they are recorded
1678and the functions on `after-change-functions' are called several times
1679when BODY is finished.
31aa282e 1680The return value is the value of the last form in BODY.
2ec9c94e
RS
1681
1682If `before-change-functions' is non-nil, then calls to the after-change
1683functions can't be deferred, so in that case this macro has no effect.
1684
1685Do not alter `after-change-functions' or `before-change-functions'
1686in BODY."
1687 `(unwind-protect
1688 (let ((combine-after-change-calls t))
1689 . ,body)
1690 (combine-after-change-execute)))
1691
c834b52c 1692
a13fe4c5
SM
1693(defvar delay-mode-hooks nil
1694 "If non-nil, `run-mode-hooks' should delay running the hooks.")
1695(defvar delayed-mode-hooks nil
1696 "List of delayed mode hooks waiting to be run.")
1697(make-variable-buffer-local 'delayed-mode-hooks)
1698
1699(defun run-mode-hooks (&rest hooks)
1700 "Run mode hooks `delayed-mode-hooks' and HOOKS, or delay HOOKS.
1701Execution is delayed if `delay-mode-hooks' is non-nil.
1702Major mode functions should use this."
1703 (if delay-mode-hooks
1704 ;; Delaying case.
1705 (dolist (hook hooks)
1706 (push hook delayed-mode-hooks))
1707 ;; Normal case, just run the hook as before plus any delayed hooks.
1708 (setq hooks (nconc (nreverse delayed-mode-hooks) hooks))
1709 (setq delayed-mode-hooks nil)
1710 (apply 'run-hooks hooks)))
1711
1712(defmacro delay-mode-hooks (&rest body)
1713 "Execute BODY, but delay any `run-mode-hooks'.
1714Only affects hooks run in the current buffer."
1715 `(progn
1716 (make-local-variable 'delay-mode-hooks)
1717 (let ((delay-mode-hooks t))
1718 ,@body)))
1719
31ca596b
RS
1720;; PUBLIC: find if the current mode derives from another.
1721
1722(defun derived-mode-p (&rest modes)
1723 "Non-nil if the current major mode is derived from one of MODES.
1724Uses the `derived-mode-parent' property of the symbol to trace backwards."
1725 (let ((parent major-mode))
1726 (while (and (not (memq parent modes))
1727 (setq parent (get parent 'derived-mode-parent))))
1728 parent))
1729
7e8539cc 1730(defmacro with-syntax-table (table &rest body)
7ec51784 1731 "Evaluate BODY with syntax table of current buffer set to TABLE.
7e8539cc
RS
1732The syntax table of the current buffer is saved, BODY is evaluated, and the
1733saved table is restored, even in case of an abnormal exit.
1734Value is what BODY returns."
b3f07093
RS
1735 (let ((old-table (make-symbol "table"))
1736 (old-buffer (make-symbol "buffer")))
7e8539cc
RS
1737 `(let ((,old-table (syntax-table))
1738 (,old-buffer (current-buffer)))
1739 (unwind-protect
1740 (progn
7ec51784 1741 (set-syntax-table ,table)
7e8539cc
RS
1742 ,@body)
1743 (save-current-buffer
1744 (set-buffer ,old-buffer)
1745 (set-syntax-table ,old-table))))))
a2fdb55c 1746\f
2493767e
RS
1747;;; Matching and substitution
1748
c7ca41e6
RS
1749(defvar save-match-data-internal)
1750
1751;; We use save-match-data-internal as the local variable because
1752;; that works ok in practice (people should not use that variable elsewhere).
1753;; We used to use an uninterned symbol; the compiler handles that properly
1754;; now, but it generates slower code.
9a5336ae 1755(defmacro save-match-data (&rest body)
e4d03691
JB
1756 "Execute the BODY forms, restoring the global value of the match data.
1757The value returned is the value of the last form in BODY."
64ed733a
PE
1758 ;; It is better not to use backquote here,
1759 ;; because that makes a bootstrapping problem
1760 ;; if you need to recompile all the Lisp files using interpreted code.
1761 (list 'let
1762 '((save-match-data-internal (match-data)))
1763 (list 'unwind-protect
1764 (cons 'progn body)
1765 '(set-match-data save-match-data-internal))))
993713ce 1766
cd323f89 1767(defun match-string (num &optional string)
993713ce
SM
1768 "Return string of text matched by last search.
1769NUM specifies which parenthesized expression in the last regexp.
1770 Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
1771Zero means the entire text matched by the whole regexp or whole string.
1772STRING should be given if the last search was by `string-match' on STRING."
cd323f89
SM
1773 (if (match-beginning num)
1774 (if string
1775 (substring string (match-beginning num) (match-end num))
1776 (buffer-substring (match-beginning num) (match-end num)))))
58f950b4 1777
bb760c71
RS
1778(defun match-string-no-properties (num &optional string)
1779 "Return string of text matched by last search, without text properties.
1780NUM specifies which parenthesized expression in the last regexp.
1781 Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
1782Zero means the entire text matched by the whole regexp or whole string.
1783STRING should be given if the last search was by `string-match' on STRING."
1784 (if (match-beginning num)
1785 (if string
1786 (let ((result
1787 (substring string (match-beginning num) (match-end num))))
1788 (set-text-properties 0 (length result) nil result)
1789 result)
1790 (buffer-substring-no-properties (match-beginning num)
1791 (match-end num)))))
1792
edce3654
RS
1793(defun split-string (string &optional separators)
1794 "Splits STRING into substrings where there are matches for SEPARATORS.
1795Each match for SEPARATORS is a splitting point.
1796The substrings between the splitting points are made into a list
1797which is returned.
b222b786
RS
1798If SEPARATORS is absent, it defaults to \"[ \\f\\t\\n\\r\\v]+\".
1799
1800If there is match for SEPARATORS at the beginning of STRING, we do not
1801include a null substring for that. Likewise, if there is a match
b021ef18
DL
1802at the end of STRING, we don't include a null substring for that.
1803
1804Modifies the match data; use `save-match-data' if necessary."
edce3654
RS
1805 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
1806 (start 0)
b222b786 1807 notfirst
edce3654 1808 (list nil))
b222b786
RS
1809 (while (and (string-match rexp string
1810 (if (and notfirst
1811 (= start (match-beginning 0))
1812 (< start (length string)))
1813 (1+ start) start))
1814 (< (match-beginning 0) (length string)))
1815 (setq notfirst t)
7eb47123 1816 (or (eq (match-beginning 0) 0)
b222b786
RS
1817 (and (eq (match-beginning 0) (match-end 0))
1818 (eq (match-beginning 0) start))
edce3654
RS
1819 (setq list
1820 (cons (substring string start (match-beginning 0))
1821 list)))
1822 (setq start (match-end 0)))
1823 (or (eq start (length string))
1824 (setq list
1825 (cons (substring string start)
1826 list)))
1827 (nreverse list)))
1ccaea52
AI
1828
1829(defun subst-char-in-string (fromchar tochar string &optional inplace)
1830 "Replace FROMCHAR with TOCHAR in STRING each time it occurs.
1831Unless optional argument INPLACE is non-nil, return a new string."
e6e71807
SM
1832 (let ((i (length string))
1833 (newstr (if inplace string (copy-sequence string))))
1834 (while (> i 0)
1835 (setq i (1- i))
1836 (if (eq (aref newstr i) fromchar)
1837 (aset newstr i tochar)))
1838 newstr))
b021ef18 1839
1697159c
DL
1840(defun replace-regexp-in-string (regexp rep string &optional
1841 fixedcase literal subexp start)
b021ef18
DL
1842 "Replace all matches for REGEXP with REP in STRING.
1843
1844Return a new string containing the replacements.
1845
1846Optional arguments FIXEDCASE, LITERAL and SUBEXP are like the
1847arguments with the same names of function `replace-match'. If START
1848is non-nil, start replacements at that index in STRING.
1849
1850REP is either a string used as the NEWTEXT arg of `replace-match' or a
1851function. If it is a function it is applied to each match to generate
1852the replacement passed to `replace-match'; the match-data at this
1853point are such that match 0 is the function's argument.
1854
1697159c
DL
1855To replace only the first match (if any), make REGEXP match up to \\'
1856and replace a sub-expression, e.g.
c9bcb507 1857 (replace-regexp-in-string \"\\\\(foo\\\\).*\\\\'\" \"bar\" \" foo foo\" nil nil 1)
1697159c
DL
1858 => \" bar foo\"
1859"
b021ef18
DL
1860
1861 ;; To avoid excessive consing from multiple matches in long strings,
1862 ;; don't just call `replace-match' continually. Walk down the
1863 ;; string looking for matches of REGEXP and building up a (reversed)
1864 ;; list MATCHES. This comprises segments of STRING which weren't
1865 ;; matched interspersed with replacements for segments that were.
08b1f8a1 1866 ;; [For a `large' number of replacements it's more efficient to
b021ef18
DL
1867 ;; operate in a temporary buffer; we can't tell from the function's
1868 ;; args whether to choose the buffer-based implementation, though it
1869 ;; might be reasonable to do so for long enough STRING.]
1870 (let ((l (length string))
1871 (start (or start 0))
1872 matches str mb me)
1873 (save-match-data
1874 (while (and (< start l) (string-match regexp string start))
1875 (setq mb (match-beginning 0)
1876 me (match-end 0))
a9853251
SM
1877 ;; If we matched the empty string, make sure we advance by one char
1878 (when (= me mb) (setq me (min l (1+ mb))))
1879 ;; Generate a replacement for the matched substring.
1880 ;; Operate only on the substring to minimize string consing.
1881 ;; Set up match data for the substring for replacement;
1882 ;; presumably this is likely to be faster than munging the
1883 ;; match data directly in Lisp.
1884 (string-match regexp (setq str (substring string mb me)))
1885 (setq matches
1886 (cons (replace-match (if (stringp rep)
1887 rep
1888 (funcall rep (match-string 0 str)))
1889 fixedcase literal str subexp)
1890 (cons (substring string start mb) ; unmatched prefix
1891 matches)))
1892 (setq start me))
b021ef18
DL
1893 ;; Reconstruct a string from the pieces.
1894 (setq matches (cons (substring string start l) matches)) ; leftover
1895 (apply #'concat (nreverse matches)))))
a7ed4c2a 1896\f
8af7df60
RS
1897(defun shell-quote-argument (argument)
1898 "Quote an argument for passing as argument to an inferior shell."
c1c74b43 1899 (if (eq system-type 'ms-dos)
8ee75d03
EZ
1900 ;; Quote using double quotes, but escape any existing quotes in
1901 ;; the argument with backslashes.
1902 (let ((result "")
1903 (start 0)
1904 end)
1905 (if (or (null (string-match "[^\"]" argument))
1906 (< (match-end 0) (length argument)))
1907 (while (string-match "[\"]" argument start)
1908 (setq end (match-beginning 0)
1909 result (concat result (substring argument start end)
1910 "\\" (substring argument end (1+ end)))
1911 start (1+ end))))
1912 (concat "\"" result (substring argument start) "\""))
c1c74b43
RS
1913 (if (eq system-type 'windows-nt)
1914 (concat "\"" argument "\"")
e1b65a6b
RS
1915 (if (equal argument "")
1916 "''"
1917 ;; Quote everything except POSIX filename characters.
1918 ;; This should be safe enough even for really weird shells.
1919 (let ((result "") (start 0) end)
1920 (while (string-match "[^-0-9a-zA-Z_./]" argument start)
1921 (setq end (match-beginning 0)
1922 result (concat result (substring argument start end)
1923 "\\" (substring argument end (1+ end)))
1924 start (1+ end)))
1925 (concat result (substring argument start)))))))
8af7df60 1926
297d863b 1927(defun make-syntax-table (&optional oldtable)
984f718a 1928 "Return a new syntax table.
0764e16f
SM
1929Create a syntax table which inherits from OLDTABLE (if non-nil) or
1930from `standard-syntax-table' otherwise."
1931 (let ((table (make-char-table 'syntax-table nil)))
1932 (set-char-table-parent table (or oldtable (standard-syntax-table)))
1933 table))
31aa282e 1934
e9f13a95
SM
1935(defun syntax-after (pos)
1936 "Return the syntax of the char after POS."
1937 (unless (or (< pos (point-min)) (>= pos (point-max)))
1938 (let ((st (if parse-sexp-lookup-properties
1939 (get-char-property pos 'syntax-table))))
1940 (if (consp st) st
1941 (aref (or st (syntax-table)) (char-after pos))))))
1942
31aa282e
KH
1943(defun add-to-invisibility-spec (arg)
1944 "Add elements to `buffer-invisibility-spec'.
1945See documentation for `buffer-invisibility-spec' for the kind of elements
1946that can be added."
c525c13c
RS
1947 (if (eq buffer-invisibility-spec t)
1948 (setq buffer-invisibility-spec (list t)))
1949 (setq buffer-invisibility-spec
1950 (cons arg buffer-invisibility-spec)))
31aa282e
KH
1951
1952(defun remove-from-invisibility-spec (arg)
1953 "Remove elements from `buffer-invisibility-spec'."
e93b8cbb 1954 (if (consp buffer-invisibility-spec)
071a2a71 1955 (setq buffer-invisibility-spec (delete arg buffer-invisibility-spec))))
baed0109
RS
1956\f
1957(defun global-set-key (key command)
1958 "Give KEY a global binding as COMMAND.
7bba1895
KH
1959COMMAND is the command definition to use; usually it is
1960a symbol naming an interactively-callable function.
1961KEY is a key sequence; noninteractively, it is a string or vector
1962of characters or event types, and non-ASCII characters with codes
1963above 127 (such as ISO Latin-1) can be included if you use a vector.
1964
1965Note that if KEY has a local binding in the current buffer,
1966that local binding will continue to shadow any global binding
1967that you make with this function."
baed0109 1968 (interactive "KSet key globally: \nCSet key %s to command: ")
a2f9aa84 1969 (or (vectorp key) (stringp key)
baed0109 1970 (signal 'wrong-type-argument (list 'arrayp key)))
ff663bbe 1971 (define-key (current-global-map) key command))
baed0109
RS
1972
1973(defun local-set-key (key command)
1974 "Give KEY a local binding as COMMAND.
7bba1895
KH
1975COMMAND is the command definition to use; usually it is
1976a symbol naming an interactively-callable function.
1977KEY is a key sequence; noninteractively, it is a string or vector
1978of characters or event types, and non-ASCII characters with codes
1979above 127 (such as ISO Latin-1) can be included if you use a vector.
1980
baed0109
RS
1981The binding goes in the current buffer's local map,
1982which in most cases is shared with all other buffers in the same major mode."
1983 (interactive "KSet key locally: \nCSet key %s locally to command: ")
1984 (let ((map (current-local-map)))
1985 (or map
1986 (use-local-map (setq map (make-sparse-keymap))))
a2f9aa84 1987 (or (vectorp key) (stringp key)
baed0109 1988 (signal 'wrong-type-argument (list 'arrayp key)))
ff663bbe 1989 (define-key map key command)))
984f718a 1990
baed0109
RS
1991(defun global-unset-key (key)
1992 "Remove global binding of KEY.
1993KEY is a string representing a sequence of keystrokes."
1994 (interactive "kUnset key globally: ")
1995 (global-set-key key nil))
1996
db2474b8 1997(defun local-unset-key (key)
baed0109
RS
1998 "Remove local binding of KEY.
1999KEY is a string representing a sequence of keystrokes."
2000 (interactive "kUnset key locally: ")
2001 (if (current-local-map)
db2474b8 2002 (local-set-key key nil))
baed0109
RS
2003 nil)
2004\f
4809d0dd
KH
2005;; We put this here instead of in frame.el so that it's defined even on
2006;; systems where frame.el isn't loaded.
2007(defun frame-configuration-p (object)
2008 "Return non-nil if OBJECT seems to be a frame configuration.
2009Any list whose car is `frame-configuration' is assumed to be a frame
2010configuration."
2011 (and (consp object)
2012 (eq (car object) 'frame-configuration)))
2013
a9a44ed1 2014(defun functionp (object)
0764e16f 2015 "Non-nil iff OBJECT is a type of object that can be called as a function."
a2d7836f 2016 (or (and (symbolp object) (fboundp object)
d7d563e3
RS
2017 (condition-case nil
2018 (setq object (indirect-function object))
2019 (error nil))
0764e16f 2020 (eq (car-safe object) 'autoload)
f1d37f3c 2021 (not (car-safe (cdr-safe (cdr-safe (cdr-safe (cdr-safe object)))))))
0764e16f 2022 (subrp object) (byte-code-function-p object)
60ab6064 2023 (eq (car-safe object) 'lambda)))
a9a44ed1 2024
f65fab59
GM
2025(defun interactive-form (function)
2026 "Return the interactive form of FUNCTION.
2027If function is a command (see `commandp'), value is a list of the form
d3200788 2028\(interactive SPEC). If function is not a command, return nil."
f65fab59
GM
2029 (setq function (indirect-function function))
2030 (when (commandp function)
2031 (cond ((byte-code-function-p function)
2032 (when (> (length function) 5)
2033 (let ((spec (aref function 5)))
2034 (if spec
2035 (list 'interactive spec)
2036 (list 'interactive)))))
2037 ((subrp function)
2038 (subr-interactive-form function))
2039 ((eq (car-safe function) 'lambda)
2040 (setq function (cddr function))
2041 (when (stringp (car function))
2042 (setq function (cdr function)))
2043 (let ((form (car function)))
a27b451e 2044 (when (eq (car-safe form) 'interactive)
f65fab59 2045 (copy-sequence form)))))))
630cc463 2046
d3a61a11 2047(defun assq-delete-all (key alist)
a62d6695
DL
2048 "Delete from ALIST all elements whose car is KEY.
2049Return the modified alist."
a62d6695
DL
2050 (let ((tail alist))
2051 (while tail
2052 (if (eq (car (car tail)) key)
2053 (setq alist (delq (car tail) alist)))
2054 (setq tail (cdr tail)))
2055 alist))
2056
10cf1ba8 2057(defun make-temp-file (prefix &optional dir-flag suffix)
cdd9f643
RS
2058 "Create a temporary file.
2059The returned file name (created by appending some random characters at the end
5ef6a86d 2060of PREFIX, and expanding against `temporary-file-directory' if necessary),
cdd9f643
RS
2061is guaranteed to point to a newly created empty file.
2062You can then use `write-region' to write new data into the file.
2063
10cf1ba8
RS
2064If DIR-FLAG is non-nil, create a new empty directory instead of a file.
2065
2066If SUFFIX is non-nil, add that at the end of the file name."
1c12af5c
SM
2067 (let ((umask (default-file-modes))
2068 file)
2069 (unwind-protect
2070 (progn
2071 ;; Create temp files with strict access rights. It's easy to
2072 ;; loosen them later, whereas it's impossible to close the
2073 ;; time-window of loose permissions otherwise.
2074 (set-default-file-modes ?\700)
2075 (while (condition-case ()
2076 (progn
2077 (setq file
2078 (make-temp-name
2079 (expand-file-name prefix temporary-file-directory)))
2080 (if suffix
2081 (setq file (concat file suffix)))
2082 (if dir-flag
2083 (make-directory file)
2084 (write-region "" nil file nil 'silent nil 'excl))
2085 nil)
2086 (file-already-exists t))
2087 ;; the file was somehow created by someone else between
2088 ;; `make-temp-name' and `write-region', let's try again.
2089 nil)
2090 file)
2091 ;; Reset the umask.
2092 (set-default-file-modes umask))))
cdd9f643 2093
d7d47268 2094\f
c94f4677 2095(defun add-minor-mode (toggle name &optional keymap after toggle-fun)
d7d47268 2096 "Register a new minor mode.
c94f4677 2097
0b2cf11f
SM
2098This is an XEmacs-compatibility function. Use `define-minor-mode' instead.
2099
c94f4677
GM
2100TOGGLE is a symbol which is the name of a buffer-local variable that
2101is toggled on or off to say whether the minor mode is active or not.
2102
2103NAME specifies what will appear in the mode line when the minor mode
2104is active. NAME should be either a string starting with a space, or a
2105symbol whose value is such a string.
2106
2107Optional KEYMAP is the keymap for the minor mode that will be added
2108to `minor-mode-map-alist'.
2109
2110Optional AFTER specifies that TOGGLE should be added after AFTER
2111in `minor-mode-alist'.
2112
0b2cf11f
SM
2113Optional TOGGLE-FUN is an interactive function to toggle the mode.
2114It defaults to (and should by convention be) TOGGLE.
2115
2116If TOGGLE has a non-nil `:included' property, an entry for the mode is
2117included in the mode-line minor mode menu.
2118If TOGGLE has a `:menu-tag', that is used for the menu item's label."
2119 (unless toggle-fun (setq toggle-fun toggle))
0b2cf11f 2120 ;; Add the name to the minor-mode-alist.
c94f4677 2121 (when name
0b2cf11f 2122 (let ((existing (assq toggle minor-mode-alist)))
0b2cf11f
SM
2123 (if existing
2124 (setcdr existing (list name))
2125 (let ((tail minor-mode-alist) found)
2126 (while (and tail (not found))
2127 (if (eq after (caar tail))
2128 (setq found tail)
2129 (setq tail (cdr tail))))
2130 (if found
2131 (let ((rest (cdr found)))
2132 (setcdr found nil)
2133 (nconc found (list (list toggle name)) rest))
2134 (setq minor-mode-alist (cons (list toggle name)
2135 minor-mode-alist)))))))
69cae2d4
RS
2136 ;; Add the toggle to the minor-modes menu if requested.
2137 (when (get toggle :included)
2138 (define-key mode-line-mode-menu
2139 (vector toggle)
2140 (list 'menu-item
2141 (concat
2142 (or (get toggle :menu-tag)
2143 (if (stringp name) name (symbol-name toggle)))
1c12af5c
SM
2144 (let ((mode-name (if (symbolp name) (symbol-value name))))
2145 (if (and (stringp mode-name) (string-match "[^ ]+" mode-name))
2146 (concat " (" (match-string 0 mode-name) ")"))))
69cae2d4
RS
2147 toggle-fun
2148 :button (cons :toggle toggle))))
2149
1c12af5c 2150 ;; Add the map to the minor-mode-map-alist.
c94f4677
GM
2151 (when keymap
2152 (let ((existing (assq toggle minor-mode-map-alist)))
0b2cf11f
SM
2153 (if existing
2154 (setcdr existing keymap)
2155 (let ((tail minor-mode-map-alist) found)
2156 (while (and tail (not found))
2157 (if (eq after (caar tail))
2158 (setq found tail)
2159 (setq tail (cdr tail))))
2160 (if found
2161 (let ((rest (cdr found)))
2162 (setcdr found nil)
2163 (nconc found (list (cons toggle keymap)) rest))
2164 (setq minor-mode-map-alist (cons (cons toggle keymap)
2165 minor-mode-map-alist))))))))
2493767e 2166\f
a13fe4c5
SM
2167;; Clones ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2168
2169(defun text-clone-maintain (ol1 after beg end &optional len)
2170 "Propagate the changes made under the overlay OL1 to the other clones.
2171This is used on the `modification-hooks' property of text clones."
2172 (when (and after (not undo-in-progress) (overlay-start ol1))
2173 (let ((margin (if (overlay-get ol1 'text-clone-spreadp) 1 0)))
2174 (setq beg (max beg (+ (overlay-start ol1) margin)))
2175 (setq end (min end (- (overlay-end ol1) margin)))
2176 (when (<= beg end)
2177 (save-excursion
2178 (when (overlay-get ol1 'text-clone-syntax)
2179 ;; Check content of the clone's text.
2180 (let ((cbeg (+ (overlay-start ol1) margin))
2181 (cend (- (overlay-end ol1) margin)))
2182 (goto-char cbeg)
2183 (save-match-data
2184 (if (not (re-search-forward
2185 (overlay-get ol1 'text-clone-syntax) cend t))
2186 ;; Mark the overlay for deletion.
2187 (overlay-put ol1 'text-clones nil)
2188 (when (< (match-end 0) cend)
2189 ;; Shrink the clone at its end.
2190 (setq end (min end (match-end 0)))
2191 (move-overlay ol1 (overlay-start ol1)
2192 (+ (match-end 0) margin)))
2193 (when (> (match-beginning 0) cbeg)
2194 ;; Shrink the clone at its beginning.
2195 (setq beg (max (match-beginning 0) beg))
2196 (move-overlay ol1 (- (match-beginning 0) margin)
2197 (overlay-end ol1)))))))
2198 ;; Now go ahead and update the clones.
2199 (let ((head (- beg (overlay-start ol1)))
2200 (tail (- (overlay-end ol1) end))
2201 (str (buffer-substring beg end))
2202 (nothing-left t)
2203 (inhibit-modification-hooks t))
2204 (dolist (ol2 (overlay-get ol1 'text-clones))
2205 (let ((oe (overlay-end ol2)))
2206 (unless (or (eq ol1 ol2) (null oe))
2207 (setq nothing-left nil)
2208 (let ((mod-beg (+ (overlay-start ol2) head)))
2209 ;;(overlay-put ol2 'modification-hooks nil)
2210 (goto-char (- (overlay-end ol2) tail))
2211 (unless (> mod-beg (point))
2212 (save-excursion (insert str))
2213 (delete-region mod-beg (point)))
2214 ;;(overlay-put ol2 'modification-hooks '(text-clone-maintain))
2215 ))))
2216 (if nothing-left (delete-overlay ol1))))))))
2217
2218(defun text-clone-create (start end &optional spreadp syntax)
2219 "Create a text clone of START...END at point.
2220Text clones are chunks of text that are automatically kept identical:
2221changes done to one of the clones will be immediately propagated to the other.
2222
2223The buffer's content at point is assumed to be already identical to
2224the one between START and END.
2225If SYNTAX is provided it's a regexp that describes the possible text of
2226the clones; the clone will be shrunk or killed if necessary to ensure that
2227its text matches the regexp.
2228If SPREADP is non-nil it indicates that text inserted before/after the
2229clone should be incorporated in the clone."
2230 ;; To deal with SPREADP we can either use an overlay with `nil t' along
2231 ;; with insert-(behind|in-front-of)-hooks or use a slightly larger overlay
2232 ;; (with a one-char margin at each end) with `t nil'.
2233 ;; We opted for a larger overlay because it behaves better in the case
2234 ;; where the clone is reduced to the empty string (we want the overlay to
2235 ;; stay when the clone's content is the empty string and we want to use
2236 ;; `evaporate' to make sure those overlays get deleted when needed).
264ef586 2237 ;;
a13fe4c5
SM
2238 (let* ((pt-end (+ (point) (- end start)))
2239 (start-margin (if (or (not spreadp) (bobp) (<= start (point-min)))
2240 0 1))
2241 (end-margin (if (or (not spreadp)
2242 (>= pt-end (point-max))
2243 (>= start (point-max)))
2244 0 1))
2245 (ol1 (make-overlay (- start start-margin) (+ end end-margin) nil t))
2246 (ol2 (make-overlay (- (point) start-margin) (+ pt-end end-margin) nil t))
2247 (dups (list ol1 ol2)))
2248 (overlay-put ol1 'modification-hooks '(text-clone-maintain))
2249 (when spreadp (overlay-put ol1 'text-clone-spreadp t))
2250 (when syntax (overlay-put ol1 'text-clone-syntax syntax))
2251 ;;(overlay-put ol1 'face 'underline)
2252 (overlay-put ol1 'evaporate t)
2253 (overlay-put ol1 'text-clones dups)
264ef586 2254 ;;
a13fe4c5
SM
2255 (overlay-put ol2 'modification-hooks '(text-clone-maintain))
2256 (when spreadp (overlay-put ol2 'text-clone-spreadp t))
2257 (when syntax (overlay-put ol2 'text-clone-syntax syntax))
2258 ;;(overlay-put ol2 'face 'underline)
2259 (overlay-put ol2 'evaporate t)
2260 (overlay-put ol2 'text-clones dups)))
27c079eb 2261
324cd947
PJ
2262(defun play-sound (sound)
2263 "SOUND is a list of the form `(sound KEYWORD VALUE...)'.
2264The following keywords are recognized:
2265
2266 :file FILE - read sound data from FILE. If FILE isn't an
2267absolute file name, it is searched in `data-directory'.
2268
2269 :data DATA - read sound data from string DATA.
2270
2271Exactly one of :file or :data must be present.
2272
2273 :volume VOL - set volume to VOL. VOL must an integer in the
2274range 0..100 or a float in the range 0..1.0. If not specified,
2275don't change the volume setting of the sound device.
2276
2277 :device DEVICE - play sound on DEVICE. If not specified,
2278a system-dependent default device name is used."
2279 (unless (fboundp 'play-sound-internal)
2280 (error "This Emacs binary lacks sound support"))
2281 (play-sound-internal sound))
2282
27c079eb
SM
2283(defun define-mail-user-agent (symbol composefunc sendfunc
2284 &optional abortfunc hookvar)
2285 "Define a symbol to identify a mail-sending package for `mail-user-agent'.
2286
2287SYMBOL can be any Lisp symbol. Its function definition and/or
2288value as a variable do not matter for this usage; we use only certain
2289properties on its property list, to encode the rest of the arguments.
2290
2291COMPOSEFUNC is program callable function that composes an outgoing
2292mail message buffer. This function should set up the basics of the
2293buffer without requiring user interaction. It should populate the
2294standard mail headers, leaving the `to:' and `subject:' headers blank
2295by default.
2296
2297COMPOSEFUNC should accept several optional arguments--the same
2298arguments that `compose-mail' takes. See that function's documentation.
2299
2300SENDFUNC is the command a user would run to send the message.
2301
2302Optional ABORTFUNC is the command a user would run to abort the
2303message. For mail packages that don't have a separate abort function,
2304this can be `kill-buffer' (the equivalent of omitting this argument).
2305
2306Optional HOOKVAR is a hook variable that gets run before the message
2307is actually sent. Callers that use the `mail-user-agent' may
2308install a hook function temporarily on this hook variable.
2309If HOOKVAR is nil, `mail-send-hook' is used.
2310
2311The properties used on SYMBOL are `composefunc', `sendfunc',
2312`abortfunc', and `hookvar'."
2313 (put symbol 'composefunc composefunc)
2314 (put symbol 'sendfunc sendfunc)
2315 (put symbol 'abortfunc (or abortfunc 'kill-buffer))
2316 (put symbol 'hookvar (or hookvar 'mail-send-hook)))
2317
630cc463 2318;;; subr.el ends here