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