cl-extra.el 23.5 KB
Newer Older
1
;;; cl-extra.el --- Common Lisp features, part 2  -*- lexical-binding: t -*-
Richard M. Stallman's avatar
Richard M. Stallman committed
2

Paul Eggert's avatar
Paul Eggert committed
3
;; Copyright (C) 1993, 2000-2015 Free Software Foundation, Inc.
Richard M. Stallman's avatar
Richard M. Stallman committed
4 5 6

;; Author: Dave Gillespie <daveg@synaptics.com>
;; Keywords: extensions
7
;; Package: emacs
Richard M. Stallman's avatar
Richard M. Stallman committed
8 9 10

;; This file is part of GNU Emacs.

11
;; GNU Emacs is free software: you can redistribute it and/or modify
Richard M. Stallman's avatar
Richard M. Stallman committed
12
;; it under the terms of the GNU General Public License as published by
13 14
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
Richard M. Stallman's avatar
Richard M. Stallman committed
15 16 17 18 19 20 21

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
22
;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
Richard M. Stallman's avatar
Richard M. Stallman committed
23

Richard M. Stallman's avatar
Richard M. Stallman committed
24
;;; Commentary:
Richard M. Stallman's avatar
Richard M. Stallman committed
25 26 27 28 29 30 31 32 33 34 35 36 37

;; These are extensions to Emacs Lisp that provide a degree of
;; Common Lisp compatibility, beyond what is already built-in
;; in Emacs Lisp.
;;
;; This package was written by Dave Gillespie; it is a complete
;; rewrite of Cesar Quiroz's original cl.el package of December 1986.
;;
;; Bug reports, comments, and suggestions are welcome!

;; This file contains portions of the Common Lisp extensions
;; package which are autoloaded since they are relatively obscure.

Richard M. Stallman's avatar
Richard M. Stallman committed
38
;;; Code:
Richard M. Stallman's avatar
Richard M. Stallman committed
39

