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