Contents in 1999-06-04-13 of release-21-2.
[chise/xemacs-chise.git.1] / lisp / cl-extra.el
1 ;;; cl-extra.el --- Common Lisp extensions for GNU Emacs Lisp (part two)
2
3 ;; Copyright (C) 1993 Free Software Foundation, Inc.
4
5 ;; Author: Dave Gillespie <daveg@synaptics.com>
6 ;; Maintainer: XEmacs Development Team
7 ;; Version: 2.02
8 ;; Keywords: extensions, dumped
9
10 ;; This file is part of XEmacs.
11
12 ;; XEmacs is free software; you can redistribute it and/or modify it
13 ;; under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; any later version.
16
17 ;; XEmacs is distributed in the hope that it will be useful, but
18 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20 ;; General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with XEmacs; see the file COPYING.  If not, write to the Free
24 ;; Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
25 ;; 02111-1307, USA.
26
27 ;;; Synched up with: FSF 19.34.
28
29 ;;; Commentary:
30
31 ;; This file is dumped with XEmacs.
32
33 ;; These are extensions to Emacs Lisp that provide a degree of
34 ;; Common Lisp compatibility, beyond what is already built-in
35 ;; in Emacs Lisp.
36 ;;
37 ;; This package was written by Dave Gillespie; it is a complete
38 ;; rewrite of Cesar Quiroz's original cl.el package of December 1986.
39 ;;
40 ;; This package works with Emacs 18, Emacs 19, and XEmacs/Lucid Emacs 19.
41 ;;
42 ;; Bug reports, comments, and suggestions are welcome!
43
44 ;; This file contains portions of the Common Lisp extensions
45 ;; package which are autoloaded since they are relatively obscure.
46
47 ;; See cl.el for Change Log.
48
49
50 ;;; Code:
51 (eval-when-compile
52   (require 'obsolete))
53
54 (or (memq 'cl-19 features)
55     (error "Tried to load `cl-extra' before `cl'!"))
56
57
58 ;;; We define these here so that this file can compile without having
59 ;;; loaded the cl.el file already.
60
61 (defmacro cl-push (x place) (list 'setq place (list 'cons x place)))
62 (defmacro cl-pop (place)
63   (list 'car (list 'prog1 place (list 'setq place (list 'cdr place)))))
64
65 (defvar cl-emacs-type)
66
67
68 ;;; Type coercion.
69
70 (defun coerce (x type)
71   "Coerce OBJECT to type TYPE.
72 TYPE is a Common Lisp type specifier."
73   (cond ((eq type 'list) (if (listp x) x (append x nil)))
74         ((eq type 'vector) (if (vectorp x) x (vconcat x)))
75         ((eq type 'string) (if (stringp x) x (concat x)))
76         ((eq type 'array) (if (arrayp x) x (vconcat x)))
77         ((and (eq type 'character) (stringp x) (= (length x) 1)) (aref x 0))
78         ((and (eq type 'character) (symbolp x)) (coerce (symbol-name x) type))
79         ((and (eq type 'character) (numberp x) (char-or-char-int-p x)
80               (int-char x)))
81         ((eq type 'float) (float x))
82         ((eq type 'bit-vector) (if (bit-vector-p x) x
83                                  (apply 'bit-vector (append x nil))))
84         ((eq type 'weak-list)
85          (if (weak-list-p x) x
86            (let ((wl (make-weak-list)))
87              (set-weak-list-list wl (if (listp x) x (append x nil)))
88              wl)))
89         ((typep x type) x)
90         (t (error "Can't coerce %s to type %s" x type))))
91
92
93 ;;; Predicates.
94
95 (defun equalp (x y)
96   "Return t if two Lisp objects have similar structures and contents.
97 This is like `equal', except that it accepts numerically equal
98 numbers of different types (float vs. integer), and also compares
99 strings case-insensitively."
100   (cond ((eq x y) t)
101         ((stringp x)
102          (and (stringp y) (= (length x) (length y))
103               (or (string-equal x y)
104                   (string-equal (downcase x) (downcase y)))))   ; lazy but simple!
105         ((characterp x)
106          (and (characterp y)
107               (or (char-equal x y)
108                   (char-equal (downcase x) (downcase y)))))
109         ((numberp x)
110          (and (numberp y) (= x y)))
111         ((consp x)
112          ;; XEmacs change
113          (while (and (consp x) (consp y) (equalp (car x) (car y)))
114            (cl-pop x) (cl-pop y))
115          (and (not (consp x)) (equalp x y)))
116         ((vectorp x)
117          (and (vectorp y) (= (length x) (length y))
118               (let ((i (length x)))
119                 (while (and (>= (setq i (1- i)) 0)
120                             (equalp (aref x i) (aref y i))))
121                 (< i 0))))
122         (t (equal x y))))
123
124
125 ;;; Control structures.
126
127 (defun cl-mapcar-many (cl-func cl-seqs)
128   (if (cdr (cdr cl-seqs))
129       (let* ((cl-res nil)
130              (cl-n (apply 'min (mapcar 'length cl-seqs)))
131              (cl-i 0)
132              (cl-args (copy-sequence cl-seqs))
133              cl-p1 cl-p2)
134         (setq cl-seqs (copy-sequence cl-seqs))
135         (while (< cl-i cl-n)
136           (setq cl-p1 cl-seqs cl-p2 cl-args)
137           (while cl-p1
138             (setcar cl-p2
139                     (if (consp (car cl-p1))
140                         (prog1 (car (car cl-p1))
141                           (setcar cl-p1 (cdr (car cl-p1))))
142                       (aref (car cl-p1) cl-i)))
143             (setq cl-p1 (cdr cl-p1) cl-p2 (cdr cl-p2)))
144           (cl-push (apply cl-func cl-args) cl-res)
145           (setq cl-i (1+ cl-i)))
146         (nreverse cl-res))
147     (let ((cl-res nil)
148           (cl-x (car cl-seqs))
149           (cl-y (nth 1 cl-seqs)))
150       (let ((cl-n (min (length cl-x) (length cl-y)))
151             (cl-i -1))
152         (while (< (setq cl-i (1+ cl-i)) cl-n)
153           (cl-push (funcall cl-func
154                             (if (consp cl-x) (cl-pop cl-x) (aref cl-x cl-i))
155                             (if (consp cl-y) (cl-pop cl-y) (aref cl-y cl-i)))
156                    cl-res)))
157       (nreverse cl-res))))
158
159 (defun map (cl-type cl-func cl-seq &rest cl-rest)
160   "Map a function across one or more sequences, returning a sequence.
161 TYPE is the sequence type to return, FUNC is the function, and SEQS
162 are the argument sequences."
163   (let ((cl-res (apply 'mapcar* cl-func cl-seq cl-rest)))
164     (and cl-type (coerce cl-res cl-type))))
165
166 (defun maplist (cl-func cl-list &rest cl-rest)
167   "Map FUNC to each sublist of LIST or LISTS.
168 Like `mapcar', except applies to lists and their cdr's rather than to
169 the elements themselves."
170   (if cl-rest
171       (let ((cl-res nil)
172             (cl-args (cons cl-list (copy-sequence cl-rest)))
173             cl-p)
174         (while (not (memq nil cl-args))
175           (cl-push (apply cl-func cl-args) cl-res)
176           (setq cl-p cl-args)
177           (while cl-p (setcar cl-p (cdr (cl-pop cl-p)) )))
178         (nreverse cl-res))
179     (let ((cl-res nil))
180       (while cl-list
181         (cl-push (funcall cl-func cl-list) cl-res)
182         (setq cl-list (cdr cl-list)))
183       (nreverse cl-res))))
184
185
186 ;; mapc is now in C, renamed from `mapc-internal'.
187
188 ;(defun mapc (cl-func cl-seq &rest cl-rest)
189 ;  "Like `mapcar', but does not accumulate values returned by the function."
190 ;  (if cl-rest
191 ;      (apply 'map nil cl-func cl-seq cl-rest)
192 ;    ;; XEmacs change: we call mapc-internal, which really doesn't
193 ;    ;; accumulate any results.
194 ;    (mapc-internal cl-func cl-seq))
195 ;  cl-seq)
196
197 (defun mapl (cl-func cl-list &rest cl-rest)
198   "Like `maplist', but does not accumulate values returned by the function."
199   (if cl-rest
200       (apply 'maplist cl-func cl-list cl-rest)
201     (let ((cl-p cl-list))
202       (while cl-p (funcall cl-func cl-p) (setq cl-p (cdr cl-p)))))
203   cl-list)
204
205 (defun mapcan (cl-func cl-seq &rest cl-rest)
206   "Like `mapcar', but nconc's together the values returned by the function."
207   (apply 'nconc (apply 'mapcar* cl-func cl-seq cl-rest)))
208
209 (defun mapcon (cl-func cl-list &rest cl-rest)
210   "Like `maplist', but nconc's together the values returned by the function."
211   (apply 'nconc (apply 'maplist cl-func cl-list cl-rest)))
212
213 (defun some (cl-pred cl-seq &rest cl-rest)
214   "Return true if PREDICATE is true of any element of SEQ or SEQs.
215 If so, return the true (non-nil) value returned by PREDICATE."
216   (if (or cl-rest (nlistp cl-seq))
217       (catch 'cl-some
218         (apply 'map nil
219                (function (lambda (&rest cl-x)
220                            (let ((cl-res (apply cl-pred cl-x)))
221                              (if cl-res (throw 'cl-some cl-res)))))
222                cl-seq cl-rest) nil)
223     (let ((cl-x nil))
224       (while (and cl-seq (not (setq cl-x (funcall cl-pred (cl-pop cl-seq))))))
225       cl-x)))
226
227 (defun every (cl-pred cl-seq &rest cl-rest)
228   "Return true if PREDICATE is true of every element of SEQ or SEQs."
229   (if (or cl-rest (nlistp cl-seq))
230       (catch 'cl-every
231         (apply 'map nil
232                (function (lambda (&rest cl-x)
233                            (or (apply cl-pred cl-x) (throw 'cl-every nil))))
234                cl-seq cl-rest) t)
235     (while (and cl-seq (funcall cl-pred (car cl-seq)))
236       (setq cl-seq (cdr cl-seq)))
237     (null cl-seq)))
238
239 (defun notany (cl-pred cl-seq &rest cl-rest)
240   "Return true if PREDICATE is false of every element of SEQ or SEQs."
241   (not (apply 'some cl-pred cl-seq cl-rest)))
242
243 (defun notevery (cl-pred cl-seq &rest cl-rest)
244   "Return true if PREDICATE is false of some element of SEQ or SEQs."
245   (not (apply 'every cl-pred cl-seq cl-rest)))
246
247 ;;; Support for `loop'.
248 (defun cl-map-keymap (cl-func cl-map)
249   (while (symbolp cl-map) (setq cl-map (symbol-function cl-map)))
250   (if (eq cl-emacs-type 'lucid) (funcall 'map-keymap cl-func cl-map)
251     (if (listp cl-map)
252         (let ((cl-p cl-map))
253           (while (consp (setq cl-p (cdr cl-p)))
254             (cond ((consp (car cl-p))
255                    (funcall cl-func (car (car cl-p)) (cdr (car cl-p))))
256                   ((vectorp (car cl-p))
257                    (cl-map-keymap cl-func (car cl-p)))
258                   ((eq (car cl-p) 'keymap)
259                    (setq cl-p nil)))))
260       (let ((cl-i -1))
261         (while (< (setq cl-i (1+ cl-i)) (length cl-map))
262           (if (aref cl-map cl-i)
263               (funcall cl-func cl-i (aref cl-map cl-i))))))))
264
265 (defun cl-map-keymap-recursively (cl-func-rec cl-map &optional cl-base)
266   (or cl-base
267       (setq cl-base (copy-sequence (if (eq cl-emacs-type 18) "0" [0]))))
268   (cl-map-keymap
269    (function
270     (lambda (cl-key cl-bind)
271       (aset cl-base (1- (length cl-base)) cl-key)
272       (if (keymapp cl-bind)
273           (cl-map-keymap-recursively
274            cl-func-rec cl-bind
275            (funcall (if (eq cl-emacs-type 18) 'concat 'vconcat)
276                     cl-base (list 0)))
277         (funcall cl-func-rec cl-base cl-bind))))
278    cl-map))
279
280 (defun cl-map-intervals (cl-func &optional cl-what cl-prop cl-start cl-end)
281   (or cl-what (setq cl-what (current-buffer)))
282   (if (bufferp cl-what)
283       (let (cl-mark cl-mark2 (cl-next t) cl-next2)
284         (save-excursion
285           (set-buffer cl-what)
286           (setq cl-mark (copy-marker (or cl-start (point-min))))
287           (setq cl-mark2 (and cl-end (copy-marker cl-end))))
288         (while (and cl-next (or (not cl-mark2) (< cl-mark cl-mark2)))
289           (setq cl-next (and (fboundp 'next-property-change)
290                              (if cl-prop (next-single-property-change
291                                           cl-mark cl-prop cl-what)
292                                (next-property-change cl-mark cl-what)))
293                 cl-next2 (or cl-next (save-excursion
294                                        (set-buffer cl-what) (point-max))))
295           (funcall cl-func (prog1 (marker-position cl-mark)
296                              (set-marker cl-mark cl-next2))
297                    (if cl-mark2 (min cl-next2 cl-mark2) cl-next2)))
298         (set-marker cl-mark nil) (if cl-mark2 (set-marker cl-mark2 nil)))
299     (or cl-start (setq cl-start 0))
300     (or cl-end (setq cl-end (length cl-what)))
301     (while (< cl-start cl-end)
302       (let ((cl-next (or (and (fboundp 'next-property-change)
303                               (if cl-prop (next-single-property-change
304                                            cl-start cl-prop cl-what)
305                                 (next-property-change cl-start cl-what)))
306                          cl-end)))
307         (funcall cl-func cl-start (min cl-next cl-end))
308         (setq cl-start cl-next)))))
309
310 (defun cl-map-overlays (cl-func &optional cl-buffer cl-start cl-end cl-arg)
311   (or cl-buffer (setq cl-buffer (current-buffer)))
312   (if (fboundp 'overlay-lists)
313
314       ;; This is the preferred algorithm, though overlay-lists is undocumented.
315       (let (cl-ovl)
316         (save-excursion
317           (set-buffer cl-buffer)
318           (setq cl-ovl (overlay-lists))
319           (if cl-start (setq cl-start (copy-marker cl-start)))
320           (if cl-end (setq cl-end (copy-marker cl-end))))
321         (setq cl-ovl (nconc (car cl-ovl) (cdr cl-ovl)))
322         (while (and cl-ovl
323                     (or (not (overlay-start (car cl-ovl)))
324                         (and cl-end (>= (overlay-start (car cl-ovl)) cl-end))
325                         (and cl-start (<= (overlay-end (car cl-ovl)) cl-start))
326                         (not (funcall cl-func (car cl-ovl) cl-arg))))
327           (setq cl-ovl (cdr cl-ovl)))
328         (if cl-start (set-marker cl-start nil))
329         (if cl-end (set-marker cl-end nil)))
330
331     ;; This alternate algorithm fails to find zero-length overlays.
332     (let ((cl-mark (save-excursion (set-buffer cl-buffer)
333                                    (copy-marker (or cl-start (point-min)))))
334           (cl-mark2 (and cl-end (save-excursion (set-buffer cl-buffer)
335                                                 (copy-marker cl-end))))
336           cl-pos cl-ovl)
337       (while (save-excursion
338                (and (setq cl-pos (marker-position cl-mark))
339                     (< cl-pos (or cl-mark2 (point-max)))
340                     (progn
341                       (set-buffer cl-buffer)
342                       (setq cl-ovl (overlays-at cl-pos))
343                       (set-marker cl-mark (next-overlay-change cl-pos)))))
344         (while (and cl-ovl
345                     (or (/= (overlay-start (car cl-ovl)) cl-pos)
346                         (not (and (funcall cl-func (car cl-ovl) cl-arg)
347                                   (set-marker cl-mark nil)))))
348           (setq cl-ovl (cdr cl-ovl))))
349       (set-marker cl-mark nil) (if cl-mark2 (set-marker cl-mark2 nil)))))
350
351 ;;; Support for `setf'.
352 (defun cl-set-frame-visible-p (frame val)
353   (cond ((null val) (make-frame-invisible frame))
354         ((eq val 'icon) (iconify-frame frame))
355         (t (make-frame-visible frame)))
356   val)
357
358 ;;; Support for `progv'.
359 (defvar cl-progv-save)
360 (defun cl-progv-before (syms values)
361   (while syms
362     (cl-push (if (boundp (car syms))
363                  (cons (car syms) (symbol-value (car syms)))
364                (car syms)) cl-progv-save)
365     (if values
366         (set (cl-pop syms) (cl-pop values))
367       (makunbound (cl-pop syms)))))
368
369 (defun cl-progv-after ()
370   (while cl-progv-save
371     (if (consp (car cl-progv-save))
372         (set (car (car cl-progv-save)) (cdr (car cl-progv-save)))
373       (makunbound (car cl-progv-save)))
374     (cl-pop cl-progv-save)))
375
376
377 ;;; Numbers.
378
379 (defun gcd (&rest args)
380   "Return the greatest common divisor of the arguments."
381   (let ((a (abs (or (cl-pop args) 0))))
382     (while args
383       (let ((b (abs (cl-pop args))))
384         (while (> b 0) (setq b (% a (setq a b))))))
385     a))
386
387 (defun lcm (&rest args)
388   "Return the least common multiple of the arguments."
389   (if (memq 0 args)
390       0
391     (let ((a (abs (or (cl-pop args) 1))))
392       (while args
393         (let ((b (abs (cl-pop args))))
394           (setq a (* (/ a (gcd a b)) b))))
395       a)))
396
397 (defun isqrt (a)
398   "Return the integer square root of the argument."
399   (if (and (integerp a) (> a 0))
400       ;; XEmacs change
401       (let ((g (cond ((>= a 1000000) 10000) ((>= a 10000) 1000)
402                      ((>= a 100) 100) (t 10)))
403             g2)
404         (while (< (setq g2 (/ (+ g (/ a g)) 2)) g)
405           (setq g g2))
406         g)
407     (if (eq a 0) 0 (signal 'arith-error nil))))
408
409 (defun cl-expt (x y)
410   "Return X raised to the power of Y.  Works only for integer arguments."
411   (if (<= y 0) (if (= y 0) 1 (if (memq x '(-1 1)) (cl-expt x (- y)) 0))
412     (* (if (= (% y 2) 0) 1 x) (cl-expt (* x x) (/ y 2)))))
413 (or (and (fboundp 'expt) (subrp (symbol-function 'expt)))
414     (defalias 'expt 'cl-expt))
415
416 (defun floor* (x &optional y)
417   "Return a list of the floor of X and the fractional part of X.
418 With two arguments, return floor and remainder of their quotient."
419   (let ((q (floor x y)))
420     (list q (- x (if y (* y q) q)))))
421
422 (defun ceiling* (x &optional y)
423   "Return a list of the ceiling of X and the fractional part of X.
424 With two arguments, return ceiling and remainder of their quotient."
425   (let ((res (floor* x y)))
426     (if (= (car (cdr res)) 0) res
427       (list (1+ (car res)) (- (car (cdr res)) (or y 1))))))
428
429 (defun truncate* (x &optional y)
430   "Return a list of the integer part of X and the fractional part of X.
431 With two arguments, return truncation and remainder of their quotient."
432   (if (eq (>= x 0) (or (null y) (>= y 0)))
433       (floor* x y) (ceiling* x y)))
434
435 (defun round* (x &optional y)
436   "Return a list of X rounded to the nearest integer and the remainder.
437 With two arguments, return rounding and remainder of their quotient."
438   (if y
439       (if (and (integerp x) (integerp y))
440           (let* ((hy (/ y 2))
441                  (res (floor* (+ x hy) y)))
442             (if (and (= (car (cdr res)) 0)
443                      (= (+ hy hy) y)
444                      (/= (% (car res) 2) 0))
445                 (list (1- (car res)) hy)
446               (list (car res) (- (car (cdr res)) hy))))
447         (let ((q (round (/ x y))))
448           (list q (- x (* q y)))))
449     (if (integerp x) (list x 0)
450       (let ((q (round x)))
451         (list q (- x q))))))
452
453 (defun mod* (x y)
454   "The remainder of X divided by Y, with the same sign as Y."
455   (nth 1 (floor* x y)))
456
457 (defun rem* (x y)
458   "The remainder of X divided by Y, with the same sign as X."
459   (nth 1 (truncate* x y)))
460
461 (defun signum (a)
462   "Return 1 if A is positive, -1 if negative, 0 if zero."
463   (cond ((> a 0) 1) ((< a 0) -1) (t 0)))
464
465
466 ;; Random numbers.
467
468 (defvar *random-state*)
469 (defun random* (lim &optional state)
470   "Return a random nonnegative number less than LIM, an integer or float.
471 Optional second arg STATE is a random-state object."
472   (or state (setq state *random-state*))
473   ;; Inspired by "ran3" from Numerical Recipes.  Additive congruential method.
474   (let ((vec (aref state 3)))
475     (if (integerp vec)
476         (let ((i 0) (j (- 1357335 (% (abs vec) 1357333))) (k 1))
477           (aset state 3 (setq vec (make-vector 55 nil)))
478           (aset vec 0 j)
479           (while (> (setq i (% (+ i 21) 55)) 0)
480             (aset vec i (setq j (prog1 k (setq k (- j k))))))
481           (while (< (setq i (1+ i)) 200) (random* 2 state))))
482     (let* ((i (aset state 1 (% (1+ (aref state 1)) 55)))
483            (j (aset state 2 (% (1+ (aref state 2)) 55)))
484            (n (logand 8388607 (aset vec i (- (aref vec i) (aref vec j))))))
485       (if (integerp lim)
486           (if (<= lim 512) (% n lim)
487             (if (> lim 8388607) (setq n (+ (lsh n 9) (random* 512 state))))
488             (let ((mask 1023))
489               (while (< mask (1- lim)) (setq mask (1+ (+ mask mask))))
490               (if (< (setq n (logand n mask)) lim) n (random* lim state))))
491         (* (/ n '8388608e0) lim)))))
492
493 (defun make-random-state (&optional state)
494   "Return a copy of random-state STATE, or of `*random-state*' if omitted.
495 If STATE is t, return a new state object seeded from the time of day."
496   (cond ((null state) (make-random-state *random-state*))
497         ((vectorp state) (cl-copy-tree state t))
498         ((integerp state) (vector 'cl-random-state-tag -1 30 state))
499         (t (make-random-state (cl-random-time)))))
500
501 (defun random-state-p (object)
502   "Return t if OBJECT is a random-state object."
503   (and (vectorp object) (= (length object) 4)
504        (eq (aref object 0) 'cl-random-state-tag)))
505
506
507 ;; Implementation limits.
508
509 (defun cl-finite-do (func a b)
510   (condition-case nil
511       (let ((res (funcall func a b)))   ; check for IEEE infinity
512         (and (numberp res) (/= res (/ res 2)) res))
513     (arith-error nil)))
514
515 (defvar most-positive-float)
516 (defvar most-negative-float)
517 (defvar least-positive-float)
518 (defvar least-negative-float)
519 (defvar least-positive-normalized-float)
520 (defvar least-negative-normalized-float)
521 (defvar float-epsilon)
522 (defvar float-negative-epsilon)
523
524 (defun cl-float-limits ()
525   (or most-positive-float (not (numberp '2e1))
526       (let ((x '2e0) y z)
527         ;; Find maximum exponent (first two loops are optimizations)
528         (while (cl-finite-do '* x x) (setq x (* x x)))
529         (while (cl-finite-do '* x (/ x 2)) (setq x (* x (/ x 2))))
530         (while (cl-finite-do '+ x x) (setq x (+ x x)))
531         (setq z x y (/ x 2))
532         ;; Now fill in 1's in the mantissa.
533         (while (and (cl-finite-do '+ x y) (/= (+ x y) x))
534           (setq x (+ x y) y (/ y 2)))
535         (setq most-positive-float x
536               most-negative-float (- x))
537         ;; Divide down until mantissa starts rounding.
538         (setq x (/ x z) y (/ 16 z) x (* x y))
539         (while (condition-case nil (and (= x (* (/ x 2) 2)) (> (/ y 2) 0))
540                  (arith-error nil))
541           (setq x (/ x 2) y (/ y 2)))
542         (setq least-positive-normalized-float y
543               least-negative-normalized-float (- y))
544         ;; Divide down until value underflows to zero.
545         (setq x (/ 1 z) y x)
546         (while (condition-case nil (> (/ x 2) 0) (arith-error nil))
547           (setq x (/ x 2)))
548         (setq least-positive-float x
549               least-negative-float (- x))
550         (setq x '1e0)
551         (while (/= (+ '1e0 x) '1e0) (setq x (/ x 2)))
552         (setq float-epsilon (* x 2))
553         (setq x '1e0)
554         (while (/= (- '1e0 x) '1e0) (setq x (/ x 2)))
555         (setq float-negative-epsilon (* x 2))))
556   nil)
557
558
559 ;;; Sequence functions.
560
561 ;XEmacs -- our built-in is more powerful.
562 ;(defun subseq (seq start &optional end)
563 ;  "Return the subsequence of SEQ from START to END.
564 ;If END is omitted, it defaults to the length of the sequence.
565 ;If START or END is negative, it counts from the end."
566 ;  (if (stringp seq) (substring seq start end)
567 ;    (let (len)
568 ;      (and end (< end 0) (setq end (+ end (setq len (length seq)))))
569 ;      (if (< start 0) (setq start (+ start (or len (setq len (length seq))))))
570 ;      (cond ((listp seq)
571 ;            (if (> start 0) (setq seq (nthcdr start seq)))
572 ;            (if end
573 ;                (let ((res nil))
574 ;                  (while (>= (setq end (1- end)) start)
575 ;                    (cl-push (cl-pop seq) res))
576 ;                  (nreverse res))
577 ;              (copy-sequence seq)))
578 ;           (t
579 ;            (or end (setq end (or len (length seq))))
580 ;            (let ((res (make-vector (max (- end start) 0) nil))
581 ;                  (i 0))
582 ;              (while (< start end)
583 ;                (aset res i (aref seq start))
584 ;                (setq i (1+ i) start (1+ start)))
585 ;              res))))))
586
587 (defun concatenate (type &rest seqs)
588   "Concatenate, into a sequence of type TYPE, the argument SEQUENCES."
589   (case type
590     (vector (apply 'vconcat seqs))
591     (string (apply 'concat seqs))
592     (list   (apply 'append (append seqs '(nil))))
593     (t (error "Not a sequence type name: %s" type))))
594
595 ;;; List functions.
596
597 (defun revappend (x y)
598   "Equivalent to (append (reverse X) Y)."
599   (nconc (reverse x) y))
600
601 (defun nreconc (x y)
602   "Equivalent to (nconc (nreverse X) Y)."
603   (nconc (nreverse x) y))
604
605 (defun list-length (x)
606   "Return the length of a list.  Return nil if list is circular."
607   (let ((n 0) (fast x) (slow x))
608     (while (and (cdr fast) (not (and (eq fast slow) (> n 0))))
609       (setq n (+ n 2) fast (cdr (cdr fast)) slow (cdr slow)))
610     (if fast (if (cdr fast) nil (1+ n)) n)))
611
612 (defun tailp (sublist list)
613   "Return true if SUBLIST is a tail of LIST."
614   (while (and (consp list) (not (eq sublist list)))
615     (setq list (cdr list)))
616   (if (numberp sublist) (equal sublist list) (eq sublist list)))
617
618 (defun cl-copy-tree (tree &optional vecp)
619   "Make a copy of TREE.
620 If TREE is a cons cell, this recursively copies both its car and its cdr.
621 Contrast to copy-sequence, which copies only along the cdrs.  With second
622 argument VECP, this copies vectors as well as conses."
623   (if (consp tree)
624       (let ((p (setq tree (copy-list tree))))
625         (while (consp p)
626           (if (or (consp (car p)) (and vecp (vectorp (car p))))
627               (setcar p (cl-copy-tree (car p) vecp)))
628           (or (listp (cdr p)) (setcdr p (cl-copy-tree (cdr p) vecp)))
629           (cl-pop p)))
630     (if (and vecp (vectorp tree))
631         (let ((i (length (setq tree (copy-sequence tree)))))
632           (while (>= (setq i (1- i)) 0)
633             (aset tree i (cl-copy-tree (aref tree i) vecp))))))
634   tree)
635 (or (and (fboundp 'copy-tree) (subrp (symbol-function 'copy-tree)))
636     (defalias 'copy-tree 'cl-copy-tree))
637
638
639 ;;; Property lists.
640
641 ;; XEmacs: our `get' groks DEFAULT.
642 (defalias 'get* 'get)
643
644 (defun getf (plist tag &optional def)
645   "Search PROPLIST for property PROPNAME; return its value or DEFAULT.
646 PROPLIST is a list of the sort returned by `symbol-plist'."
647   (setplist '--cl-getf-symbol-- plist)
648   (or (get '--cl-getf-symbol-- tag)
649       (and def (get* '--cl-getf-symbol-- tag def))))
650
651 (defun cl-set-getf (plist tag val)
652   (let ((p plist))
653     (while (and p (not (eq (car p) tag))) (setq p (cdr (cdr p))))
654     (if p (progn (setcar (cdr p) val) plist) (list* tag val plist))))
655
656 (defun cl-do-remf (plist tag)
657   (let ((p (cdr plist)))
658     (while (and (cdr p) (not (eq (car (cdr p)) tag))) (setq p (cdr (cdr p))))
659     (and (cdr p) (progn (setcdr p (cdr (cdr (cdr p)))) t))))
660
661 (defun cl-remprop (sym tag)
662   "Remove from SYMBOL's plist the property PROP and its value."
663   (let ((plist (symbol-plist sym)))
664     (if (and plist (eq tag (car plist)))
665         (progn (setplist sym (cdr (cdr plist))) t)
666       (cl-do-remf plist tag))))
667 (or (and (fboundp 'remprop) (subrp (symbol-function 'remprop)))
668     (defalias 'remprop 'cl-remprop))
669
670
671
672 ;;; Hash tables.
673
674 ;; The `regular' Common Lisp hash-table stuff has been moved into C.
675 ;; Only backward compatibility stuff remains here.
676 (defun make-hashtable (size &optional test)
677   (make-hash-table :size size :test test :type 'non-weak))
678 (defun make-weak-hashtable (size &optional test)
679   (make-hash-table :size size :test test :type 'weak))
680 (defun make-key-weak-hashtable (size &optional test)
681   (make-hash-table :size size :test test :type 'key-weak))
682 (defun make-value-weak-hashtable (size &optional test)
683   (make-hash-table :size size :test test :type 'value-weak))
684
685 (define-obsolete-function-alias 'hashtablep 'hash-table-p)
686 (define-obsolete-function-alias 'hashtable-fullness 'hash-table-count)
687 (define-obsolete-function-alias 'hashtable-test-function 'hash-table-test)
688 (define-obsolete-function-alias 'hashtable-type 'hash-table-type)
689 (define-obsolete-function-alias 'hashtable-size 'hash-table-size)
690 (define-obsolete-function-alias 'copy-hashtable 'copy-hash-table)
691
692 (make-obsolete 'make-hashtable            'make-hash-table)
693 (make-obsolete 'make-weak-hashtable       'make-hash-table)
694 (make-obsolete 'make-key-weak-hashtable   'make-hash-table)
695 (make-obsolete 'make-value-weak-hashtable 'make-hash-table)
696
697 (when (fboundp 'x-keysym-hash-table)
698   (make-obsolete 'x-keysym-hashtable 'x-keysym-hash-table))
699
700 ;; Compatibility stuff for old kludgy cl.el hash table implementation
701 (defvar cl-builtin-gethash (symbol-function 'gethash))
702 (defvar cl-builtin-remhash (symbol-function 'remhash))
703 (defvar cl-builtin-clrhash (symbol-function 'clrhash))
704 (defvar cl-builtin-maphash (symbol-function 'maphash))
705
706 (defalias 'cl-gethash 'gethash)
707 (defalias 'cl-puthash 'puthash)
708 (defalias 'cl-remhash 'remhash)
709 (defalias 'cl-clrhash 'clrhash)
710 (defalias 'cl-maphash 'maphash)
711
712 ;;; Some debugging aids.
713
714 (defun cl-prettyprint (form)
715   "Insert a pretty-printed rendition of a Lisp FORM in current buffer."
716   (let ((pt (point)) last)
717     (insert "\n" (prin1-to-string form) "\n")
718     (setq last (point))
719     (goto-char (1+ pt))
720     (while (search-forward "(quote " last t)
721       (delete-backward-char 7)
722       (insert "'")
723       (forward-sexp)
724       (delete-char 1))
725     (goto-char (1+ pt))
726     (cl-do-prettyprint)))
727
728 (defun cl-do-prettyprint ()
729   (skip-chars-forward " ")
730   (if (looking-at "(")
731       (let ((skip (or (looking-at "((") (looking-at "(prog")
732                       (looking-at "(unwind-protect ")
733                       (looking-at "(function (")
734                       (looking-at "(cl-block-wrapper ")))
735             (two (or (looking-at "(defun ") (looking-at "(defmacro ")))
736             (let (or (looking-at "(let\\*? ") (looking-at "(while ")))
737             (set (looking-at "(p?set[qf] ")))
738         (if (or skip let
739                 (progn
740                   (forward-sexp)
741                   (and (>= (current-column) 78) (progn (backward-sexp) t))))
742             (let ((nl t))
743               (forward-char 1)
744               (cl-do-prettyprint)
745               (or skip (looking-at ")") (cl-do-prettyprint))
746               (or (not two) (looking-at ")") (cl-do-prettyprint))
747               (while (not (looking-at ")"))
748                 (if set (setq nl (not nl)))
749                 (if nl (insert "\n"))
750                 (lisp-indent-line)
751                 (cl-do-prettyprint))
752               (forward-char 1))))
753     (forward-sexp)))
754
755 (defvar cl-macroexpand-cmacs nil)
756 (defvar cl-closure-vars nil)
757
758 (defun cl-macroexpand-all (form &optional env)
759   "Expand all macro calls through a Lisp FORM.
760 This also does some trivial optimizations to make the form prettier."
761   (while (or (not (eq form (setq form (macroexpand form env))))
762              (and cl-macroexpand-cmacs
763                   (not (eq form (setq form (compiler-macroexpand form)))))))
764   (cond ((not (consp form)) form)
765         ((memq (car form) '(let let*))
766          (if (null (nth 1 form))
767              (cl-macroexpand-all (cons 'progn (cddr form)) env)
768            (let ((letf nil) (res nil) (lets (cadr form)))
769              (while lets
770                (cl-push (if (consp (car lets))
771                             (let ((exp (cl-macroexpand-all (caar lets) env)))
772                               (or (symbolp exp) (setq letf t))
773                               (cons exp (cl-macroexpand-body (cdar lets) env)))
774                           (let ((exp (cl-macroexpand-all (car lets) env)))
775                             (if (symbolp exp) exp
776                               (setq letf t) (list exp nil)))) res)
777                (setq lets (cdr lets)))
778              (list* (if letf (if (eq (car form) 'let) 'letf 'letf*) (car form))
779                     (nreverse res) (cl-macroexpand-body (cddr form) env)))))
780         ((eq (car form) 'cond)
781          (cons (car form)
782                (mapcar (function (lambda (x) (cl-macroexpand-body x env)))
783                        (cdr form))))
784         ((eq (car form) 'condition-case)
785          (list* (car form) (nth 1 form) (cl-macroexpand-all (nth 2 form) env)
786                 (mapcar (function
787                          (lambda (x)
788                            (cons (car x) (cl-macroexpand-body (cdr x) env))))
789                         (cdddr form))))
790         ((memq (car form) '(quote function))
791          (if (eq (car-safe (nth 1 form)) 'lambda)
792              (let ((body (cl-macroexpand-body (cddadr form) env)))
793                (if (and cl-closure-vars (eq (car form) 'function)
794                         (cl-expr-contains-any body cl-closure-vars))
795                    (let* ((new (mapcar 'gensym cl-closure-vars))
796                           (sub (pairlis cl-closure-vars new)) (decls nil))
797                      (while (or (stringp (car body))
798                                 (eq (car-safe (car body)) 'interactive))
799                        (cl-push (list 'quote (cl-pop body)) decls))
800                      (put (car (last cl-closure-vars)) 'used t)
801                      (append
802                       (list 'list '(quote lambda) '(quote (&rest --cl-rest--)))
803                       (sublis sub (nreverse decls))
804                       (list
805                        (list* 'list '(quote apply)
806                               (list 'list '(quote quote)
807                                     (list 'function
808                                           (list* 'lambda
809                                                  (append new (cadadr form))
810                                                  (sublis sub body))))
811                               (nconc (mapcar (function
812                                               (lambda (x)
813                                                 (list 'list '(quote quote) x)))
814                                              cl-closure-vars)
815                                      '((quote --cl-rest--)))))))
816                  (list (car form) (list* 'lambda (cadadr form) body))))
817            (let ((found (assq (cadr form) env)))
818              (if (eq (cadr (caddr found)) 'cl-labels-args)
819                  (cl-macroexpand-all (cadr (caddr (cadddr found))) env)
820                form))))
821         ((memq (car form) '(defun defmacro))
822          (list* (car form) (nth 1 form) (cl-macroexpand-body (cddr form) env)))
823         ((and (eq (car form) 'progn) (not (cddr form)))
824          (cl-macroexpand-all (nth 1 form) env))
825         ((eq (car form) 'setq)
826          (let* ((args (cl-macroexpand-body (cdr form) env)) (p args))
827            (while (and p (symbolp (car p))) (setq p (cddr p)))
828            (if p (cl-macroexpand-all (cons 'setf args)) (cons 'setq args))))
829         (t (cons (car form) (cl-macroexpand-body (cdr form) env)))))
830
831 (defun cl-macroexpand-body (body &optional env)
832   (mapcar (function (lambda (x) (cl-macroexpand-all x env))) body))
833
834 (defun cl-prettyexpand (form &optional full)
835   (message "Expanding...")
836   (let ((cl-macroexpand-cmacs full) (cl-compiling-file full)
837         (byte-compile-macro-environment nil))
838     (setq form (cl-macroexpand-all form
839                                    (and (not full) '((block) (eval-when)))))
840     (message "Formatting...")
841     (prog1 (cl-prettyprint form)
842       (message ""))))
843
844
845
846 (run-hooks 'cl-extra-load-hook)
847
848 (provide 'cl-extra)
849
850 ;;; cl-extra.el ends here