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