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