]> code.delx.au - gnu-emacs/blob - lisp/emacs-lisp/cl-extra.el
Include versioned preloaded libraries in `package--builtin-versions'
[gnu-emacs] / lisp / emacs-lisp / cl-extra.el
1 ;;; cl-extra.el --- Common Lisp features, part 2 -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 1993, 2000-2016 Free Software Foundation, Inc.
4
5 ;; Author: Dave Gillespie <daveg@synaptics.com>
6 ;; Keywords: extensions
7 ;; Package: emacs
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
20
21 ;; 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/>.
23
24 ;;; Commentary:
25
26 ;; These are extensions to Emacs Lisp that provide a degree of
27 ;; Common Lisp compatibility, beyond what is already built-in
28 ;; in Emacs Lisp.
29 ;;
30 ;; This package was written by Dave Gillespie; it is a complete
31 ;; rewrite of Cesar Quiroz's original cl.el package of December 1986.
32 ;;
33 ;; Bug reports, comments, and suggestions are welcome!
34
35 ;; This file contains portions of the Common Lisp extensions
36 ;; package which are autoloaded since they are relatively obscure.
37
38 ;;; Code:
39
40 (require 'cl-lib)
41
42 ;;; Type coercion.
43
44 ;;;###autoload
45 (defun cl-coerce (x type)
46 "Coerce OBJECT to type TYPE.
47 TYPE is a Common Lisp type specifier.
48 \n(fn OBJECT TYPE)"
49 (cond ((eq type 'list) (if (listp x) x (append x nil)))
50 ((eq type 'vector) (if (vectorp x) x (vconcat x)))
51 ((eq type 'string) (if (stringp x) x (concat x)))
52 ((eq type 'array) (if (arrayp x) x (vconcat x)))
53 ((and (eq type 'character) (stringp x) (= (length x) 1)) (aref x 0))
54 ((and (eq type 'character) (symbolp x))
55 (cl-coerce (symbol-name x) type))
56 ((eq type 'float) (float x))
57 ((cl-typep x type) x)
58 (t (error "Can't coerce %s to type %s" x type))))
59
60
61 ;;; Predicates.
62
63 ;;;###autoload
64 (defun cl-equalp (x y)
65 "Return t if two Lisp objects have similar structures and contents.
66 This is like `equal', except that it accepts numerically equal
67 numbers of different types (float vs. integer), and also compares
68 strings case-insensitively."
69 (cond ((eq x y) t)
70 ((stringp x)
71 (and (stringp y) (= (length x) (length y))
72 (or (string-equal x y)
73 (string-equal (downcase x) (downcase y))))) ;Lazy but simple!
74 ((numberp x)
75 (and (numberp y) (= x y)))
76 ((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)))
80 ((vectorp x)
81 (and (vectorp y) (= (length x) (length y))
82 (let ((i (length x)))
83 (while (and (>= (setq i (1- i)) 0)
84 (cl-equalp (aref x i) (aref y i))))
85 (< i 0))))
86 (t (equal x y))))
87
88
89 ;;; Control structures.
90
91 ;;;###autoload
92 (defun cl--mapcar-many (cl-func cl-seqs)
93 (if (cdr (cdr cl-seqs))
94 (let* ((cl-res nil)
95 (cl-n (apply 'min (mapcar 'length cl-seqs)))
96 (cl-i 0)
97 (cl-args (copy-sequence cl-seqs))
98 cl-p1 cl-p2)
99 (setq cl-seqs (copy-sequence cl-seqs))
100 (while (< cl-i cl-n)
101 (setq cl-p1 cl-seqs cl-p2 cl-args)
102 (while cl-p1
103 (setcar cl-p2
104 (if (consp (car cl-p1))
105 (prog1 (car (car cl-p1))
106 (setcar cl-p1 (cdr (car cl-p1))))
107 (aref (car cl-p1) cl-i)))
108 (setq cl-p1 (cdr cl-p1) cl-p2 (cdr cl-p2)))
109 (push (apply cl-func cl-args) cl-res)
110 (setq cl-i (1+ cl-i)))
111 (nreverse cl-res))
112 (let ((cl-res nil)
113 (cl-x (car cl-seqs))
114 (cl-y (nth 1 cl-seqs)))
115 (let ((cl-n (min (length cl-x) (length cl-y)))
116 (cl-i -1))
117 (while (< (setq cl-i (1+ cl-i)) cl-n)
118 (push (funcall cl-func
119 (if (consp cl-x) (pop cl-x) (aref cl-x cl-i))
120 (if (consp cl-y) (pop cl-y) (aref cl-y cl-i)))
121 cl-res)))
122 (nreverse cl-res))))
123
124 ;;;###autoload
125 (defun cl-map (cl-type cl-func cl-seq &rest cl-rest)
126 "Map a FUNCTION across one or more SEQUENCEs, returning a sequence.
127 TYPE is the sequence type to return.
128 \n(fn TYPE FUNCTION SEQUENCE...)"
129 (let ((cl-res (apply 'cl-mapcar cl-func cl-seq cl-rest)))
130 (and cl-type (cl-coerce cl-res cl-type))))
131
132 ;;;###autoload
133 (defun cl-maplist (cl-func cl-list &rest cl-rest)
134 "Map FUNCTION to each sublist of LIST or LISTs.
135 Like `cl-mapcar', except applies to lists and their cdr's rather than to
136 the elements themselves.
137 \n(fn FUNCTION LIST...)"
138 (if cl-rest
139 (let ((cl-res nil)
140 (cl-args (cons cl-list (copy-sequence cl-rest)))
141 cl-p)
142 (while (not (memq nil cl-args))
143 (push (apply cl-func cl-args) cl-res)
144 (setq cl-p cl-args)
145 (while cl-p (setcar cl-p (cdr (pop cl-p)) )))
146 (nreverse cl-res))
147 (let ((cl-res nil))
148 (while cl-list
149 (push (funcall cl-func cl-list) cl-res)
150 (setq cl-list (cdr cl-list)))
151 (nreverse cl-res))))
152
153 ;;;###autoload
154 (defun cl-mapc (cl-func cl-seq &rest cl-rest)
155 "Like `cl-mapcar', but does not accumulate values returned by the function.
156 \n(fn FUNCTION SEQUENCE...)"
157 (if cl-rest
158 (progn (apply 'cl-map nil cl-func cl-seq cl-rest)
159 cl-seq)
160 (mapc cl-func cl-seq)))
161
162 ;;;###autoload
163 (defun cl-mapl (cl-func cl-list &rest cl-rest)
164 "Like `cl-maplist', but does not accumulate values returned by the function.
165 \n(fn FUNCTION LIST...)"
166 (if cl-rest
167 (apply 'cl-maplist cl-func cl-list cl-rest)
168 (let ((cl-p cl-list))
169 (while cl-p (funcall cl-func cl-p) (setq cl-p (cdr cl-p)))))
170 cl-list)
171
172 ;;;###autoload
173 (defun cl-mapcan (cl-func cl-seq &rest cl-rest)
174 "Like `cl-mapcar', but nconc's together the values returned by the function.
175 \n(fn FUNCTION SEQUENCE...)"
176 (if cl-rest
177 (apply 'nconc (apply 'cl-mapcar cl-func cl-seq cl-rest))
178 (mapcan cl-func cl-seq)))
179
180 ;;;###autoload
181 (defun cl-mapcon (cl-func cl-list &rest cl-rest)
182 "Like `cl-maplist', but nconc's together the values returned by the function.
183 \n(fn FUNCTION LIST...)"
184 (apply 'nconc (apply 'cl-maplist cl-func cl-list cl-rest)))
185
186 ;;;###autoload
187 (defun cl-some (cl-pred cl-seq &rest cl-rest)
188 "Return true if PREDICATE is true of any element of SEQ or SEQs.
189 If so, return the true (non-nil) value returned by PREDICATE.
190 \n(fn PREDICATE SEQ...)"
191 (if (or cl-rest (nlistp cl-seq))
192 (catch 'cl-some
193 (apply 'cl-map nil
194 (function (lambda (&rest cl-x)
195 (let ((cl-res (apply cl-pred cl-x)))
196 (if cl-res (throw 'cl-some cl-res)))))
197 cl-seq cl-rest) nil)
198 (let ((cl-x nil))
199 (while (and cl-seq (not (setq cl-x (funcall cl-pred (pop cl-seq))))))
200 cl-x)))
201
202 ;;;###autoload
203 (defun cl-every (cl-pred cl-seq &rest cl-rest)
204 "Return true if PREDICATE is true of every element of SEQ or SEQs.
205 \n(fn PREDICATE SEQ...)"
206 (if (or cl-rest (nlistp cl-seq))
207 (catch 'cl-every
208 (apply 'cl-map nil
209 (function (lambda (&rest cl-x)
210 (or (apply cl-pred cl-x) (throw 'cl-every nil))))
211 cl-seq cl-rest) t)
212 (while (and cl-seq (funcall cl-pred (car cl-seq)))
213 (setq cl-seq (cdr cl-seq)))
214 (null cl-seq)))
215
216 ;;;###autoload
217 (defun cl-notany (cl-pred cl-seq &rest cl-rest)
218 "Return true if PREDICATE is false of every element of SEQ or SEQs.
219 \n(fn PREDICATE SEQ...)"
220 (not (apply 'cl-some cl-pred cl-seq cl-rest)))
221
222 ;;;###autoload
223 (defun cl-notevery (cl-pred cl-seq &rest cl-rest)
224 "Return true if PREDICATE is false of some element of SEQ or SEQs.
225 \n(fn PREDICATE SEQ...)"
226 (not (apply 'cl-every cl-pred cl-seq cl-rest)))
227
228 ;;;###autoload
229 (defun cl--map-keymap-recursively (cl-func-rec cl-map &optional cl-base)
230 (or cl-base
231 (setq cl-base (copy-sequence [0])))
232 (map-keymap
233 (function
234 (lambda (cl-key cl-bind)
235 (aset cl-base (1- (length cl-base)) cl-key)
236 (if (keymapp cl-bind)
237 (cl--map-keymap-recursively
238 cl-func-rec cl-bind
239 (vconcat cl-base (list 0)))
240 (funcall cl-func-rec cl-base cl-bind))))
241 cl-map))
242
243 ;;;###autoload
244 (defun cl--map-intervals (cl-func &optional cl-what cl-prop cl-start cl-end)
245 (or cl-what (setq cl-what (current-buffer)))
246 (if (bufferp cl-what)
247 (let (cl-mark cl-mark2 (cl-next t) cl-next2)
248 (with-current-buffer cl-what
249 (setq cl-mark (copy-marker (or cl-start (point-min))))
250 (setq cl-mark2 (and cl-end (copy-marker cl-end))))
251 (while (and cl-next (or (not cl-mark2) (< cl-mark cl-mark2)))
252 (setq cl-next (if cl-prop (next-single-property-change
253 cl-mark cl-prop cl-what)
254 (next-property-change cl-mark cl-what))
255 cl-next2 (or cl-next (with-current-buffer cl-what
256 (point-max))))
257 (funcall cl-func (prog1 (marker-position cl-mark)
258 (set-marker cl-mark cl-next2))
259 (if cl-mark2 (min cl-next2 cl-mark2) cl-next2)))
260 (set-marker cl-mark nil) (if cl-mark2 (set-marker cl-mark2 nil)))
261 (or cl-start (setq cl-start 0))
262 (or cl-end (setq cl-end (length cl-what)))
263 (while (< cl-start cl-end)
264 (let ((cl-next (or (if cl-prop (next-single-property-change
265 cl-start cl-prop cl-what)
266 (next-property-change cl-start cl-what))
267 cl-end)))
268 (funcall cl-func cl-start (min cl-next cl-end))
269 (setq cl-start cl-next)))))
270
271 ;;;###autoload
272 (defun cl--map-overlays (cl-func &optional cl-buffer cl-start cl-end cl-arg)
273 (or cl-buffer (setq cl-buffer (current-buffer)))
274 (let (cl-ovl)
275 (with-current-buffer cl-buffer
276 (setq cl-ovl (overlay-lists))
277 (if cl-start (setq cl-start (copy-marker cl-start)))
278 (if cl-end (setq cl-end (copy-marker cl-end))))
279 (setq cl-ovl (nconc (car cl-ovl) (cdr cl-ovl)))
280 (while (and cl-ovl
281 (or (not (overlay-start (car cl-ovl)))
282 (and cl-end (>= (overlay-start (car cl-ovl)) cl-end))
283 (and cl-start (<= (overlay-end (car cl-ovl)) cl-start))
284 (not (funcall cl-func (car cl-ovl) cl-arg))))
285 (setq cl-ovl (cdr cl-ovl)))
286 (if cl-start (set-marker cl-start nil))
287 (if cl-end (set-marker cl-end nil))))
288
289 ;;; Support for `setf'.
290 ;;;###autoload
291 (defun cl--set-frame-visible-p (frame val)
292 (cond ((null val) (make-frame-invisible frame))
293 ((eq val 'icon) (iconify-frame frame))
294 (t (make-frame-visible frame)))
295 val)
296
297
298 ;;; Numbers.
299
300 ;;;###autoload
301 (defun cl-gcd (&rest args)
302 "Return the greatest common divisor of the arguments."
303 (let ((a (or (pop args) 0)))
304 (dolist (b args)
305 (while (/= b 0)
306 (setq b (% a (setq a b)))))
307 (abs a)))
308
309 ;;;###autoload
310 (defun cl-lcm (&rest args)
311 "Return the least common multiple of the arguments."
312 (if (memq 0 args)
313 0
314 (let ((a (or (pop args) 1)))
315 (dolist (b args)
316 (setq a (* (/ a (cl-gcd a b)) b)))
317 (abs a))))
318
319 ;;;###autoload
320 (defun cl-isqrt (x)
321 "Return the integer square root of the argument."
322 (if (and (integerp x) (> x 0))
323 (let ((g (cond ((<= x 100) 10) ((<= x 10000) 100)
324 ((<= x 1000000) 1000) (t x)))
325 g2)
326 (while (< (setq g2 (/ (+ g (/ x g)) 2)) g)
327 (setq g g2))
328 g)
329 (if (eq x 0) 0 (signal 'arith-error nil))))
330
331 ;;;###autoload
332 (defun cl-floor (x &optional y)
333 "Return a list of the floor of X and the fractional part of X.
334 With two arguments, return floor and remainder of their quotient."
335 (let ((q (floor x y)))
336 (list q (- x (if y (* y q) q)))))
337
338 ;;;###autoload
339 (defun cl-ceiling (x &optional y)
340 "Return a list of the ceiling of X and the fractional part of X.
341 With two arguments, return ceiling and remainder of their quotient."
342 (let ((res (cl-floor x y)))
343 (if (= (car (cdr res)) 0) res
344 (list (1+ (car res)) (- (car (cdr res)) (or y 1))))))
345
346 ;;;###autoload
347 (defun cl-truncate (x &optional y)
348 "Return a list of the integer part of X and the fractional part of X.
349 With two arguments, return truncation and remainder of their quotient."
350 (if (eq (>= x 0) (or (null y) (>= y 0)))
351 (cl-floor x y) (cl-ceiling x y)))
352
353 ;;;###autoload
354 (defun cl-round (x &optional y)
355 "Return a list of X rounded to the nearest integer and the remainder.
356 With two arguments, return rounding and remainder of their quotient."
357 (if y
358 (if (and (integerp x) (integerp y))
359 (let* ((hy (/ y 2))
360 (res (cl-floor (+ x hy) y)))
361 (if (and (= (car (cdr res)) 0)
362 (= (+ hy hy) y)
363 (/= (% (car res) 2) 0))
364 (list (1- (car res)) hy)
365 (list (car res) (- (car (cdr res)) hy))))
366 (let ((q (round (/ x y))))
367 (list q (- x (* q y)))))
368 (if (integerp x) (list x 0)
369 (let ((q (round x)))
370 (list q (- x q))))))
371
372 ;;;###autoload
373 (defun cl-mod (x y)
374 "The remainder of X divided by Y, with the same sign as Y."
375 (nth 1 (cl-floor x y)))
376
377 ;;;###autoload
378 (defun cl-rem (x y)
379 "The remainder of X divided by Y, with the same sign as X."
380 (nth 1 (cl-truncate x y)))
381
382 ;;;###autoload
383 (defun cl-signum (x)
384 "Return 1 if X is positive, -1 if negative, 0 if zero."
385 (cond ((> x 0) 1) ((< x 0) -1) (t 0)))
386
387 ;;;###autoload
388 (cl-defun cl-parse-integer (string &key start end radix junk-allowed)
389 "Parse integer from the substring of STRING from START to END.
390 STRING may be surrounded by whitespace chars (chars with syntax ` ').
391 Other non-digit chars are considered junk.
392 RADIX is an integer between 2 and 36, the default is 10. Signal
393 an error if the substring between START and END cannot be parsed
394 as an integer unless JUNK-ALLOWED is non-nil."
395 (cl-check-type string string)
396 (let* ((start (or start 0))
397 (len (length string))
398 (end (or end len))
399 (radix (or radix 10)))
400 (or (<= start end len)
401 (error "Bad interval: [%d, %d)" start end))
402 (cl-flet ((skip-whitespace ()
403 (while (and (< start end)
404 (= 32 (char-syntax (aref string start))))
405 (setq start (1+ start)))))
406 (skip-whitespace)
407 (let ((sign (cl-case (and (< start end) (aref string start))
408 (?+ (cl-incf start) +1)
409 (?- (cl-incf start) -1)
410 (t +1)))
411 digit sum)
412 (while (and (< start end)
413 (setq digit (cl-digit-char-p (aref string start) radix)))
414 (setq sum (+ (* (or sum 0) radix) digit)
415 start (1+ start)))
416 (skip-whitespace)
417 (cond ((and junk-allowed (null sum)) sum)
418 (junk-allowed (* sign sum))
419 ((or (/= start end) (null sum))
420 (error "Not an integer string: `%s'" string))
421 (t (* sign sum)))))))
422
423
424 ;; Random numbers.
425
426 ;;;###autoload
427 (defun cl-random (lim &optional state)
428 "Return a random nonnegative number less than LIM, an integer or float.
429 Optional second arg STATE is a random-state object."
430 (or state (setq state cl--random-state))
431 ;; Inspired by "ran3" from Numerical Recipes. Additive congruential method.
432 (let ((vec (aref state 3)))
433 (if (integerp vec)
434 (let ((i 0) (j (- 1357335 (abs (% vec 1357333)))) (k 1))
435 (aset state 3 (setq vec (make-vector 55 nil)))
436 (aset vec 0 j)
437 (while (> (setq i (% (+ i 21) 55)) 0)
438 (aset vec i (setq j (prog1 k (setq k (- j k))))))
439 (while (< (setq i (1+ i)) 200) (cl-random 2 state))))
440 (let* ((i (aset state 1 (% (1+ (aref state 1)) 55)))
441 (j (aset state 2 (% (1+ (aref state 2)) 55)))
442 (n (logand 8388607 (aset vec i (- (aref vec i) (aref vec j))))))
443 (if (integerp lim)
444 (if (<= lim 512) (% n lim)
445 (if (> lim 8388607) (setq n (+ (lsh n 9) (cl-random 512 state))))
446 (let ((mask 1023))
447 (while (< mask (1- lim)) (setq mask (1+ (+ mask mask))))
448 (if (< (setq n (logand n mask)) lim) n (cl-random lim state))))
449 (* (/ n '8388608e0) lim)))))
450
451 ;;;###autoload
452 (defun cl-make-random-state (&optional state)
453 "Return a copy of random-state STATE, or of the internal state if omitted.
454 If STATE is t, return a new state object seeded from the time of day."
455 (cond ((null state) (cl-make-random-state cl--random-state))
456 ((vectorp state) (copy-tree state t))
457 ((integerp state) (vector 'cl--random-state-tag -1 30 state))
458 (t (cl-make-random-state (cl--random-time)))))
459
460 ;;;###autoload
461 (defun cl-random-state-p (object)
462 "Return t if OBJECT is a random-state object."
463 (and (vectorp object) (= (length object) 4)
464 (eq (aref object 0) 'cl--random-state-tag)))
465
466
467 ;; Implementation limits.
468
469 (defun cl--finite-do (func a b)
470 (condition-case _
471 (let ((res (funcall func a b))) ; check for IEEE infinity
472 (and (numberp res) (/= res (/ res 2)) res))
473 (arith-error nil)))
474
475 ;;;###autoload
476 (defun cl-float-limits ()
477 "Initialize the Common Lisp floating-point parameters.
478 This sets the values of: `cl-most-positive-float', `cl-most-negative-float',
479 `cl-least-positive-float', `cl-least-negative-float', `cl-float-epsilon',
480 `cl-float-negative-epsilon', `cl-least-positive-normalized-float', and
481 `cl-least-negative-normalized-float'."
482 (or cl-most-positive-float (not (numberp '2e1))
483 (let ((x '2e0) y z)
484 ;; Find maximum exponent (first two loops are optimizations)
485 (while (cl--finite-do '* x x) (setq x (* x x)))
486 (while (cl--finite-do '* x (/ x 2)) (setq x (* x (/ x 2))))
487 (while (cl--finite-do '+ x x) (setq x (+ x x)))
488 (setq z x y (/ x 2))
489 ;; Now cl-fill in 1's in the mantissa.
490 (while (and (cl--finite-do '+ x y) (/= (+ x y) x))
491 (setq x (+ x y) y (/ y 2)))
492 (setq cl-most-positive-float x
493 cl-most-negative-float (- x))
494 ;; Divide down until mantissa starts rounding.
495 (setq x (/ x z) y (/ 16 z) x (* x y))
496 (while (condition-case _ (and (= x (* (/ x 2) 2)) (> (/ y 2) 0))
497 (arith-error nil))
498 (setq x (/ x 2) y (/ y 2)))
499 (setq cl-least-positive-normalized-float y
500 cl-least-negative-normalized-float (- y))
501 ;; Divide down until value underflows to zero.
502 (setq x (/ z) y x)
503 (while (condition-case _ (> (/ x 2) 0) (arith-error nil))
504 (setq x (/ x 2)))
505 (setq cl-least-positive-float x
506 cl-least-negative-float (- x))
507 (setq x '1e0)
508 (while (/= (+ '1e0 x) '1e0) (setq x (/ x 2)))
509 (setq cl-float-epsilon (* x 2))
510 (setq x '1e0)
511 (while (/= (- '1e0 x) '1e0) (setq x (/ x 2)))
512 (setq cl-float-negative-epsilon (* x 2))))
513 nil)
514
515
516 ;;; Sequence functions.
517
518 ;;;###autoload
519 (defun cl-subseq (seq start &optional end)
520 "Return the subsequence of SEQ from START to END.
521 If END is omitted, it defaults to the length of the sequence.
522 If START or END is negative, it counts from the end.
523 Signal an error if START or END are outside of the sequence (i.e
524 too large if positive or too small if negative)."
525 (declare (gv-setter
526 (lambda (new)
527 (macroexp-let2 nil new new
528 `(progn (cl-replace ,seq ,new :start1 ,start :end1 ,end)
529 ,new)))))
530 (cond ((or (stringp seq) (vectorp seq)) (substring seq start end))
531 ((listp seq)
532 (let (len
533 (errtext (format "Bad bounding indices: %s, %s" start end)))
534 (and end (< end 0) (setq end (+ end (setq len (length seq)))))
535 (if (< start 0) (setq start (+ start (or len (setq len (length seq))))))
536 (unless (>= start 0)
537 (error "%s" errtext))
538 (when (> start 0)
539 (setq seq (nthcdr (1- start) seq))
540 (or seq (error "%s" errtext))
541 (setq seq (cdr seq)))
542 (if end
543 (let ((res nil))
544 (while (and (>= (setq end (1- end)) start) seq)
545 (push (pop seq) res))
546 (or (= (1+ end) start) (error "%s" errtext))
547 (nreverse res))
548 (copy-sequence seq))))
549 (t (error "Unsupported sequence: %s" seq))))
550
551 ;;;###autoload
552 (defun cl-concatenate (type &rest sequences)
553 "Concatenate, into a sequence of type TYPE, the argument SEQUENCEs.
554 \n(fn TYPE SEQUENCE...)"
555 (pcase type
556 (`vector (apply #'vconcat sequences))
557 (`string (apply #'concat sequences))
558 (`list (apply #'append (append sequences '(nil))))
559 (_ (error "Not a sequence type name: %S" type))))
560
561 ;;; List functions.
562
563 ;;;###autoload
564 (defun cl-revappend (x y)
565 "Equivalent to (append (reverse X) Y)."
566 (nconc (reverse x) y))
567
568 ;;;###autoload
569 (defun cl-nreconc (x y)
570 "Equivalent to (nconc (nreverse X) Y)."
571 (nconc (nreverse x) y))
572
573 ;;;###autoload
574 (defun cl-list-length (x)
575 "Return the length of list X. Return nil if list is circular."
576 (let ((n 0) (fast x) (slow x))
577 (while (and (cdr fast) (not (and (eq fast slow) (> n 0))))
578 (setq n (+ n 2) fast (cdr (cdr fast)) slow (cdr slow)))
579 (if fast (if (cdr fast) nil (1+ n)) n)))
580
581 ;;;###autoload
582 (defun cl-tailp (sublist list)
583 "Return true if SUBLIST is a tail of LIST."
584 (while (and (consp list) (not (eq sublist list)))
585 (setq list (cdr list)))
586 (if (numberp sublist) (equal sublist list) (eq sublist list)))
587
588 ;;; Property lists.
589
590 ;;;###autoload
591 (defun cl-get (sym tag &optional def)
592 "Return the value of SYMBOL's PROPNAME property, or DEFAULT if none.
593 \n(fn SYMBOL PROPNAME &optional DEFAULT)"
594 (declare (compiler-macro cl--compiler-macro-get)
595 (gv-setter (lambda (store) (ignore def) `(put ,sym ,tag ,store))))
596 (or (get sym tag)
597 (and def
598 ;; Make sure `def' is really absent as opposed to set to nil.
599 (let ((plist (symbol-plist sym)))
600 (while (and plist (not (eq (car plist) tag)))
601 (setq plist (cdr (cdr plist))))
602 (if plist (car (cdr plist)) def)))))
603 (autoload 'cl--compiler-macro-get "cl-macs")
604
605 ;;;###autoload
606 (defun cl-getf (plist tag &optional def)
607 "Search PROPLIST for property PROPNAME; return its value or DEFAULT.
608 PROPLIST is a list of the sort returned by `symbol-plist'.
609 \n(fn PROPLIST PROPNAME &optional DEFAULT)"
610 (declare (gv-expander
611 (lambda (do)
612 (gv-letplace (getter setter) plist
613 (macroexp-let2* nil ((k tag) (d def))
614 (funcall do `(cl-getf ,getter ,k ,d)
615 (lambda (v)
616 (macroexp-let2 nil val v
617 `(progn
618 ,(funcall setter
619 `(cl--set-getf ,getter ,k ,val))
620 ,val)))))))))
621 (setplist '--cl-getf-symbol-- plist)
622 (or (get '--cl-getf-symbol-- tag)
623 ;; Originally we called cl-get here,
624 ;; but that fails, because cl-get has a compiler macro
625 ;; definition that uses getf!
626 (when def
627 ;; Make sure `def' is really absent as opposed to set to nil.
628 (while (and plist (not (eq (car plist) tag)))
629 (setq plist (cdr (cdr plist))))
630 (if plist (car (cdr plist)) def))))
631
632 ;;;###autoload
633 (defun cl--set-getf (plist tag val)
634 (let ((p plist))
635 (while (and p (not (eq (car p) tag))) (setq p (cdr (cdr p))))
636 (if p (progn (setcar (cdr p) val) plist) (cl-list* tag val plist))))
637
638 ;;;###autoload
639 (defun cl--do-remf (plist tag)
640 (let ((p (cdr plist)))
641 (while (and (cdr p) (not (eq (car (cdr p)) tag))) (setq p (cdr (cdr p))))
642 (and (cdr p) (progn (setcdr p (cdr (cdr (cdr p)))) t))))
643
644 ;;;###autoload
645 (defun cl-remprop (sym tag)
646 "Remove from SYMBOL's plist the property PROPNAME and its value.
647 \n(fn SYMBOL PROPNAME)"
648 (let ((plist (symbol-plist sym)))
649 (if (and plist (eq tag (car plist)))
650 (progn (setplist sym (cdr (cdr plist))) t)
651 (cl--do-remf plist tag))))
652
653 ;;; Streams.
654
655 ;;;###autoload
656 (defun cl-fresh-line (&optional stream)
657 "Output a newline unless already at the beginning of a line."
658 (terpri stream 'ensure))
659
660 ;;; Some debugging aids.
661
662 (defun cl-prettyprint (form)
663 "Insert a pretty-printed rendition of a Lisp FORM in current buffer."
664 (let ((pt (point)) last)
665 (insert "\n" (prin1-to-string form) "\n")
666 (setq last (point))
667 (goto-char (1+ pt))
668 (while (search-forward "(quote " last t)
669 (delete-char -7)
670 (insert "'")
671 (forward-sexp)
672 (delete-char 1))
673 (goto-char (1+ pt))
674 (cl--do-prettyprint)))
675
676 (defun cl--do-prettyprint ()
677 (skip-chars-forward " ")
678 (if (looking-at "(")
679 (let ((skip (or (looking-at "((") (looking-at "(prog")
680 (looking-at "(unwind-protect ")
681 (looking-at "(function (")
682 (looking-at "(cl--block-wrapper ")))
683 (two (or (looking-at "(defun ") (looking-at "(defmacro ")))
684 (let (or (looking-at "(let\\*? ") (looking-at "(while ")))
685 (set (looking-at "(p?set[qf] ")))
686 (if (or skip let
687 (progn
688 (forward-sexp)
689 (and (>= (current-column) 78) (progn (backward-sexp) t))))
690 (let ((nl t))
691 (forward-char 1)
692 (cl--do-prettyprint)
693 (or skip (looking-at ")") (cl--do-prettyprint))
694 (or (not two) (looking-at ")") (cl--do-prettyprint))
695 (while (not (looking-at ")"))
696 (if set (setq nl (not nl)))
697 (if nl (insert "\n"))
698 (lisp-indent-line)
699 (cl--do-prettyprint))
700 (forward-char 1))))
701 (forward-sexp)))
702
703 ;;;###autoload
704 (defun cl-prettyexpand (form &optional full)
705 "Expand macros in FORM and insert the pretty-printed result.
706 Optional argument FULL non-nil means to expand all macros,
707 including `cl-block' and `cl-eval-when'."
708 (message "Expanding...")
709 (let ((cl--compiling-file full)
710 (byte-compile-macro-environment nil))
711 (setq form (macroexpand-all form
712 (and (not full) '((cl-block) (cl-eval-when)))))
713 (message "Formatting...")
714 (prog1 (cl-prettyprint form)
715 (message ""))))
716
717 ;;; Integration into the online help system.
718
719 (eval-when-compile (require 'cl-macs)) ;Explicitly, for cl--find-class.
720 (require 'help-mode)
721
722 ;; FIXME: We could go crazy and add another entry so describe-symbol can be
723 ;; used with the slot names of CL structs (and/or EIEIO objects).
724 (add-to-list 'describe-symbol-backends
725 `(nil ,#'cl-find-class ,(lambda (s _b _f) (cl-describe-type s))))
726
727 (defconst cl--typedef-regexp
728 (concat "(" (regexp-opt '("defclass" "defstruct" "cl-defstruct"
729 "cl-deftype" "deftype"))
730 "[ \t\r\n]+%s[ \t\r\n]+"))
731 (with-eval-after-load 'find-func
732 (defvar find-function-regexp-alist)
733 (add-to-list 'find-function-regexp-alist
734 `(define-type . cl--typedef-regexp)))
735
736 (define-button-type 'cl-help-type
737 :supertype 'help-function-def
738 'help-function #'cl-describe-type
739 'help-echo (purecopy "mouse-2, RET: describe this type"))
740
741 (define-button-type 'cl-type-definition
742 :supertype 'help-function-def
743 'help-echo (purecopy "mouse-2, RET: find type definition"))
744
745 (declare-function help-fns-short-filename "help-fns" (filename))
746
747 ;;;###autoload
748 (defun cl-find-class (type) (cl--find-class type))
749
750 ;;;###autoload
751 (defun cl-describe-type (type)
752 "Display the documentation for type TYPE (a symbol)."
753 (interactive
754 (let ((str (completing-read "Describe type: " obarray #'cl-find-class t)))
755 (if (<= (length str) 0)
756 (user-error "Abort!")
757 (list (intern str)))))
758 (help-setup-xref (list #'cl-describe-type type)
759 (called-interactively-p 'interactive))
760 (save-excursion
761 (with-help-window (help-buffer)
762 (with-current-buffer standard-output
763 (let ((class (cl-find-class type)))
764 (if class
765 (cl--describe-class type class)
766 ;; FIXME: Describe other types (the built-in ones, or those from
767 ;; cl-deftype).
768 (user-error "Unknown type %S" type))))
769 (with-current-buffer standard-output
770 ;; Return the text we displayed.
771 (buffer-string)))))
772
773 (defun cl--describe-class (type &optional class)
774 (unless class (setq class (cl--find-class type)))
775 (let ((location (find-lisp-object-file-name type 'define-type))
776 ;; FIXME: Add a `cl-class-of' or `cl-typeof' or somesuch.
777 (metatype (cl--class-name (symbol-value (aref class 0)))))
778 (insert (symbol-name type)
779 (substitute-command-keys " is a type (of kind `"))
780 (help-insert-xref-button (symbol-name metatype)
781 'cl-help-type metatype)
782 (insert (substitute-command-keys "')"))
783 (when location
784 (insert (substitute-command-keys " in `"))
785 (help-insert-xref-button
786 (help-fns-short-filename location)
787 'cl-type-definition type location 'define-type)
788 (insert (substitute-command-keys "'")))
789 (insert ".\n")
790
791 ;; Parents.
792 (let ((pl (cl--class-parents class))
793 cur)
794 (when pl
795 (insert " Inherits from ")
796 (while (setq cur (pop pl))
797 (setq cur (cl--class-name cur))
798 (insert (substitute-command-keys "`"))
799 (help-insert-xref-button (symbol-name cur)
800 'cl-help-type cur)
801 (insert (substitute-command-keys (if pl "', " "'"))))
802 (insert ".\n")))
803
804 ;; Children, if available. ¡For EIEIO!
805 (let ((ch (condition-case nil
806 (cl-struct-slot-value metatype 'children class)
807 (cl-struct-unknown-slot nil)))
808 cur)
809 (when ch
810 (insert " Children ")
811 (while (setq cur (pop ch))
812 (insert (substitute-command-keys "`"))
813 (help-insert-xref-button (symbol-name cur)
814 'cl-help-type cur)
815 (insert (substitute-command-keys (if ch "', " "'"))))
816 (insert ".\n")))
817
818 ;; Type's documentation.
819 (let ((doc (cl--class-docstring class)))
820 (when doc
821 (insert "\n" doc "\n\n")))
822
823 ;; Describe all the slots in this class.
824 (cl--describe-class-slots class)
825
826 ;; Describe all the methods specific to this class.
827 (let ((generics (cl-generic-all-functions type)))
828 (when generics
829 (insert (propertize "Specialized Methods:\n\n" 'face 'bold))
830 (dolist (generic generics)
831 (insert (substitute-command-keys "`"))
832 (help-insert-xref-button (symbol-name generic)
833 'help-function generic)
834 (insert (substitute-command-keys "'"))
835 (pcase-dolist (`(,qualifiers ,args ,doc)
836 (cl--generic-method-documentation generic type))
837 (insert (format " %s%S\n" qualifiers args)
838 (or doc "")))
839 (insert "\n\n"))))))
840
841 (defun cl--describe-class-slot (slot)
842 (insert
843 (concat
844 (propertize "Slot: " 'face 'bold)
845 (prin1-to-string (cl--slot-descriptor-name slot))
846 (unless (eq (cl--slot-descriptor-type slot) t)
847 (concat " type = "
848 (prin1-to-string (cl--slot-descriptor-type slot))))
849 ;; FIXME: The default init form is treated differently for structs and for
850 ;; eieio objects: for structs, the default is nil, for eieio-objects
851 ;; it's a special "unbound" value.
852 (unless nil ;; (eq (cl--slot-descriptor-initform slot) eieio-unbound)
853 (concat " default = "
854 (prin1-to-string (cl--slot-descriptor-initform slot))))
855 (when (alist-get :printer (cl--slot-descriptor-props slot))
856 (concat " printer = "
857 (prin1-to-string
858 (alist-get :printer (cl--slot-descriptor-props slot)))))
859 (when (alist-get :documentation (cl--slot-descriptor-props slot))
860 (concat "\n "
861 (substitute-command-keys
862 (alist-get :documentation (cl--slot-descriptor-props slot)))
863 "\n")))
864 "\n"))
865
866 (defun cl--describe-class-slots (class)
867 "Print help description for the slots in CLASS.
868 Outputs to the current buffer."
869 (let* ((slots (cl--class-slots class))
870 ;; FIXME: Add a `cl-class-of' or `cl-typeof' or somesuch.
871 (metatype (cl--class-name (symbol-value (aref class 0))))
872 ;; ¡For EIEIO!
873 (cslots (condition-case nil
874 (cl-struct-slot-value metatype 'class-slots class)
875 (cl-struct-unknown-slot nil))))
876 (insert (propertize "Instance Allocated Slots:\n\n"
877 'face 'bold))
878 (mapc #'cl--describe-class-slot slots)
879 (when (> (length cslots) 0)
880 (insert (propertize "\nClass Allocated Slots:\n\n" 'face 'bold))
881 (mapc #'cl--describe-class-slot cslots))))
882
883
884 (run-hooks 'cl-extra-load-hook)
885
886 ;; Local variables:
887 ;; byte-compile-dynamic: t
888 ;; generated-autoload-file: "cl-loaddefs.el"
889 ;; End:
890
891 (provide 'cl-extra)
892 ;;; cl-extra.el ends here