40
(require 'cl-lib)
Richard M. Stallman's avatar
Richard M. Stallman committed
41 42 43

;;; Type coercion.

44
;;;###autoload
45
(defun cl-coerce (x type)
Richard M. Stallman's avatar
Richard M. Stallman committed
46
  "Coerce OBJECT to type TYPE.
47 48
TYPE is a Common Lisp type specifier.
\n(fn OBJECT TYPE)"
Richard M. Stallman's avatar
Richard M. Stallman committed
49 50 51 52 53
  (cond ((eq type 'list) (if (listp x) x (append x nil)))
	((eq type 'vector) (if (vectorp x) x (vconcat x)))
	((eq type 'string) (if (stringp x) x (concat x)))
	((eq type 'array) (if (arrayp x) x (vconcat x)))
	((and (eq type 'character) (stringp x) (= (length x) 1)) (aref x 0))
54 55
	((and (eq type 'character) (symbolp x))
         (cl-coerce (symbol-name x) type))
Richard M. Stallman's avatar
Richard M. Stallman committed
56
	((eq type 'float) (float x))
57
	((cl-typep x type) x)
Richard M. Stallman's avatar
Richard M. Stallman committed
58 59 60 61 62
	(t (error "Can't coerce %s to type %s" x type))))


;;; Predicates.

63
;;;###autoload
64
(defun cl-equalp (x y)
Juanma Barranquero's avatar
Juanma Barranquero committed
65
  "Return t if two Lisp objects have similar structures and contents.
Richard M. Stallman's avatar
Richard M. Stallman committed
66 67 68 69 70 71
This is like `equal', except that it accepts numerically equal
numbers of different types (float vs. integer), and also compares
strings case-insensitively."
  (cond ((eq x y) t)
	((stringp x)
	 (and (stringp y) (= (length x) (length y))
72
	      (or (string-equal x y)
73
		  (string-equal (downcase x) (downcase y))))) ;Lazy but simple!
Richard M. Stallman's avatar
Richard M. Stallman committed
74 75 76
	((numberp x)
	 (and (numberp y) (= x y)))
	((consp x)
77
	 (while (and (consp x) (consp y) (cl-equalp (car x) (car y)))
78
	   (setq x (cdr x) y (cdr y)))
79
	 (and (not (consp x)) (cl-equalp x y)))
Richard M. Stallman's avatar
Richard M. Stallman committed
80 81 82 83
	((vectorp x)
	 (and (vectorp y) (= (length x) (length y))
	      (let ((i (length x)))
		(while (and (>= (setq i (1- i)) 0)
84
			    (cl-equalp (aref x i) (aref y i))))
Richard M. Stallman's avatar
Richard M. Stallman committed
85 86 87 88 89 90
		(< i 0))))
	(t (equal x y))))


;;; Control structures.

91
;;;###autoload
92
(defun cl--mapcar-many (cl-func cl-seqs)
Richard M. Stallman's avatar
Richard M. Stallman committed
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
  (if (cdr (cdr cl-seqs))
      (let* ((cl-res nil)
	     (cl-n (apply 'min (mapcar 'length cl-seqs)))
	     (cl-i 0)
	     (cl-args (copy-sequence cl-seqs))
	     cl-p1 cl-p2)
	(setq cl-seqs (copy-sequence cl-seqs))
	(while (< cl-i cl-n)
	  (setq cl-p1 cl-seqs cl-p2 cl-args)
	  (while cl-p1
	    (setcar cl-p2
		    (if (consp (car cl-p1))
			(prog1 (car (car cl-p1))
			  (setcar cl-p1 (cdr (car cl-p1))))
		      (aref (car cl-p1) cl-i)))
	    (setq cl-p1 (cdr cl-p1) cl-p2 (cdr cl-p2)))
109
	  (push (apply cl-func cl-args) cl-res)
Richard M. Stallman's avatar
Richard M. Stallman committed
110 111 112 113 114 115 116 117
	  (setq cl-i (1+ cl-i)))
	(nreverse cl-res))
    (let ((cl-res nil)
	  (cl-x (car cl-seqs))
	  (cl-y (nth 1 cl-seqs)))
      (let ((cl-n (min (length cl-x) (length cl-y)))
	    (cl-i -1))
	(while (< (setq cl-i (1+ cl-i)) cl-n)
118
	  (push (funcall cl-func
119 120 121
                         (if (consp cl-x) (pop cl-x) (aref cl-x cl-i))
                         (if (consp cl-y) (pop cl-y) (aref cl-y cl-i)))
                cl-res)))
Richard M. Stallman's avatar
Richard M. Stallman committed
122 123
      (nreverse cl-res))))

124
;;;###autoload
125
(defun cl-map (cl-type cl-func cl-seq &rest cl-rest)
126 127 128
  "Map a FUNCTION across one or more SEQUENCEs, returning a sequence.
TYPE is the sequence type to return.
\n(fn TYPE FUNCTION SEQUENCE...)"
129 130
  (let ((cl-res (apply 'cl-mapcar cl-func cl-seq cl-rest)))
    (and cl-type (cl-coerce cl-res cl-type))))
Richard M. Stallman's avatar
Richard M. Stallman committed
131

132
;;;###autoload
133
(defun cl-maplist (cl-func cl-list &rest cl-rest)
134
  "Map FUNCTION to each sublist of LIST or LISTs.
Glenn Morris's avatar
Glenn Morris committed
135
Like `cl-mapcar', except applies to lists and their cdr's rather than to
136 137
the elements themselves.
\n(fn FUNCTION LIST...)"
Richard M. Stallman's avatar
Richard M. Stallman committed
138 139 140 141 142
  (if cl-rest
      (let ((cl-res nil)
	    (cl-args (cons cl-list (copy-sequence cl-rest)))
	    cl-p)
	(while (not (memq nil cl-args))
143
	  (push (apply cl-func cl-args) cl-res)
Richard M. Stallman's avatar
Richard M. Stallman committed
144
	  (setq cl-p cl-args)
145
	  (while cl-p (setcar cl-p (cdr (pop cl-p)) )))
Richard M. Stallman's avatar
Richard M. Stallman committed
146 147 148
	(nreverse cl-res))
    (let ((cl-res nil))
      (while cl-list
149
	(push (funcall cl-func cl-list) cl-res)
Richard M. Stallman's avatar
Richard M. Stallman committed
150 151 152
	(setq cl-list (cdr cl-list)))
      (nreverse cl-res))))

Glenn Morris's avatar
Glenn Morris committed
153
;;;###autoload
Dave Love's avatar
Dave Love committed
154
(defun cl-mapc (cl-func cl-seq &rest cl-rest)
Glenn Morris's avatar
Glenn Morris committed
155
  "Like `cl-mapcar', but does not accumulate values returned by the function.
156
\n(fn FUNCTION SEQUENCE...)"
Richard M. Stallman's avatar
Richard M. Stallman committed
157
  (if cl-rest
158
      (progn (apply 'cl-map nil cl-func cl-seq cl-rest)
Dave Love's avatar
Dave Love committed
159
	     cl-seq)
160
    (mapc cl-func cl-seq)))
Richard M. Stallman's avatar
Richard M. Stallman committed
161

162
;;;###autoload
163 164
(defun cl-mapl (cl-func cl-list &rest cl-rest)
  "Like `cl-maplist', but does not accumulate values returned by the function.
165
\n(fn FUNCTION LIST...)"
Richard M. Stallman's avatar
Richard M. Stallman committed
166
  (if cl-rest
167
      (apply 'cl-maplist cl-func cl-list cl-rest)
Richard M. Stallman's avatar
Richard M. Stallman committed
168 169 170 171
    (let ((cl-p cl-list))
      (while cl-p (funcall cl-func cl-p) (setq cl-p (cdr cl-p)))))
  cl-list)

172
;;;###autoload
173
(defun cl-mapcan (cl-func cl-seq &rest cl-rest)
Glenn Morris's avatar
Glenn Morris committed
174
  "Like `cl-mapcar', but nconc's together the values returned by the function.
175
\n(fn FUNCTION SEQUENCE...)"
176
  (apply 'nconc (apply 'cl-mapcar cl-func cl-seq cl-rest)))
Richard M. Stallman's avatar
Richard M. Stallman committed
177

178
;;;###autoload
179 180
(defun cl-mapcon (cl-func cl-list &rest cl-rest)
  "Like `cl-maplist', but nconc's together the values returned by the function.
181
\n(fn FUNCTION LIST...)"
182
  (apply 'nconc (apply 'cl-maplist cl-func cl-list cl-rest)))
Richard M. Stallman's avatar
Richard M. Stallman committed
183

184
;;;###autoload
185
(defun cl-some (cl-pred cl-seq &rest cl-rest)
Richard M. Stallman's avatar
Richard M. Stallman committed
186
  "Return true if PREDICATE is true of any element of SEQ or SEQs.
187 188
If so, return the true (non-nil) value returned by PREDICATE.
\n(fn PREDICATE SEQ...)"
Richard M. Stallman's avatar
Richard M. Stallman committed
189 190
  (if (or cl-rest (nlistp cl-seq))
      (catch 'cl-some
191
	(apply 'cl-map nil
Richard M. Stallman's avatar
Richard M. Stallman committed
192 193 194 195 196
	       (function (lambda (&rest cl-x)
			   (let ((cl-res (apply cl-pred cl-x)))
			     (if cl-res (throw 'cl-some cl-res)))))
	       cl-seq cl-rest) nil)
    (let ((cl-x nil))
197
      (while (and cl-seq (not (setq cl-x (funcall cl-pred (pop cl-seq))))))
Richard M. Stallman's avatar
Richard M. Stallman committed
198 199
      cl-x)))

200
;;;###autoload
201
(defun cl-every (cl-pred cl-seq &rest cl-rest)
202 203
  "Return true if PREDICATE is true of every element of SEQ or SEQs.
\n(fn PREDICATE SEQ...)"
Richard M. Stallman's avatar
Richard M. Stallman committed
204 205
  (if (or cl-rest (nlistp cl-seq))
      (catch 'cl-every
206
	(apply 'cl-map nil
Richard M. Stallman's avatar
Richard M. Stallman committed
207 208 209 210 211 212 213
	       (function (lambda (&rest cl-x)
			   (or (apply cl-pred cl-x) (throw 'cl-every nil))))
	       cl-seq cl-rest) t)
    (while (and cl-seq (funcall cl-pred (car cl-seq)))
      (setq cl-seq (cdr cl-seq)))
    (null cl-seq)))

214
;;;###autoload
215
(defun cl-notany (cl-pred cl-seq &rest cl-rest)
216 217
  "Return true if PREDICATE is false of every element of SEQ or SEQs.
\n(fn PREDICATE SEQ...)"
218
  (not (apply 'cl-some cl-pred cl-seq cl-rest)))
Richard M. Stallman's avatar
Richard M. Stallman committed
219

220
;;;###autoload
221
(defun cl-notevery (cl-pred cl-seq &rest cl-rest)
222 223
  "Return true if PREDICATE is false of some element of SEQ or SEQs.
\n(fn PREDICATE SEQ...)"
224
  (not (apply 'cl-every cl-pred cl-seq cl-rest)))
Richard M. Stallman's avatar
Richard M. Stallman committed
225

226
;;;###autoload
227
(defun cl--map-keymap-recursively (cl-func-rec cl-map &optional cl-base)
Richard M. Stallman's avatar
Richard M. Stallman committed
228
  (or cl-base
Dave Love's avatar
Dave Love committed
229
      (setq cl-base (copy-sequence [0])))
230
  (map-keymap
Richard M. Stallman's avatar
Richard M. Stallman committed
231 232 233 234
   (function
    (lambda (cl-key cl-bind)
      (aset cl-base (1- (length cl-base)) cl-key)
      (if (keymapp cl-bind)
235
	  (cl--map-keymap-recursively
Richard M. Stallman's avatar
Richard M. Stallman committed
236
	   cl-func-rec cl-bind
Dave Love's avatar
Dave Love committed
237
	   (vconcat cl-base (list 0)))
Richard M. Stallman's avatar
Richard M. Stallman committed
238 239 240
	(funcall cl-func-rec cl-base cl-bind))))
   cl-map))

241
;;;###autoload
242
(defun cl--map-intervals (cl-func &optional cl-what cl-prop cl-start cl-end)
Richard M. Stallman's avatar
Richard M. Stallman committed
243 244 245
  (or cl-what (setq cl-what (current-buffer)))
  (if (bufferp cl-what)
      (let (cl-mark cl-mark2 (cl-next t) cl-next2)
Dave Love's avatar
Dave Love committed
246
	(with-current-buffer cl-what
Richard M. Stallman's avatar
Richard M. Stallman committed
247 248 249
	  (setq cl-mark (copy-marker (or cl-start (point-min))))
	  (setq cl-mark2 (and cl-end (copy-marker cl-end))))
	(while (and cl-next (or (not cl-mark2) (< cl-mark cl-mark2)))
Dave Love's avatar
Dave Love committed
250 251 252 253 254
	  (setq cl-next (if cl-prop (next-single-property-change
				     cl-mark cl-prop cl-what)
			  (next-property-change cl-mark cl-what))
		cl-next2 (or cl-next (with-current-buffer cl-what
				       (point-max))))
Richard M. Stallman's avatar
Richard M. Stallman committed
255 256 257 258 259 260 261
	  (funcall cl-func (prog1 (marker-position cl-mark)
			     (set-marker cl-mark cl-next2))
		   (if cl-mark2 (min cl-next2 cl-mark2) cl-next2)))
	(set-marker cl-mark nil) (if cl-mark2 (set-marker cl-mark2 nil)))
    (or cl-start (setq cl-start 0))
    (or cl-end (setq cl-end (length cl-what)))
    (while (< cl-start cl-end)
Dave Love's avatar
Dave Love committed
262 263 264
      (let ((cl-next (or (if cl-prop (next-single-property-change
				      cl-start cl-prop cl-what)
			   (next-property-change cl-start cl-what))
Richard M. Stallman's avatar
Richard M. Stallman committed
265 266 267 268
			 cl-end)))
	(funcall cl-func cl-start (min cl-next cl-end))
	(setq cl-start cl-next)))))

269
;;;###autoload
270
(defun cl--map-overlays (cl-func &optional cl-buffer cl-start cl-end cl-arg)
Richard M. Stallman's avatar
Richard M. Stallman committed
271 272 273 274 275
  (or cl-buffer (setq cl-buffer (current-buffer)))
  (if (fboundp 'overlay-lists)

      ;; This is the preferred algorithm, though overlay-lists is undocumented.
      (let (cl-ovl)
Dave Love's avatar
Dave Love committed
276
	(with-current-buffer cl-buffer
Richard M. Stallman's avatar
Richard M. Stallman committed
277 278 279 280 281 282 283 284 285 286 287 288 289 290
	  (setq cl-ovl (overlay-lists))
	  (if cl-start (setq cl-start (copy-marker cl-start)))
	  (if cl-end (setq cl-end (copy-marker cl-end))))
	(setq cl-ovl (nconc (car cl-ovl) (cdr cl-ovl)))
	(while (and cl-ovl
		    (or (not (overlay-start (car cl-ovl)))
			(and cl-end (>= (overlay-start (car cl-ovl)) cl-end))
			(and cl-start (<= (overlay-end (car cl-ovl)) cl-start))
			(not (funcall cl-func (car cl-ovl) cl-arg))))
	  (setq cl-ovl (cdr cl-ovl)))
	(if cl-start (set-marker cl-start nil))
	(if cl-end (set-marker cl-end nil)))

    ;; This alternate algorithm fails to find zero-length overlays.
Dave Love's avatar
Dave Love committed
291 292 293 294
    (let ((cl-mark (with-current-buffer cl-buffer
		     (copy-marker (or cl-start (point-min)))))
	  (cl-mark2 (and cl-end (with-current-buffer cl-buffer
				  (copy-marker cl-end))))
Richard M. Stallman's avatar
Richard M. Stallman committed
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
	  cl-pos cl-ovl)
      (while (save-excursion
	       (and (setq cl-pos (marker-position cl-mark))
		    (< cl-pos (or cl-mark2 (point-max)))
		    (progn
		      (set-buffer cl-buffer)
		      (setq cl-ovl (overlays-at cl-pos))
		      (set-marker cl-mark (next-overlay-change cl-pos)))))
	(while (and cl-ovl
		    (or (/= (overlay-start (car cl-ovl)) cl-pos)
			(not (and (funcall cl-func (car cl-ovl) cl-arg)
				  (set-marker cl-mark nil)))))
	  (setq cl-ovl (cdr cl-ovl))))
      (set-marker cl-mark nil) (if cl-mark2 (set-marker cl-mark2 nil)))))

310
;;; Support for `setf'.
311
;;;###autoload
312
(defun cl--set-frame-visible-p (frame val)
Richard M. Stallman's avatar
Richard M. Stallman committed
313 314 315 316 317 318 319 320
  (cond ((null val) (make-frame-invisible frame))
	((eq val 'icon) (iconify-frame frame))
	(t (make-frame-visible frame)))
  val)


;;; Numbers.

321
;;;###autoload
322
(defun cl-gcd (&rest args)
Richard M. Stallman's avatar
Richard M. Stallman committed
323
  "Return the greatest common divisor of the arguments."
324
  (let ((a (abs (or (pop args) 0))))
Richard M. Stallman's avatar
Richard M. Stallman committed
325
    (while args
326
      (let ((b (abs (pop args))))
Richard M. Stallman's avatar
Richard M. Stallman committed
327 328 329
	(while (> b 0) (setq b (% a (setq a b))))))
    a))

330
;;;###autoload
331
(defun cl-lcm (&rest args)
Richard M. Stallman's avatar
Richard M. Stallman committed
332 333 334
  "Return the least common multiple of the arguments."
  (if (memq 0 args)
      0
335
    (let ((a (abs (or (pop args) 1))))
Richard M. Stallman's avatar
Richard M. Stallman committed
336
      (while args
337
	(let ((b (abs (pop args))))
338
	  (setq a (* (/ a (cl-gcd a b)) b))))
Richard M. Stallman's avatar
Richard M. Stallman committed
339 340
      a)))

341
;;;###autoload
342
(defun cl-isqrt (x)
Richard M. Stallman's avatar
Richard M. Stallman committed
343
  "Return the integer square root of the argument."
344 345 346
  (if (and (integerp x) (> x 0))
      (let ((g (cond ((<= x 100) 10) ((<= x 10000) 100)
		     ((<= x 1000000) 1000) (t x)))
Richard M. Stallman's avatar
Richard M. Stallman committed
347
	    g2)
348
	(while (< (setq g2 (/ (+ g (/ x g)) 2)) g)
Richard M. Stallman's avatar
Richard M. Stallman committed
349 350
	  (setq g g2))
	g)
351
    (if (eq x 0) 0 (signal 'arith-error nil))))
Richard M. Stallman's avatar
Richard M. Stallman committed
352

353
;;;###autoload
354
(defun cl-floor (x &optional y)
Richard M. Stallman's avatar
Richard M. Stallman committed
355 356
  "Return a list of the floor of X and the fractional part of X.
With two arguments, return floor and remainder of their quotient."
357 358
  (let ((q (floor x y)))
    (list q (- x (if y (* y q) q)))))
Richard M. Stallman's avatar
Richard M. Stallman committed
359

360
;;;###autoload
361
(defun cl-ceiling (x &optional y)
Richard M. Stallman's avatar
Richard M. Stallman committed
362 363
  "Return a list of the ceiling of X and the fractional part of X.
With two arguments, return ceiling and remainder of their quotient."
364
  (let ((res (cl-floor x y)))
Richard M. Stallman's avatar
Richard M. Stallman committed
365 366 367
    (if (= (car (cdr res)) 0) res
      (list (1+ (car res)) (- (car (cdr res)) (or y 1))))))

368
;;;###autoload
369
(defun cl-truncate (x &optional y)
Richard M. Stallman's avatar
Richard M. Stallman committed
370 371 372
  "Return a list of the integer part of X and the fractional part of X.
With two arguments, return truncation and remainder of their quotient."
  (if (eq (>= x 0) (or (null y) (>= y 0)))
373
      (cl-floor x y) (cl-ceiling x y)))
Richard M. Stallman's avatar
Richard M. Stallman committed
374

375
;;;###autoload
376
(defun cl-round (x &optional y)
Richard M. Stallman's avatar
Richard M. Stallman committed
377 378 379 380 381
  "Return a list of X rounded to the nearest integer and the remainder.
With two arguments, return rounding and remainder of their quotient."
  (if y
      (if (and (integerp x) (integerp y))
	  (let* ((hy (/ y 2))
382
		 (res (cl-floor (+ x hy) y)))
Richard M. Stallman's avatar
Richard M. Stallman committed
383 384 385 386 387 388 389 390 391 392 393
	    (if (and (= (car (cdr res)) 0)
		     (= (+ hy hy) y)
		     (/= (% (car res) 2) 0))
		(list (1- (car res)) hy)
	      (list (car res) (- (car (cdr res)) hy))))
	(let ((q (round (/ x y))))
	  (list q (- x (* q y)))))
    (if (integerp x) (list x 0)
      (let ((q (round x)))
	(list q (- x q))))))

394
;;;###autoload
395
(defun cl-mod (x y)
Richard M. Stallman's avatar
Richard M. Stallman committed
396
  "The remainder of X divided by Y, with the same sign as Y."
397
  (nth 1 (cl-floor x y)))
Richard M. Stallman's avatar
Richard M. Stallman committed
398

399
;;;###autoload
400
(defun cl-rem (x y)
Richard M. Stallman's avatar
Richard M. Stallman committed
401
  "The remainder of X divided by Y, with the same sign as X."
402
  (nth 1 (cl-truncate x y)))
Richard M. Stallman's avatar
Richard M. Stallman committed
403

404
;;;###autoload
405
(defun cl-signum (x)
406 407
  "Return 1 if X is positive, -1 if negative, 0 if zero."
  (cond ((> x 0) 1) ((< x 0) -1) (t 0)))
Richard M. Stallman's avatar
Richard M. Stallman committed
408 409 410 411


;; Random numbers.

412
;;;###autoload
413
(defun cl-random (lim &optional state)
Richard M. Stallman's avatar
Richard M. Stallman committed
414 415
  "Return a random nonnegative number less than LIM, an integer or float.
Optional second arg STATE is a random-state object."
416
  (or state (setq state cl--random-state))
Richard M. Stallman's avatar
Richard M. Stallman committed
417 418 419
  ;; Inspired by "ran3" from Numerical Recipes.  Additive congruential method.
  (let ((vec (aref state 3)))
    (if (integerp vec)
420
	(let ((i 0) (j (- 1357335 (% (abs vec) 1357333))) (k 1))
Richard M. Stallman's avatar
Richard M. Stallman committed
421 422 423 424
	  (aset state 3 (setq vec (make-vector 55 nil)))
	  (aset vec 0 j)
	  (while (> (setq i (% (+ i 21) 55)) 0)
	    (aset vec i (setq j (prog1 k (setq k (- j k))))))
425
	  (while (< (setq i (1+ i)) 200) (cl-random 2 state))))
Richard M. Stallman's avatar
Richard M. Stallman committed
426 427 428 429 430
    (let* ((i (aset state 1 (% (1+ (aref state 1)) 55)))
	   (j (aset state 2 (% (1+ (aref state 2)) 55)))
	   (n (logand 8388607 (aset vec i (- (aref vec i) (aref vec j))))))
      (if (integerp lim)
	  (if (<= lim 512) (% n lim)
431
	    (if (> lim 8388607) (setq n (+ (lsh n 9) (cl-random 512 state))))
Richard M. Stallman's avatar
Richard M. Stallman committed
432 433
	    (let ((mask 1023))
	      (while (< mask (1- lim)) (setq mask (1+ (+ mask mask))))
434
	      (if (< (setq n (logand n mask)) lim) n (cl-random lim state))))
Richard M. Stallman's avatar
Richard M. Stallman committed
435 436
	(* (/ n '8388608e0) lim)))))

437
;;;###autoload
438
(defun cl-make-random-state (&optional state)
439
  "Return a copy of random-state STATE, or of the internal state if omitted.
Richard M. Stallman's avatar
Richard M. Stallman committed
440
If STATE is t, return a new state object seeded from the time of day."
441
  (cond ((null state) (cl-make-random-state cl--random-state))
442
	((vectorp state) (copy-tree state t))
443
	((integerp state) (vector 'cl--random-state-tag -1 30 state))
444
	(t (cl-make-random-state (cl--random-time)))))
Richard M. Stallman's avatar
Richard M. Stallman committed
445

446
;;;###autoload
447
(defun cl-random-state-p (object)
Richard M. Stallman's avatar
Richard M. Stallman committed
448 449
  "Return t if OBJECT is a random-state object."
  (and (vectorp object) (= (length object) 4)
450
       (eq (aref object 0) 'cl--random-state-tag)))
Richard M. Stallman's avatar
Richard M. Stallman committed
451 452 453 454


;; Implementation limits.

455 456
(defun cl--finite-do (func a b)
  (condition-case _
Richard M. Stallman's avatar
Richard M. Stallman committed
457 458 459 460
      (let ((res (funcall func a b)))   ; check for IEEE infinity
	(and (numberp res) (/= res (/ res 2)) res))
    (arith-error nil)))

461
;;;###autoload
Richard M. Stallman's avatar
Richard M. Stallman committed
462
(defun cl-float-limits ()
463
  "Initialize the Common Lisp floating-point parameters.
464 465 466 467 468
This sets the values of: `cl-most-positive-float', `cl-most-negative-float',
`cl-least-positive-float', `cl-least-negative-float', `cl-float-epsilon',
`cl-float-negative-epsilon', `cl-least-positive-normalized-float', and
`cl-least-negative-normalized-float'."
  (or cl-most-positive-float (not (numberp '2e1))
Richard M. Stallman's avatar
Richard M. Stallman committed
469 470
      (let ((x '2e0) y z)
	;; Find maximum exponent (first two loops are optimizations)
471 472 473
	(while (cl--finite-do '* x x) (setq x (* x x)))
	(while (cl--finite-do '* x (/ x 2)) (setq x (* x (/ x 2))))
	(while (cl--finite-do '+ x x) (setq x (+ x x)))
Richard M. Stallman's avatar
Richard M. Stallman committed
474
	(setq z x y (/ x 2))
475
	;; Now cl-fill in 1's in the mantissa.
476
	(while (and (cl--finite-do '+ x y) (/= (+ x y) x))
Richard M. Stallman's avatar
Richard M. Stallman committed
477
	  (setq x (+ x y) y (/ y 2)))
478 479
	(setq cl-most-positive-float x
	      cl-most-negative-float (- x))
Richard M. Stallman's avatar
Richard M. Stallman committed
480 481
	;; Divide down until mantissa starts rounding.
	(setq x (/ x z) y (/ 16 z) x (* x y))
482
	(while (condition-case _ (and (= x (* (/ x 2) 2)) (> (/ y 2) 0))
Richard M. Stallman's avatar
Richard M. Stallman committed
483 484
		 (arith-error nil))
	  (setq x (/ x 2) y (/ y 2)))
485 486
	(setq cl-least-positive-normalized-float y
	      cl-least-negative-normalized-float (- y))
Richard M. Stallman's avatar
Richard M. Stallman committed
487 488
	;; Divide down until value underflows to zero.
	(setq x (/ 1 z) y x)
489
	(while (condition-case _ (> (/ x 2) 0) (arith-error nil))
Richard M. Stallman's avatar
Richard M. Stallman committed
490
	  (setq x (/ x 2)))
491 492
	(setq cl-least-positive-float x
	      cl-least-negative-float (- x))
Richard M. Stallman's avatar
Richard M. Stallman committed
493 494
	(setq x '1e0)
	(while (/= (+ '1e0 x) '1e0) (setq x (/ x 2)))
495
	(setq cl-float-epsilon (* x 2))
Richard M. Stallman's avatar
Richard M. Stallman committed
496 497
	(setq x '1e0)
	(while (/= (- '1e0 x) '1e0) (setq x (/ x 2)))
498
	(setq cl-float-negative-epsilon (* x 2))))
Richard M. Stallman's avatar
Richard M. Stallman committed
499 500 501 502 503
  nil)


;;; Sequence functions.

504
;;;###autoload
505
(defun cl-subseq (seq start &optional end)
Richard M. Stallman's avatar
Richard M. Stallman committed
506 507 508
  "Return the subsequence of SEQ from START to END.
If END is omitted, it defaults to the length of the sequence.
If START or END is negative, it counts from the end."
Stefan Monnier's avatar
Stefan Monnier committed
509 510 511 512
  (declare (gv-setter
            (lambda (new)
              `(progn (cl-replace ,seq ,new :start1 ,start :end1 ,end)
                      ,new))))
Richard M. Stallman's avatar
Richard M. Stallman committed
513 514 515 516 517 518 519 520 521
  (if (stringp seq) (substring seq start end)
    (let (len)
      (and end (< end 0) (setq end (+ end (setq len (length seq)))))
      (if (< start 0) (setq start (+ start (or len (setq len (length seq))))))
      (cond ((listp seq)
	     (if (> start 0) (setq seq (nthcdr start seq)))
	     (if end
		 (let ((res nil))
		   (while (>= (setq end (1- end)) start)
522
		     (push (pop seq) res))
Richard M. Stallman's avatar
Richard M. Stallman committed
523 524 525 526 527 528 529 530 531 532 533
		   (nreverse res))
	       (copy-sequence seq)))
	    (t
	     (or end (setq end (or len (length seq))))
	     (let ((res (make-vector (max (- end start) 0) nil))
		   (i 0))
	       (while (< start end)
		 (aset res i (aref seq start))
		 (setq i (1+ i) start (1+ start)))
	       res))))))

534
;;;###autoload
535
(defun cl-concatenate (type &rest seqs)
536 537
  "Concatenate, into a sequence of type TYPE, the argument SEQUENCEs.
\n(fn TYPE SEQUENCE...)"
Richard M. Stallman's avatar
Richard M. Stallman committed
538 539 540 541 542 543 544 545
  (cond ((eq type 'vector) (apply 'vconcat seqs))
	((eq type 'string) (apply 'concat seqs))
	((eq type 'list) (apply 'append (append seqs '(nil))))
	(t (error "Not a sequence type name: %s" type))))


;;; List functions.

546
;;;###autoload
547
(defun cl-revappend (x y)
Richard M. Stallman's avatar
Richard M. Stallman committed
548 549 550
  "Equivalent to (append (reverse X) Y)."
  (nconc (reverse x) y))

551
;;;###autoload
552
(defun cl-nreconc (x y)
Richard M. Stallman's avatar
Richard M. Stallman committed
553 554 555
  "Equivalent to (nconc (nreverse X) Y)."
  (nconc (nreverse x) y))

556
;;;###autoload
557
(defun cl-list-length (x)
558
  "Return the length of list X.  Return nil if list is circular."
Richard M. Stallman's avatar
Richard M. Stallman committed
559 560 561 562 563
  (let ((n 0) (fast x) (slow x))
    (while (and (cdr fast) (not (and (eq fast slow) (> n 0))))
      (setq n (+ n 2) fast (cdr (cdr fast)) slow (cdr slow)))
    (if fast (if (cdr fast) nil (1+ n)) n)))

564
;;;###autoload
565
(defun cl-tailp (sublist list)
Richard M. Stallman's avatar
Richard M. Stallman committed
566 567 568 569 570 571 572
  "Return true if SUBLIST is a tail of LIST."
  (while (and (consp list) (not (eq sublist list)))
    (setq list (cdr list)))
  (if (numberp sublist) (equal sublist list) (eq sublist list)))

;;; Property lists.

573
;;;###autoload
574
(defun cl-get (sym tag &optional def)
575 576
  "Return the value of SYMBOL's PROPNAME property, or DEFAULT if none.
\n(fn SYMBOL PROPNAME &optional DEFAULT)"
Stefan Monnier's avatar
Stefan Monnier committed
577 578
  (declare (compiler-macro cl--compiler-macro-get)
           (gv-setter (lambda (store) `(put ,sym ,tag ,store))))
Richard M. Stallman's avatar
Richard M. Stallman committed
579 580
  (or (get sym tag)
      (and def
581
           ;; Make sure `def' is really absent as opposed to set to nil.
Richard M. Stallman's avatar
Richard M. Stallman committed
582 583 584 585
	   (let ((plist (symbol-plist sym)))
	     (while (and plist (not (eq (car plist) tag)))
	       (setq plist (cdr (cdr plist))))
	     (if plist (car (cdr plist)) def)))))
586
(autoload 'cl--compiler-macro-get "cl-macs")
Richard M. Stallman's avatar
Richard M. Stallman committed
587

588
;;;###autoload
589
(defun cl-getf (plist tag &optional def)
Richard M. Stallman's avatar
Richard M. Stallman committed
590
  "Search PROPLIST for property PROPNAME; return its value or DEFAULT.
591 592
PROPLIST is a list of the sort returned by `symbol-plist'.
\n(fn PROPLIST PROPNAME &optional DEFAULT)"
Stefan Monnier's avatar
Stefan Monnier committed
593 594 595 596 597 598 599
  (declare (gv-expander
            (lambda (do)
              (gv-letplace (getter setter) plist
                (macroexp-let2 nil k tag
                  (macroexp-let2 nil d def
                    (funcall do `(cl-getf ,getter ,k ,d)
                             (lambda (v)
600 601 602 603 604
                               (macroexp-let2 nil val v
                                 `(progn
                                    ,(funcall setter
                                              `(cl--set-getf ,getter ,k ,val))
                                    ,val))))))))))
Richard M. Stallman's avatar
Richard M. Stallman committed
605 606
  (setplist '--cl-getf-symbol-- plist)
  (or (get '--cl-getf-symbol-- tag)
607 608
      ;; Originally we called cl-get here,
      ;; but that fails, because cl-get has a compiler macro
Karl Heuer's avatar
Karl Heuer committed
609 610
      ;; definition that uses getf!
      (when def
611
        ;; Make sure `def' is really absent as opposed to set to nil.
Karl Heuer's avatar
Karl Heuer committed
612 613 614
	(while (and plist (not (eq (car plist) tag)))
	  (setq plist (cdr (cdr plist))))
	(if plist (car (cdr plist)) def))))
Richard M. Stallman's avatar
Richard M. Stallman committed
615

616
;;;###autoload
617
(defun cl--set-getf (plist tag val)
Richard M. Stallman's avatar
Richard M. Stallman committed
618 619
  (let ((p plist))
    (while (and p (not (eq (car p) tag))) (setq p (cdr (cdr p))))
620
    (if p (progn (setcar (cdr p) val) plist) (cl-list* tag val plist))))
Richard M. Stallman's avatar
Richard M. Stallman committed
621

622
;;;###autoload
623
(defun cl--do-remf (plist tag)
Richard M. Stallman's avatar
Richard M. Stallman committed
624 625 626 627
  (let ((p (cdr plist)))
    (while (and (cdr p) (not (eq (car (cdr p)) tag))) (setq p (cdr (cdr p))))
    (and (cdr p) (progn (setcdr p (cdr (cdr (cdr p)))) t))))

628
;;;###autoload
Richard M. Stallman's avatar
Richard M. Stallman committed
629
(defun cl-remprop (sym tag)
630 631
  "Remove from SYMBOL's plist the property PROPNAME and its value.
\n(fn SYMBOL PROPNAME)"
Richard M. Stallman's avatar
Richard M. Stallman committed
632 633 634
  (let ((plist (symbol-plist sym)))
    (if (and plist (eq tag (car plist)))
	(progn (setplist sym (cdr (cdr plist))) t)
635
      (cl--do-remf plist tag))))
Richard M. Stallman's avatar
Richard M. Stallman committed
636 637 638 639 640 641 642 643 644 645

;;; Some debugging aids.

(defun cl-prettyprint (form)
  "Insert a pretty-printed rendition of a Lisp FORM in current buffer."
  (let ((pt (point)) last)
    (insert "\n" (prin1-to-string form) "\n")
    (setq last (point))
    (goto-char (1+ pt))
    (while (search-forward "(quote " last t)
646
      (delete-char -7)
Richard M. Stallman's avatar
Richard M. Stallman committed
647 648 649 650
      (insert "'")
      (forward-sexp)
      (delete-char 1))
    (goto-char (1+ pt))
651
    (cl--do-prettyprint)))
Richard M. Stallman's avatar
Richard M. Stallman committed
652

653
(defun cl--do-prettyprint ()
Richard M. Stallman's avatar
Richard M. Stallman committed
654 655 656 657 658
  (skip-chars-forward " ")
  (if (looking-at "(")
      (let ((skip (or (looking-at "((") (looking-at "(prog")
		      (looking-at "(unwind-protect ")
		      (looking-at "(function (")
659
		      (looking-at "(cl--block-wrapper ")))
Richard M. Stallman's avatar
Richard M. Stallman committed
660 661 662 663 664 665 666 667 668
	    (two (or (looking-at "(defun ") (looking-at "(defmacro ")))
	    (let (or (looking-at "(let\\*? ") (looking-at "(while ")))
	    (set (looking-at "(p?set[qf] ")))
	(if (or skip let
		(progn
		  (forward-sexp)
		  (and (>= (current-column) 78) (progn (backward-sexp) t))))
	    (let ((nl t))
	      (forward-char 1)
669 670 671
	      (cl--do-prettyprint)
	      (or skip (looking-at ")") (cl--do-prettyprint))
	      (or (not two) (looking-at ")") (cl--do-prettyprint))
Richard M. Stallman's avatar
Richard M. Stallman committed
672 673 674 675
	      (while (not (looking-at ")"))
		(if set (setq nl (not nl)))
		(if nl (insert "\n"))
		(lisp-indent-line)
676
		(cl--do-prettyprint))
Richard M. Stallman's avatar
Richard M. Stallman committed
677 678 679
	      (forward-char 1))))
    (forward-sexp)))

680
;;;###autoload
Richard M. Stallman's avatar
Richard M. Stallman committed
681
(defun cl-prettyexpand (form &optional full)
Glenn Morris's avatar
Glenn Morris committed
682 683 684
  "Expand macros in FORM and insert the pretty-printed result.
Optional argument FULL non-nil means to expand all macros,
including `cl-block' and `cl-eval-when'."
Richard M. Stallman's avatar
Richard M. Stallman committed
685
  (message "Expanding...")
686
  (let ((cl--compiling-file full)
Richard M. Stallman's avatar
Richard M. Stallman committed
687
	(byte-compile-macro-environment nil))
688 689
    (setq form (macroexpand-all form
                                (and (not full) '((cl-block) (cl-eval-when)))))
Richard M. Stallman's avatar
Richard M. Stallman committed
690 691 692 693 694 695 696 697
    (message "Formatting...")
    (prog1 (cl-prettyprint form)
      (message ""))))



(run-hooks 'cl-extra-load-hook)

698
;; Local variables:
Glenn Morris's avatar
Glenn Morris committed
699
;; byte-compile-dynamic: t
700 701 702
;; generated-autoload-file: "cl-loaddefs.el"
;; End:

703
(provide 'cl-extra)
Richard M. Stallman's avatar
Richard M. Stallman committed
704
;;; cl-extra.el ends here