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