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