(substitute-key-definition): Mention command remapping in doc string.
[emacs.git] / lisp / subr.el
blob3c4f870918e1f1645e0e6ab5f97db88dffb90acf
1 ;;; subr.el --- basic lisp subroutines for Emacs
3 ;; Copyright (C) 1985, 1986, 1992, 1994, 1995, 1999, 2000, 2001, 2002, 2003,
4 ;; 2004 Free Software Foundation, Inc.
6 ;; Maintainer: FSF
7 ;; Keywords: internal
9 ;; This file is part of GNU Emacs.
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.
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.
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.
26 ;;; Commentary:
28 ;;; Code:
29 (defvar custom-declare-variable-list nil
30 "Record `defcustom' calls made before `custom.el' is loaded to handle them.
31 Each element of this list holds the arguments to one call to `defcustom'.")
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)))
40 (defun macro-declaration-function (macro decl)
41 "Process a declaration found in a macro definition.
42 This is set as the value of the variable `macro-declaration-function'.
43 MACRO is the name of the macro being defined.
44 DECL is a list `(declare ...)' containing the declarations.
45 The return value of this function is not used."
46 ;; We can't use `dolist' or `cadr' yet for bootstrapping reasons.
47 (let (d)
48 ;; Ignore the first element of `decl' (it's always `declare').
49 (while (setq decl (cdr decl))
50 (setq d (car decl))
51 (cond ((and (consp d) (eq (car d) 'indent))
52 (put macro 'lisp-indent-function (car (cdr d))))
53 ((and (consp d) (eq (car d) 'debug))
54 (put macro 'edebug-form-spec (car (cdr d))))
56 (message "Unknown declaration %s" d))))))
58 (setq macro-declaration-function 'macro-declaration-function)
61 ;;;; Lisp language features.
63 (defalias 'not 'null)
65 (defmacro noreturn (form)
66 "Evaluates FORM, with the expectation that the evaluation will signal an error
67 instead of returning to its caller. If FORM does return, an error is
68 signalled."
69 `(prog1 ,form
70 (error "Form marked with `noreturn' did return")))
72 (defmacro 1value (form)
73 "Evaluates FORM, with the expectation that all the same value will be returned
74 from all evaluations of FORM. This is the global do-nothing
75 version of `1value'. There is also `testcover-1value' that
76 complains if FORM ever does return differing values."
77 form)
79 (defmacro lambda (&rest cdr)
80 "Return a lambda expression.
81 A call of the form (lambda ARGS DOCSTRING INTERACTIVE BODY) is
82 self-quoting; the result of evaluating the lambda expression is the
83 expression itself. The lambda expression may then be treated as a
84 function, i.e., stored as the function value of a symbol, passed to
85 funcall or mapcar, etc.
87 ARGS should take the same form as an argument list for a `defun'.
88 DOCSTRING is an optional documentation string.
89 If present, it should describe how to call the function.
90 But documentation strings are usually not useful in nameless functions.
91 INTERACTIVE should be a call to the function `interactive', which see.
92 It may also be omitted.
93 BODY should be a list of Lisp expressions.
95 \(fn ARGS [DOCSTRING] [INTERACTIVE] BODY)"
96 ;; Note that this definition should not use backquotes; subr.el should not
97 ;; depend on backquote.el.
98 (list 'function (cons 'lambda cdr)))
100 (defmacro push (newelt listname)
101 "Add NEWELT to the list stored in the symbol LISTNAME.
102 This is equivalent to (setq LISTNAME (cons NEWELT LISTNAME)).
103 LISTNAME must be a symbol."
104 (declare (debug (form sexp)))
105 (list 'setq listname
106 (list 'cons newelt listname)))
108 (defmacro pop (listname)
109 "Return the first element of LISTNAME's value, and remove it from the list.
110 LISTNAME must be a symbol whose value is a list.
111 If the value is nil, `pop' returns nil but does not actually
112 change the list."
113 (declare (debug (sexp)))
114 (list 'car
115 (list 'prog1 listname
116 (list 'setq listname (list 'cdr listname)))))
118 (defmacro when (cond &rest body)
119 "If COND yields non-nil, do BODY, else return nil."
120 (declare (indent 1) (debug t))
121 (list 'if cond (cons 'progn body)))
123 (defmacro unless (cond &rest body)
124 "If COND yields nil, do BODY, else return nil."
125 (declare (indent 1) (debug t))
126 (cons 'if (cons cond (cons nil body))))
128 (defmacro dolist (spec &rest body)
129 "Loop over a list.
130 Evaluate BODY with VAR bound to each car from LIST, in turn.
131 Then evaluate RESULT to get return value, default nil.
133 \(fn (VAR LIST [RESULT]) BODY...)"
134 (declare (indent 1) (debug ((symbolp form &optional form) body)))
135 (let ((temp (make-symbol "--dolist-temp--")))
136 `(let ((,temp ,(nth 1 spec))
137 ,(car spec))
138 (while ,temp
139 (setq ,(car spec) (car ,temp))
140 (setq ,temp (cdr ,temp))
141 ,@body)
142 ,@(if (cdr (cdr spec))
143 `((setq ,(car spec) nil) ,@(cdr (cdr spec)))))))
145 (defmacro dotimes (spec &rest body)
146 "Loop a certain number of times.
147 Evaluate BODY with VAR bound to successive integers running from 0,
148 inclusive, to COUNT, exclusive. Then evaluate RESULT to get
149 the return value (nil if RESULT is omitted).
151 \(fn (VAR COUNT [RESULT]) BODY...)"
152 (declare (indent 1) (debug dolist))
153 (let ((temp (make-symbol "--dotimes-temp--"))
154 (start 0)
155 (end (nth 1 spec)))
156 `(let ((,temp ,end)
157 (,(car spec) ,start))
158 (while (< ,(car spec) ,temp)
159 ,@body
160 (setq ,(car spec) (1+ ,(car spec))))
161 ,@(cdr (cdr spec)))))
163 (defmacro declare (&rest specs)
164 "Do not evaluate any arguments and return nil.
165 Treated as a declaration when used at the right place in a
166 `defmacro' form. \(See Info anchor `(elisp)Definition of declare'.)"
167 nil)
169 (defsubst caar (x)
170 "Return the car of the car of X."
171 (car (car x)))
173 (defsubst cadr (x)
174 "Return the car of the cdr of X."
175 (car (cdr x)))
177 (defsubst cdar (x)
178 "Return the cdr of the car of X."
179 (cdr (car x)))
181 (defsubst cddr (x)
182 "Return the cdr of the cdr of X."
183 (cdr (cdr x)))
185 (defun last (list &optional n)
186 "Return the last link of LIST. Its car is the last element.
187 If LIST is nil, return nil.
188 If N is non-nil, return the Nth-to-last link of LIST.
189 If N is bigger than the length of LIST, return LIST."
190 (if n
191 (let ((m 0) (p list))
192 (while (consp p)
193 (setq m (1+ m) p (cdr p)))
194 (if (<= n 0) p
195 (if (< n m) (nthcdr (- m n) list) list)))
196 (while (consp (cdr list))
197 (setq list (cdr list)))
198 list))
200 (defun butlast (list &optional n)
201 "Return a copy of LIST with the last N elements removed."
202 (if (and n (<= n 0)) list
203 (nbutlast (copy-sequence list) n)))
205 (defun nbutlast (list &optional n)
206 "Modifies LIST to remove the last N elements."
207 (let ((m (length list)))
208 (or n (setq n 1))
209 (and (< n m)
210 (progn
211 (if (> n 0) (setcdr (nthcdr (- (1- m) n) list) nil))
212 list))))
214 (defun delete-dups (list)
215 "Destructively remove `equal' duplicates from LIST.
216 Store the result in LIST and return it. LIST must be a proper list.
217 Of several `equal' occurrences of an element in LIST, the first
218 one is kept."
219 (let ((tail list))
220 (while tail
221 (setcdr tail (delete (car tail) (cdr tail)))
222 (setq tail (cdr tail))))
223 list)
225 (defun number-sequence (from &optional to inc)
226 "Return a sequence of numbers from FROM to TO (both inclusive) as a list.
227 INC is the increment used between numbers in the sequence and defaults to 1.
228 So, the Nth element of the list is \(+ FROM \(* N INC)) where N counts from
229 zero. TO is only included if there is an N for which TO = FROM + N * INC.
230 If TO is nil or numerically equal to FROM, return \(FROM).
231 If INC is positive and TO is less than FROM, or INC is negative
232 and TO is larger than FROM, return nil.
233 If INC is zero and TO is neither nil nor numerically equal to
234 FROM, signal an error.
236 This function is primarily designed for integer arguments.
237 Nevertheless, FROM, TO and INC can be integer or float. However,
238 floating point arithmetic is inexact. For instance, depending on
239 the machine, it may quite well happen that
240 \(number-sequence 0.4 0.6 0.2) returns the one element list \(0.4),
241 whereas \(number-sequence 0.4 0.8 0.2) returns a list with three
242 elements. Thus, if some of the arguments are floats and one wants
243 to make sure that TO is included, one may have to explicitly write
244 TO as \(+ FROM \(* N INC)) or use a variable whose value was
245 computed with this exact expression. Alternatively, you can,
246 of course, also replace TO with a slightly larger value
247 \(or a slightly more negative value if INC is negative)."
248 (if (or (not to) (= from to))
249 (list from)
250 (or inc (setq inc 1))
251 (when (zerop inc) (error "The increment can not be zero"))
252 (let (seq (n 0) (next from))
253 (if (> inc 0)
254 (while (<= next to)
255 (setq seq (cons next seq)
256 n (1+ n)
257 next (+ from (* n inc))))
258 (while (>= next to)
259 (setq seq (cons next seq)
260 n (1+ n)
261 next (+ from (* n inc)))))
262 (nreverse seq))))
264 (defun remove (elt seq)
265 "Return a copy of SEQ with all occurrences of ELT removed.
266 SEQ must be a list, vector, or string. The comparison is done with `equal'."
267 (if (nlistp seq)
268 ;; If SEQ isn't a list, there's no need to copy SEQ because
269 ;; `delete' will return a new object.
270 (delete elt seq)
271 (delete elt (copy-sequence seq))))
273 (defun remq (elt list)
274 "Return LIST with all occurrences of ELT removed.
275 The comparison is done with `eq'. Contrary to `delq', this does not use
276 side-effects, and the argument LIST is not modified."
277 (if (memq elt list)
278 (delq elt (copy-sequence list))
279 list))
281 (defun copy-tree (tree &optional vecp)
282 "Make a copy of TREE.
283 If TREE is a cons cell, this recursively copies both its car and its cdr.
284 Contrast to `copy-sequence', which copies only along the cdrs. With second
285 argument VECP, this copies vectors as well as conses."
286 (if (consp tree)
287 (let (result)
288 (while (consp tree)
289 (let ((newcar (car tree)))
290 (if (or (consp (car tree)) (and vecp (vectorp (car tree))))
291 (setq newcar (copy-tree (car tree) vecp)))
292 (push newcar result))
293 (setq tree (cdr tree)))
294 (nconc (nreverse result) tree))
295 (if (and vecp (vectorp tree))
296 (let ((i (length (setq tree (copy-sequence tree)))))
297 (while (>= (setq i (1- i)) 0)
298 (aset tree i (copy-tree (aref tree i) vecp)))
299 tree)
300 tree)))
302 (defun assoc-default (key alist &optional test default)
303 "Find object KEY in a pseudo-alist ALIST.
304 ALIST is a list of conses or objects. Each element (or the element's car,
305 if it is a cons) is compared with KEY by evaluating (TEST (car elt) KEY).
306 If that is non-nil, the element matches;
307 then `assoc-default' returns the element's cdr, if it is a cons,
308 or DEFAULT if the element is not a cons.
310 If no element matches, the value is nil.
311 If TEST is omitted or nil, `equal' is used."
312 (let (found (tail alist) value)
313 (while (and tail (not found))
314 (let ((elt (car tail)))
315 (when (funcall (or test 'equal) (if (consp elt) (car elt) elt) key)
316 (setq found t value (if (consp elt) (cdr elt) default))))
317 (setq tail (cdr tail)))
318 value))
320 (make-obsolete 'assoc-ignore-case 'assoc-string)
321 (defun assoc-ignore-case (key alist)
322 "Like `assoc', but ignores differences in case and text representation.
323 KEY must be a string. Upper-case and lower-case letters are treated as equal.
324 Unibyte strings are converted to multibyte for comparison."
325 (assoc-string key alist t))
327 (make-obsolete 'assoc-ignore-representation 'assoc-string)
328 (defun assoc-ignore-representation (key alist)
329 "Like `assoc', but ignores differences in text representation.
330 KEY must be a string.
331 Unibyte strings are converted to multibyte for comparison."
332 (assoc-string key alist nil))
334 (defun member-ignore-case (elt list)
335 "Like `member', but ignores differences in case and text representation.
336 ELT must be a string. Upper-case and lower-case letters are treated as equal.
337 Unibyte strings are converted to multibyte for comparison.
338 Non-strings in LIST are ignored."
339 (while (and list
340 (not (and (stringp (car list))
341 (eq t (compare-strings elt 0 nil (car list) 0 nil t)))))
342 (setq list (cdr list)))
343 list)
346 ;;;; Keymap support.
348 (defun undefined ()
349 (interactive)
350 (ding))
352 ;Prevent the \{...} documentation construct
353 ;from mentioning keys that run this command.
354 (put 'undefined 'suppress-keymap t)
356 (defun suppress-keymap (map &optional nodigits)
357 "Make MAP override all normally self-inserting keys to be undefined.
358 Normally, as an exception, digits and minus-sign are set to make prefix args,
359 but optional second arg NODIGITS non-nil treats them like other chars."
360 (define-key map [remap self-insert-command] 'undefined)
361 (or nodigits
362 (let (loop)
363 (define-key map "-" 'negative-argument)
364 ;; Make plain numbers do numeric args.
365 (setq loop ?0)
366 (while (<= loop ?9)
367 (define-key map (char-to-string loop) 'digit-argument)
368 (setq loop (1+ loop))))))
370 ;Moved to keymap.c
371 ;(defun copy-keymap (keymap)
372 ; "Return a copy of KEYMAP"
373 ; (while (not (keymapp keymap))
374 ; (setq keymap (signal 'wrong-type-argument (list 'keymapp keymap))))
375 ; (if (vectorp keymap)
376 ; (copy-sequence keymap)
377 ; (copy-alist keymap)))
379 (defvar key-substitution-in-progress nil
380 "Used internally by substitute-key-definition.")
382 (defun substitute-key-definition (olddef newdef keymap &optional oldmap prefix)
383 "Replace OLDDEF with NEWDEF for any keys in KEYMAP now defined as OLDDEF.
384 In other words, OLDDEF is replaced with NEWDEF where ever it appears.
385 Alternatively, if optional fourth argument OLDMAP is specified, we redefine
386 in KEYMAP as NEWDEF those keys which are defined as OLDDEF in OLDMAP.
388 For most uses, it is simpler and safer to use command remappping like this:
389 \(define-key KEYMAP [remap OLDDEF] NEWDEF)"
390 ;; Don't document PREFIX in the doc string because we don't want to
391 ;; advertise it. It's meant for recursive calls only. Here's its
392 ;; meaning
394 ;; If optional argument PREFIX is specified, it should be a key
395 ;; prefix, a string. Redefined bindings will then be bound to the
396 ;; original key, with PREFIX added at the front.
397 (or prefix (setq prefix ""))
398 (let* ((scan (or oldmap keymap))
399 (vec1 (vector nil))
400 (prefix1 (vconcat prefix vec1))
401 (key-substitution-in-progress
402 (cons scan key-substitution-in-progress)))
403 ;; Scan OLDMAP, finding each char or event-symbol that
404 ;; has any definition, and act on it with hack-key.
405 (while (consp scan)
406 (if (consp (car scan))
407 (let ((char (car (car scan)))
408 (defn (cdr (car scan))))
409 ;; The inside of this let duplicates exactly
410 ;; the inside of the following let that handles array elements.
411 (aset vec1 0 char)
412 (aset prefix1 (length prefix) char)
413 (let (inner-def skipped)
414 ;; Skip past menu-prompt.
415 (while (stringp (car-safe defn))
416 (setq skipped (cons (car defn) skipped))
417 (setq defn (cdr defn)))
418 ;; Skip past cached key-equivalence data for menu items.
419 (and (consp defn) (consp (car defn))
420 (setq defn (cdr defn)))
421 (setq inner-def defn)
422 ;; Look past a symbol that names a keymap.
423 (while (and (symbolp inner-def)
424 (fboundp inner-def))
425 (setq inner-def (symbol-function inner-def)))
426 (if (or (eq defn olddef)
427 ;; Compare with equal if definition is a key sequence.
428 ;; That is useful for operating on function-key-map.
429 (and (or (stringp defn) (vectorp defn))
430 (equal defn olddef)))
431 (define-key keymap prefix1 (nconc (nreverse skipped) newdef))
432 (if (and (keymapp defn)
433 ;; Avoid recursively scanning
434 ;; where KEYMAP does not have a submap.
435 (let ((elt (lookup-key keymap prefix1)))
436 (or (null elt)
437 (keymapp elt)))
438 ;; Avoid recursively rescanning keymap being scanned.
439 (not (memq inner-def
440 key-substitution-in-progress)))
441 ;; If this one isn't being scanned already,
442 ;; scan it now.
443 (substitute-key-definition olddef newdef keymap
444 inner-def
445 prefix1)))))
446 (if (vectorp (car scan))
447 (let* ((array (car scan))
448 (len (length array))
449 (i 0))
450 (while (< i len)
451 (let ((char i) (defn (aref array i)))
452 ;; The inside of this let duplicates exactly
453 ;; the inside of the previous let.
454 (aset vec1 0 char)
455 (aset prefix1 (length prefix) char)
456 (let (inner-def skipped)
457 ;; Skip past menu-prompt.
458 (while (stringp (car-safe defn))
459 (setq skipped (cons (car defn) skipped))
460 (setq defn (cdr defn)))
461 (and (consp defn) (consp (car defn))
462 (setq defn (cdr defn)))
463 (setq inner-def defn)
464 (while (and (symbolp inner-def)
465 (fboundp inner-def))
466 (setq inner-def (symbol-function inner-def)))
467 (if (or (eq defn olddef)
468 (and (or (stringp defn) (vectorp defn))
469 (equal defn olddef)))
470 (define-key keymap prefix1
471 (nconc (nreverse skipped) newdef))
472 (if (and (keymapp defn)
473 (let ((elt (lookup-key keymap prefix1)))
474 (or (null elt)
475 (keymapp elt)))
476 (not (memq inner-def
477 key-substitution-in-progress)))
478 (substitute-key-definition olddef newdef keymap
479 inner-def
480 prefix1)))))
481 (setq i (1+ i))))
482 (if (char-table-p (car scan))
483 (map-char-table
484 (function (lambda (char defn)
485 (let ()
486 ;; The inside of this let duplicates exactly
487 ;; the inside of the previous let,
488 ;; except that it uses set-char-table-range
489 ;; instead of define-key.
490 (aset vec1 0 char)
491 (aset prefix1 (length prefix) char)
492 (let (inner-def skipped)
493 ;; Skip past menu-prompt.
494 (while (stringp (car-safe defn))
495 (setq skipped (cons (car defn) skipped))
496 (setq defn (cdr defn)))
497 (and (consp defn) (consp (car defn))
498 (setq defn (cdr defn)))
499 (setq inner-def defn)
500 (while (and (symbolp inner-def)
501 (fboundp inner-def))
502 (setq inner-def (symbol-function inner-def)))
503 (if (or (eq defn olddef)
504 (and (or (stringp defn) (vectorp defn))
505 (equal defn olddef)))
506 (define-key keymap prefix1
507 (nconc (nreverse skipped) newdef))
508 (if (and (keymapp defn)
509 (let ((elt (lookup-key keymap prefix1)))
510 (or (null elt)
511 (keymapp elt)))
512 (not (memq inner-def
513 key-substitution-in-progress)))
514 (substitute-key-definition olddef newdef keymap
515 inner-def
516 prefix1)))))))
517 (car scan)))))
518 (setq scan (cdr scan)))))
520 (defun define-key-after (keymap key definition &optional after)
521 "Add binding in KEYMAP for KEY => DEFINITION, right after AFTER's binding.
522 This is like `define-key' except that the binding for KEY is placed
523 just after the binding for the event AFTER, instead of at the beginning
524 of the map. Note that AFTER must be an event type (like KEY), NOT a command
525 \(like DEFINITION).
527 If AFTER is t or omitted, the new binding goes at the end of the keymap.
528 AFTER should be a single event type--a symbol or a character, not a sequence.
530 Bindings are always added before any inherited map.
532 The order of bindings in a keymap matters when it is used as a menu."
533 (unless after (setq after t))
534 (or (keymapp keymap)
535 (signal 'wrong-type-argument (list 'keymapp keymap)))
536 (setq key
537 (if (<= (length key) 1) (aref key 0)
538 (setq keymap (lookup-key keymap
539 (apply 'vector
540 (butlast (mapcar 'identity key)))))
541 (aref key (1- (length key)))))
542 (let ((tail keymap) done inserted)
543 (while (and (not done) tail)
544 ;; Delete any earlier bindings for the same key.
545 (if (eq (car-safe (car (cdr tail))) key)
546 (setcdr tail (cdr (cdr tail))))
547 ;; If we hit an included map, go down that one.
548 (if (keymapp (car tail)) (setq tail (car tail)))
549 ;; When we reach AFTER's binding, insert the new binding after.
550 ;; If we reach an inherited keymap, insert just before that.
551 ;; If we reach the end of this keymap, insert at the end.
552 (if (or (and (eq (car-safe (car tail)) after)
553 (not (eq after t)))
554 (eq (car (cdr tail)) 'keymap)
555 (null (cdr tail)))
556 (progn
557 ;; Stop the scan only if we find a parent keymap.
558 ;; Keep going past the inserted element
559 ;; so we can delete any duplications that come later.
560 (if (eq (car (cdr tail)) 'keymap)
561 (setq done t))
562 ;; Don't insert more than once.
563 (or inserted
564 (setcdr tail (cons (cons key definition) (cdr tail))))
565 (setq inserted t)))
566 (setq tail (cdr tail)))))
569 (defmacro kbd (keys)
570 "Convert KEYS to the internal Emacs key representation.
571 KEYS should be a string constant in the format used for
572 saving keyboard macros (see `edmacro-mode')."
573 (read-kbd-macro keys))
575 (put 'keyboard-translate-table 'char-table-extra-slots 0)
577 (defun keyboard-translate (from to)
578 "Translate character FROM to TO at a low level.
579 This function creates a `keyboard-translate-table' if necessary
580 and then modifies one entry in it."
581 (or (char-table-p keyboard-translate-table)
582 (setq keyboard-translate-table
583 (make-char-table 'keyboard-translate-table nil)))
584 (aset keyboard-translate-table from to))
587 ;;;; The global keymap tree.
589 ;;; global-map, esc-map, and ctl-x-map have their values set up in
590 ;;; keymap.c; we just give them docstrings here.
592 (defvar global-map nil
593 "Default global keymap mapping Emacs keyboard input into commands.
594 The value is a keymap which is usually (but not necessarily) Emacs's
595 global map.")
597 (defvar esc-map nil
598 "Default keymap for ESC (meta) commands.
599 The normal global definition of the character ESC indirects to this keymap.")
601 (defvar ctl-x-map nil
602 "Default keymap for C-x commands.
603 The normal global definition of the character C-x indirects to this keymap.")
605 (defvar ctl-x-4-map (make-sparse-keymap)
606 "Keymap for subcommands of C-x 4.")
607 (defalias 'ctl-x-4-prefix ctl-x-4-map)
608 (define-key ctl-x-map "4" 'ctl-x-4-prefix)
610 (defvar ctl-x-5-map (make-sparse-keymap)
611 "Keymap for frame commands.")
612 (defalias 'ctl-x-5-prefix ctl-x-5-map)
613 (define-key ctl-x-map "5" 'ctl-x-5-prefix)
616 ;;;; Event manipulation functions.
618 ;; The call to `read' is to ensure that the value is computed at load time
619 ;; and not compiled into the .elc file. The value is negative on most
620 ;; machines, but not on all!
621 (defconst listify-key-sequence-1 (logior 128 (read "?\\M-\\^@")))
623 (defun listify-key-sequence (key)
624 "Convert a key sequence to a list of events."
625 (if (vectorp key)
626 (append key nil)
627 (mapcar (function (lambda (c)
628 (if (> c 127)
629 (logxor c listify-key-sequence-1)
630 c)))
631 key)))
633 (defsubst eventp (obj)
634 "True if the argument is an event object."
635 (or (and (integerp obj)
636 ;; Filter out integers too large to be events.
637 ;; M is the biggest modifier.
638 (zerop (logand obj (lognot (1- (lsh ?\M-\^@ 1)))))
639 (char-valid-p (event-basic-type obj)))
640 (and (symbolp obj)
641 (get obj 'event-symbol-elements))
642 (and (consp obj)
643 (symbolp (car obj))
644 (get (car obj) 'event-symbol-elements))))
646 (defun event-modifiers (event)
647 "Return a list of symbols representing the modifier keys in event EVENT.
648 The elements of the list may include `meta', `control',
649 `shift', `hyper', `super', `alt', `click', `double', `triple', `drag',
650 and `down'.
651 EVENT may be an event or an event type. If EVENT is a symbol
652 that has never been used in an event that has been read as input
653 in the current Emacs session, then this function can return nil,
654 even when EVENT actually has modifiers."
655 (let ((type event))
656 (if (listp type)
657 (setq type (car type)))
658 (if (symbolp type)
659 (cdr (get type 'event-symbol-elements))
660 (let ((list nil)
661 (char (logand type (lognot (logior ?\M-\^@ ?\C-\^@ ?\S-\^@
662 ?\H-\^@ ?\s-\^@ ?\A-\^@)))))
663 (if (not (zerop (logand type ?\M-\^@)))
664 (setq list (cons 'meta list)))
665 (if (or (not (zerop (logand type ?\C-\^@)))
666 (< char 32))
667 (setq list (cons 'control list)))
668 (if (or (not (zerop (logand type ?\S-\^@)))
669 (/= char (downcase char)))
670 (setq list (cons 'shift list)))
671 (or (zerop (logand type ?\H-\^@))
672 (setq list (cons 'hyper list)))
673 (or (zerop (logand type ?\s-\^@))
674 (setq list (cons 'super list)))
675 (or (zerop (logand type ?\A-\^@))
676 (setq list (cons 'alt list)))
677 list))))
679 (defun event-basic-type (event)
680 "Return the basic type of the given event (all modifiers removed).
681 The value is a printing character (not upper case) or a symbol.
682 EVENT may be an event or an event type. If EVENT is a symbol
683 that has never been used in an event that has been read as input
684 in the current Emacs session, then this function may return nil."
685 (if (consp event)
686 (setq event (car event)))
687 (if (symbolp event)
688 (car (get event 'event-symbol-elements))
689 (let ((base (logand event (1- ?\A-\^@))))
690 (downcase (if (< base 32) (logior base 64) base)))))
692 (defsubst mouse-movement-p (object)
693 "Return non-nil if OBJECT is a mouse movement event."
694 (and (consp object)
695 (eq (car object) 'mouse-movement)))
697 (defsubst event-start (event)
698 "Return the starting position of EVENT.
699 If EVENT is a mouse or key press or a mouse click, this returns the location
700 of the event.
701 If EVENT is a drag, this returns the drag's starting position.
702 The return value is of the form
703 (WINDOW AREA-OR-POS (X . Y) TIMESTAMP OBJECT POS (COL . ROW)
704 IMAGE (DX . DY) (WIDTH . HEIGHT))
705 The `posn-' functions access elements of such lists."
706 (if (consp event) (nth 1 event)
707 (list (selected-window) (point) '(0 . 0) 0)))
709 (defsubst event-end (event)
710 "Return the ending location of EVENT.
711 EVENT should be a click, drag, or key press event.
712 If EVENT is a click event, this function is the same as `event-start'.
713 The return value is of the form
714 (WINDOW AREA-OR-POS (X . Y) TIMESTAMP OBJECT POS (COL . ROW)
715 IMAGE (DX . DY) (WIDTH . HEIGHT))
716 The `posn-' functions access elements of such lists."
717 (if (consp event) (nth (if (consp (nth 2 event)) 2 1) event)
718 (list (selected-window) (point) '(0 . 0) 0)))
720 (defsubst event-click-count (event)
721 "Return the multi-click count of EVENT, a click or drag event.
722 The return value is a positive integer."
723 (if (and (consp event) (integerp (nth 2 event))) (nth 2 event) 1))
725 (defsubst posn-window (position)
726 "Return the window in POSITION.
727 POSITION should be a list of the form returned by the `event-start'
728 and `event-end' functions."
729 (nth 0 position))
731 (defsubst posn-area (position)
732 "Return the window area recorded in POSITION, or nil for the text area.
733 POSITION should be a list of the form returned by the `event-start'
734 and `event-end' functions."
735 (let ((area (if (consp (nth 1 position))
736 (car (nth 1 position))
737 (nth 1 position))))
738 (and (symbolp area) area)))
740 (defsubst posn-point (position)
741 "Return the buffer location in POSITION.
742 POSITION should be a list of the form returned by the `event-start'
743 and `event-end' functions."
744 (or (nth 5 position)
745 (if (consp (nth 1 position))
746 (car (nth 1 position))
747 (nth 1 position))))
749 (defun posn-set-point (position)
750 "Move point to POSITION.
751 Select the corresponding window as well."
752 (if (not (windowp (posn-window position)))
753 (error "Position not in text area of window"))
754 (select-window (posn-window position))
755 (if (numberp (posn-point position))
756 (goto-char (posn-point position))))
758 (defsubst posn-x-y (position)
759 "Return the x and y coordinates in POSITION.
760 POSITION should be a list of the form returned by the `event-start'
761 and `event-end' functions."
762 (nth 2 position))
764 (defun posn-col-row (position)
765 "Return the nominal column and row in POSITION, measured in characters.
766 The column and row values are approximations calculated from the x
767 and y coordinates in POSITION and the frame's default character width
768 and height.
769 For a scroll-bar event, the result column is 0, and the row
770 corresponds to the vertical position of the click in the scroll bar.
771 POSITION should be a list of the form returned by the `event-start'
772 and `event-end' functions."
773 (let* ((pair (posn-x-y position))
774 (window (posn-window position))
775 (area (posn-area position)))
776 (cond
777 ((null window)
778 '(0 . 0))
779 ((eq area 'vertical-scroll-bar)
780 (cons 0 (scroll-bar-scale pair (1- (window-height window)))))
781 ((eq area 'horizontal-scroll-bar)
782 (cons (scroll-bar-scale pair (window-width window)) 0))
784 (let* ((frame (if (framep window) window (window-frame window)))
785 (x (/ (car pair) (frame-char-width frame)))
786 (y (/ (cdr pair) (+ (frame-char-height frame)
787 (or (frame-parameter frame 'line-spacing)
788 default-line-spacing
789 0)))))
790 (cons x y))))))
792 (defun posn-actual-col-row (position)
793 "Return the actual column and row in POSITION, measured in characters.
794 These are the actual row number in the window and character number in that row.
795 Return nil if POSITION does not contain the actual position; in that case
796 `posn-col-row' can be used to get approximate values.
797 POSITION should be a list of the form returned by the `event-start'
798 and `event-end' functions."
799 (nth 6 position))
801 (defsubst posn-timestamp (position)
802 "Return the timestamp of POSITION.
803 POSITION should be a list of the form returned by the `event-start'
804 and `event-end' functions."
805 (nth 3 position))
807 (defsubst posn-string (position)
808 "Return the string object of POSITION, or nil if a buffer position.
809 POSITION should be a list of the form returned by the `event-start'
810 and `event-end' functions."
811 (nth 4 position))
813 (defsubst posn-image (position)
814 "Return the image object of POSITION, or nil if a not an image.
815 POSITION should be a list of the form returned by the `event-start'
816 and `event-end' functions."
817 (nth 7 position))
819 (defsubst posn-object (position)
820 "Return the object (image or string) of POSITION.
821 POSITION should be a list of the form returned by the `event-start'
822 and `event-end' functions."
823 (or (posn-image position) (posn-string position)))
825 (defsubst posn-object-x-y (position)
826 "Return the x and y coordinates relative to the object of POSITION.
827 POSITION should be a list of the form returned by the `event-start'
828 and `event-end' functions."
829 (nth 8 position))
831 (defsubst posn-object-width-height (position)
832 "Return the pixel width and height of the object of POSITION.
833 POSITION should be a list of the form returned by the `event-start'
834 and `event-end' functions."
835 (nth 9 position))
838 ;;;; Obsolescent names for functions.
840 (defalias 'dot 'point)
841 (defalias 'dot-marker 'point-marker)
842 (defalias 'dot-min 'point-min)
843 (defalias 'dot-max 'point-max)
844 (defalias 'window-dot 'window-point)
845 (defalias 'set-window-dot 'set-window-point)
846 (defalias 'read-input 'read-string)
847 (defalias 'send-string 'process-send-string)
848 (defalias 'send-region 'process-send-region)
849 (defalias 'show-buffer 'set-window-buffer)
850 (defalias 'buffer-flush-undo 'buffer-disable-undo)
851 (defalias 'eval-current-buffer 'eval-buffer)
852 (defalias 'compiled-function-p 'byte-code-function-p)
853 (defalias 'define-function 'defalias)
855 (defalias 'sref 'aref)
856 (make-obsolete 'sref 'aref "20.4")
857 (make-obsolete 'char-bytes "now always returns 1." "20.4")
858 (make-obsolete 'chars-in-region "use (abs (- BEG END))." "20.3")
859 (make-obsolete 'dot 'point "before 19.15")
860 (make-obsolete 'dot-max 'point-max "before 19.15")
861 (make-obsolete 'dot-min 'point-min "before 19.15")
862 (make-obsolete 'dot-marker 'point-marker "before 19.15")
863 (make-obsolete 'buffer-flush-undo 'buffer-disable-undo "before 19.15")
864 (make-obsolete 'baud-rate "use the `baud-rate' variable instead." "before 19.15")
865 (make-obsolete 'compiled-function-p 'byte-code-function-p "before 19.15")
866 (make-obsolete 'define-function 'defalias "20.1")
867 (make-obsolete 'focus-frame "it does nothing." "19.32")
868 (make-obsolete 'unfocus-frame "it does nothing." "19.32")
870 (defun insert-string (&rest args)
871 "Mocklisp-compatibility insert function.
872 Like the function `insert' except that any argument that is a number
873 is converted into a string by expressing it in decimal."
874 (dolist (el args)
875 (insert (if (integerp el) (number-to-string el) el))))
876 (make-obsolete 'insert-string 'insert "21.4")
877 (defun makehash (&optional test) (make-hash-table :test (or test 'eql)))
878 (make-obsolete 'makehash 'make-hash-table "21.4")
880 ;; Some programs still use this as a function.
881 (defun baud-rate ()
882 "Return the value of the `baud-rate' variable."
883 baud-rate)
885 (defalias 'focus-frame 'ignore "")
886 (defalias 'unfocus-frame 'ignore "")
889 ;;;; Obsolescence declarations for variables.
891 (make-obsolete-variable 'directory-sep-char "do not use it." "21.1")
892 (make-obsolete-variable 'mode-line-inverse-video "use the appropriate faces instead." "21.1")
893 (make-obsolete-variable 'unread-command-char
894 "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."
895 "before 19.15")
896 (make-obsolete-variable 'executing-macro 'executing-kbd-macro "before 19.34")
897 (make-obsolete-variable 'post-command-idle-hook
898 "use timers instead, with `run-with-idle-timer'." "before 19.34")
899 (make-obsolete-variable 'post-command-idle-delay
900 "use timers instead, with `run-with-idle-timer'." "before 19.34")
903 ;;;; Alternate names for functions - these are not being phased out.
905 (defalias 'string= 'string-equal)
906 (defalias 'string< 'string-lessp)
907 (defalias 'move-marker 'set-marker)
908 (defalias 'rplaca 'setcar)
909 (defalias 'rplacd 'setcdr)
910 (defalias 'beep 'ding) ;preserve lingual purity
911 (defalias 'indent-to-column 'indent-to)
912 (defalias 'backward-delete-char 'delete-backward-char)
913 (defalias 'search-forward-regexp (symbol-function 're-search-forward))
914 (defalias 'search-backward-regexp (symbol-function 're-search-backward))
915 (defalias 'int-to-string 'number-to-string)
916 (defalias 'store-match-data 'set-match-data)
917 (defalias 'make-variable-frame-localizable 'make-variable-frame-local)
918 ;; These are the XEmacs names:
919 (defalias 'point-at-eol 'line-end-position)
920 (defalias 'point-at-bol 'line-beginning-position)
922 ;;; Should this be an obsolete name? If you decide it should, you get
923 ;;; to go through all the sources and change them.
924 (defalias 'string-to-int 'string-to-number)
926 ;;;; Hook manipulation functions.
928 (defun make-local-hook (hook)
929 "Make the hook HOOK local to the current buffer.
930 The return value is HOOK.
932 You never need to call this function now that `add-hook' does it for you
933 if its LOCAL argument is non-nil.
935 When a hook is local, its local and global values
936 work in concert: running the hook actually runs all the hook
937 functions listed in *either* the local value *or* the global value
938 of the hook variable.
940 This function works by making t a member of the buffer-local value,
941 which acts as a flag to run the hook functions in the default value as
942 well. This works for all normal hooks, but does not work for most
943 non-normal hooks yet. We will be changing the callers of non-normal
944 hooks so that they can handle localness; this has to be done one by
945 one.
947 This function does nothing if HOOK is already local in the current
948 buffer.
950 Do not use `make-local-variable' to make a hook variable buffer-local."
951 (if (local-variable-p hook)
953 (or (boundp hook) (set hook nil))
954 (make-local-variable hook)
955 (set hook (list t)))
956 hook)
957 (make-obsolete 'make-local-hook "not necessary any more." "21.1")
959 (defun add-hook (hook function &optional append local)
960 "Add to the value of HOOK the function FUNCTION.
961 FUNCTION is not added if already present.
962 FUNCTION is added (if necessary) at the beginning of the hook list
963 unless the optional argument APPEND is non-nil, in which case
964 FUNCTION is added at the end.
966 The optional fourth argument, LOCAL, if non-nil, says to modify
967 the hook's buffer-local value rather than its default value.
968 This makes the hook buffer-local if needed, and it makes t a member
969 of the buffer-local value. That acts as a flag to run the hook
970 functions in the default value as well as in the local value.
972 HOOK should be a symbol, and FUNCTION may be any valid function. If
973 HOOK is void, it is first set to nil. If HOOK's value is a single
974 function, it is changed to a list of functions."
975 (or (boundp hook) (set hook nil))
976 (or (default-boundp hook) (set-default hook nil))
977 (if local (unless (local-variable-if-set-p hook)
978 (set (make-local-variable hook) (list t)))
979 ;; Detect the case where make-local-variable was used on a hook
980 ;; and do what we used to do.
981 (unless (and (consp (symbol-value hook)) (memq t (symbol-value hook)))
982 (setq local t)))
983 (let ((hook-value (if local (symbol-value hook) (default-value hook))))
984 ;; If the hook value is a single function, turn it into a list.
985 (when (or (not (listp hook-value)) (eq (car hook-value) 'lambda))
986 (setq hook-value (list hook-value)))
987 ;; Do the actual addition if necessary
988 (unless (member function hook-value)
989 (setq hook-value
990 (if append
991 (append hook-value (list function))
992 (cons function hook-value))))
993 ;; Set the actual variable
994 (if local (set hook hook-value) (set-default hook hook-value))))
996 (defun remove-hook (hook function &optional local)
997 "Remove from the value of HOOK the function FUNCTION.
998 HOOK should be a symbol, and FUNCTION may be any valid function. If
999 FUNCTION isn't the value of HOOK, or, if FUNCTION doesn't appear in the
1000 list of hooks to run in HOOK, then nothing is done. See `add-hook'.
1002 The optional third argument, LOCAL, if non-nil, says to modify
1003 the hook's buffer-local value rather than its default value."
1004 (or (boundp hook) (set hook nil))
1005 (or (default-boundp hook) (set-default hook nil))
1006 ;; Do nothing if LOCAL is t but this hook has no local binding.
1007 (unless (and local (not (local-variable-p hook)))
1008 ;; Detect the case where make-local-variable was used on a hook
1009 ;; and do what we used to do.
1010 (when (and (local-variable-p hook)
1011 (not (and (consp (symbol-value hook))
1012 (memq t (symbol-value hook)))))
1013 (setq local t))
1014 (let ((hook-value (if local (symbol-value hook) (default-value hook))))
1015 ;; Remove the function, for both the list and the non-list cases.
1016 (if (or (not (listp hook-value)) (eq (car hook-value) 'lambda))
1017 (if (equal hook-value function) (setq hook-value nil))
1018 (setq hook-value (delete function (copy-sequence hook-value))))
1019 ;; If the function is on the global hook, we need to shadow it locally
1020 ;;(when (and local (member function (default-value hook))
1021 ;; (not (member (cons 'not function) hook-value)))
1022 ;; (push (cons 'not function) hook-value))
1023 ;; Set the actual variable
1024 (if (not local)
1025 (set-default hook hook-value)
1026 (if (equal hook-value '(t))
1027 (kill-local-variable hook)
1028 (set hook hook-value))))))
1030 (defun add-to-list (list-var element &optional append)
1031 "Add to the value of LIST-VAR the element ELEMENT if it isn't there yet.
1032 The test for presence of ELEMENT is done with `equal'.
1033 If ELEMENT is added, it is added at the beginning of the list,
1034 unless the optional argument APPEND is non-nil, in which case
1035 ELEMENT is added at the end.
1037 The return value is the new value of LIST-VAR.
1039 If you want to use `add-to-list' on a variable that is not defined
1040 until a certain package is loaded, you should put the call to `add-to-list'
1041 into a hook function that will be run only after loading the package.
1042 `eval-after-load' provides one way to do this. In some cases
1043 other hooks, such as major mode hooks, can do the job."
1044 (if (member element (symbol-value list-var))
1045 (symbol-value list-var)
1046 (set list-var
1047 (if append
1048 (append (symbol-value list-var) (list element))
1049 (cons element (symbol-value list-var))))))
1052 ;;; Load history
1054 ;;; (defvar symbol-file-load-history-loaded nil
1055 ;;; "Non-nil means we have loaded the file `fns-VERSION.el' in `exec-directory'.
1056 ;;; That file records the part of `load-history' for preloaded files,
1057 ;;; which is cleared out before dumping to make Emacs smaller.")
1059 ;;; (defun load-symbol-file-load-history ()
1060 ;;; "Load the file `fns-VERSION.el' in `exec-directory' if not already done.
1061 ;;; That file records the part of `load-history' for preloaded files,
1062 ;;; which is cleared out before dumping to make Emacs smaller."
1063 ;;; (unless symbol-file-load-history-loaded
1064 ;;; (load (expand-file-name
1065 ;;; ;; fns-XX.YY.ZZ.el does not work on DOS filesystem.
1066 ;;; (if (eq system-type 'ms-dos)
1067 ;;; "fns.el"
1068 ;;; (format "fns-%s.el" emacs-version))
1069 ;;; exec-directory)
1070 ;;; ;; The file name fns-%s.el already has a .el extension.
1071 ;;; nil nil t)
1072 ;;; (setq symbol-file-load-history-loaded t)))
1074 (defun symbol-file (function)
1075 "Return the input source from which FUNCTION was loaded.
1076 The value is normally a string that was passed to `load':
1077 either an absolute file name, or a library name
1078 \(with no directory name and no `.el' or `.elc' at the end).
1079 It can also be nil, if the definition is not associated with any file."
1080 (if (and (symbolp function) (fboundp function)
1081 (eq 'autoload (car-safe (symbol-function function))))
1082 (nth 1 (symbol-function function))
1083 (let ((files load-history)
1084 file)
1085 (while files
1086 (if (member function (cdr (car files)))
1087 (setq file (car (car files)) files nil))
1088 (setq files (cdr files)))
1089 file)))
1092 ;;;; Specifying things to do after certain files are loaded.
1094 (defun eval-after-load (file form)
1095 "Arrange that, if FILE is ever loaded, FORM will be run at that time.
1096 This makes or adds to an entry on `after-load-alist'.
1097 If FILE is already loaded, evaluate FORM right now.
1098 It does nothing if FORM is already on the list for FILE.
1099 FILE must match exactly. Normally FILE is the name of a library,
1100 with no directory or extension specified, since that is how `load'
1101 is normally called.
1102 FILE can also be a feature (i.e. a symbol), in which case FORM is
1103 evaluated whenever that feature is `provide'd."
1104 (let ((elt (assoc file after-load-alist)))
1105 ;; Make sure there is an element for FILE.
1106 (unless elt (setq elt (list file)) (push elt after-load-alist))
1107 ;; Add FORM to the element if it isn't there.
1108 (unless (member form (cdr elt))
1109 (nconc elt (list form))
1110 ;; If the file has been loaded already, run FORM right away.
1111 (if (if (symbolp file)
1112 (featurep file)
1113 ;; Make sure `load-history' contains the files dumped with
1114 ;; Emacs for the case that FILE is one of them.
1115 ;; (load-symbol-file-load-history)
1116 (assoc file load-history))
1117 (eval form))))
1118 form)
1120 (defun eval-next-after-load (file)
1121 "Read the following input sexp, and run it whenever FILE is loaded.
1122 This makes or adds to an entry on `after-load-alist'.
1123 FILE should be the name of a library, with no directory name."
1124 (eval-after-load file (read)))
1126 ;;; make-network-process wrappers
1128 (if (featurep 'make-network-process)
1129 (progn
1131 (defun open-network-stream (name buffer host service)
1132 "Open a TCP connection for a service to a host.
1133 Returns a subprocess-object to represent the connection.
1134 Input and output work as for subprocesses; `delete-process' closes it.
1136 Args are NAME BUFFER HOST SERVICE.
1137 NAME is name for process. It is modified if necessary to make it unique.
1138 BUFFER is the buffer (or buffer name) to associate with the process.
1139 Process output goes at end of that buffer, unless you specify
1140 an output stream or filter function to handle the output.
1141 BUFFER may be also nil, meaning that this process is not associated
1142 with any buffer.
1143 HOST is name of the host to connect to, or its IP address.
1144 SERVICE is name of the service desired, or an integer specifying
1145 a port number to connect to."
1146 (make-network-process :name name :buffer buffer
1147 :host host :service service))
1149 (defun open-network-stream-nowait (name buffer host service &optional sentinel filter)
1150 "Initiate connection to a TCP connection for a service to a host.
1151 It returns nil if non-blocking connects are not supported; otherwise,
1152 it returns a subprocess-object to represent the connection.
1154 This function is similar to `open-network-stream', except that it
1155 returns before the connection is established. When the connection
1156 is completed, the sentinel function will be called with second arg
1157 matching `open' (if successful) or `failed' (on error).
1159 Args are NAME BUFFER HOST SERVICE SENTINEL FILTER.
1160 NAME, BUFFER, HOST, and SERVICE are as for `open-network-stream'.
1161 Optional args SENTINEL and FILTER specify the sentinel and filter
1162 functions to be used for this network stream."
1163 (if (featurep 'make-network-process '(:nowait t))
1164 (make-network-process :name name :buffer buffer :nowait t
1165 :host host :service service
1166 :filter filter :sentinel sentinel)))
1168 (defun open-network-stream-server (name buffer service &optional sentinel filter)
1169 "Create a network server process for a TCP service.
1170 It returns nil if server processes are not supported; otherwise,
1171 it returns a subprocess-object to represent the server.
1173 When a client connects to the specified service, a new subprocess
1174 is created to handle the new connection, and the sentinel function
1175 is called for the new process.
1177 Args are NAME BUFFER SERVICE SENTINEL FILTER.
1178 NAME is name for the server process. Client processes are named by
1179 appending the ip-address and port number of the client to NAME.
1180 BUFFER is the buffer (or buffer name) to associate with the server
1181 process. Client processes will not get a buffer if a process filter
1182 is specified or BUFFER is nil; otherwise, a new buffer is created for
1183 the client process. The name is similar to the process name.
1184 Third arg SERVICE is name of the service desired, or an integer
1185 specifying a port number to connect to. It may also be t to select
1186 an unused port number for the server.
1187 Optional args SENTINEL and FILTER specify the sentinel and filter
1188 functions to be used for the client processes; the server process
1189 does not use these function."
1190 (if (featurep 'make-network-process '(:server t))
1191 (make-network-process :name name :buffer buffer
1192 :service service :server t :noquery t
1193 :sentinel sentinel :filter filter)))
1195 )) ;; (featurep 'make-network-process)
1198 ;; compatibility
1200 (make-obsolete 'process-kill-without-query
1201 "use `process-query-on-exit-flag' or `set-process-query-on-exit-flag'."
1202 "21.4")
1203 (defun process-kill-without-query (process &optional flag)
1204 "Say no query needed if PROCESS is running when Emacs is exited.
1205 Optional second argument if non-nil says to require a query.
1206 Value is t if a query was formerly required."
1207 (let ((old (process-query-on-exit-flag process)))
1208 (set-process-query-on-exit-flag process nil)
1209 old))
1211 ;; process plist management
1213 (defun process-get (process propname)
1214 "Return the value of PROCESS' PROPNAME property.
1215 This is the last value stored with `(process-put PROCESS PROPNAME VALUE)'."
1216 (plist-get (process-plist process) propname))
1218 (defun process-put (process propname value)
1219 "Change PROCESS' PROPNAME property to VALUE.
1220 It can be retrieved with `(process-get PROCESS PROPNAME)'."
1221 (set-process-plist process
1222 (plist-put (process-plist process) propname value)))
1225 ;;;; Input and display facilities.
1227 (defvar read-quoted-char-radix 8
1228 "*Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
1229 Legitimate radix values are 8, 10 and 16.")
1231 (custom-declare-variable-early
1232 'read-quoted-char-radix 8
1233 "*Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
1234 Legitimate radix values are 8, 10 and 16."
1235 :type '(choice (const 8) (const 10) (const 16))
1236 :group 'editing-basics)
1238 (defun read-quoted-char (&optional prompt)
1239 "Like `read-char', but do not allow quitting.
1240 Also, if the first character read is an octal digit,
1241 we read any number of octal digits and return the
1242 specified character code. Any nondigit terminates the sequence.
1243 If the terminator is RET, it is discarded;
1244 any other terminator is used itself as input.
1246 The optional argument PROMPT specifies a string to use to prompt the user.
1247 The variable `read-quoted-char-radix' controls which radix to use
1248 for numeric input."
1249 (let ((message-log-max nil) done (first t) (code 0) char translated)
1250 (while (not done)
1251 (let ((inhibit-quit first)
1252 ;; Don't let C-h get the help message--only help function keys.
1253 (help-char nil)
1254 (help-form
1255 "Type the special character you want to use,
1256 or the octal character code.
1257 RET terminates the character code and is discarded;
1258 any other non-digit terminates the character code and is then used as input."))
1259 (setq char (read-event (and prompt (format "%s-" prompt)) t))
1260 (if inhibit-quit (setq quit-flag nil)))
1261 ;; Translate TAB key into control-I ASCII character, and so on.
1262 ;; Note: `read-char' does it using the `ascii-character' property.
1263 ;; We could try and use read-key-sequence instead, but then C-q ESC
1264 ;; or C-q C-x might not return immediately since ESC or C-x might be
1265 ;; bound to some prefix in function-key-map or key-translation-map.
1266 (setq translated char)
1267 (let ((translation (lookup-key function-key-map (vector char))))
1268 (if (arrayp translation)
1269 (setq translated (aref translation 0))))
1270 (cond ((null translated))
1271 ((not (integerp translated))
1272 (setq unread-command-events (list char)
1273 done t))
1274 ((/= (logand translated ?\M-\^@) 0)
1275 ;; Turn a meta-character into a character with the 0200 bit set.
1276 (setq code (logior (logand translated (lognot ?\M-\^@)) 128)
1277 done t))
1278 ((and (<= ?0 translated) (< translated (+ ?0 (min 10 read-quoted-char-radix))))
1279 (setq code (+ (* code read-quoted-char-radix) (- translated ?0)))
1280 (and prompt (setq prompt (message "%s %c" prompt translated))))
1281 ((and (<= ?a (downcase translated))
1282 (< (downcase translated) (+ ?a -10 (min 36 read-quoted-char-radix))))
1283 (setq code (+ (* code read-quoted-char-radix)
1284 (+ 10 (- (downcase translated) ?a))))
1285 (and prompt (setq prompt (message "%s %c" prompt translated))))
1286 ((and (not first) (eq translated ?\C-m))
1287 (setq done t))
1288 ((not first)
1289 (setq unread-command-events (list char)
1290 done t))
1291 (t (setq code translated
1292 done t)))
1293 (setq first nil))
1294 code))
1296 (defun read-passwd (prompt &optional confirm default)
1297 "Read a password, prompting with PROMPT. Echo `.' for each character typed.
1298 End with RET, LFD, or ESC. DEL or C-h rubs out. C-u kills line.
1299 If optional CONFIRM is non-nil, read password twice to make sure.
1300 Optional DEFAULT is a default password to use instead of empty input."
1301 (if confirm
1302 (let (success)
1303 (while (not success)
1304 (let ((first (read-passwd prompt nil default))
1305 (second (read-passwd "Confirm password: " nil default)))
1306 (if (equal first second)
1307 (progn
1308 (and (arrayp second) (clear-string second))
1309 (setq success first))
1310 (and (arrayp first) (clear-string first))
1311 (and (arrayp second) (clear-string second))
1312 (message "Password not repeated accurately; please start over")
1313 (sit-for 1))))
1314 success)
1315 (let ((pass nil)
1316 (c 0)
1317 (echo-keystrokes 0)
1318 (cursor-in-echo-area t))
1319 (while (progn (message "%s%s"
1320 prompt
1321 (make-string (length pass) ?.))
1322 (setq c (read-char-exclusive nil t))
1323 (and (/= c ?\r) (/= c ?\n) (/= c ?\e)))
1324 (clear-this-command-keys)
1325 (if (= c ?\C-u)
1326 (progn
1327 (and (arrayp pass) (clear-string pass))
1328 (setq pass ""))
1329 (if (and (/= c ?\b) (/= c ?\177))
1330 (let* ((new-char (char-to-string c))
1331 (new-pass (concat pass new-char)))
1332 (and (arrayp pass) (clear-string pass))
1333 (clear-string new-char)
1334 (setq c ?\0)
1335 (setq pass new-pass))
1336 (if (> (length pass) 0)
1337 (let ((new-pass (substring pass 0 -1)))
1338 (and (arrayp pass) (clear-string pass))
1339 (setq pass new-pass))))))
1340 (message nil)
1341 (or pass default ""))))
1343 ;; This should be used by `call-interactively' for `n' specs.
1344 (defun read-number (prompt &optional default)
1345 (let ((n nil))
1346 (when default
1347 (setq prompt
1348 (if (string-match "\\(\\):[ \t]*\\'" prompt)
1349 (replace-match (format " (default %s)" default) t t prompt 1)
1350 (replace-regexp-in-string "[ \t]*\\'"
1351 (format " (default %s) " default)
1352 prompt t t))))
1353 (while
1354 (progn
1355 (let ((str (read-from-minibuffer prompt nil nil nil nil
1356 (and default
1357 (number-to-string default)))))
1358 (setq n (cond
1359 ((zerop (length str)) default)
1360 ((stringp str) (read str)))))
1361 (unless (numberp n)
1362 (message "Please enter a number.")
1363 (sit-for 1)
1364 t)))
1367 ;;; Atomic change groups.
1369 (defmacro atomic-change-group (&rest body)
1370 "Perform BODY as an atomic change group.
1371 This means that if BODY exits abnormally,
1372 all of its changes to the current buffer are undone.
1373 This works regardless of whether undo is enabled in the buffer.
1375 This mechanism is transparent to ordinary use of undo;
1376 if undo is enabled in the buffer and BODY succeeds, the
1377 user can undo the change normally."
1378 (let ((handle (make-symbol "--change-group-handle--"))
1379 (success (make-symbol "--change-group-success--")))
1380 `(let ((,handle (prepare-change-group))
1381 (,success nil))
1382 (unwind-protect
1383 (progn
1384 ;; This is inside the unwind-protect because
1385 ;; it enables undo if that was disabled; we need
1386 ;; to make sure that it gets disabled again.
1387 (activate-change-group ,handle)
1388 ,@body
1389 (setq ,success t))
1390 ;; Either of these functions will disable undo
1391 ;; if it was disabled before.
1392 (if ,success
1393 (accept-change-group ,handle)
1394 (cancel-change-group ,handle))))))
1396 (defun prepare-change-group (&optional buffer)
1397 "Return a handle for the current buffer's state, for a change group.
1398 If you specify BUFFER, make a handle for BUFFER's state instead.
1400 Pass the handle to `activate-change-group' afterward to initiate
1401 the actual changes of the change group.
1403 To finish the change group, call either `accept-change-group' or
1404 `cancel-change-group' passing the same handle as argument. Call
1405 `accept-change-group' to accept the changes in the group as final;
1406 call `cancel-change-group' to undo them all. You should use
1407 `unwind-protect' to make sure the group is always finished. The call
1408 to `activate-change-group' should be inside the `unwind-protect'.
1409 Once you finish the group, don't use the handle again--don't try to
1410 finish the same group twice. For a simple example of correct use, see
1411 the source code of `atomic-change-group'.
1413 The handle records only the specified buffer. To make a multibuffer
1414 change group, call this function once for each buffer you want to
1415 cover, then use `nconc' to combine the returned values, like this:
1417 (nconc (prepare-change-group buffer-1)
1418 (prepare-change-group buffer-2))
1420 You can then activate that multibuffer change group with a single
1421 call to `activate-change-group' and finish it with a single call
1422 to `accept-change-group' or `cancel-change-group'."
1424 (if buffer
1425 (list (cons buffer (with-current-buffer buffer buffer-undo-list)))
1426 (list (cons (current-buffer) buffer-undo-list))))
1428 (defun activate-change-group (handle)
1429 "Activate a change group made with `prepare-change-group' (which see)."
1430 (dolist (elt handle)
1431 (with-current-buffer (car elt)
1432 (if (eq buffer-undo-list t)
1433 (setq buffer-undo-list nil)))))
1435 (defun accept-change-group (handle)
1436 "Finish a change group made with `prepare-change-group' (which see).
1437 This finishes the change group by accepting its changes as final."
1438 (dolist (elt handle)
1439 (with-current-buffer (car elt)
1440 (if (eq elt t)
1441 (setq buffer-undo-list t)))))
1443 (defun cancel-change-group (handle)
1444 "Finish a change group made with `prepare-change-group' (which see).
1445 This finishes the change group by reverting all of its changes."
1446 (dolist (elt handle)
1447 (with-current-buffer (car elt)
1448 (setq elt (cdr elt))
1449 (let ((old-car
1450 (if (consp elt) (car elt)))
1451 (old-cdr
1452 (if (consp elt) (cdr elt))))
1453 ;; Temporarily truncate the undo log at ELT.
1454 (when (consp elt)
1455 (setcar elt nil) (setcdr elt nil))
1456 (unless (eq last-command 'undo) (undo-start))
1457 ;; Make sure there's no confusion.
1458 (when (and (consp elt) (not (eq elt (last pending-undo-list))))
1459 (error "Undoing to some unrelated state"))
1460 ;; Undo it all.
1461 (while pending-undo-list (undo-more 1))
1462 ;; Reset the modified cons cell ELT to its original content.
1463 (when (consp elt)
1464 (setcar elt old-car)
1465 (setcdr elt old-cdr))
1466 ;; Revert the undo info to what it was when we grabbed the state.
1467 (setq buffer-undo-list elt)))))
1469 ;; For compatibility.
1470 (defalias 'redraw-modeline 'force-mode-line-update)
1472 (defun force-mode-line-update (&optional all)
1473 "Force redisplay of the current buffer's mode line and header line.
1474 With optional non-nil ALL, force redisplay of all mode lines and
1475 header lines. This function also forces recomputation of the
1476 menu bar menus and the frame title."
1477 (if all (save-excursion (set-buffer (other-buffer))))
1478 (set-buffer-modified-p (buffer-modified-p)))
1480 (defun momentary-string-display (string pos &optional exit-char message)
1481 "Momentarily display STRING in the buffer at POS.
1482 Display remains until next event is input.
1483 Optional third arg EXIT-CHAR can be a character, event or event
1484 description list. EXIT-CHAR defaults to SPC. If the input is
1485 EXIT-CHAR it is swallowed; otherwise it is then available as
1486 input (as a command if nothing else).
1487 Display MESSAGE (optional fourth arg) in the echo area.
1488 If MESSAGE is nil, instructions to type EXIT-CHAR are displayed there."
1489 (or exit-char (setq exit-char ?\ ))
1490 (let ((inhibit-read-only t)
1491 ;; Don't modify the undo list at all.
1492 (buffer-undo-list t)
1493 (modified (buffer-modified-p))
1494 (name buffer-file-name)
1495 insert-end)
1496 (unwind-protect
1497 (progn
1498 (save-excursion
1499 (goto-char pos)
1500 ;; defeat file locking... don't try this at home, kids!
1501 (setq buffer-file-name nil)
1502 (insert-before-markers string)
1503 (setq insert-end (point))
1504 ;; If the message end is off screen, recenter now.
1505 (if (< (window-end nil t) insert-end)
1506 (recenter (/ (window-height) 2)))
1507 ;; If that pushed message start off the screen,
1508 ;; scroll to start it at the top of the screen.
1509 (move-to-window-line 0)
1510 (if (> (point) pos)
1511 (progn
1512 (goto-char pos)
1513 (recenter 0))))
1514 (message (or message "Type %s to continue editing.")
1515 (single-key-description exit-char))
1516 (let (char)
1517 (if (integerp exit-char)
1518 (condition-case nil
1519 (progn
1520 (setq char (read-char))
1521 (or (eq char exit-char)
1522 (setq unread-command-events (list char))))
1523 (error
1524 ;; `exit-char' is a character, hence it differs
1525 ;; from char, which is an event.
1526 (setq unread-command-events (list char))))
1527 ;; `exit-char' can be an event, or an event description
1528 ;; list.
1529 (setq char (read-event))
1530 (or (eq char exit-char)
1531 (eq char (event-convert-list exit-char))
1532 (setq unread-command-events (list char))))))
1533 (if insert-end
1534 (save-excursion
1535 (delete-region pos insert-end)))
1536 (setq buffer-file-name name)
1537 (set-buffer-modified-p modified))))
1540 ;;;; Overlay operations
1542 (defun copy-overlay (o)
1543 "Return a copy of overlay O."
1544 (let ((o1 (make-overlay (overlay-start o) (overlay-end o)
1545 ;; FIXME: there's no easy way to find the
1546 ;; insertion-type of the two markers.
1547 (overlay-buffer o)))
1548 (props (overlay-properties o)))
1549 (while props
1550 (overlay-put o1 (pop props) (pop props)))
1551 o1))
1553 (defun remove-overlays (&optional beg end name val)
1554 "Clear BEG and END of overlays whose property NAME has value VAL.
1555 Overlays might be moved and/or split.
1556 BEG and END default respectively to the beginning and end of buffer."
1557 (unless beg (setq beg (point-min)))
1558 (unless end (setq end (point-max)))
1559 (if (< end beg)
1560 (setq beg (prog1 end (setq end beg))))
1561 (save-excursion
1562 (dolist (o (overlays-in beg end))
1563 (when (eq (overlay-get o name) val)
1564 ;; Either push this overlay outside beg...end
1565 ;; or split it to exclude beg...end
1566 ;; or delete it entirely (if it is contained in beg...end).
1567 (if (< (overlay-start o) beg)
1568 (if (> (overlay-end o) end)
1569 (progn
1570 (move-overlay (copy-overlay o)
1571 (overlay-start o) beg)
1572 (move-overlay o end (overlay-end o)))
1573 (move-overlay o (overlay-start o) beg))
1574 (if (> (overlay-end o) end)
1575 (move-overlay o end (overlay-end o))
1576 (delete-overlay o)))))))
1578 ;;;; Miscellanea.
1580 ;; A number of major modes set this locally.
1581 ;; Give it a global value to avoid compiler warnings.
1582 (defvar font-lock-defaults nil)
1584 (defvar suspend-hook nil
1585 "Normal hook run by `suspend-emacs', before suspending.")
1587 (defvar suspend-resume-hook nil
1588 "Normal hook run by `suspend-emacs', after Emacs is continued.")
1590 (defvar temp-buffer-show-hook nil
1591 "Normal hook run by `with-output-to-temp-buffer' after displaying the buffer.
1592 When the hook runs, the temporary buffer is current, and the window it
1593 was displayed in is selected. This hook is normally set up with a
1594 function to make the buffer read only, and find function names and
1595 variable names in it, provided the major mode is still Help mode.")
1597 (defvar temp-buffer-setup-hook nil
1598 "Normal hook run by `with-output-to-temp-buffer' at the start.
1599 When the hook runs, the temporary buffer is current.
1600 This hook is normally set up with a function to put the buffer in Help
1601 mode.")
1603 ;; Avoid compiler warnings about this variable,
1604 ;; which has a special meaning on certain system types.
1605 (defvar buffer-file-type nil
1606 "Non-nil if the visited file is a binary file.
1607 This variable is meaningful on MS-DOG and Windows NT.
1608 On those systems, it is automatically local in every buffer.
1609 On other systems, this variable is normally always nil.")
1611 ;; This should probably be written in C (i.e., without using `walk-windows').
1612 (defun get-buffer-window-list (buffer &optional minibuf frame)
1613 "Return list of all windows displaying BUFFER, or nil if none.
1614 BUFFER can be a buffer or a buffer name.
1615 See `walk-windows' for the meaning of MINIBUF and FRAME."
1616 (let ((buffer (if (bufferp buffer) buffer (get-buffer buffer))) windows)
1617 (walk-windows (function (lambda (window)
1618 (if (eq (window-buffer window) buffer)
1619 (setq windows (cons window windows)))))
1620 minibuf frame)
1621 windows))
1623 (defun ignore (&rest ignore)
1624 "Do nothing and return nil.
1625 This function accepts any number of arguments, but ignores them."
1626 (interactive)
1627 nil)
1629 (defun error (&rest args)
1630 "Signal an error, making error message by passing all args to `format'.
1631 In Emacs, the convention is that error messages start with a capital
1632 letter but *do not* end with a period. Please follow this convention
1633 for the sake of consistency."
1634 (while t
1635 (signal 'error (list (apply 'format args)))))
1637 (defalias 'user-original-login-name 'user-login-name)
1639 (defvar yank-excluded-properties)
1641 (defun remove-yank-excluded-properties (start end)
1642 "Remove `yank-excluded-properties' between START and END positions.
1643 Replaces `category' properties with their defined properties."
1644 (let ((inhibit-read-only t))
1645 ;; Replace any `category' property with the properties it stands for.
1646 (unless (memq yank-excluded-properties '(t nil))
1647 (save-excursion
1648 (goto-char start)
1649 (while (< (point) end)
1650 (let ((cat (get-text-property (point) 'category))
1651 run-end)
1652 (setq run-end
1653 (next-single-property-change (point) 'category nil end))
1654 (when cat
1655 (let (run-end2 original)
1656 (remove-list-of-text-properties (point) run-end '(category))
1657 (while (< (point) run-end)
1658 (setq run-end2 (next-property-change (point) nil run-end))
1659 (setq original (text-properties-at (point)))
1660 (set-text-properties (point) run-end2 (symbol-plist cat))
1661 (add-text-properties (point) run-end2 original)
1662 (goto-char run-end2))))
1663 (goto-char run-end)))))
1664 (if (eq yank-excluded-properties t)
1665 (set-text-properties start end nil)
1666 (remove-list-of-text-properties start end yank-excluded-properties))))
1668 (defvar yank-undo-function)
1670 (defun insert-for-yank (string)
1671 "Calls `insert-for-yank-1' repetitively for each `yank-handler' segment.
1673 See `insert-for-yank-1' for more details."
1674 (let (to)
1675 (while (setq to (next-single-property-change 0 'yank-handler string))
1676 (insert-for-yank-1 (substring string 0 to))
1677 (setq string (substring string to))))
1678 (insert-for-yank-1 string))
1680 (defun insert-for-yank-1 (string)
1681 "Insert STRING at point, stripping some text properties.
1683 Strip text properties from the inserted text according to
1684 `yank-excluded-properties'. Otherwise just like (insert STRING).
1686 If STRING has a non-nil `yank-handler' property on the first character,
1687 the normal insert behaviour is modified in various ways. The value of
1688 the yank-handler property must be a list with one to five elements
1689 with the following format: (FUNCTION PARAM NOEXCLUDE UNDO).
1690 When FUNCTION is present and non-nil, it is called instead of `insert'
1691 to insert the string. FUNCTION takes one argument--the object to insert.
1692 If PARAM is present and non-nil, it replaces STRING as the object
1693 passed to FUNCTION (or `insert'); for example, if FUNCTION is
1694 `yank-rectangle', PARAM may be a list of strings to insert as a
1695 rectangle.
1696 If NOEXCLUDE is present and non-nil, the normal removal of the
1697 yank-excluded-properties is not performed; instead FUNCTION is
1698 responsible for removing those properties. This may be necessary
1699 if FUNCTION adjusts point before or after inserting the object.
1700 If UNDO is present and non-nil, it is a function that will be called
1701 by `yank-pop' to undo the insertion of the current object. It is
1702 called with two arguments, the start and end of the current region.
1703 FUNCTION may set `yank-undo-function' to override the UNDO value."
1704 (let* ((handler (and (stringp string)
1705 (get-text-property 0 'yank-handler string)))
1706 (param (or (nth 1 handler) string))
1707 (opoint (point)))
1708 (setq yank-undo-function t)
1709 (if (nth 0 handler) ;; FUNCTION
1710 (funcall (car handler) param)
1711 (insert param))
1712 (unless (nth 2 handler) ;; NOEXCLUDE
1713 (remove-yank-excluded-properties opoint (point)))
1714 (if (eq yank-undo-function t) ;; not set by FUNCTION
1715 (setq yank-undo-function (nth 3 handler))) ;; UNDO
1716 (if (nth 4 handler) ;; COMMAND
1717 (setq this-command (nth 4 handler)))))
1719 (defun insert-buffer-substring-no-properties (buffer &optional start end)
1720 "Insert before point a substring of BUFFER, without text properties.
1721 BUFFER may be a buffer or a buffer name.
1722 Arguments START and END are character positions specifying the substring.
1723 They default to the values of (point-min) and (point-max) in BUFFER."
1724 (let ((opoint (point)))
1725 (insert-buffer-substring buffer start end)
1726 (let ((inhibit-read-only t))
1727 (set-text-properties opoint (point) nil))))
1729 (defun insert-buffer-substring-as-yank (buffer &optional start end)
1730 "Insert before point a part of BUFFER, stripping some text properties.
1731 BUFFER may be a buffer or a buffer name.
1732 Arguments START and END are character positions specifying the substring.
1733 They default to the values of (point-min) and (point-max) in BUFFER.
1734 Strip text properties from the inserted text according to
1735 `yank-excluded-properties'."
1736 ;; Since the buffer text should not normally have yank-handler properties,
1737 ;; there is no need to handle them here.
1738 (let ((opoint (point)))
1739 (insert-buffer-substring buffer start end)
1740 (remove-yank-excluded-properties opoint (point))))
1743 ;; Synchronous shell commands.
1745 (defun start-process-shell-command (name buffer &rest args)
1746 "Start a program in a subprocess. Return the process object for it.
1747 NAME is name for process. It is modified if necessary to make it unique.
1748 BUFFER is the buffer (or buffer name) to associate with the process.
1749 Process output goes at end of that buffer, unless you specify
1750 an output stream or filter function to handle the output.
1751 BUFFER may be also nil, meaning that this process is not associated
1752 with any buffer
1753 COMMAND is the name of a shell command.
1754 Remaining arguments are the arguments for the command.
1755 Wildcards and redirection are handled as usual in the shell.
1757 \(fn NAME BUFFER COMMAND &rest COMMAND-ARGS)"
1758 (cond
1759 ((eq system-type 'vax-vms)
1760 (apply 'start-process name buffer args))
1761 ;; We used to use `exec' to replace the shell with the command,
1762 ;; but that failed to handle (...) and semicolon, etc.
1764 (start-process name buffer shell-file-name shell-command-switch
1765 (mapconcat 'identity args " ")))))
1767 (defun call-process-shell-command (command &optional infile buffer display
1768 &rest args)
1769 "Execute the shell command COMMAND synchronously in separate process.
1770 The remaining arguments are optional.
1771 The program's input comes from file INFILE (nil means `/dev/null').
1772 Insert output in BUFFER before point; t means current buffer;
1773 nil for BUFFER means discard it; 0 means discard and don't wait.
1774 BUFFER can also have the form (REAL-BUFFER STDERR-FILE); in that case,
1775 REAL-BUFFER says what to do with standard output, as above,
1776 while STDERR-FILE says what to do with standard error in the child.
1777 STDERR-FILE may be nil (discard standard error output),
1778 t (mix it with ordinary output), or a file name string.
1780 Fourth arg DISPLAY non-nil means redisplay buffer as output is inserted.
1781 Remaining arguments are strings passed as additional arguments for COMMAND.
1782 Wildcards and redirection are handled as usual in the shell.
1784 If BUFFER is 0, `call-process-shell-command' returns immediately with value nil.
1785 Otherwise it waits for COMMAND to terminate and returns a numeric exit
1786 status or a signal description string.
1787 If you quit, the process is killed with SIGINT, or SIGKILL if you quit again."
1788 (cond
1789 ((eq system-type 'vax-vms)
1790 (apply 'call-process command infile buffer display args))
1791 ;; We used to use `exec' to replace the shell with the command,
1792 ;; but that failed to handle (...) and semicolon, etc.
1794 (call-process shell-file-name
1795 infile buffer display
1796 shell-command-switch
1797 (mapconcat 'identity (cons command args) " ")))))
1799 (defmacro with-current-buffer (buffer &rest body)
1800 "Execute the forms in BODY with BUFFER as the current buffer.
1801 The value returned is the value of the last form in BODY.
1802 See also `with-temp-buffer'."
1803 (declare (indent 1) (debug t))
1804 `(save-current-buffer
1805 (set-buffer ,buffer)
1806 ,@body))
1808 (defmacro with-selected-window (window &rest body)
1809 "Execute the forms in BODY with WINDOW as the selected window.
1810 The value returned is the value of the last form in BODY.
1811 This does not alter the buffer list ordering.
1812 This function saves and restores the selected window, as well as
1813 the selected window in each frame. If the previously selected
1814 window of some frame is no longer live at the end of BODY, that
1815 frame's selected window is left alone. If the selected window is
1816 no longer live, then whatever window is selected at the end of
1817 BODY remains selected.
1818 See also `with-temp-buffer'."
1819 (declare (indent 1) (debug t))
1820 ;; Most of this code is a copy of save-selected-window.
1821 `(let ((save-selected-window-window (selected-window))
1822 ;; It is necessary to save all of these, because calling
1823 ;; select-window changes frame-selected-window for whatever
1824 ;; frame that window is in.
1825 (save-selected-window-alist
1826 (mapcar (lambda (frame) (list frame (frame-selected-window frame)))
1827 (frame-list))))
1828 (unwind-protect
1829 (progn (select-window ,window 'norecord)
1830 ,@body)
1831 (dolist (elt save-selected-window-alist)
1832 (and (frame-live-p (car elt))
1833 (window-live-p (cadr elt))
1834 (set-frame-selected-window (car elt) (cadr elt))))
1835 (if (window-live-p save-selected-window-window)
1836 (select-window save-selected-window-window 'norecord)))))
1838 (defmacro with-temp-file (file &rest body)
1839 "Create a new buffer, evaluate BODY there, and write the buffer to FILE.
1840 The value returned is the value of the last form in BODY.
1841 See also `with-temp-buffer'."
1842 (declare (debug t))
1843 (let ((temp-file (make-symbol "temp-file"))
1844 (temp-buffer (make-symbol "temp-buffer")))
1845 `(let ((,temp-file ,file)
1846 (,temp-buffer
1847 (get-buffer-create (generate-new-buffer-name " *temp file*"))))
1848 (unwind-protect
1849 (prog1
1850 (with-current-buffer ,temp-buffer
1851 ,@body)
1852 (with-current-buffer ,temp-buffer
1853 (widen)
1854 (write-region (point-min) (point-max) ,temp-file nil 0)))
1855 (and (buffer-name ,temp-buffer)
1856 (kill-buffer ,temp-buffer))))))
1858 (defmacro with-temp-message (message &rest body)
1859 "Display MESSAGE temporarily if non-nil while BODY is evaluated.
1860 The original message is restored to the echo area after BODY has finished.
1861 The value returned is the value of the last form in BODY.
1862 MESSAGE is written to the message log buffer if `message-log-max' is non-nil.
1863 If MESSAGE is nil, the echo area and message log buffer are unchanged.
1864 Use a MESSAGE of \"\" to temporarily clear the echo area."
1865 (declare (debug t))
1866 (let ((current-message (make-symbol "current-message"))
1867 (temp-message (make-symbol "with-temp-message")))
1868 `(let ((,temp-message ,message)
1869 (,current-message))
1870 (unwind-protect
1871 (progn
1872 (when ,temp-message
1873 (setq ,current-message (current-message))
1874 (message "%s" ,temp-message))
1875 ,@body)
1876 (and ,temp-message
1877 (if ,current-message
1878 (message "%s" ,current-message)
1879 (message nil)))))))
1881 (defmacro with-temp-buffer (&rest body)
1882 "Create a temporary buffer, and evaluate BODY there like `progn'.
1883 See also `with-temp-file' and `with-output-to-string'."
1884 (declare (indent 0) (debug t))
1885 (let ((temp-buffer (make-symbol "temp-buffer")))
1886 `(let ((,temp-buffer
1887 (get-buffer-create (generate-new-buffer-name " *temp*"))))
1888 (unwind-protect
1889 (with-current-buffer ,temp-buffer
1890 ,@body)
1891 (and (buffer-name ,temp-buffer)
1892 (kill-buffer ,temp-buffer))))))
1894 (defmacro with-output-to-string (&rest body)
1895 "Execute BODY, return the text it sent to `standard-output', as a string."
1896 (declare (indent 0) (debug t))
1897 `(let ((standard-output
1898 (get-buffer-create (generate-new-buffer-name " *string-output*"))))
1899 (let ((standard-output standard-output))
1900 ,@body)
1901 (with-current-buffer standard-output
1902 (prog1
1903 (buffer-string)
1904 (kill-buffer nil)))))
1906 (defmacro with-local-quit (&rest body)
1907 "Execute BODY, allowing quits to terminate BODY but not escape further.
1908 When a quit terminates BODY, `with-local-quit' requests another quit when
1909 it finishes. That quit will be processed in turn, the next time quitting
1910 is again allowed."
1911 (declare (debug t) (indent 0))
1912 `(condition-case nil
1913 (let ((inhibit-quit nil))
1914 ,@body)
1915 (quit (setq quit-flag t))))
1917 (defmacro combine-after-change-calls (&rest body)
1918 "Execute BODY, but don't call the after-change functions till the end.
1919 If BODY makes changes in the buffer, they are recorded
1920 and the functions on `after-change-functions' are called several times
1921 when BODY is finished.
1922 The return value is the value of the last form in BODY.
1924 If `before-change-functions' is non-nil, then calls to the after-change
1925 functions can't be deferred, so in that case this macro has no effect.
1927 Do not alter `after-change-functions' or `before-change-functions'
1928 in BODY."
1929 (declare (indent 0) (debug t))
1930 `(unwind-protect
1931 (let ((combine-after-change-calls t))
1932 . ,body)
1933 (combine-after-change-execute)))
1936 (defvar delay-mode-hooks nil
1937 "If non-nil, `run-mode-hooks' should delay running the hooks.")
1938 (defvar delayed-mode-hooks nil
1939 "List of delayed mode hooks waiting to be run.")
1940 (make-variable-buffer-local 'delayed-mode-hooks)
1941 (put 'delay-mode-hooks 'permanent-local t)
1943 (defvar after-change-major-mode-hook nil
1944 "Normal hook run at the very end of major mode functions.")
1946 (defun run-mode-hooks (&rest hooks)
1947 "Run mode hooks `delayed-mode-hooks' and HOOKS, or delay HOOKS.
1948 Execution is delayed if `delay-mode-hooks' is non-nil.
1949 If `delay-mode-hooks' is nil, run `after-change-major-mode-hook'
1950 after running the mode hooks.
1951 Major mode functions should use this."
1952 (if delay-mode-hooks
1953 ;; Delaying case.
1954 (dolist (hook hooks)
1955 (push hook delayed-mode-hooks))
1956 ;; Normal case, just run the hook as before plus any delayed hooks.
1957 (setq hooks (nconc (nreverse delayed-mode-hooks) hooks))
1958 (setq delayed-mode-hooks nil)
1959 (apply 'run-hooks hooks)
1960 (run-hooks 'after-change-major-mode-hook)))
1962 (defmacro delay-mode-hooks (&rest body)
1963 "Execute BODY, but delay any `run-mode-hooks'.
1964 These hooks will be executed by the first following call to
1965 `run-mode-hooks' that occurs outside any `delayed-mode-hooks' form.
1966 Only affects hooks run in the current buffer."
1967 (declare (debug t))
1968 `(progn
1969 (make-local-variable 'delay-mode-hooks)
1970 (let ((delay-mode-hooks t))
1971 ,@body)))
1973 ;; PUBLIC: find if the current mode derives from another.
1975 (defun derived-mode-p (&rest modes)
1976 "Non-nil if the current major mode is derived from one of MODES.
1977 Uses the `derived-mode-parent' property of the symbol to trace backwards."
1978 (let ((parent major-mode))
1979 (while (and (not (memq parent modes))
1980 (setq parent (get parent 'derived-mode-parent))))
1981 parent))
1983 (defun find-tag-default ()
1984 "Determine default tag to search for, based on text at point.
1985 If there is no plausible default, return nil."
1986 (save-excursion
1987 (while (looking-at "\\sw\\|\\s_")
1988 (forward-char 1))
1989 (if (or (re-search-backward "\\sw\\|\\s_"
1990 (save-excursion (beginning-of-line) (point))
1992 (re-search-forward "\\(\\sw\\|\\s_\\)+"
1993 (save-excursion (end-of-line) (point))
1995 (progn (goto-char (match-end 0))
1996 (buffer-substring-no-properties
1997 (point)
1998 (progn (forward-sexp -1)
1999 (while (looking-at "\\s'")
2000 (forward-char 1))
2001 (point))))
2002 nil)))
2004 (defmacro with-syntax-table (table &rest body)
2005 "Evaluate BODY with syntax table of current buffer set to TABLE.
2006 The syntax table of the current buffer is saved, BODY is evaluated, and the
2007 saved table is restored, even in case of an abnormal exit.
2008 Value is what BODY returns."
2009 (declare (debug t))
2010 (let ((old-table (make-symbol "table"))
2011 (old-buffer (make-symbol "buffer")))
2012 `(let ((,old-table (syntax-table))
2013 (,old-buffer (current-buffer)))
2014 (unwind-protect
2015 (progn
2016 (set-syntax-table ,table)
2017 ,@body)
2018 (save-current-buffer
2019 (set-buffer ,old-buffer)
2020 (set-syntax-table ,old-table))))))
2022 (defmacro dynamic-completion-table (fun)
2023 "Use function FUN as a dynamic completion table.
2024 FUN is called with one argument, the string for which completion is required,
2025 and it should return an alist containing all the intended possible
2026 completions. This alist may be a full list of possible completions so that FUN
2027 can ignore the value of its argument. If completion is performed in the
2028 minibuffer, FUN will be called in the buffer from which the minibuffer was
2029 entered.
2031 The result of the `dynamic-completion-table' form is a function
2032 that can be used as the ALIST argument to `try-completion' and
2033 `all-completion'. See Info node `(elisp)Programmed Completion'."
2034 (let ((win (make-symbol "window"))
2035 (string (make-symbol "string"))
2036 (predicate (make-symbol "predicate"))
2037 (mode (make-symbol "mode")))
2038 `(lambda (,string ,predicate ,mode)
2039 (with-current-buffer (let ((,win (minibuffer-selected-window)))
2040 (if (window-live-p ,win) (window-buffer ,win)
2041 (current-buffer)))
2042 (cond
2043 ((eq ,mode t) (all-completions ,string (,fun ,string) ,predicate))
2044 ((not ,mode) (try-completion ,string (,fun ,string) ,predicate))
2045 (t (test-completion ,string (,fun ,string) ,predicate)))))))
2047 (defmacro lazy-completion-table (var fun &rest args)
2048 "Initialize variable VAR as a lazy completion table.
2049 If the completion table VAR is used for the first time (e.g., by passing VAR
2050 as an argument to `try-completion'), the function FUN is called with arguments
2051 ARGS. FUN must return the completion table that will be stored in VAR.
2052 If completion is requested in the minibuffer, FUN will be called in the buffer
2053 from which the minibuffer was entered. The return value of
2054 `lazy-completion-table' must be used to initialize the value of VAR."
2055 (let ((str (make-symbol "string")))
2056 `(dynamic-completion-table
2057 (lambda (,str)
2058 (unless (listp ,var)
2059 (setq ,var (funcall ',fun ,@args)))
2060 ,var))))
2062 ;;; Matching and substitution
2064 (defvar save-match-data-internal)
2066 ;; We use save-match-data-internal as the local variable because
2067 ;; that works ok in practice (people should not use that variable elsewhere).
2068 ;; We used to use an uninterned symbol; the compiler handles that properly
2069 ;; now, but it generates slower code.
2070 (defmacro save-match-data (&rest body)
2071 "Execute the BODY forms, restoring the global value of the match data.
2072 The value returned is the value of the last form in BODY."
2073 ;; It is better not to use backquote here,
2074 ;; because that makes a bootstrapping problem
2075 ;; if you need to recompile all the Lisp files using interpreted code.
2076 (declare (indent 0) (debug t))
2077 (list 'let
2078 '((save-match-data-internal (match-data)))
2079 (list 'unwind-protect
2080 (cons 'progn body)
2081 '(set-match-data save-match-data-internal))))
2083 (defun match-string (num &optional string)
2084 "Return string of text matched by last search.
2085 NUM specifies which parenthesized expression in the last regexp.
2086 Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
2087 Zero means the entire text matched by the whole regexp or whole string.
2088 STRING should be given if the last search was by `string-match' on STRING."
2089 (if (match-beginning num)
2090 (if string
2091 (substring string (match-beginning num) (match-end num))
2092 (buffer-substring (match-beginning num) (match-end num)))))
2094 (defun match-string-no-properties (num &optional string)
2095 "Return string of text matched by last search, without text properties.
2096 NUM specifies which parenthesized expression in the last regexp.
2097 Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
2098 Zero means the entire text matched by the whole regexp or whole string.
2099 STRING should be given if the last search was by `string-match' on STRING."
2100 (if (match-beginning num)
2101 (if string
2102 (substring-no-properties string (match-beginning num)
2103 (match-end num))
2104 (buffer-substring-no-properties (match-beginning num)
2105 (match-end num)))))
2107 (defun looking-back (regexp &optional limit)
2108 "Return non-nil if text before point matches regular expression REGEXP.
2109 Like `looking-at' except backwards and slower.
2110 LIMIT if non-nil speeds up the search by specifying how far back the
2111 match can start."
2112 (save-excursion
2113 (re-search-backward (concat "\\(?:" regexp "\\)\\=") limit t)))
2115 (defconst split-string-default-separators "[ \f\t\n\r\v]+"
2116 "The default value of separators for `split-string'.
2118 A regexp matching strings of whitespace. May be locale-dependent
2119 \(as yet unimplemented). Should not match non-breaking spaces.
2121 Warning: binding this to a different value and using it as default is
2122 likely to have undesired semantics.")
2124 ;; The specification says that if both SEPARATORS and OMIT-NULLS are
2125 ;; defaulted, OMIT-NULLS should be treated as t. Simplifying the logical
2126 ;; expression leads to the equivalent implementation that if SEPARATORS
2127 ;; is defaulted, OMIT-NULLS is treated as t.
2128 (defun split-string (string &optional separators omit-nulls)
2129 "Split STRING into substrings bounded by matches for SEPARATORS.
2131 The beginning and end of STRING, and each match for SEPARATORS, are
2132 splitting points. The substrings matching SEPARATORS are removed, and
2133 the substrings between the splitting points are collected as a list,
2134 which is returned.
2136 If SEPARATORS is non-nil, it should be a regular expression matching text
2137 which separates, but is not part of, the substrings. If nil it defaults to
2138 `split-string-default-separators', normally \"[ \\f\\t\\n\\r\\v]+\", and
2139 OMIT-NULLS is forced to t.
2141 If OMIT-NULLS is t, zero-length substrings are omitted from the list \(so
2142 that for the default value of SEPARATORS leading and trailing whitespace
2143 are effectively trimmed). If nil, all zero-length substrings are retained,
2144 which correctly parses CSV format, for example.
2146 Note that the effect of `(split-string STRING)' is the same as
2147 `(split-string STRING split-string-default-separators t)'). In the rare
2148 case that you wish to retain zero-length substrings when splitting on
2149 whitespace, use `(split-string STRING split-string-default-separators)'.
2151 Modifies the match data; use `save-match-data' if necessary."
2152 (let ((keep-nulls (not (if separators omit-nulls t)))
2153 (rexp (or separators split-string-default-separators))
2154 (start 0)
2155 notfirst
2156 (list nil))
2157 (while (and (string-match rexp string
2158 (if (and notfirst
2159 (= start (match-beginning 0))
2160 (< start (length string)))
2161 (1+ start) start))
2162 (< start (length string)))
2163 (setq notfirst t)
2164 (if (or keep-nulls (< start (match-beginning 0)))
2165 (setq list
2166 (cons (substring string start (match-beginning 0))
2167 list)))
2168 (setq start (match-end 0)))
2169 (if (or keep-nulls (< start (length string)))
2170 (setq list
2171 (cons (substring string start)
2172 list)))
2173 (nreverse list)))
2175 (defun subst-char-in-string (fromchar tochar string &optional inplace)
2176 "Replace FROMCHAR with TOCHAR in STRING each time it occurs.
2177 Unless optional argument INPLACE is non-nil, return a new string."
2178 (let ((i (length string))
2179 (newstr (if inplace string (copy-sequence string))))
2180 (while (> i 0)
2181 (setq i (1- i))
2182 (if (eq (aref newstr i) fromchar)
2183 (aset newstr i tochar)))
2184 newstr))
2186 (defun replace-regexp-in-string (regexp rep string &optional
2187 fixedcase literal subexp start)
2188 "Replace all matches for REGEXP with REP in STRING.
2190 Return a new string containing the replacements.
2192 Optional arguments FIXEDCASE, LITERAL and SUBEXP are like the
2193 arguments with the same names of function `replace-match'. If START
2194 is non-nil, start replacements at that index in STRING.
2196 REP is either a string used as the NEWTEXT arg of `replace-match' or a
2197 function. If it is a function it is applied to each match to generate
2198 the replacement passed to `replace-match'; the match-data at this
2199 point are such that match 0 is the function's argument.
2201 To replace only the first match (if any), make REGEXP match up to \\'
2202 and replace a sub-expression, e.g.
2203 (replace-regexp-in-string \"\\\\(foo\\\\).*\\\\'\" \"bar\" \" foo foo\" nil nil 1)
2204 => \" bar foo\"
2207 ;; To avoid excessive consing from multiple matches in long strings,
2208 ;; don't just call `replace-match' continually. Walk down the
2209 ;; string looking for matches of REGEXP and building up a (reversed)
2210 ;; list MATCHES. This comprises segments of STRING which weren't
2211 ;; matched interspersed with replacements for segments that were.
2212 ;; [For a `large' number of replacements it's more efficient to
2213 ;; operate in a temporary buffer; we can't tell from the function's
2214 ;; args whether to choose the buffer-based implementation, though it
2215 ;; might be reasonable to do so for long enough STRING.]
2216 (let ((l (length string))
2217 (start (or start 0))
2218 matches str mb me)
2219 (save-match-data
2220 (while (and (< start l) (string-match regexp string start))
2221 (setq mb (match-beginning 0)
2222 me (match-end 0))
2223 ;; If we matched the empty string, make sure we advance by one char
2224 (when (= me mb) (setq me (min l (1+ mb))))
2225 ;; Generate a replacement for the matched substring.
2226 ;; Operate only on the substring to minimize string consing.
2227 ;; Set up match data for the substring for replacement;
2228 ;; presumably this is likely to be faster than munging the
2229 ;; match data directly in Lisp.
2230 (string-match regexp (setq str (substring string mb me)))
2231 (setq matches
2232 (cons (replace-match (if (stringp rep)
2234 (funcall rep (match-string 0 str)))
2235 fixedcase literal str subexp)
2236 (cons (substring string start mb) ; unmatched prefix
2237 matches)))
2238 (setq start me))
2239 ;; Reconstruct a string from the pieces.
2240 (setq matches (cons (substring string start l) matches)) ; leftover
2241 (apply #'concat (nreverse matches)))))
2243 (defun shell-quote-argument (argument)
2244 "Quote an argument for passing as argument to an inferior shell."
2245 (if (eq system-type 'ms-dos)
2246 ;; Quote using double quotes, but escape any existing quotes in
2247 ;; the argument with backslashes.
2248 (let ((result "")
2249 (start 0)
2250 end)
2251 (if (or (null (string-match "[^\"]" argument))
2252 (< (match-end 0) (length argument)))
2253 (while (string-match "[\"]" argument start)
2254 (setq end (match-beginning 0)
2255 result (concat result (substring argument start end)
2256 "\\" (substring argument end (1+ end)))
2257 start (1+ end))))
2258 (concat "\"" result (substring argument start) "\""))
2259 (if (eq system-type 'windows-nt)
2260 (concat "\"" argument "\"")
2261 (if (equal argument "")
2262 "''"
2263 ;; Quote everything except POSIX filename characters.
2264 ;; This should be safe enough even for really weird shells.
2265 (let ((result "") (start 0) end)
2266 (while (string-match "[^-0-9a-zA-Z_./]" argument start)
2267 (setq end (match-beginning 0)
2268 result (concat result (substring argument start end)
2269 "\\" (substring argument end (1+ end)))
2270 start (1+ end)))
2271 (concat result (substring argument start)))))))
2273 (defun make-syntax-table (&optional oldtable)
2274 "Return a new syntax table.
2275 Create a syntax table which inherits from OLDTABLE (if non-nil) or
2276 from `standard-syntax-table' otherwise."
2277 (let ((table (make-char-table 'syntax-table nil)))
2278 (set-char-table-parent table (or oldtable (standard-syntax-table)))
2279 table))
2281 (defun syntax-after (pos)
2282 "Return the syntax of the char after POS."
2283 (unless (or (< pos (point-min)) (>= pos (point-max)))
2284 (let ((st (if parse-sexp-lookup-properties
2285 (get-char-property pos 'syntax-table))))
2286 (if (consp st) st
2287 (aref (or st (syntax-table)) (char-after pos))))))
2289 (defun add-to-invisibility-spec (arg)
2290 "Add elements to `buffer-invisibility-spec'.
2291 See documentation for `buffer-invisibility-spec' for the kind of elements
2292 that can be added."
2293 (if (eq buffer-invisibility-spec t)
2294 (setq buffer-invisibility-spec (list t)))
2295 (setq buffer-invisibility-spec
2296 (cons arg buffer-invisibility-spec)))
2298 (defun remove-from-invisibility-spec (arg)
2299 "Remove elements from `buffer-invisibility-spec'."
2300 (if (consp buffer-invisibility-spec)
2301 (setq buffer-invisibility-spec (delete arg buffer-invisibility-spec))))
2303 (defun global-set-key (key command)
2304 "Give KEY a global binding as COMMAND.
2305 COMMAND is the command definition to use; usually it is
2306 a symbol naming an interactively-callable function.
2307 KEY is a key sequence; noninteractively, it is a string or vector
2308 of characters or event types, and non-ASCII characters with codes
2309 above 127 (such as ISO Latin-1) can be included if you use a vector.
2311 Note that if KEY has a local binding in the current buffer,
2312 that local binding will continue to shadow any global binding
2313 that you make with this function."
2314 (interactive "KSet key globally: \nCSet key %s to command: ")
2315 (or (vectorp key) (stringp key)
2316 (signal 'wrong-type-argument (list 'arrayp key)))
2317 (define-key (current-global-map) key command))
2319 (defun local-set-key (key command)
2320 "Give KEY a local binding as COMMAND.
2321 COMMAND is the command definition to use; usually it is
2322 a symbol naming an interactively-callable function.
2323 KEY is a key sequence; noninteractively, it is a string or vector
2324 of characters or event types, and non-ASCII characters with codes
2325 above 127 (such as ISO Latin-1) can be included if you use a vector.
2327 The binding goes in the current buffer's local map,
2328 which in most cases is shared with all other buffers in the same major mode."
2329 (interactive "KSet key locally: \nCSet key %s locally to command: ")
2330 (let ((map (current-local-map)))
2331 (or map
2332 (use-local-map (setq map (make-sparse-keymap))))
2333 (or (vectorp key) (stringp key)
2334 (signal 'wrong-type-argument (list 'arrayp key)))
2335 (define-key map key command)))
2337 (defun global-unset-key (key)
2338 "Remove global binding of KEY.
2339 KEY is a string or vector representing a sequence of keystrokes."
2340 (interactive "kUnset key globally: ")
2341 (global-set-key key nil))
2343 (defun local-unset-key (key)
2344 "Remove local binding of KEY.
2345 KEY is a string or vector representing a sequence of keystrokes."
2346 (interactive "kUnset key locally: ")
2347 (if (current-local-map)
2348 (local-set-key key nil))
2349 nil)
2351 ;; We put this here instead of in frame.el so that it's defined even on
2352 ;; systems where frame.el isn't loaded.
2353 (defun frame-configuration-p (object)
2354 "Return non-nil if OBJECT seems to be a frame configuration.
2355 Any list whose car is `frame-configuration' is assumed to be a frame
2356 configuration."
2357 (and (consp object)
2358 (eq (car object) 'frame-configuration)))
2360 (defun functionp (object)
2361 "Non-nil if OBJECT is any kind of function or a special form.
2362 Also non-nil if OBJECT is a symbol and its function definition is
2363 \(recursively) a function or special form. This does not include
2364 macros."
2365 (or (and (symbolp object) (fboundp object)
2366 (condition-case nil
2367 (setq object (indirect-function object))
2368 (error nil))
2369 (eq (car-safe object) 'autoload)
2370 (not (car-safe (cdr-safe (cdr-safe (cdr-safe (cdr-safe object)))))))
2371 (subrp object) (byte-code-function-p object)
2372 (eq (car-safe object) 'lambda)))
2374 (defun assq-delete-all (key alist)
2375 "Delete from ALIST all elements whose car is KEY.
2376 Return the modified alist.
2377 Elements of ALIST that are not conses are ignored."
2378 (let ((tail alist))
2379 (while tail
2380 (if (and (consp (car tail)) (eq (car (car tail)) key))
2381 (setq alist (delq (car tail) alist)))
2382 (setq tail (cdr tail)))
2383 alist))
2385 (defun make-temp-file (prefix &optional dir-flag suffix)
2386 "Create a temporary file.
2387 The returned file name (created by appending some random characters at the end
2388 of PREFIX, and expanding against `temporary-file-directory' if necessary),
2389 is guaranteed to point to a newly created empty file.
2390 You can then use `write-region' to write new data into the file.
2392 If DIR-FLAG is non-nil, create a new empty directory instead of a file.
2394 If SUFFIX is non-nil, add that at the end of the file name."
2395 (let ((umask (default-file-modes))
2396 file)
2397 (unwind-protect
2398 (progn
2399 ;; Create temp files with strict access rights. It's easy to
2400 ;; loosen them later, whereas it's impossible to close the
2401 ;; time-window of loose permissions otherwise.
2402 (set-default-file-modes ?\700)
2403 (while (condition-case ()
2404 (progn
2405 (setq file
2406 (make-temp-name
2407 (expand-file-name prefix temporary-file-directory)))
2408 (if suffix
2409 (setq file (concat file suffix)))
2410 (if dir-flag
2411 (make-directory file)
2412 (write-region "" nil file nil 'silent nil 'excl))
2413 nil)
2414 (file-already-exists t))
2415 ;; the file was somehow created by someone else between
2416 ;; `make-temp-name' and `write-region', let's try again.
2417 nil)
2418 file)
2419 ;; Reset the umask.
2420 (set-default-file-modes umask))))
2423 ;; If a minor mode is not defined with define-minor-mode,
2424 ;; add it here explicitly.
2425 ;; isearch-mode is deliberately excluded, since you should
2426 ;; not call it yourself.
2427 (defvar minor-mode-list '(auto-save-mode auto-fill-mode abbrev-mode
2428 overwrite-mode view-mode
2429 hs-minor-mode)
2430 "List of all minor mode functions.")
2432 (defun add-minor-mode (toggle name &optional keymap after toggle-fun)
2433 "Register a new minor mode.
2435 This is an XEmacs-compatibility function. Use `define-minor-mode' instead.
2437 TOGGLE is a symbol which is the name of a buffer-local variable that
2438 is toggled on or off to say whether the minor mode is active or not.
2440 NAME specifies what will appear in the mode line when the minor mode
2441 is active. NAME should be either a string starting with a space, or a
2442 symbol whose value is such a string.
2444 Optional KEYMAP is the keymap for the minor mode that will be added
2445 to `minor-mode-map-alist'.
2447 Optional AFTER specifies that TOGGLE should be added after AFTER
2448 in `minor-mode-alist'.
2450 Optional TOGGLE-FUN is an interactive function to toggle the mode.
2451 It defaults to (and should by convention be) TOGGLE.
2453 If TOGGLE has a non-nil `:included' property, an entry for the mode is
2454 included in the mode-line minor mode menu.
2455 If TOGGLE has a `:menu-tag', that is used for the menu item's label."
2456 (unless (memq toggle minor-mode-list)
2457 (push toggle minor-mode-list))
2459 (unless toggle-fun (setq toggle-fun toggle))
2460 ;; Add the name to the minor-mode-alist.
2461 (when name
2462 (let ((existing (assq toggle minor-mode-alist)))
2463 (if existing
2464 (setcdr existing (list name))
2465 (let ((tail minor-mode-alist) found)
2466 (while (and tail (not found))
2467 (if (eq after (caar tail))
2468 (setq found tail)
2469 (setq tail (cdr tail))))
2470 (if found
2471 (let ((rest (cdr found)))
2472 (setcdr found nil)
2473 (nconc found (list (list toggle name)) rest))
2474 (setq minor-mode-alist (cons (list toggle name)
2475 minor-mode-alist)))))))
2476 ;; Add the toggle to the minor-modes menu if requested.
2477 (when (get toggle :included)
2478 (define-key mode-line-mode-menu
2479 (vector toggle)
2480 (list 'menu-item
2481 (concat
2482 (or (get toggle :menu-tag)
2483 (if (stringp name) name (symbol-name toggle)))
2484 (let ((mode-name (if (symbolp name) (symbol-value name))))
2485 (if (and (stringp mode-name) (string-match "[^ ]+" mode-name))
2486 (concat " (" (match-string 0 mode-name) ")"))))
2487 toggle-fun
2488 :button (cons :toggle toggle))))
2490 ;; Add the map to the minor-mode-map-alist.
2491 (when keymap
2492 (let ((existing (assq toggle minor-mode-map-alist)))
2493 (if existing
2494 (setcdr existing keymap)
2495 (let ((tail minor-mode-map-alist) found)
2496 (while (and tail (not found))
2497 (if (eq after (caar tail))
2498 (setq found tail)
2499 (setq tail (cdr tail))))
2500 (if found
2501 (let ((rest (cdr found)))
2502 (setcdr found nil)
2503 (nconc found (list (cons toggle keymap)) rest))
2504 (setq minor-mode-map-alist (cons (cons toggle keymap)
2505 minor-mode-map-alist))))))))
2507 ;; Clones ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2509 (defun text-clone-maintain (ol1 after beg end &optional len)
2510 "Propagate the changes made under the overlay OL1 to the other clones.
2511 This is used on the `modification-hooks' property of text clones."
2512 (when (and after (not undo-in-progress) (overlay-start ol1))
2513 (let ((margin (if (overlay-get ol1 'text-clone-spreadp) 1 0)))
2514 (setq beg (max beg (+ (overlay-start ol1) margin)))
2515 (setq end (min end (- (overlay-end ol1) margin)))
2516 (when (<= beg end)
2517 (save-excursion
2518 (when (overlay-get ol1 'text-clone-syntax)
2519 ;; Check content of the clone's text.
2520 (let ((cbeg (+ (overlay-start ol1) margin))
2521 (cend (- (overlay-end ol1) margin)))
2522 (goto-char cbeg)
2523 (save-match-data
2524 (if (not (re-search-forward
2525 (overlay-get ol1 'text-clone-syntax) cend t))
2526 ;; Mark the overlay for deletion.
2527 (overlay-put ol1 'text-clones nil)
2528 (when (< (match-end 0) cend)
2529 ;; Shrink the clone at its end.
2530 (setq end (min end (match-end 0)))
2531 (move-overlay ol1 (overlay-start ol1)
2532 (+ (match-end 0) margin)))
2533 (when (> (match-beginning 0) cbeg)
2534 ;; Shrink the clone at its beginning.
2535 (setq beg (max (match-beginning 0) beg))
2536 (move-overlay ol1 (- (match-beginning 0) margin)
2537 (overlay-end ol1)))))))
2538 ;; Now go ahead and update the clones.
2539 (let ((head (- beg (overlay-start ol1)))
2540 (tail (- (overlay-end ol1) end))
2541 (str (buffer-substring beg end))
2542 (nothing-left t)
2543 (inhibit-modification-hooks t))
2544 (dolist (ol2 (overlay-get ol1 'text-clones))
2545 (let ((oe (overlay-end ol2)))
2546 (unless (or (eq ol1 ol2) (null oe))
2547 (setq nothing-left nil)
2548 (let ((mod-beg (+ (overlay-start ol2) head)))
2549 ;;(overlay-put ol2 'modification-hooks nil)
2550 (goto-char (- (overlay-end ol2) tail))
2551 (unless (> mod-beg (point))
2552 (save-excursion (insert str))
2553 (delete-region mod-beg (point)))
2554 ;;(overlay-put ol2 'modification-hooks '(text-clone-maintain))
2555 ))))
2556 (if nothing-left (delete-overlay ol1))))))))
2558 (defun text-clone-create (start end &optional spreadp syntax)
2559 "Create a text clone of START...END at point.
2560 Text clones are chunks of text that are automatically kept identical:
2561 changes done to one of the clones will be immediately propagated to the other.
2563 The buffer's content at point is assumed to be already identical to
2564 the one between START and END.
2565 If SYNTAX is provided it's a regexp that describes the possible text of
2566 the clones; the clone will be shrunk or killed if necessary to ensure that
2567 its text matches the regexp.
2568 If SPREADP is non-nil it indicates that text inserted before/after the
2569 clone should be incorporated in the clone."
2570 ;; To deal with SPREADP we can either use an overlay with `nil t' along
2571 ;; with insert-(behind|in-front-of)-hooks or use a slightly larger overlay
2572 ;; (with a one-char margin at each end) with `t nil'.
2573 ;; We opted for a larger overlay because it behaves better in the case
2574 ;; where the clone is reduced to the empty string (we want the overlay to
2575 ;; stay when the clone's content is the empty string and we want to use
2576 ;; `evaporate' to make sure those overlays get deleted when needed).
2578 (let* ((pt-end (+ (point) (- end start)))
2579 (start-margin (if (or (not spreadp) (bobp) (<= start (point-min)))
2580 0 1))
2581 (end-margin (if (or (not spreadp)
2582 (>= pt-end (point-max))
2583 (>= start (point-max)))
2584 0 1))
2585 (ol1 (make-overlay (- start start-margin) (+ end end-margin) nil t))
2586 (ol2 (make-overlay (- (point) start-margin) (+ pt-end end-margin) nil t))
2587 (dups (list ol1 ol2)))
2588 (overlay-put ol1 'modification-hooks '(text-clone-maintain))
2589 (when spreadp (overlay-put ol1 'text-clone-spreadp t))
2590 (when syntax (overlay-put ol1 'text-clone-syntax syntax))
2591 ;;(overlay-put ol1 'face 'underline)
2592 (overlay-put ol1 'evaporate t)
2593 (overlay-put ol1 'text-clones dups)
2595 (overlay-put ol2 'modification-hooks '(text-clone-maintain))
2596 (when spreadp (overlay-put ol2 'text-clone-spreadp t))
2597 (when syntax (overlay-put ol2 'text-clone-syntax syntax))
2598 ;;(overlay-put ol2 'face 'underline)
2599 (overlay-put ol2 'evaporate t)
2600 (overlay-put ol2 'text-clones dups)))
2602 (defun play-sound (sound)
2603 "SOUND is a list of the form `(sound KEYWORD VALUE...)'.
2604 The following keywords are recognized:
2606 :file FILE - read sound data from FILE. If FILE isn't an
2607 absolute file name, it is searched in `data-directory'.
2609 :data DATA - read sound data from string DATA.
2611 Exactly one of :file or :data must be present.
2613 :volume VOL - set volume to VOL. VOL must an integer in the
2614 range 0..100 or a float in the range 0..1.0. If not specified,
2615 don't change the volume setting of the sound device.
2617 :device DEVICE - play sound on DEVICE. If not specified,
2618 a system-dependent default device name is used."
2619 (unless (fboundp 'play-sound-internal)
2620 (error "This Emacs binary lacks sound support"))
2621 (play-sound-internal sound))
2623 (defun define-mail-user-agent (symbol composefunc sendfunc
2624 &optional abortfunc hookvar)
2625 "Define a symbol to identify a mail-sending package for `mail-user-agent'.
2627 SYMBOL can be any Lisp symbol. Its function definition and/or
2628 value as a variable do not matter for this usage; we use only certain
2629 properties on its property list, to encode the rest of the arguments.
2631 COMPOSEFUNC is program callable function that composes an outgoing
2632 mail message buffer. This function should set up the basics of the
2633 buffer without requiring user interaction. It should populate the
2634 standard mail headers, leaving the `to:' and `subject:' headers blank
2635 by default.
2637 COMPOSEFUNC should accept several optional arguments--the same
2638 arguments that `compose-mail' takes. See that function's documentation.
2640 SENDFUNC is the command a user would run to send the message.
2642 Optional ABORTFUNC is the command a user would run to abort the
2643 message. For mail packages that don't have a separate abort function,
2644 this can be `kill-buffer' (the equivalent of omitting this argument).
2646 Optional HOOKVAR is a hook variable that gets run before the message
2647 is actually sent. Callers that use the `mail-user-agent' may
2648 install a hook function temporarily on this hook variable.
2649 If HOOKVAR is nil, `mail-send-hook' is used.
2651 The properties used on SYMBOL are `composefunc', `sendfunc',
2652 `abortfunc', and `hookvar'."
2653 (put symbol 'composefunc composefunc)
2654 (put symbol 'sendfunc sendfunc)
2655 (put symbol 'abortfunc (or abortfunc 'kill-buffer))
2656 (put symbol 'hookvar (or hookvar 'mail-send-hook)))
2658 ;; Standardized progress reporting
2660 ;; Progress reporter has the following structure:
2662 ;; (NEXT-UPDATE-VALUE . [NEXT-UPDATE-TIME
2663 ;; MIN-VALUE
2664 ;; MAX-VALUE
2665 ;; MESSAGE
2666 ;; MIN-CHANGE
2667 ;; MIN-TIME])
2669 ;; This weirdeness is for optimization reasons: we want
2670 ;; `progress-reporter-update' to be as fast as possible, so
2671 ;; `(car reporter)' is better than `(aref reporter 0)'.
2673 ;; NEXT-UPDATE-TIME is a float. While `float-time' loses a couple
2674 ;; digits of precision, it doesn't really matter here. On the other
2675 ;; hand, it greatly simplifies the code.
2677 (defsubst progress-reporter-update (reporter value)
2678 "Report progress of an operation in the echo area.
2679 However, if the change since last echo area update is too small
2680 or not enough time has passed, then do nothing (see
2681 `make-progress-reporter' for details).
2683 First parameter, REPORTER, should be the result of a call to
2684 `make-progress-reporter'. Second, VALUE, determines the actual
2685 progress of operation; it must be between MIN-VALUE and MAX-VALUE
2686 as passed to `make-progress-reporter'.
2688 This function is very inexpensive, you may not bother how often
2689 you call it."
2690 (when (>= value (car reporter))
2691 (progress-reporter-do-update reporter value)))
2693 (defun make-progress-reporter (message min-value max-value
2694 &optional current-value
2695 min-change min-time)
2696 "Return progress reporter object usage with `progress-reporter-update'.
2698 MESSAGE is shown in the echo area. When at least 1% of operation
2699 is complete, the exact percentage will be appended to the
2700 MESSAGE. When you call `progress-reporter-done', word \"done\"
2701 is printed after the MESSAGE. You can change MESSAGE of an
2702 existing progress reporter with `progress-reporter-force-update'.
2704 MIN-VALUE and MAX-VALUE designate starting (0% complete) and
2705 final (100% complete) states of operation. The latter should be
2706 larger; if this is not the case, then simply negate all values.
2707 Optional CURRENT-VALUE specifies the progress by the moment you
2708 call this function. You should omit it or set it to nil in most
2709 cases since it defaults to MIN-VALUE.
2711 Optional MIN-CHANGE determines the minimal change in percents to
2712 report (default is 1%.) Optional MIN-TIME specifies the minimal
2713 time before echo area updates (default is 0.2 seconds.) If
2714 `float-time' function is not present, then time is not tracked
2715 at all. If OS is not capable of measuring fractions of seconds,
2716 then this parameter is effectively rounded up."
2718 (unless min-time
2719 (setq min-time 0.2))
2720 (let ((reporter
2721 (cons min-value ;; Force a call to `message' now
2722 (vector (if (and (fboundp 'float-time)
2723 (>= min-time 0.02))
2724 (float-time) nil)
2725 min-value
2726 max-value
2727 message
2728 (if min-change (max (min min-change 50) 1) 1)
2729 min-time))))
2730 (progress-reporter-update reporter (or current-value min-value))
2731 reporter))
2733 (defun progress-reporter-force-update (reporter value &optional new-message)
2734 "Report progress of an operation in the echo area unconditionally.
2736 First two parameters are the same as for
2737 `progress-reporter-update'. Optional NEW-MESSAGE allows you to
2738 change the displayed message."
2739 (let ((parameters (cdr reporter)))
2740 (when new-message
2741 (aset parameters 3 new-message))
2742 (when (aref parameters 0)
2743 (aset parameters 0 (float-time)))
2744 (progress-reporter-do-update reporter value)))
2746 (defun progress-reporter-do-update (reporter value)
2747 (let* ((parameters (cdr reporter))
2748 (min-value (aref parameters 1))
2749 (max-value (aref parameters 2))
2750 (one-percent (/ (- max-value min-value) 100.0))
2751 (percentage (truncate (/ (- value min-value) one-percent)))
2752 (update-time (aref parameters 0))
2753 (current-time (float-time))
2754 (enough-time-passed
2755 ;; See if enough time has passed since the last update.
2756 (or (not update-time)
2757 (when (>= current-time update-time)
2758 ;; Calculate time for the next update
2759 (aset parameters 0 (+ update-time (aref parameters 5)))))))
2761 ;; Calculate NEXT-UPDATE-VALUE. If we are not going to print
2762 ;; message this time because not enough time has passed, then use
2763 ;; 1 instead of MIN-CHANGE. This makes delays between echo area
2764 ;; updates closer to MIN-TIME.
2765 (setcar reporter
2766 (min (+ min-value (* (+ percentage
2767 (if enough-time-passed
2768 (aref parameters 4) ;; MIN-CHANGE
2770 one-percent))
2771 max-value))
2772 (when (integerp value)
2773 (setcar reporter (ceiling (car reporter))))
2775 ;; Only print message if enough time has passed
2776 (when enough-time-passed
2777 (if (> percentage 0)
2778 (message "%s%d%%" (aref parameters 3) percentage)
2779 (message "%s" (aref parameters 3))))))
2781 (defun progress-reporter-done (reporter)
2782 "Print reporter's message followed by word \"done\" in echo area."
2783 (message "%sdone" (aref (cdr reporter) 3)))
2785 ;; arch-tag: f7e0e6e5-70aa-4897-ae72-7a3511ec40bc
2786 ;;; subr.el ends here