*** empty log message ***
[emacs.git] / lisp / subr.el
blob767e2a8cde3f452b823b246f73780eb4d7c31df1
1 ;;; subr.el --- basic lisp subroutines for Emacs
3 ;; Copyright (C) 1985, 86, 92, 94, 95, 99, 2000 Free Software Foundation, Inc.
5 ;; This file is part of GNU Emacs.
7 ;; GNU Emacs is free software; you can redistribute it and/or modify
8 ;; it under the terms of the GNU General Public License as published by
9 ;; the Free Software Foundation; either version 2, or (at your option)
10 ;; any later version.
12 ;; GNU Emacs is distributed in the hope that it will be useful,
13 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
14 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 ;; GNU General Public License for more details.
17 ;; You should have received a copy of the GNU General Public License
18 ;; along with GNU Emacs; see the file COPYING. If not, write to the
19 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 ;; Boston, MA 02111-1307, USA.
22 ;;; Code:
23 (defvar custom-declare-variable-list nil
24 "Record `defcustom' calls made before `custom.el' is loaded to handle them.
25 Each element of this list holds the arguments to one call to `defcustom'.")
27 ;; Use this, rather than defcustom, in subr.el and other files loaded
28 ;; before custom.el.
29 (defun custom-declare-variable-early (&rest arguments)
30 (setq custom-declare-variable-list
31 (cons arguments custom-declare-variable-list)))
33 ;;;; Lisp language features.
35 (defmacro lambda (&rest cdr)
36 "Return a lambda expression.
37 A call of the form (lambda ARGS DOCSTRING INTERACTIVE BODY) is
38 self-quoting; the result of evaluating the lambda expression is the
39 expression itself. The lambda expression may then be treated as a
40 function, i.e., stored as the function value of a symbol, passed to
41 funcall or mapcar, etc.
43 ARGS should take the same form as an argument list for a `defun'.
44 DOCSTRING is an optional documentation string.
45 If present, it should describe how to call the function.
46 But documentation strings are usually not useful in nameless functions.
47 INTERACTIVE should be a call to the function `interactive', which see.
48 It may also be omitted.
49 BODY should be a list of lisp expressions."
50 ;; Note that this definition should not use backquotes; subr.el should not
51 ;; depend on backquote.el.
52 (list 'function (cons 'lambda cdr)))
54 (defmacro push (newelt listname)
55 "Add NEWELT to the list stored in the symbol LISTNAME.
56 This is equivalent to (setq LISTNAME (cons NEWELT LISTNAME)).
57 LISTNAME must be a symbol."
58 (list 'setq listname
59 (list 'cons newelt listname)))
61 (defmacro pop (listname)
62 "Return the first element of LISTNAME's value, and remove it from the list.
63 LISTNAME must be a symbol whose value is a list.
64 If the value is nil, `pop' returns nil but does not actually
65 change the list."
66 (list 'prog1 (list 'car listname)
67 (list 'setq listname (list 'cdr listname))))
69 (defmacro when (cond &rest body)
70 "If COND yields non-nil, do BODY, else return nil."
71 (list 'if cond (cons 'progn body)))
73 (defmacro unless (cond &rest body)
74 "If COND yields nil, do BODY, else return nil."
75 (cons 'if (cons cond (cons nil body))))
77 (defmacro dolist (spec &rest body)
78 "(dolist (VAR LIST [RESULT]) BODY...): loop over a list.
79 Evaluate BODY with VAR bound to each car from LIST, in turn.
80 Then evaluate RESULT to get return value, default nil."
81 (let ((temp (make-symbol "--dolist-temp--")))
82 (list 'let (list (list temp (nth 1 spec)) (car spec))
83 (list 'while temp
84 (list 'setq (car spec) (list 'car temp))
85 (cons 'progn
86 (append body
87 (list (list 'setq temp (list 'cdr temp))))))
88 (if (cdr (cdr spec))
89 (cons 'progn
90 (cons (list 'setq (car spec) nil) (cdr (cdr spec))))))))
92 (defmacro dotimes (spec &rest body)
93 "(dotimes (VAR COUNT [RESULT]) BODY...): loop a certain number of times.
94 Evaluate BODY with VAR bound to successive integers running from 0,
95 inclusive, to COUNT, exclusive. Then evaluate RESULT to get
96 the return value (nil if RESULT is omitted)."
97 (let ((temp (make-symbol "--dotimes-temp--")))
98 (list 'let (list (list temp (nth 1 spec)) (list (car spec) 0))
99 (list 'while (list '< (car spec) temp)
100 (cons 'progn
101 (append body (list (list 'setq (car spec)
102 (list '1+ (car spec)))))))
103 (if (cdr (cdr spec))
104 (car (cdr (cdr spec)))
105 nil))))
107 (defsubst caar (x)
108 "Return the car of the car of X."
109 (car (car x)))
111 (defsubst cadr (x)
112 "Return the car of the cdr of X."
113 (car (cdr x)))
115 (defsubst cdar (x)
116 "Return the cdr of the car of X."
117 (cdr (car x)))
119 (defsubst cddr (x)
120 "Return the cdr of the cdr of X."
121 (cdr (cdr x)))
123 (defun last (x &optional n)
124 "Return the last link of the list X. Its car is the last element.
125 If X is nil, return nil.
126 If N is non-nil, return the Nth-to-last link of X.
127 If N is bigger than the length of X, return X."
128 (if n
129 (let ((m 0) (p x))
130 (while (consp p)
131 (setq m (1+ m) p (cdr p)))
132 (if (<= n 0) p
133 (if (< n m) (nthcdr (- m n) x) x)))
134 (while (cdr x)
135 (setq x (cdr x)))
138 (defun remove (elt seq)
139 "Return a copy of SEQ with all occurences of ELT removed.
140 SEQ must be a list, vector, or string. The comparison is done with `equal'."
141 (if (nlistp seq)
142 ;; If SEQ isn't a list, there's no need to copy SEQ because
143 ;; `delete' will return a new object.
144 (delete elt seq)
145 (delete elt (copy-sequence seq))))
147 (defun remq (elt list)
148 "Return a copy of LIST with all occurences of ELT removed.
149 The comparison is done with `eq'."
150 (if (memq elt list)
151 (delq elt (copy-sequence list))
152 list))
154 (defun assoc-default (key alist &optional test default)
155 "Find object KEY in a pseudo-alist ALIST.
156 ALIST is a list of conses or objects. Each element (or the element's car,
157 if it is a cons) is compared with KEY by evaluating (TEST (car elt) KEY).
158 If that is non-nil, the element matches;
159 then `assoc-default' returns the element's cdr, if it is a cons,
160 or DEFAULT if the element is not a cons.
162 If no element matches, the value is nil.
163 If TEST is omitted or nil, `equal' is used."
164 (let (found (tail alist) value)
165 (while (and tail (not found))
166 (let ((elt (car tail)))
167 (when (funcall (or test 'equal) (if (consp elt) (car elt) elt) key)
168 (setq found t value (if (consp elt) (cdr elt) default))))
169 (setq tail (cdr tail)))
170 value))
172 (defun assoc-ignore-case (key alist)
173 "Like `assoc', but ignores differences in case and text representation.
174 KEY must be a string. Upper-case and lower-case letters are treated as equal.
175 Unibyte strings are converted to multibyte for comparison."
176 (let (element)
177 (while (and alist (not element))
178 (if (eq t (compare-strings key 0 nil (car (car alist)) 0 nil t))
179 (setq element (car alist)))
180 (setq alist (cdr alist)))
181 element))
183 (defun assoc-ignore-representation (key alist)
184 "Like `assoc', but ignores differences in text representation.
185 KEY must be a string.
186 Unibyte strings are converted to multibyte for comparison."
187 (let (element)
188 (while (and alist (not element))
189 (if (eq t (compare-strings key 0 nil (car (car alist)) 0 nil))
190 (setq element (car alist)))
191 (setq alist (cdr alist)))
192 element))
194 (defun member-ignore-case (elt list)
195 "Like `member', but ignores differences in case and text representation.
196 ELT must be a string. Upper-case and lower-case letters are treated as equal.
197 Unibyte strings are converted to multibyte for comparison."
198 (let (element)
199 (while (and list (not element))
200 (if (eq t (compare-strings elt 0 nil (car list) 0 nil t))
201 (setq element (car list)))
202 (setq list (cdr list)))
203 element))
206 ;;;; Keymap support.
208 (defun undefined ()
209 (interactive)
210 (ding))
212 ;Prevent the \{...} documentation construct
213 ;from mentioning keys that run this command.
214 (put 'undefined 'suppress-keymap t)
216 (defun suppress-keymap (map &optional nodigits)
217 "Make MAP override all normally self-inserting keys to be undefined.
218 Normally, as an exception, digits and minus-sign are set to make prefix args,
219 but optional second arg NODIGITS non-nil treats them like other chars."
220 (substitute-key-definition 'self-insert-command 'undefined map global-map)
221 (or nodigits
222 (let (loop)
223 (define-key map "-" 'negative-argument)
224 ;; Make plain numbers do numeric args.
225 (setq loop ?0)
226 (while (<= loop ?9)
227 (define-key map (char-to-string loop) 'digit-argument)
228 (setq loop (1+ loop))))))
230 ;Moved to keymap.c
231 ;(defun copy-keymap (keymap)
232 ; "Return a copy of KEYMAP"
233 ; (while (not (keymapp keymap))
234 ; (setq keymap (signal 'wrong-type-argument (list 'keymapp keymap))))
235 ; (if (vectorp keymap)
236 ; (copy-sequence keymap)
237 ; (copy-alist keymap)))
239 (defvar key-substitution-in-progress nil
240 "Used internally by substitute-key-definition.")
242 (defun substitute-key-definition (olddef newdef keymap &optional oldmap prefix)
243 "Replace OLDDEF with NEWDEF for any keys in KEYMAP now defined as OLDDEF.
244 In other words, OLDDEF is replaced with NEWDEF where ever it appears.
245 Alternatively, if optional fourth argument OLDMAP is specified, we redefine
246 in KEYMAP as NEWDEF those chars which are defined as OLDDEF in OLDMAP."
247 ;; Don't document PREFIX in the doc string because we don't want to
248 ;; advertise it. It's meant for recursive calls only. Here's its
249 ;; meaning
251 ;; If optional argument PREFIX is specified, it should be a key
252 ;; prefix, a string. Redefined bindings will then be bound to the
253 ;; original key, with PREFIX added at the front.
254 (or prefix (setq prefix ""))
255 (let* ((scan (or oldmap keymap))
256 (vec1 (vector nil))
257 (prefix1 (vconcat prefix vec1))
258 (key-substitution-in-progress
259 (cons scan key-substitution-in-progress)))
260 ;; Scan OLDMAP, finding each char or event-symbol that
261 ;; has any definition, and act on it with hack-key.
262 (while (consp scan)
263 (if (consp (car scan))
264 (let ((char (car (car scan)))
265 (defn (cdr (car scan))))
266 ;; The inside of this let duplicates exactly
267 ;; the inside of the following let that handles array elements.
268 (aset vec1 0 char)
269 (aset prefix1 (length prefix) char)
270 (let (inner-def skipped)
271 ;; Skip past menu-prompt.
272 (while (stringp (car-safe defn))
273 (setq skipped (cons (car defn) skipped))
274 (setq defn (cdr defn)))
275 ;; Skip past cached key-equivalence data for menu items.
276 (and (consp defn) (consp (car defn))
277 (setq defn (cdr defn)))
278 (setq inner-def defn)
279 ;; Look past a symbol that names a keymap.
280 (while (and (symbolp inner-def)
281 (fboundp inner-def))
282 (setq inner-def (symbol-function inner-def)))
283 (if (or (eq defn olddef)
284 ;; Compare with equal if definition is a key sequence.
285 ;; That is useful for operating on function-key-map.
286 (and (or (stringp defn) (vectorp defn))
287 (equal defn olddef)))
288 (define-key keymap prefix1 (nconc (nreverse skipped) newdef))
289 (if (and (keymapp defn)
290 ;; Avoid recursively scanning
291 ;; where KEYMAP does not have a submap.
292 (let ((elt (lookup-key keymap prefix1)))
293 (or (null elt)
294 (keymapp elt)))
295 ;; Avoid recursively rescanning keymap being scanned.
296 (not (memq inner-def
297 key-substitution-in-progress)))
298 ;; If this one isn't being scanned already,
299 ;; scan it now.
300 (substitute-key-definition olddef newdef keymap
301 inner-def
302 prefix1)))))
303 (if (vectorp (car scan))
304 (let* ((array (car scan))
305 (len (length array))
306 (i 0))
307 (while (< i len)
308 (let ((char i) (defn (aref array i)))
309 ;; The inside of this let duplicates exactly
310 ;; the inside of the previous let.
311 (aset vec1 0 char)
312 (aset prefix1 (length prefix) char)
313 (let (inner-def skipped)
314 ;; Skip past menu-prompt.
315 (while (stringp (car-safe defn))
316 (setq skipped (cons (car defn) skipped))
317 (setq defn (cdr defn)))
318 (and (consp defn) (consp (car defn))
319 (setq defn (cdr defn)))
320 (setq inner-def defn)
321 (while (and (symbolp inner-def)
322 (fboundp inner-def))
323 (setq inner-def (symbol-function inner-def)))
324 (if (or (eq defn olddef)
325 (and (or (stringp defn) (vectorp defn))
326 (equal defn olddef)))
327 (define-key keymap prefix1
328 (nconc (nreverse skipped) newdef))
329 (if (and (keymapp defn)
330 (let ((elt (lookup-key keymap prefix1)))
331 (or (null elt)
332 (keymapp elt)))
333 (not (memq inner-def
334 key-substitution-in-progress)))
335 (substitute-key-definition olddef newdef keymap
336 inner-def
337 prefix1)))))
338 (setq i (1+ i))))
339 (if (char-table-p (car scan))
340 (map-char-table
341 (function (lambda (char defn)
342 (let ()
343 ;; The inside of this let duplicates exactly
344 ;; the inside of the previous let,
345 ;; except that it uses set-char-table-range
346 ;; instead of define-key.
347 (aset vec1 0 char)
348 (aset prefix1 (length prefix) char)
349 (let (inner-def skipped)
350 ;; Skip past menu-prompt.
351 (while (stringp (car-safe defn))
352 (setq skipped (cons (car defn) skipped))
353 (setq defn (cdr defn)))
354 (and (consp defn) (consp (car defn))
355 (setq defn (cdr defn)))
356 (setq inner-def defn)
357 (while (and (symbolp inner-def)
358 (fboundp inner-def))
359 (setq inner-def (symbol-function inner-def)))
360 (if (or (eq defn olddef)
361 (and (or (stringp defn) (vectorp defn))
362 (equal defn olddef)))
363 (define-key keymap prefix1
364 (nconc (nreverse skipped) newdef))
365 (if (and (keymapp defn)
366 (let ((elt (lookup-key keymap prefix1)))
367 (or (null elt)
368 (keymapp elt)))
369 (not (memq inner-def
370 key-substitution-in-progress)))
371 (substitute-key-definition olddef newdef keymap
372 inner-def
373 prefix1)))))))
374 (car scan)))))
375 (setq scan (cdr scan)))))
377 (defun define-key-after (keymap key definition &optional after)
378 "Add binding in KEYMAP for KEY => DEFINITION, right after AFTER's binding.
379 This is like `define-key' except that the binding for KEY is placed
380 just after the binding for the event AFTER, instead of at the beginning
381 of the map. Note that AFTER must be an event type (like KEY), NOT a command
382 \(like DEFINITION).
384 If AFTER is t or omitted, the new binding goes at the end of the keymap.
386 KEY must contain just one event type--that is to say, it must be a
387 string or vector of length 1, but AFTER should be a single event
388 type--a symbol or a character, not a sequence.
390 Bindings are always added before any inherited map.
392 The order of bindings in a keymap matters when it is used as a menu."
393 (unless after (setq after t))
394 (or (keymapp keymap)
395 (signal 'wrong-type-argument (list 'keymapp keymap)))
396 (if (> (length key) 1)
397 (error "multi-event key specified in `define-key-after'"))
398 (let ((tail keymap) done inserted
399 (first (aref key 0)))
400 (while (and (not done) tail)
401 ;; Delete any earlier bindings for the same key.
402 (if (eq (car-safe (car (cdr tail))) first)
403 (setcdr tail (cdr (cdr tail))))
404 ;; When we reach AFTER's binding, insert the new binding after.
405 ;; If we reach an inherited keymap, insert just before that.
406 ;; If we reach the end of this keymap, insert at the end.
407 (if (or (and (eq (car-safe (car tail)) after)
408 (not (eq after t)))
409 (eq (car (cdr tail)) 'keymap)
410 (null (cdr tail)))
411 (progn
412 ;; Stop the scan only if we find a parent keymap.
413 ;; Keep going past the inserted element
414 ;; so we can delete any duplications that come later.
415 (if (eq (car (cdr tail)) 'keymap)
416 (setq done t))
417 ;; Don't insert more than once.
418 (or inserted
419 (setcdr tail (cons (cons (aref key 0) definition) (cdr tail))))
420 (setq inserted t)))
421 (setq tail (cdr tail)))))
423 (defmacro kbd (keys)
424 "Convert KEYS to the internal Emacs key representation.
425 KEYS should be a string constant in the format used for
426 saving keyboard macros (see `insert-kbd-macro')."
427 (read-kbd-macro keys))
429 (put 'keyboard-translate-table 'char-table-extra-slots 0)
431 (defun keyboard-translate (from to)
432 "Translate character FROM to TO at a low level.
433 This function creates a `keyboard-translate-table' if necessary
434 and then modifies one entry in it."
435 (or (char-table-p keyboard-translate-table)
436 (setq keyboard-translate-table
437 (make-char-table 'keyboard-translate-table nil)))
438 (aset keyboard-translate-table from to))
441 ;;;; The global keymap tree.
443 ;;; global-map, esc-map, and ctl-x-map have their values set up in
444 ;;; keymap.c; we just give them docstrings here.
446 (defvar global-map nil
447 "Default global keymap mapping Emacs keyboard input into commands.
448 The value is a keymap which is usually (but not necessarily) Emacs's
449 global map.")
451 (defvar esc-map nil
452 "Default keymap for ESC (meta) commands.
453 The normal global definition of the character ESC indirects to this keymap.")
455 (defvar ctl-x-map nil
456 "Default keymap for C-x commands.
457 The normal global definition of the character C-x indirects to this keymap.")
459 (defvar ctl-x-4-map (make-sparse-keymap)
460 "Keymap for subcommands of C-x 4")
461 (defalias 'ctl-x-4-prefix ctl-x-4-map)
462 (define-key ctl-x-map "4" 'ctl-x-4-prefix)
464 (defvar ctl-x-5-map (make-sparse-keymap)
465 "Keymap for frame commands.")
466 (defalias 'ctl-x-5-prefix ctl-x-5-map)
467 (define-key ctl-x-map "5" 'ctl-x-5-prefix)
470 ;;;; Event manipulation functions.
472 ;; The call to `read' is to ensure that the value is computed at load time
473 ;; and not compiled into the .elc file. The value is negative on most
474 ;; machines, but not on all!
475 (defconst listify-key-sequence-1 (logior 128 (read "?\\M-\\^@")))
477 (defun listify-key-sequence (key)
478 "Convert a key sequence to a list of events."
479 (if (vectorp key)
480 (append key nil)
481 (mapcar (function (lambda (c)
482 (if (> c 127)
483 (logxor c listify-key-sequence-1)
484 c)))
485 (append key nil))))
487 (defsubst eventp (obj)
488 "True if the argument is an event object."
489 (or (integerp obj)
490 (and (symbolp obj)
491 (get obj 'event-symbol-elements))
492 (and (consp obj)
493 (symbolp (car obj))
494 (get (car obj) 'event-symbol-elements))))
496 (defun event-modifiers (event)
497 "Returns a list of symbols representing the modifier keys in event EVENT.
498 The elements of the list may include `meta', `control',
499 `shift', `hyper', `super', `alt', `click', `double', `triple', `drag',
500 and `down'."
501 (let ((type event))
502 (if (listp type)
503 (setq type (car type)))
504 (if (symbolp type)
505 (cdr (get type 'event-symbol-elements))
506 (let ((list nil))
507 (or (zerop (logand type ?\M-\^@))
508 (setq list (cons 'meta list)))
509 (or (and (zerop (logand type ?\C-\^@))
510 (>= (logand type 127) 32))
511 (setq list (cons 'control list)))
512 (or (and (zerop (logand type ?\S-\^@))
513 (= (logand type 255) (downcase (logand type 255))))
514 (setq list (cons 'shift list)))
515 (or (zerop (logand type ?\H-\^@))
516 (setq list (cons 'hyper list)))
517 (or (zerop (logand type ?\s-\^@))
518 (setq list (cons 'super list)))
519 (or (zerop (logand type ?\A-\^@))
520 (setq list (cons 'alt list)))
521 list))))
523 (defun event-basic-type (event)
524 "Returns the basic type of the given event (all modifiers removed).
525 The value is an ASCII printing character (not upper case) or a symbol."
526 (if (consp event)
527 (setq event (car event)))
528 (if (symbolp event)
529 (car (get event 'event-symbol-elements))
530 (let ((base (logand event (1- (lsh 1 18)))))
531 (downcase (if (< base 32) (logior base 64) base)))))
533 (defsubst mouse-movement-p (object)
534 "Return non-nil if OBJECT is a mouse movement event."
535 (and (consp object)
536 (eq (car object) 'mouse-movement)))
538 (defsubst event-start (event)
539 "Return the starting position of EVENT.
540 If EVENT is a mouse press or a mouse click, this returns the location
541 of the event.
542 If EVENT is a drag, this returns the drag's starting position.
543 The return value is of the form
544 (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
545 The `posn-' functions access elements of such lists."
546 (nth 1 event))
548 (defsubst event-end (event)
549 "Return the ending location of EVENT. EVENT should be a click or drag event.
550 If EVENT is a click event, this function is the same as `event-start'.
551 The return value is of the form
552 (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
553 The `posn-' functions access elements of such lists."
554 (nth (if (consp (nth 2 event)) 2 1) event))
556 (defsubst event-click-count (event)
557 "Return the multi-click count of EVENT, a click or drag event.
558 The return value is a positive integer."
559 (if (integerp (nth 2 event)) (nth 2 event) 1))
561 (defsubst posn-window (position)
562 "Return the window in POSITION.
563 POSITION should be a list of the form
564 (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
565 as returned by the `event-start' and `event-end' functions."
566 (nth 0 position))
568 (defsubst posn-point (position)
569 "Return the buffer location in POSITION.
570 POSITION should be a list of the form
571 (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
572 as returned by the `event-start' and `event-end' functions."
573 (if (consp (nth 1 position))
574 (car (nth 1 position))
575 (nth 1 position)))
577 (defsubst posn-x-y (position)
578 "Return the x and y coordinates in POSITION.
579 POSITION should be a list of the form
580 (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
581 as returned by the `event-start' and `event-end' functions."
582 (nth 2 position))
584 (defun posn-col-row (position)
585 "Return the column and row in POSITION, measured in characters.
586 POSITION should be a list of the form
587 (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
588 as returned by the `event-start' and `event-end' functions.
589 For a scroll-bar event, the result column is 0, and the row
590 corresponds to the vertical position of the click in the scroll bar."
591 (let ((pair (nth 2 position))
592 (window (posn-window position)))
593 (if (eq (if (consp (nth 1 position))
594 (car (nth 1 position))
595 (nth 1 position))
596 'vertical-scroll-bar)
597 (cons 0 (scroll-bar-scale pair (1- (window-height window))))
598 (if (eq (if (consp (nth 1 position))
599 (car (nth 1 position))
600 (nth 1 position))
601 'horizontal-scroll-bar)
602 (cons (scroll-bar-scale pair (window-width window)) 0)
603 (let* ((frame (if (framep window) window (window-frame window)))
604 (x (/ (car pair) (frame-char-width frame)))
605 (y (/ (cdr pair) (frame-char-height frame))))
606 (cons x y))))))
608 (defsubst posn-timestamp (position)
609 "Return the timestamp of POSITION.
610 POSITION should be a list of the form
611 (WINDOW BUFFER-POSITION (X . Y) TIMESTAMP)
612 as returned by the `event-start' and `event-end' functions."
613 (nth 3 position))
616 ;;;; Obsolescent names for functions.
618 (defalias 'dot 'point)
619 (defalias 'dot-marker 'point-marker)
620 (defalias 'dot-min 'point-min)
621 (defalias 'dot-max 'point-max)
622 (defalias 'window-dot 'window-point)
623 (defalias 'set-window-dot 'set-window-point)
624 (defalias 'read-input 'read-string)
625 (defalias 'send-string 'process-send-string)
626 (defalias 'send-region 'process-send-region)
627 (defalias 'show-buffer 'set-window-buffer)
628 (defalias 'buffer-flush-undo 'buffer-disable-undo)
629 (defalias 'eval-current-buffer 'eval-buffer)
630 (defalias 'compiled-function-p 'byte-code-function-p)
631 (defalias 'define-function 'defalias)
633 (defalias 'sref 'aref)
634 (make-obsolete 'sref 'aref "20.4")
635 (make-obsolete 'char-bytes "Now this function always returns 1" "20.4")
637 ;; Some programs still use this as a function.
638 (defun baud-rate ()
639 "Obsolete function returning the value of the `baud-rate' variable.
640 Please convert your programs to use the variable `baud-rate' directly."
641 baud-rate)
643 (defalias 'focus-frame 'ignore)
644 (defalias 'unfocus-frame 'ignore)
646 ;;;; Alternate names for functions - these are not being phased out.
648 (defalias 'string= 'string-equal)
649 (defalias 'string< 'string-lessp)
650 (defalias 'move-marker 'set-marker)
651 (defalias 'not 'null)
652 (defalias 'rplaca 'setcar)
653 (defalias 'rplacd 'setcdr)
654 (defalias 'beep 'ding) ;preserve lingual purity
655 (defalias 'indent-to-column 'indent-to)
656 (defalias 'backward-delete-char 'delete-backward-char)
657 (defalias 'search-forward-regexp (symbol-function 're-search-forward))
658 (defalias 'search-backward-regexp (symbol-function 're-search-backward))
659 (defalias 'int-to-string 'number-to-string)
660 (defalias 'store-match-data 'set-match-data)
661 (defalias 'point-at-eol 'line-end-position)
662 (defalias 'point-at-bol 'line-beginning-position)
664 ;;; Should this be an obsolete name? If you decide it should, you get
665 ;;; to go through all the sources and change them.
666 (defalias 'string-to-int 'string-to-number)
668 ;;;; Hook manipulation functions.
670 (defun make-local-hook (hook)
671 "Make the hook HOOK local to the current buffer.
672 The return value is HOOK.
674 When a hook is local, its local and global values
675 work in concert: running the hook actually runs all the hook
676 functions listed in *either* the local value *or* the global value
677 of the hook variable.
679 This function works by making `t' a member of the buffer-local value,
680 which acts as a flag to run the hook functions in the default value as
681 well. This works for all normal hooks, but does not work for most
682 non-normal hooks yet. We will be changing the callers of non-normal
683 hooks so that they can handle localness; this has to be done one by
684 one.
686 This function does nothing if HOOK is already local in the current
687 buffer.
689 Do not use `make-local-variable' to make a hook variable buffer-local."
690 (if (local-variable-p hook)
692 (or (boundp hook) (set hook nil))
693 (make-local-variable hook)
694 (set hook (list t)))
695 hook)
697 (defun add-hook (hook function &optional append local)
698 "Add to the value of HOOK the function FUNCTION.
699 FUNCTION is not added if already present.
700 FUNCTION is added (if necessary) at the beginning of the hook list
701 unless the optional argument APPEND is non-nil, in which case
702 FUNCTION is added at the end.
704 The optional fourth argument, LOCAL, if non-nil, says to modify
705 the hook's buffer-local value rather than its default value.
706 This makes the hook buffer-local if needed.
707 To make a hook variable buffer-local, always use
708 `make-local-hook', not `make-local-variable'.
710 HOOK should be a symbol, and FUNCTION may be any valid function. If
711 HOOK is void, it is first set to nil. If HOOK's value is a single
712 function, it is changed to a list of functions."
713 (or (boundp hook) (set hook nil))
714 (or (default-boundp hook) (set-default hook nil))
715 (if local (make-local-hook hook)
716 ;; Detect the case where make-local-variable was used on a hook
717 ;; and do what we used to do.
718 (unless (and (consp (symbol-value hook)) (memq t (symbol-value hook)))
719 (setq local t)))
720 (let ((hook-value (if local (symbol-value hook) (default-value hook))))
721 ;; If the hook value is a single function, turn it into a list.
722 (when (or (not (listp hook-value)) (eq (car hook-value) 'lambda))
723 (setq hook-value (list hook-value)))
724 ;; Do the actual addition if necessary
725 (unless (member function hook-value)
726 (setq hook-value
727 (if append
728 (append hook-value (list function))
729 (cons function hook-value))))
730 ;; Set the actual variable
731 (if local (set hook hook-value) (set-default hook hook-value))))
733 (defun remove-hook (hook function &optional local)
734 "Remove from the value of HOOK the function FUNCTION.
735 HOOK should be a symbol, and FUNCTION may be any valid function. If
736 FUNCTION isn't the value of HOOK, or, if FUNCTION doesn't appear in the
737 list of hooks to run in HOOK, then nothing is done. See `add-hook'.
739 The optional third argument, LOCAL, if non-nil, says to modify
740 the hook's buffer-local value rather than its default value.
741 This makes the hook buffer-local if needed.
742 To make a hook variable buffer-local, always use
743 `make-local-hook', not `make-local-variable'."
744 (or (boundp hook) (set hook nil))
745 (or (default-boundp hook) (set-default hook nil))
746 (if local (make-local-hook hook)
747 ;; Detect the case where make-local-variable was used on a hook
748 ;; and do what we used to do.
749 (unless (and (consp (symbol-value hook)) (memq t (symbol-value hook)))
750 (setq local t)))
751 (let ((hook-value (if local (symbol-value hook) (default-value hook))))
752 ;; Remove the function, for both the list and the non-list cases.
753 (if (or (not (listp hook-value)) (eq (car hook-value) 'lambda))
754 (if (equal hook-value function) (setq hook-value nil))
755 (setq hook-value (delete function (copy-sequence hook-value))))
756 ;; If the function is on the global hook, we need to shadow it locally
757 ;;(when (and local (member function (default-value hook))
758 ;; (not (member (cons 'not function) hook-value)))
759 ;; (push (cons 'not function) hook-value))
760 ;; Set the actual variable
761 (if local (set hook hook-value) (set-default hook hook-value))))
763 (defun add-to-list (list-var element)
764 "Add to the value of LIST-VAR the element ELEMENT if it isn't there yet.
765 The test for presence of ELEMENT is done with `equal'.
766 If ELEMENT is added, it is added at the beginning of the list.
768 If you want to use `add-to-list' on a variable that is not defined
769 until a certain package is loaded, you should put the call to `add-to-list'
770 into a hook function that will be run only after loading the package.
771 `eval-after-load' provides one way to do this. In some cases
772 other hooks, such as major mode hooks, can do the job."
773 (if (member element (symbol-value list-var))
774 (symbol-value list-var)
775 (set list-var (cons element (symbol-value list-var)))))
777 ;;;; Specifying things to do after certain files are loaded.
779 (defun eval-after-load (file form)
780 "Arrange that, if FILE is ever loaded, FORM will be run at that time.
781 This makes or adds to an entry on `after-load-alist'.
782 If FILE is already loaded, evaluate FORM right now.
783 It does nothing if FORM is already on the list for FILE.
784 FILE should be the name of a library, with no directory name."
785 ;; Make sure there is an element for FILE.
786 (or (assoc file after-load-alist)
787 (setq after-load-alist (cons (list file) after-load-alist)))
788 ;; Add FORM to the element if it isn't there.
789 (let ((elt (assoc file after-load-alist)))
790 (or (member form (cdr elt))
791 (progn
792 (nconc elt (list form))
793 ;; If the file has been loaded already, run FORM right away.
794 (and (assoc file load-history)
795 (eval form)))))
796 form)
798 (defun eval-next-after-load (file)
799 "Read the following input sexp, and run it whenever FILE is loaded.
800 This makes or adds to an entry on `after-load-alist'.
801 FILE should be the name of a library, with no directory name."
802 (eval-after-load file (read)))
805 ;;;; Input and display facilities.
807 (defvar read-quoted-char-radix 8
808 "*Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
809 Legitimate radix values are 8, 10 and 16.")
811 (custom-declare-variable-early
812 'read-quoted-char-radix 8
813 "*Radix for \\[quoted-insert] and other uses of `read-quoted-char'.
814 Legitimate radix values are 8, 10 and 16."
815 :type '(choice (const 8) (const 10) (const 16))
816 :group 'editing-basics)
818 (defun read-quoted-char (&optional prompt)
819 "Like `read-char', but do not allow quitting.
820 Also, if the first character read is an octal digit,
821 we read any number of octal digits and return the
822 specified character code. Any nondigit terminates the sequence.
823 If the terminator is RET, it is discarded;
824 any other terminator is used itself as input.
826 The optional argument PROMPT specifies a string to use to prompt the user.
827 The variable `read-quoted-char-radix' controls which radix to use
828 for numeric input."
829 (let ((message-log-max nil) done (first t) (code 0) char)
830 (while (not done)
831 (let ((inhibit-quit first)
832 ;; Don't let C-h get the help message--only help function keys.
833 (help-char nil)
834 (help-form
835 "Type the special character you want to use,
836 or the octal character code.
837 RET terminates the character code and is discarded;
838 any other non-digit terminates the character code and is then used as input."))
839 (setq char (read-event (and prompt (format "%s-" prompt)) t))
840 (if inhibit-quit (setq quit-flag nil)))
841 ;; Translate TAB key into control-I ASCII character, and so on.
842 (and char
843 (let ((translated (lookup-key function-key-map (vector char))))
844 (if (arrayp translated)
845 (setq char (aref translated 0)))))
846 (cond ((null char))
847 ((not (integerp char))
848 (setq unread-command-events (list char)
849 done t))
850 ((/= (logand char ?\M-\^@) 0)
851 ;; Turn a meta-character into a character with the 0200 bit set.
852 (setq code (logior (logand char (lognot ?\M-\^@)) 128)
853 done t))
854 ((and (<= ?0 char) (< char (+ ?0 (min 10 read-quoted-char-radix))))
855 (setq code (+ (* code read-quoted-char-radix) (- char ?0)))
856 (and prompt (setq prompt (message "%s %c" prompt char))))
857 ((and (<= ?a (downcase char))
858 (< (downcase char) (+ ?a -10 (min 26 read-quoted-char-radix))))
859 (setq code (+ (* code read-quoted-char-radix)
860 (+ 10 (- (downcase char) ?a))))
861 (and prompt (setq prompt (message "%s %c" prompt char))))
862 ((and (not first) (eq char ?\C-m))
863 (setq done t))
864 ((not first)
865 (setq unread-command-events (list char)
866 done t))
867 (t (setq code char
868 done t)))
869 (setq first nil))
870 code))
872 (defun read-passwd (prompt &optional confirm default)
873 "Read a password, prompting with PROMPT. Echo `.' for each character typed.
874 End with RET, LFD, or ESC. DEL or C-h rubs out. C-u kills line.
875 Optional argument CONFIRM, if non-nil, then read it twice to make sure.
876 Optional DEFAULT is a default password to use instead of empty input."
877 (if confirm
878 (let (success)
879 (while (not success)
880 (let ((first (read-passwd prompt nil default))
881 (second (read-passwd "Confirm password: " nil default)))
882 (if (equal first second)
883 (setq success first)
884 (message "Password not repeated accurately; please start over")
885 (sit-for 1))))
886 success)
887 (let ((pass nil)
888 (c 0)
889 (echo-keystrokes 0)
890 (cursor-in-echo-area t))
891 (while (progn (message "%s%s"
892 prompt
893 (make-string (length pass) ?.))
894 (setq c (read-char-exclusive nil t))
895 (and (/= c ?\r) (/= c ?\n) (/= c ?\e)))
896 (if (= c ?\C-u)
897 (setq pass "")
898 (if (and (/= c ?\b) (/= c ?\177))
899 (setq pass (concat pass (char-to-string c)))
900 (if (> (length pass) 0)
901 (setq pass (substring pass 0 -1))))))
902 (clear-this-command-keys)
903 (message nil)
904 (or pass default ""))))
906 (defun force-mode-line-update (&optional all)
907 "Force the mode-line of the current buffer to be redisplayed.
908 With optional non-nil ALL, force redisplay of all mode-lines."
909 (if all (save-excursion (set-buffer (other-buffer))))
910 (set-buffer-modified-p (buffer-modified-p)))
912 (defun momentary-string-display (string pos &optional exit-char message)
913 "Momentarily display STRING in the buffer at POS.
914 Display remains until next character is typed.
915 If the char is EXIT-CHAR (optional third arg, default is SPC) it is swallowed;
916 otherwise it is then available as input (as a command if nothing else).
917 Display MESSAGE (optional fourth arg) in the echo area.
918 If MESSAGE is nil, instructions to type EXIT-CHAR are displayed there."
919 (or exit-char (setq exit-char ?\ ))
920 (let ((inhibit-read-only t)
921 ;; Don't modify the undo list at all.
922 (buffer-undo-list t)
923 (modified (buffer-modified-p))
924 (name buffer-file-name)
925 insert-end)
926 (unwind-protect
927 (progn
928 (save-excursion
929 (goto-char pos)
930 ;; defeat file locking... don't try this at home, kids!
931 (setq buffer-file-name nil)
932 (insert-before-markers string)
933 (setq insert-end (point))
934 ;; If the message end is off screen, recenter now.
935 (if (< (window-end nil t) insert-end)
936 (recenter (/ (window-height) 2)))
937 ;; If that pushed message start off the screen,
938 ;; scroll to start it at the top of the screen.
939 (move-to-window-line 0)
940 (if (> (point) pos)
941 (progn
942 (goto-char pos)
943 (recenter 0))))
944 (message (or message "Type %s to continue editing.")
945 (single-key-description exit-char))
946 (let ((char (read-event)))
947 (or (eq char exit-char)
948 (setq unread-command-events (list char)))))
949 (if insert-end
950 (save-excursion
951 (delete-region pos insert-end)))
952 (setq buffer-file-name name)
953 (set-buffer-modified-p modified))))
956 ;;;; Miscellanea.
958 ;; A number of major modes set this locally.
959 ;; Give it a global value to avoid compiler warnings.
960 (defvar font-lock-defaults nil)
962 (defvar suspend-hook nil
963 "Normal hook run by `suspend-emacs', before suspending.")
965 (defvar suspend-resume-hook nil
966 "Normal hook run by `suspend-emacs', after Emacs is continued.")
968 ;; Avoid compiler warnings about this variable,
969 ;; which has a special meaning on certain system types.
970 (defvar buffer-file-type nil
971 "Non-nil if the visited file is a binary file.
972 This variable is meaningful on MS-DOG and Windows NT.
973 On those systems, it is automatically local in every buffer.
974 On other systems, this variable is normally always nil.")
976 ;; This should probably be written in C (i.e., without using `walk-windows').
977 (defun get-buffer-window-list (buffer &optional minibuf frame)
978 "Return windows currently displaying BUFFER, or nil if none.
979 See `walk-windows' for the meaning of MINIBUF and FRAME."
980 (let ((buffer (if (bufferp buffer) buffer (get-buffer buffer))) windows)
981 (walk-windows (function (lambda (window)
982 (if (eq (window-buffer window) buffer)
983 (setq windows (cons window windows)))))
984 minibuf frame)
985 windows))
987 (defun ignore (&rest ignore)
988 "Do nothing and return nil.
989 This function accepts any number of arguments, but ignores them."
990 (interactive)
991 nil)
993 (defun error (&rest args)
994 "Signal an error, making error message by passing all args to `format'.
995 In Emacs, the convention is that error messages start with a capital
996 letter but *do not* end with a period. Please follow this convention
997 for the sake of consistency."
998 (while t
999 (signal 'error (list (apply 'format args)))))
1001 (defalias 'user-original-login-name 'user-login-name)
1003 (defun start-process-shell-command (name buffer &rest args)
1004 "Start a program in a subprocess. Return the process object for it.
1005 Args are NAME BUFFER COMMAND &rest COMMAND-ARGS.
1006 NAME is name for process. It is modified if necessary to make it unique.
1007 BUFFER is the buffer or (buffer-name) to associate with the process.
1008 Process output goes at end of that buffer, unless you specify
1009 an output stream or filter function to handle the output.
1010 BUFFER may be also nil, meaning that this process is not associated
1011 with any buffer
1012 Third arg is command name, the name of a shell command.
1013 Remaining arguments are the arguments for the command.
1014 Wildcards and redirection are handled as usual in the shell."
1015 (cond
1016 ((eq system-type 'vax-vms)
1017 (apply 'start-process name buffer args))
1018 ;; We used to use `exec' to replace the shell with the command,
1019 ;; but that failed to handle (...) and semicolon, etc.
1021 (start-process name buffer shell-file-name shell-command-switch
1022 (mapconcat 'identity args " ")))))
1024 (defmacro with-current-buffer (buffer &rest body)
1025 "Execute the forms in BODY with BUFFER as the current buffer.
1026 The value returned is the value of the last form in BODY.
1027 See also `with-temp-buffer'."
1028 (cons 'save-current-buffer
1029 (cons (list 'set-buffer buffer)
1030 body)))
1032 (defmacro with-temp-file (file &rest body)
1033 "Create a new buffer, evaluate BODY there, and write the buffer to FILE.
1034 The value returned is the value of the last form in BODY.
1035 See also `with-temp-buffer'."
1036 (let ((temp-file (make-symbol "temp-file"))
1037 (temp-buffer (make-symbol "temp-buffer")))
1038 `(let ((,temp-file ,file)
1039 (,temp-buffer
1040 (get-buffer-create (generate-new-buffer-name " *temp file*"))))
1041 (unwind-protect
1042 (prog1
1043 (with-current-buffer ,temp-buffer
1044 ,@body)
1045 (with-current-buffer ,temp-buffer
1046 (widen)
1047 (write-region (point-min) (point-max) ,temp-file nil 0)))
1048 (and (buffer-name ,temp-buffer)
1049 (kill-buffer ,temp-buffer))))))
1051 (defmacro with-temp-message (message &rest body)
1052 "Display MESSAGE temporarily if non-nil while BODY is evaluated.
1053 The original message is restored to the echo area after BODY has finished.
1054 The value returned is the value of the last form in BODY.
1055 MESSAGE is written to the message log buffer if `message-log-max' is non-nil.
1056 If MESSAGE is nil, the echo area and message log buffer are unchanged.
1057 Use a MESSAGE of \"\" to temporarily clear the echo area."
1058 (let ((current-message (make-symbol "current-message"))
1059 (temp-message (make-symbol "with-temp-message")))
1060 `(let ((,temp-message ,message)
1061 (,current-message))
1062 (unwind-protect
1063 (progn
1064 (when ,temp-message
1065 (setq ,current-message (current-message))
1066 (message "%s" ,temp-message))
1067 ,@body)
1068 (and ,temp-message ,current-message
1069 (message "%s" ,current-message))))))
1071 (defmacro with-temp-buffer (&rest body)
1072 "Create a temporary buffer, and evaluate BODY there like `progn'.
1073 See also `with-temp-file' and `with-output-to-string'."
1074 (let ((temp-buffer (make-symbol "temp-buffer")))
1075 `(let ((,temp-buffer
1076 (get-buffer-create (generate-new-buffer-name " *temp*"))))
1077 (unwind-protect
1078 (with-current-buffer ,temp-buffer
1079 ,@body)
1080 (and (buffer-name ,temp-buffer)
1081 (kill-buffer ,temp-buffer))))))
1083 (defmacro with-output-to-string (&rest body)
1084 "Execute BODY, return the text it sent to `standard-output', as a string."
1085 `(let ((standard-output
1086 (get-buffer-create (generate-new-buffer-name " *string-output*"))))
1087 (let ((standard-output standard-output))
1088 ,@body)
1089 (with-current-buffer standard-output
1090 (prog1
1091 (buffer-string)
1092 (kill-buffer nil)))))
1094 (defmacro combine-after-change-calls (&rest body)
1095 "Execute BODY, but don't call the after-change functions till the end.
1096 If BODY makes changes in the buffer, they are recorded
1097 and the functions on `after-change-functions' are called several times
1098 when BODY is finished.
1099 The return value is the value of the last form in BODY.
1101 If `before-change-functions' is non-nil, then calls to the after-change
1102 functions can't be deferred, so in that case this macro has no effect.
1104 Do not alter `after-change-functions' or `before-change-functions'
1105 in BODY."
1106 `(unwind-protect
1107 (let ((combine-after-change-calls t))
1108 . ,body)
1109 (combine-after-change-execute)))
1112 (defvar combine-run-hooks t
1113 "List of hooks delayed. Or t if we're not delaying hooks.")
1115 (defmacro combine-run-hooks (&rest body)
1116 "Execute BODY, but delay any `run-hooks' until the end."
1117 (let ((saved-combine-run-hooks (make-symbol "saved-combine-run-hooks"))
1118 (saved-run-hooks (make-symbol "saved-run-hooks")))
1119 `(let ((,saved-combine-run-hooks combine-run-hooks)
1120 (,saved-run-hooks (symbol-function 'run-hooks)))
1121 (unwind-protect
1122 (progn
1123 ;; If we're not delaying hooks yet, setup the delaying mode
1124 (unless (listp combine-run-hooks)
1125 (setq combine-run-hooks nil)
1126 (fset 'run-hooks
1127 ,(lambda (&rest hooks)
1128 (setq combine-run-hooks
1129 (append combine-run-hooks hooks)))))
1130 ,@body)
1131 ;; If we were not already delaying, then it's now time to set things
1132 ;; back to normal and to execute the delayed hooks.
1133 (unless (listp ,saved-combine-run-hooks)
1134 (setq ,saved-combine-run-hooks combine-run-hooks)
1135 (fset 'run-hooks ,saved-run-hooks)
1136 (setq combine-run-hooks t)
1137 (apply 'run-hooks ,saved-combine-run-hooks))))))
1140 (defmacro with-syntax-table (table &rest body)
1141 "Evaluate BODY with syntax table of current buffer set to a copy of TABLE.
1142 The syntax table of the current buffer is saved, BODY is evaluated, and the
1143 saved table is restored, even in case of an abnormal exit.
1144 Value is what BODY returns."
1145 (let ((old-table (make-symbol "table"))
1146 (old-buffer (make-symbol "buffer")))
1147 `(let ((,old-table (syntax-table))
1148 (,old-buffer (current-buffer)))
1149 (unwind-protect
1150 (progn
1151 (set-syntax-table (copy-syntax-table ,table))
1152 ,@body)
1153 (save-current-buffer
1154 (set-buffer ,old-buffer)
1155 (set-syntax-table ,old-table))))))
1157 (defvar save-match-data-internal)
1159 ;; We use save-match-data-internal as the local variable because
1160 ;; that works ok in practice (people should not use that variable elsewhere).
1161 ;; We used to use an uninterned symbol; the compiler handles that properly
1162 ;; now, but it generates slower code.
1163 (defmacro save-match-data (&rest body)
1164 "Execute the BODY forms, restoring the global value of the match data."
1165 ;; It is better not to use backquote here,
1166 ;; because that makes a bootstrapping problem
1167 ;; if you need to recompile all the Lisp files using interpreted code.
1168 (list 'let
1169 '((save-match-data-internal (match-data)))
1170 (list 'unwind-protect
1171 (cons 'progn body)
1172 '(set-match-data save-match-data-internal))))
1174 (defun match-string (num &optional string)
1175 "Return string of text matched by last search.
1176 NUM specifies which parenthesized expression in the last regexp.
1177 Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
1178 Zero means the entire text matched by the whole regexp or whole string.
1179 STRING should be given if the last search was by `string-match' on STRING."
1180 (if (match-beginning num)
1181 (if string
1182 (substring string (match-beginning num) (match-end num))
1183 (buffer-substring (match-beginning num) (match-end num)))))
1185 (defun match-string-no-properties (num &optional string)
1186 "Return string of text matched by last search, without text properties.
1187 NUM specifies which parenthesized expression in the last regexp.
1188 Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
1189 Zero means the entire text matched by the whole regexp or whole string.
1190 STRING should be given if the last search was by `string-match' on STRING."
1191 (if (match-beginning num)
1192 (if string
1193 (let ((result
1194 (substring string (match-beginning num) (match-end num))))
1195 (set-text-properties 0 (length result) nil result)
1196 result)
1197 (buffer-substring-no-properties (match-beginning num)
1198 (match-end num)))))
1200 (defun split-string (string &optional separators)
1201 "Splits STRING into substrings where there are matches for SEPARATORS.
1202 Each match for SEPARATORS is a splitting point.
1203 The substrings between the splitting points are made into a list
1204 which is returned.
1205 If SEPARATORS is absent, it defaults to \"[ \\f\\t\\n\\r\\v]+\".
1207 If there is match for SEPARATORS at the beginning of STRING, we do not
1208 include a null substring for that. Likewise, if there is a match
1209 at the end of STRING, we don't include a null substring for that.
1211 Modifies the match data; use `save-match-data' if necessary."
1212 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
1213 (start 0)
1214 notfirst
1215 (list nil))
1216 (while (and (string-match rexp string
1217 (if (and notfirst
1218 (= start (match-beginning 0))
1219 (< start (length string)))
1220 (1+ start) start))
1221 (< (match-beginning 0) (length string)))
1222 (setq notfirst t)
1223 (or (eq (match-beginning 0) 0)
1224 (and (eq (match-beginning 0) (match-end 0))
1225 (eq (match-beginning 0) start))
1226 (setq list
1227 (cons (substring string start (match-beginning 0))
1228 list)))
1229 (setq start (match-end 0)))
1230 (or (eq start (length string))
1231 (setq list
1232 (cons (substring string start)
1233 list)))
1234 (nreverse list)))
1236 (defun subst-char-in-string (fromchar tochar string &optional inplace)
1237 "Replace FROMCHAR with TOCHAR in STRING each time it occurs.
1238 Unless optional argument INPLACE is non-nil, return a new string."
1239 (let ((i (length string))
1240 (newstr (if inplace string (copy-sequence string))))
1241 (while (> i 0)
1242 (setq i (1- i))
1243 (if (eq (aref newstr i) fromchar)
1244 (aset newstr i tochar)))
1245 newstr))
1247 (defun replace-regexp-in-string (regexp rep string &optional
1248 fixedcase literal subexp start)
1249 "Replace all matches for REGEXP with REP in STRING.
1251 Return a new string containing the replacements.
1253 Optional arguments FIXEDCASE, LITERAL and SUBEXP are like the
1254 arguments with the same names of function `replace-match'. If START
1255 is non-nil, start replacements at that index in STRING.
1257 REP is either a string used as the NEWTEXT arg of `replace-match' or a
1258 function. If it is a function it is applied to each match to generate
1259 the replacement passed to `replace-match'; the match-data at this
1260 point are such that match 0 is the function's argument.
1262 To replace only the first match (if any), make REGEXP match up to \\'
1263 and replace a sub-expression, e.g.
1264 (replace-regexp-in-string \"\\(foo\\).*\\'\" \"bar\" \" foo foo\" nil nil 1)
1265 => \" bar foo\"
1268 ;; To avoid excessive consing from multiple matches in long strings,
1269 ;; don't just call `replace-match' continually. Walk down the
1270 ;; string looking for matches of REGEXP and building up a (reversed)
1271 ;; list MATCHES. This comprises segments of STRING which weren't
1272 ;; matched interspersed with replacements for segments that were.
1273 ;; [For a `large' number of replacments it's more efficient to
1274 ;; operate in a temporary buffer; we can't tell from the function's
1275 ;; args whether to choose the buffer-based implementation, though it
1276 ;; might be reasonable to do so for long enough STRING.]
1277 (let ((l (length string))
1278 (start (or start 0))
1279 matches str mb me)
1280 (save-match-data
1281 (while (and (< start l) (string-match regexp string start))
1282 (setq mb (match-beginning 0)
1283 me (match-end 0))
1284 ;; If we matched the empty string, make sure we advance by one char
1285 (when (= me mb) (setq me (min l (1+ mb))))
1286 ;; Generate a replacement for the matched substring.
1287 ;; Operate only on the substring to minimize string consing.
1288 ;; Set up match data for the substring for replacement;
1289 ;; presumably this is likely to be faster than munging the
1290 ;; match data directly in Lisp.
1291 (string-match regexp (setq str (substring string mb me)))
1292 (setq matches
1293 (cons (replace-match (if (stringp rep)
1295 (funcall rep (match-string 0 str)))
1296 fixedcase literal str subexp)
1297 (cons (substring string start mb) ; unmatched prefix
1298 matches)))
1299 (setq start me))
1300 ;; Reconstruct a string from the pieces.
1301 (setq matches (cons (substring string start l) matches)) ; leftover
1302 (apply #'concat (nreverse matches)))))
1304 (defun shell-quote-argument (argument)
1305 "Quote an argument for passing as argument to an inferior shell."
1306 (if (eq system-type 'ms-dos)
1307 ;; Quote using double quotes, but escape any existing quotes in
1308 ;; the argument with backslashes.
1309 (let ((result "")
1310 (start 0)
1311 end)
1312 (if (or (null (string-match "[^\"]" argument))
1313 (< (match-end 0) (length argument)))
1314 (while (string-match "[\"]" argument start)
1315 (setq end (match-beginning 0)
1316 result (concat result (substring argument start end)
1317 "\\" (substring argument end (1+ end)))
1318 start (1+ end))))
1319 (concat "\"" result (substring argument start) "\""))
1320 (if (eq system-type 'windows-nt)
1321 (concat "\"" argument "\"")
1322 (if (equal argument "")
1323 "''"
1324 ;; Quote everything except POSIX filename characters.
1325 ;; This should be safe enough even for really weird shells.
1326 (let ((result "") (start 0) end)
1327 (while (string-match "[^-0-9a-zA-Z_./]" argument start)
1328 (setq end (match-beginning 0)
1329 result (concat result (substring argument start end)
1330 "\\" (substring argument end (1+ end)))
1331 start (1+ end)))
1332 (concat result (substring argument start)))))))
1334 (defun make-syntax-table (&optional oldtable)
1335 "Return a new syntax table.
1336 If OLDTABLE is non-nil, copy OLDTABLE.
1337 Otherwise, create a syntax table which inherits
1338 all letters and control characters from the standard syntax table;
1339 other characters are copied from the standard syntax table."
1340 (if oldtable
1341 (copy-syntax-table oldtable)
1342 (let ((table (copy-syntax-table))
1344 (setq i 0)
1345 (while (<= i 31)
1346 (aset table i nil)
1347 (setq i (1+ i)))
1348 (setq i ?A)
1349 (while (<= i ?Z)
1350 (aset table i nil)
1351 (setq i (1+ i)))
1352 (setq i ?a)
1353 (while (<= i ?z)
1354 (aset table i nil)
1355 (setq i (1+ i)))
1356 (setq i 128)
1357 (while (<= i 255)
1358 (aset table i nil)
1359 (setq i (1+ i)))
1360 table)))
1362 (defun add-to-invisibility-spec (arg)
1363 "Add elements to `buffer-invisibility-spec'.
1364 See documentation for `buffer-invisibility-spec' for the kind of elements
1365 that can be added."
1366 (cond
1367 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
1368 (setq buffer-invisibility-spec (list arg)))
1370 (setq buffer-invisibility-spec
1371 (cons arg buffer-invisibility-spec)))))
1373 (defun remove-from-invisibility-spec (arg)
1374 "Remove elements from `buffer-invisibility-spec'."
1375 (if (consp buffer-invisibility-spec)
1376 (setq buffer-invisibility-spec (delete arg buffer-invisibility-spec))))
1378 (defun global-set-key (key command)
1379 "Give KEY a global binding as COMMAND.
1380 COMMAND is the command definition to use; usually it is
1381 a symbol naming an interactively-callable function.
1382 KEY is a key sequence; noninteractively, it is a string or vector
1383 of characters or event types, and non-ASCII characters with codes
1384 above 127 (such as ISO Latin-1) can be included if you use a vector.
1386 Note that if KEY has a local binding in the current buffer,
1387 that local binding will continue to shadow any global binding
1388 that you make with this function."
1389 (interactive "KSet key globally: \nCSet key %s to command: ")
1390 (or (vectorp key) (stringp key)
1391 (signal 'wrong-type-argument (list 'arrayp key)))
1392 (define-key (current-global-map) key command))
1394 (defun local-set-key (key command)
1395 "Give KEY a local binding as COMMAND.
1396 COMMAND is the command definition to use; usually it is
1397 a symbol naming an interactively-callable function.
1398 KEY is a key sequence; noninteractively, it is a string or vector
1399 of characters or event types, and non-ASCII characters with codes
1400 above 127 (such as ISO Latin-1) can be included if you use a vector.
1402 The binding goes in the current buffer's local map,
1403 which in most cases is shared with all other buffers in the same major mode."
1404 (interactive "KSet key locally: \nCSet key %s locally to command: ")
1405 (let ((map (current-local-map)))
1406 (or map
1407 (use-local-map (setq map (make-sparse-keymap))))
1408 (or (vectorp key) (stringp key)
1409 (signal 'wrong-type-argument (list 'arrayp key)))
1410 (define-key map key command)))
1412 (defun global-unset-key (key)
1413 "Remove global binding of KEY.
1414 KEY is a string representing a sequence of keystrokes."
1415 (interactive "kUnset key globally: ")
1416 (global-set-key key nil))
1418 (defun local-unset-key (key)
1419 "Remove local binding of KEY.
1420 KEY is a string representing a sequence of keystrokes."
1421 (interactive "kUnset key locally: ")
1422 (if (current-local-map)
1423 (local-set-key key nil))
1424 nil)
1426 ;; We put this here instead of in frame.el so that it's defined even on
1427 ;; systems where frame.el isn't loaded.
1428 (defun frame-configuration-p (object)
1429 "Return non-nil if OBJECT seems to be a frame configuration.
1430 Any list whose car is `frame-configuration' is assumed to be a frame
1431 configuration."
1432 (and (consp object)
1433 (eq (car object) 'frame-configuration)))
1435 (defun functionp (object)
1436 "Non-nil if OBJECT is a type of object that can be called as a function."
1437 (or (subrp object) (byte-code-function-p object)
1438 (eq (car-safe object) 'lambda)
1439 (and (symbolp object) (fboundp object))))
1441 ;; now in fns.c
1442 ;(defun nth (n list)
1443 ; "Returns the Nth element of LIST.
1444 ;N counts from zero. If LIST is not that long, nil is returned."
1445 ; (car (nthcdr n list)))
1447 ;(defun copy-alist (alist)
1448 ; "Return a copy of ALIST.
1449 ;This is a new alist which represents the same mapping
1450 ;from objects to objects, but does not share the alist structure with ALIST.
1451 ;The objects mapped (cars and cdrs of elements of the alist)
1452 ;are shared, however."
1453 ; (setq alist (copy-sequence alist))
1454 ; (let ((tail alist))
1455 ; (while tail
1456 ; (if (consp (car tail))
1457 ; (setcar tail (cons (car (car tail)) (cdr (car tail)))))
1458 ; (setq tail (cdr tail))))
1459 ; alist)
1461 (defun assq-delete-all (key alist)
1462 "Delete from ALIST all elements whose car is KEY.
1463 Return the modified alist."
1464 (let ((tail alist))
1465 (while tail
1466 (if (eq (car (car tail)) key)
1467 (setq alist (delq (car tail) alist)))
1468 (setq tail (cdr tail)))
1469 alist))
1471 (defun make-temp-file (prefix &optional dir-flag)
1472 "Create a temporary file.
1473 The returned file name (created by appending some random characters at the end
1474 of PREFIX, and expanding against `temporary-file-directory' if necessary,
1475 is guaranteed to point to a newly created empty file.
1476 You can then use `write-region' to write new data into the file.
1478 If DIR-FLAG is non-nil, create a new empty directory instead of a file."
1479 (let (file)
1480 (while (condition-case ()
1481 (progn
1482 (setq file
1483 (make-temp-name
1484 (expand-file-name prefix temporary-file-directory)))
1485 (if dir-flag
1486 (make-directory file)
1487 (write-region "" nil file nil 'silent nil 'excl))
1488 nil)
1489 (file-already-exists t))
1490 ;; the file was somehow created by someone else between
1491 ;; `make-temp-name' and `write-region', let's try again.
1492 nil)
1493 file))
1496 (defun add-minor-mode (toggle name &optional keymap after toggle-fun)
1497 "Register a new minor mode.
1499 TOGGLE is a symbol which is the name of a buffer-local variable that
1500 is toggled on or off to say whether the minor mode is active or not.
1502 NAME specifies what will appear in the mode line when the minor mode
1503 is active. NAME should be either a string starting with a space, or a
1504 symbol whose value is such a string.
1506 Optional KEYMAP is the keymap for the minor mode that will be added
1507 to `minor-mode-map-alist'.
1509 Optional AFTER specifies that TOGGLE should be added after AFTER
1510 in `minor-mode-alist'.
1512 Optional TOGGLE-FUN is there for compatiblity with other Emacsen.
1513 It is currently not used.
1515 In most cases, `define-minor-mode' should be used instead."
1516 (when name
1517 (let ((existing (assq toggle minor-mode-alist))
1518 (name (if (symbolp name) (symbol-value name) name)))
1519 (cond ((null existing)
1520 (let ((tail minor-mode-alist) found)
1521 (while (and tail (not found))
1522 (if (eq after (caar tail))
1523 (setq found tail)
1524 (setq tail (cdr tail))))
1525 (if found
1526 (let ((rest (cdr found)))
1527 (setcdr found nil)
1528 (nconc found (list (list toggle name)) rest))
1529 (setq minor-mode-alist (cons (list toggle name)
1530 minor-mode-alist)))))
1532 (setcdr existing (list name))))))
1534 (when keymap
1535 (let ((existing (assq toggle minor-mode-map-alist)))
1536 (cond ((null existing)
1537 (let ((tail minor-mode-map-alist) found)
1538 (while (and tail (not found))
1539 (if (eq after (caar tail))
1540 (setq found tail)
1541 (setq tail (cdr tail))))
1542 (if found
1543 (let ((rest (cdr found)))
1544 (setcdr found nil)
1545 (nconc found (list (cons toggle keymap)) rest))
1546 (setq minor-mode-map-alist (cons (cons toggle keymap)
1547 minor-mode-map-alist)))))
1549 (setcdr existing keymap))))))
1552 ;;; subr.el ends here