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