1 ;; Common-Lisp extensions for GNU Emacs Lisp.
2 ;; Copyright (C) 1987, 1988, 1989, 1992 Free Software Foundation, Inc.
4 ;; Author: Cesar Quiroz <quiroz@cs.rochester.edu>
5 ;; Keywords: extensions
7 (defvar cl-version "3.0 07-February-1993")
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is distributed in the hope that it will be useful,
12 ;; but WITHOUT ANY WARRANTY. No author or distributor
13 ;; accepts responsibility to anyone for the consequences of using it
14 ;; or for whether it serves any particular purpose or works at all,
15 ;; unless he says so in writing. Refer to the GNU Emacs General Public
16 ;; License for full details.
18 ;; Everyone is granted permission to copy, modify and redistribute
19 ;; GNU Emacs, but only under the conditions described in the
20 ;; GNU Emacs General Public License. A copy of this license is
21 ;; supposed to have been given to you along with GNU Emacs so you
22 ;; can know your rights and responsibilities. It should be in a
23 ;; file named COPYING. Among other things, the copyright notice
24 ;; and this notice must be preserved on all copies.
26 ;;; Notes from Rob Austein on his mods
27 ;; yaya:/usr/u/sra/cl/cl.el, 5-May-1991 16:01:34, sra
29 ;; Slightly hacked copy of cl.el 2.0 beta 27.
31 ;; Various minor performance improvements:
32 ;; a) Don't use MAPCAR when we're going to discard its results.
33 ;; b) Make various macros a little more clever about optimizing
34 ;; generated code in common cases.
35 ;; c) Fix DEFSETF to expand to the right code at compile-time.
36 ;; d) Make various macros cleverer about generating reasonable
37 ;; code when compiled, particularly forms like DEFSTRUCT which
38 ;; are usually used at top-level and thus are only compiled if
39 ;; you use Hallvard Furuseth's hacked bytecomp.el.
41 ;; New features: GETF, REMF, and REMPROP.
44 ;; 1) I'm sceptical about the FBOUNDP checks in SETF. Why should
45 ;; the SETF expansion fail because the SETF method isn't defined
46 ;; at compile time? Lisp is going to check for a binding at run-time
47 ;; anyway, so maybe we should just assume the user's right here.
51 ;;;; These are extensions to Emacs Lisp that provide some form of
52 ;;;; Common Lisp compatibility, beyond what is already built-in
55 ;;;; When developing them, I had the code spread among several files.
56 ;;;; This file 'cl.el' is a concatenation of those original files,
57 ;;;; minus some declarations that became redundant. The marks between
58 ;;;; the original files can be found easily, as they are lines that
59 ;;;; begin with four semicolons (as this does). The names of the
60 ;;;; original parts follow the four semicolons in uppercase, those
61 ;;;; names are GLOBAL, SYMBOLS, LISTS, SEQUENCES, CONDITIONALS,
62 ;;;; ITERATIONS, MULTIPLE VALUES, ARITH, SETF and DEFSTRUCT. If you
63 ;;;; add functions to this file, you might want to put them in a place
64 ;;;; that is compatible with the division above (or invent your own
67 ;;;; To compile this file, make sure you load it first. This is
68 ;;;; because many things are implemented as macros and now that all
69 ;;;; the files are concatenated together one cannot ensure that
70 ;;;; declaration always precedes use.
72 ;;;; Bug reports, suggestions and comments,
73 ;;;; to quiroz@cs.rochester.edu
77 ;;;; This file provides utilities and declarations that are global
78 ;;;; to Common Lisp and so might be used by more than one of the
79 ;;;; other libraries. Especially, I intend to keep here some
80 ;;;; utilities that help parsing/destructuring some difficult calls.
83 ;;;; Cesar Quiroz @ UofR DofCSc - Dec. 1986
84 ;;;; (quiroz@cs.rochester.edu)
86 ;;; Too many pieces of the rest of this package use psetq. So it is unwise to
87 ;;; use here anything but plain Emacs Lisp! There is a neater recursive form
88 ;;; for the algorithm that deals with the bodies.
92 ;;; This version is due to Hallvard Furuseth (hallvard@ifi.uio.no, 6 Jul 91)
93 (defmacro psetq (&rest args)
94 "(psetq {VARIABLE VALUE}...): In parallel, set each VARIABLE to its VALUE.
95 All the VALUEs are evaluated, and then all the VARIABLEs are set.
96 Aside from order of evaluation, this is the same as `setq'."
97 ;; check there is a reasonable number of forms
98 (if (/= (% (length args) 2) 0)
99 (error "Odd number of arguments to `psetq'"))
100 (setq args (copy-sequence args)) ;for safety below
101 (prog1 (cons 'setq args)
102 (while (progn (if (not (symbolp (car args)))
103 (error "`psetq' expected a symbol, found '%s'."
104 (prin1-to-string (car args))))
106 (setcdr args (list (list 'prog1 (nth 1 args)
108 (setq args (cdr (cdr args))))))))))
112 ;;; pair-with-newsyms takes a list and returns a list of lists of the
113 ;;; form (newsym form), such that a let* can then bind the evaluation
114 ;;; of the forms to the newsyms. The idea is to guarantee correct
115 ;;; order of evaluation of the subforms of a setf. It also returns a
116 ;;; list of the newsyms generated, in the corresponding order.
118 (defun pair-with-newsyms (oldforms)
119 "PAIR-WITH-NEWSYMS OLDFORMS
120 The top-level components of the list oldforms are paired with fresh
121 symbols, the pairings list and the newsyms list are returned."
122 (do ((ptr oldforms (cdr ptr))
125 ((endp ptr) (values (nreverse bindings) (nreverse newsyms)))
126 (let ((newsym (gentemp)))
127 (setq bindings (cons (list newsym (car ptr)) bindings))
128 (setq newsyms (cons newsym newsyms)))))
130 (defun zip-lists (evens odds)
131 "Merge two lists EVENS and ODDS, taking elts from each list alternatingly.
132 EVENS and ODDS are two lists. ZIP-LISTS constructs a new list, whose
133 even numbered elements (0,2,...) come from EVENS and whose odd
134 numbered elements (1,3,...) come from ODDS.
135 The construction stops when the shorter list is exhausted."
136 (do* ((p0 evens (cdr p0))
138 (even (car p0) (car p0))
139 (odd (car p1) (car p1))
141 ((or (endp p0) (endp p1))
144 (cons odd (cons even result)))))
146 (defun unzip-list (list)
147 "Extract even and odd elements of LIST into two separate lists.
148 The argument LIST is separated in two strands, the even and the odd
149 numbered elements. Numbering starts with 0, so the first element
150 belongs in EVENS. No check is made that there is an even number of
151 elements to start with."
152 (do* ((ptr list (cddr ptr))
153 (this (car ptr) (car ptr))
154 (next (cadr ptr) (cadr ptr))
158 (values (nreverse evens) (nreverse odds)))
159 (setq evens (cons this evens))
160 (setq odds (cons next odds))))
162 (defun reassemble-argslists (argslists)
163 "(reassemble-argslists ARGSLISTS) => a list of lists
164 ARGSLISTS is a list of sequences. Return a list of lists, the first
165 sublist being all the entries coming from ELT 0 of the original
166 sublists, the next those coming from ELT 1 and so on, until the
167 shortest list is exhausted."
168 (let* ((minlen (apply 'min (mapcar 'length argslists)))
170 (dotimes (i minlen (nreverse result))
171 ;; capture all the elements at index i
173 (cons (mapcar (function (lambda (sublist) (elt sublist i)))
178 ;;; Checking that a list of symbols contains no duplicates is a common
179 ;;; task when checking the legality of some macros. The check for 'eq
180 ;;; pairs can be too expensive, as it is quadratic on the length of
181 ;;; the list. I use a 4-pass, linear, counting approach. It surely
182 ;;; loses on small lists (less than 5 elements?), but should win for
183 ;;; larger lists. The fourth pass could be eliminated.
184 ;;; 10 dec 1986. Emacs Lisp has no REMPROP, so I just eliminated the
187 ;;; [22 April 1991, sra] REMPROP now in library, so restored 4th pass.
188 (defun duplicate-symbols-p (list)
189 "Find all symbols appearing more than once in LIST.
190 Return a list of all such duplicates; `nil' if there are no duplicates."
191 (let ((duplicates '()) ;result built here
192 (propname (gensym)) ;we use a fresh property
195 (unless (and (listp list)
196 (every 'symbolp list))
197 (error "a list of symbols is needed"))
203 (put x propname (1+ (get x propname))))
206 (if (> (get x propname) 1)
207 (setq duplicates (cons x duplicates))))
210 (remprop x propname))
214 ;;;; end of cl-global.el
217 ;;;; This file provides the gentemp function, which generates fresh
218 ;;;; symbols, plus some other minor Common Lisp symbol tools.
220 ;;;; Cesar Quiroz @ UofR DofCSc - Dec. 1986
221 ;;;; (quiroz@cs.rochester.edu)
223 ;;; Keywords. There are no packages in Emacs Lisp, so this is only a
224 ;;; kludge around to let things be "as if" a keyword package was around.
226 (defmacro defkeyword (x &optional docstring)
227 "Make symbol X a keyword (symbol whose value is itself).
228 Optional second argument is a documentation string for it."
230 (list 'defconst x (list 'quote x) docstring))
232 (error "`%s' is not a symbol" (prin1-to-string x)))))
234 (defun keywordp (sym)
235 "t if SYM is a keyword."
236 (if (and (symbolp sym) (char-equal (aref (symbol-name sym) 0) ?\:))
237 ;; looks like one, make sure value is right
241 (defun keyword-of (sym)
242 "Return a keyword that is naturally associated with symbol SYM.
243 If SYM is keyword, the value is SYM.
244 Otherwise it is a keyword whose name is `:' followed by SYM's name."
245 (cond ((keywordp sym)
248 (let ((newsym (intern (concat ":" (symbol-name sym)))))
249 (set newsym newsym)))
251 (error "expected a symbol, not `%s'" (prin1-to-string sym)))))
253 ;;; Temporary symbols.
256 (defvar *gentemp-index* 0
257 "Integer used by gentemp to produce new names.")
259 (defvar *gentemp-prefix* "T$$_"
260 "Names generated by gentemp begin with this string by default.")
262 (defun gentemp (&optional prefix oblist)
263 "Generate a fresh interned symbol.
264 There are 2 optional arguments, PREFIX and OBLIST. PREFIX is the
265 string that begins the new name, OBLIST is the obarray used to search for
266 old names. The defaults are just right, YOU SHOULD NEVER NEED THESE
267 ARGUMENTS IN YOUR OWN CODE."
269 (setq prefix *gentemp-prefix*))
271 (setq oblist obarray)) ;default for the intern functions
272 (let ((newsymbol nil)
274 (while (not newsymbol)
275 (setq newname (concat prefix *gentemp-index*))
276 (setq *gentemp-index* (+ *gentemp-index* 1))
277 (if (not (intern-soft newname oblist))
278 (setq newsymbol (intern newname oblist))))
281 (defvar *gensym-index* 0
282 "Integer used by gensym to produce new names.")
284 (defvar *gensym-prefix* "G$$_"
285 "Names generated by gensym begin with this string by default.")
287 (defun gensym (&optional prefix)
288 "Generate a fresh uninterned symbol.
289 There is an optional argument, PREFIX. PREFIX is the
290 string that begins the new name. Most people take just the default,
291 except when debugging needs suggest otherwise."
293 (setq prefix *gensym-prefix*))
294 (let ((newsymbol nil)
296 (while (not newsymbol)
297 (setq newname (concat prefix *gensym-index*))
298 (setq *gensym-index* (+ *gensym-index* 1))
299 (if (not (intern-soft newname))
300 (setq newsymbol (make-symbol newname))))
303 ;;;; end of cl-symbols.el
306 ;;;; This file provides some of the conditional constructs of
307 ;;;; Common Lisp. Total compatibility is again impossible, as the
308 ;;;; 'if' form is different in both languages, so only a good
309 ;;;; approximation is desired.
311 ;;;; Cesar Quiroz @ UofR DofCSc - Dec. 1986
312 ;;;; (quiroz@cs.rochester.edu)
315 (put 'case 'lisp-indent-hook 1)
316 (put 'ecase 'lisp-indent-hook 1)
317 (put 'when 'lisp-indent-hook 1)
318 (put 'unless 'lisp-indent-hook 1)
321 ;;; These two forms are simplified ifs, with a single branch.
323 (defmacro when (condition &rest body)
324 "(when CONDITION . BODY) => evaluate BODY if CONDITION is true."
325 (list* 'if (list 'not condition) '() body))
327 (defmacro unless (condition &rest body)
328 "(unless CONDITION . BODY) => evaluate BODY if CONDITION is false."
329 (list* 'if condition '() body))
332 ;;; CASE selects among several clauses, based on the value (evaluated)
333 ;;; of a expression and a list of (unevaluated) key values. ECASE is
334 ;;; the same, but signals an error if no clause is activated.
336 (defmacro case (expr &rest cases)
337 "(case EXPR . CASES) => evals EXPR, chooses from CASES on that value.
339 CASES -> list of clauses, non empty
340 CLAUSE -> HEAD . BODY
341 HEAD -> t = catch all, must be last clause
342 -> otherwise = same as t
344 -> atom = activated if (eql EXPR HEAD)
345 -> list of atoms = activated if (memq EXPR HEAD)
346 BODY -> list of forms, implicit PROGN is built around it.
347 EXPR is evaluated only once."
348 (let* ((newsym (gentemp))
349 (clauses (case-clausify cases newsym)))
350 ;; convert case into a cond inside a let
352 (list (list newsym expr))
353 (list* 'cond (nreverse clauses)))))
355 (defmacro ecase (expr &rest cases)
356 "(ecase EXPR . CASES) => like `case', but error if no case fits.
357 `t'-clauses are not allowed."
358 (let* ((newsym (gentemp))
359 (clauses (case-clausify cases newsym)))
360 ;; check that no 't clause is present.
361 ;; case-clausify would put one such at the beginning of clauses
362 (if (eq (caar clauses) t)
363 (error "no clause-head should be `t' or `otherwise' for `ecase'"))
364 ;; insert error-catching clause
367 (list 't (list 'error
368 "ecase on %s = %s failed to take any branch"
370 (list 'prin1-to-string newsym)))
372 ;; generate code as usual
374 (list (list newsym expr))
375 (list* 'cond (nreverse clauses)))))
378 (defun case-clausify (cases newsym)
379 "CASE-CLAUSIFY CASES NEWSYM => clauses for a 'cond'
380 Converts the CASES of a [e]case macro into cond clauses to be
381 evaluated inside a let that binds NEWSYM. Returns the clauses in
383 (do* ((currentpos cases (cdr currentpos))
384 (nextpos (cdr cases) (cdr nextpos))
385 (curclause (car cases) (car currentpos))
387 ((endp currentpos) result)
388 (let ((head (car curclause))
389 (body (cdr curclause)))
390 ;; construct a cond-clause according to the head
392 (error "case clauses cannot have null heads: `%s'"
393 (prin1-to-string curclause)))
395 (eq head 'otherwise))
396 ;; check it is the last clause
397 (if (not (endp nextpos))
398 (error "clause with `t' or `otherwise' head must be last"))
399 ;; accept this clause as a 't' for cond
400 (setq result (cons (cons 't body) result)))
403 (cons (cons (list 'eql newsym (list 'quote head)) body)
407 (cons (cons (list 'memq newsym (list 'quote head)) body)
410 ;; catch-all for this parser
411 (error "don't know how to parse case clause `%s'"
412 (prin1-to-string head)))))))
414 ;;;; end of cl-conditionals.el
417 ;;;; This file provides simple iterative macros (a la Common Lisp)
418 ;;;; constructed on the basis of let, let* and while, which are the
419 ;;;; primitive binding/iteration constructs of Emacs Lisp
421 ;;;; The Common Lisp iterations use to have a block named nil
422 ;;;; wrapped around them, and allow declarations at the beginning
423 ;;;; of their bodies and you can return a value using (return ...).
424 ;;;; Nothing of the sort exists in Emacs Lisp, so I haven't tried
425 ;;;; to imitate these behaviors.
427 ;;;; Other than the above, the semantics of Common Lisp are
428 ;;;; correctly reproduced to the extent this was reasonable.
430 ;;;; Cesar Quiroz @ UofR DofCSc - Dec. 1986
431 ;;;; (quiroz@cs.rochester.edu)
433 ;;; some lisp-indentation information
434 (put 'do 'lisp-indent-hook 2)
435 (put 'do* 'lisp-indent-hook 2)
436 (put 'dolist 'lisp-indent-hook 1)
437 (put 'dotimes 'lisp-indent-hook 1)
438 (put 'do-symbols 'lisp-indent-hook 1)
439 (put 'do-all-symbols 'lisp-indent-hook 1)
442 (defmacro do (stepforms endforms &rest body)
443 "(do STEPFORMS ENDFORMS . BODY): Iterate BODY, stepping some local variables.
444 STEPFORMS must be a list of symbols or lists. In the second case, the
445 lists must start with a symbol and contain up to two more forms. In
446 the STEPFORMS, a symbol is the same as a (symbol). The other 2 forms
447 are the initial value (def. NIL) and the form to step (def. itself).
448 The values used by initialization and stepping are computed in parallel.
449 The ENDFORMS are a list (CONDITION . ENDBODY). If the CONDITION
450 evaluates to true in any iteration, ENDBODY is evaluated and the last
451 form in it is returned.
452 The BODY (which may be empty) is evaluated at every iteration, with
453 the symbols of the STEPFORMS bound to the initial or stepped values."
454 ;; check the syntax of the macro
455 (and (check-do-stepforms stepforms)
456 (check-do-endforms endforms))
457 ;; construct emacs-lisp equivalent
458 (let ((initlist (extract-do-inits stepforms))
459 (steplist (extract-do-steps stepforms))
460 (endcond (car endforms))
461 (endbody (cdr endforms)))
462 (cons 'let (cons initlist
463 (cons (cons 'while (cons (list 'not endcond)
464 (append body steplist)))
465 (append endbody))))))
468 (defmacro do* (stepforms endforms &rest body)
469 "`do*' is to `do' as `let*' is to `let'.
470 STEPFORMS must be a list of symbols or lists. In the second case, the
471 lists must start with a symbol and contain up to two more forms. In
472 the STEPFORMS, a symbol is the same as a (symbol). The other 2 forms
473 are the initial value (def. NIL) and the form to step (def. itself).
474 Initializations and steppings are done in the sequence they are written.
475 The ENDFORMS are a list (CONDITION . ENDBODY). If the CONDITION
476 evaluates to true in any iteration, ENDBODY is evaluated and the last
477 form in it is returned.
478 The BODY (which may be empty) is evaluated at every iteration, with
479 the symbols of the STEPFORMS bound to the initial or stepped values."
480 ;; check the syntax of the macro
481 (and (check-do-stepforms stepforms)
482 (check-do-endforms endforms))
483 ;; construct emacs-lisp equivalent
484 (let ((initlist (extract-do-inits stepforms))
485 (steplist (extract-do*-steps stepforms))
486 (endcond (car endforms))
487 (endbody (cdr endforms)))
488 (cons 'let* (cons initlist
489 (cons (cons 'while (cons (list 'not endcond)
490 (append body steplist)))
491 (append endbody))))))
494 ;;; DO and DO* share the syntax checking functions that follow.
496 (defun check-do-stepforms (forms)
497 "True if FORMS is a valid stepforms for the do[*] macro (q.v.)"
499 (error "init/step form for do[*] should be a list, not `%s'"
500 (prin1-to-string forms))
504 (if (not (or (symbolp entry)
506 (symbolp (car entry))
507 (< (length entry) 4))))
508 (error "init/step must be %s, not `%s'"
509 "symbol or (symbol [init [step]])"
510 (prin1-to-string entry)))))
513 (defun check-do-endforms (forms)
514 "True if FORMS is a valid endforms for the do[*] macro (q.v.)"
516 (error "termination form for do macro should be a list, not `%s'"
517 (prin1-to-string forms))))
519 (defun extract-do-inits (forms)
520 "Returns a list of the initializations (for do) in FORMS
521 --a stepforms, see the do macro--. FORMS is assumed syntactically valid."
525 (cond ((symbolp entry)
528 (list (car entry) (cadr entry))))))
531 ;;; There used to be a reason to deal with DO differently than with
532 ;;; DO*. The writing of PSETQ has made it largely unnecessary.
534 (defun extract-do-steps (forms)
535 "EXTRACT-DO-STEPS FORMS => an s-expr
536 FORMS is the stepforms part of a DO macro (q.v.). This function
537 constructs an s-expression that does the stepping at the end of an
539 (list (cons 'psetq (select-stepping-forms forms))))
541 (defun extract-do*-steps (forms)
542 "EXTRACT-DO*-STEPS FORMS => an s-expr
543 FORMS is the stepforms part of a DO* macro (q.v.). This function
544 constructs an s-expression that does the stepping at the end of an
546 (list (cons 'setq (select-stepping-forms forms))))
548 (defun select-stepping-forms (forms)
549 "Separate only the forms that cause stepping."
550 (let ((result '()) ;ends up being (... var form ...)
551 (ptr forms) ;to traverse the forms
552 entry ;to explore each form in turn
554 (while ptr ;(not (endp entry)) might be safer
555 (setq entry (car ptr))
556 (cond ((and (listp entry) (= (length entry) 3))
557 (setq result (append ;append in reverse order!
558 (list (caddr entry) (car entry))
560 (setq ptr (cdr ptr))) ;step in the list of forms
563 ;;; Other iterative constructs
565 (defmacro dolist (stepform &rest body)
566 "(dolist (VAR LIST [RESULTFORM]) . BODY): do BODY for each elt of LIST.
567 The RESULTFORM defaults to nil. The VAR is bound to successive
568 elements of the value of LIST and remains bound (to the nil value) when the
569 RESULTFORM is evaluated."
573 (error "stepform for `dolist' should be (VAR LIST [RESULT]), not `%s'"
574 (prin1-to-string stepform)))
575 ((not (symbolp (car stepform)))
576 (error "first component of stepform should be a symbol, not `%s'"
577 (prin1-to-string (car stepform))))
578 ((> (length stepform) 3)
579 (error "too many components in stepform `%s'"
580 (prin1-to-string stepform))))
582 (let* ((var (car stepform))
583 (listform (cadr stepform))
584 (resultform (caddr stepform))
587 (list 'let (list var (list listsym listform))
591 var (list 'car listsym)
592 listsym (list 'cdr listsym)))
595 (cons (list 'setq var nil)
596 (list resultform))))))
598 (defmacro dotimes (stepform &rest body)
599 "(dotimes (VAR COUNTFORM [RESULTFORM]) . BODY): Repeat BODY, counting in VAR.
600 The COUNTFORM should return a positive integer. The VAR is bound to
601 successive integers from 0 to COUNTFORM-1 and the BODY is repeated for
602 each of them. At the end, the RESULTFORM is evaluated and its value
603 returned. During this last evaluation, the VAR is still bound, and its
604 value is the number of times the iteration occurred. An omitted RESULTFORM
609 (error "stepform for `dotimes' should be (VAR COUNT [RESULT]), not `%s'"
610 (prin1-to-string stepform)))
611 ((not (symbolp (car stepform)))
612 (error "first component of stepform should be a symbol, not `%s'"
613 (prin1-to-string (car stepform))))
614 ((> (length stepform) 3)
615 (error "too many components in stepform `%s'"
616 (prin1-to-string stepform))))
618 (let* ((var (car stepform))
619 (countform (cadr stepform))
620 (resultform (caddr stepform))
621 (testsym (if (consp countform) (gentemp) countform)))
624 'let (cons (list var -1)
625 (and (not (eq countform testsym))
626 (list (list testsym countform))))
628 (list 'while (list '< (list 'setq var (list '1+ var)) testsym))
630 (and resultform (list resultform)))))
632 (defmacro do-symbols (stepform &rest body)
633 "(do_symbols (VAR [OBARRAY [RESULTFORM]]) . BODY)
634 The VAR is bound to each of the symbols in OBARRAY (def. obarray) and
635 the BODY is repeatedly performed for each of those bindings. At the
636 end, RESULTFORM (def. nil) is evaluated and its value returned.
637 During this last evaluation, the VAR is still bound and its value is nil.
638 See also the function `mapatoms'."
642 (error "stepform for `do-symbols' should be (VAR OBARRAY [RESULT]), not `%s'"
643 (prin1-to-string stepform)))
644 ((not (symbolp (car stepform)))
645 (error "first component of stepform should be a symbol, not `%s'"
646 (prin1-to-string (car stepform))))
647 ((> (length stepform) 3)
648 (error "too many components in stepform `%s'"
649 (prin1-to-string stepform))))
651 (let* ((var (car stepform))
652 (oblist (cadr stepform))
653 (resultform (caddr stepform)))
657 (cons 'lambda (cons (list var) body)))
660 (list (list var nil))
664 (defmacro do-all-symbols (stepform &rest body)
665 "(do-all-symbols (VAR [RESULTFORM]) . BODY)
666 Is the same as (do-symbols (VAR obarray RESULTFORM) . BODY)."
669 (list (car stepform) 'obarray (cadr stepform))
672 (defmacro loop (&rest body)
673 "(loop . BODY) repeats BODY indefinitely and does not return.
674 Normally BODY uses `throw' or `signal' to cause an exit.
675 The forms in BODY should be lists, as non-lists are reserved for new features."
676 ;; check that the body doesn't have atomic forms
678 (error "body of `loop' should be a list of lists or nil")
679 ;; ok, it is a list, check for atomic components
681 (function (lambda (component)
682 (if (nlistp component)
683 (error "components of `loop' should be lists"))))
685 ;; build the infinite loop
686 (cons 'while (cons 't body))))
688 ;;;; end of cl-iterations.el
691 ;;;; This file provides some of the lists machinery of Common-Lisp
692 ;;;; in a way compatible with Emacs Lisp. Especially, see the the
693 ;;;; typical c[ad]*r functions.
695 ;;;; Cesar Quiroz @ UofR DofCSc - Dec. 1986
696 ;;;; (quiroz@cs.rochester.edu)
698 ;;; Synonyms for list functions
704 "Return the second element of the list LIST."
708 "Return the third element of the list LIST."
712 "Return the fourth element of the list LIST."
716 "Return the fifth element of the list LIST."
720 "Return the sixth element of the list LIST."
723 (defsubst seventh (x)
724 "Return the seventh element of the list LIST."
728 "Return the eighth element of the list LIST."
732 "Return the ninth element of the list LIST."
736 "Return the tenth element of the list LIST."
744 "t if X is nil, nil if X is a cons; error otherwise."
747 (error "endp received a non-cons, non-null argument `%s'"
748 (prin1-to-string x))))
751 "Returns the last link in the list LIST."
753 (error "arg to `last' must be a list"))
754 (do ((current-cons x (cdr current-cons))
755 (next-cons (cdr x) (cdr next-cons)))
756 ((endp next-cons) current-cons)))
758 (defun list-length (x) ;taken from CLtL sect. 15.2
759 "Returns the length of a non-circular list, or `nil' for a circular one."
761 (fast x (cddr fast)) ;fast pointer, leaps by 2
762 (slow x (cdr slow)) ;slow pointer, leaps by 1
763 (ready nil)) ;indicates termination
766 (setq ready t)) ;return n
769 (setq ready t)) ;return n+1
770 ((and (eq fast slow) (> n 0))
772 (setq ready t)) ;return nil
774 (setq n (+ n 2)))))) ;just advance counter
776 (defun butlast (list &optional n)
777 "Return a new list like LIST but sans the last N elements.
778 N defaults to 1. If the list doesn't have N elements, nil is returned."
779 (if (null n) (setq n 1))
780 (nreverse (nthcdr n (reverse list)))) ;optim. due to macrakis@osf.org
782 ;;; This version due to Aaron Larson (alarson@src.honeywell.com, 26 Jul 91)
783 (defun list* (arg &rest others)
784 "Return a new list containing the first arguments consed onto the last arg.
785 Thus, (list* 1 2 3 '(a b)) returns (1 2 3 a b)."
788 (let* ((others (cons arg (copy-sequence others)))
792 (setcdr a (car (cdr a)))
795 (defun adjoin (item list)
796 "Return a list which contains ITEM but is otherwise like LIST.
797 If ITEM occurs in LIST, the value is LIST. Otherwise it is (cons ITEM LIST).
798 When comparing ITEM against elements, `eql' is used."
803 (defun ldiff (list sublist)
804 "Return a new list like LIST but sans SUBLIST.
805 SUBLIST must be one of the links in LIST; otherwise the value is LIST itself."
807 (curcons list (cdr curcons)))
808 ((or (endp curcons) (eq curcons sublist))
810 (setq result (cons (car curcons) result))))
812 ;;; The popular c[ad]*r functions and other list accessors.
814 ;;; To implement this efficiently, a new byte compile handler is used to
815 ;;; generate the minimal code, saving one function call.
818 "Return the car of the car of X."
822 "Return the car of the cdr of X."
826 "Return the cdr of the car of X."
830 "Return the cdr of the cdr of X."
834 "Return the car of the car of the car of X."
838 "Return the car of the car of the cdr of X."
842 "Return the car of the cdr of the car of X."
846 "Return the cdr of the car of the car of X."
850 "Return the car of the cdr of the cdr of X."
854 "Return the cdr of the car of the cdr of X."
858 "Return the cdr of the cdr of the car of X."
862 "Return the cdr of the cdr of the cdr of X."
866 "Return the car of the car of the car of the car of X."
867 (car (car (car (car X)))))
870 "Return the car of the car of the car of the cdr of X."
871 (car (car (car (cdr X)))))
874 "Return the car of the car of the cdr of the car of X."
875 (car (car (cdr (car X)))))
878 "Return the car of the cdr of the car of the car of X."
879 (car (cdr (car (car X)))))
882 "Return the cdr of the car of the car of the car of X."
883 (cdr (car (car (car X)))))
886 "Return the car of the car of the cdr of the cdr of X."
887 (car (car (cdr (cdr X)))))
890 "Return the car of the cdr of the car of the cdr of X."
891 (car (cdr (car (cdr X)))))
894 "Return the cdr of the car of the car of the cdr of X."
895 (cdr (car (car (cdr X)))))
898 "Return the car of the cdr of the cdr of the car of X."
899 (car (cdr (cdr (car X)))))
902 "Return the cdr of the car of the cdr of the car of X."
903 (cdr (car (cdr (car X)))))
906 "Return the cdr of the cdr of the car of the car of X."
907 (cdr (cdr (car (car X)))))
910 "Return the car of the cdr of the cdr of the cdr of X."
911 (car (cdr (cdr (cdr X)))))
914 "Return the cdr of the cdr of the car of the cdr of X."
915 (cdr (cdr (car (cdr X)))))
918 "Return the cdr of the car of the cdr of the cdr of X."
919 (cdr (car (cdr (cdr X)))))
922 "Return the cdr of the cdr of the cdr of the car of X."
923 (cdr (cdr (cdr (car X)))))
926 "Return the cdr of the cdr of the cdr of the cdr of X."
927 (cdr (cdr (cdr (cdr X)))))
929 ;;; some inverses of the accessors are needed for setf purposes
931 (defsubst setnth (n list newval)
932 "Set (nth N LIST) to NEWVAL. Returns NEWVAL."
933 (rplaca (nthcdr n list) newval))
935 (defun setnthcdr (n list newval)
936 "(setnthcdr N LIST NEWVAL) => NEWVAL
937 As a side effect, sets the Nth cdr of LIST to NEWVAL."
939 (error "N must be 0 or greater, not %d" n))
941 (setq list (cdr list)
943 ;; here only if (zerop n)
944 (rplaca list (car newval))
945 (rplacd list (cdr newval))
948 ;;; A-lists machinery
950 (defsubst acons (key item alist)
951 "Return a new alist with KEY paired with ITEM; otherwise like ALIST.
952 Does not copy ALIST."
953 (cons (cons key item) alist))
955 (defun pairlis (keys data &optional alist)
956 "Return a new alist with each elt of KEYS paired with an elt of DATA;
957 optional 3rd arg ALIST is nconc'd at the end. KEYS and DATA must
958 have the same length."
959 (unless (= (length keys) (length data))
960 (error "keys and data should be the same length"))
961 (do* ;;collect keys and data in front of alist
962 ((kptr keys (cdr kptr)) ;traverses the keys
963 (dptr data (cdr dptr)) ;traverses the data
964 (key (car kptr) (car kptr)) ;current key
965 (item (car dptr) (car dptr)) ;current data item
968 (setq result (acons key item result))))
970 ;;;; end of cl-lists.el
973 ;;;; Emacs Lisp provides many of the 'sequences' functionality of
974 ;;;; Common Lisp. This file provides a few things that were left out.
978 (defkeyword :test "Used to designate positive (selection) tests.")
979 (defkeyword :test-not "Used to designate negative (rejection) tests.")
980 (defkeyword :key "Used to designate component extractions.")
981 (defkeyword :predicate "Used to define matching of sequence components.")
982 (defkeyword :start "Inclusive low index in sequence")
983 (defkeyword :end "Exclusive high index in sequence")
984 (defkeyword :start1 "Inclusive low index in first of two sequences.")
985 (defkeyword :start2 "Inclusive low index in second of two sequences.")
986 (defkeyword :end1 "Exclusive high index in first of two sequences.")
987 (defkeyword :end2 "Exclusive high index in second of two sequences.")
988 (defkeyword :count "Number of elements to affect.")
989 (defkeyword :from-end "T when counting backwards.")
990 (defkeyword :initial-value "For the syntax of #'reduce")
992 (defun some (pred seq &rest moreseqs)
993 "Test PREDICATE on each element of SEQUENCE; is it ever non-nil?
994 Extra args are additional sequences; PREDICATE gets one arg from each
995 sequence and we advance down all the sequences together in lock-step.
996 A sequence means either a list or a vector."
997 (let ((args (reassemble-argslists (list* seq moreseqs))))
998 (do* ((ready nil) ;flag: return when t
999 (result nil) ;resulting value
1000 (applyval nil) ;result of applying pred once
1002 (cdr remaining)) ;remaining argument sets
1003 (current (car remaining) ;current argument set
1005 ((or ready (endp remaining)) result)
1006 (setq applyval (apply pred current))
1009 (setq result applyval)))))
1011 (defun every (pred seq &rest moreseqs)
1012 "Test PREDICATE on each element of SEQUENCE; is it always non-nil?
1013 Extra args are additional sequences; PREDICATE gets one arg from each
1014 sequence and we advance down all the sequences together in lock-step.
1015 A sequence means either a list or a vector."
1016 (let ((args (reassemble-argslists (list* seq moreseqs))))
1017 (do* ((ready nil) ;flag: return when t
1018 (result t) ;resulting value
1019 (applyval nil) ;result of applying pred once
1021 (cdr remaining)) ;remaining argument sets
1022 (current (car remaining) ;current argument set
1024 ((or ready (endp remaining)) result)
1025 (setq applyval (apply pred current))
1028 (setq result nil)))))
1030 (defun notany (pred seq &rest moreseqs)
1031 "Test PREDICATE on each element of SEQUENCE; is it always nil?
1032 Extra args are additional sequences; PREDICATE gets one arg from each
1033 sequence and we advance down all the sequences together in lock-step.
1034 A sequence means either a list or a vector."
1035 (let ((args (reassemble-argslists (list* seq moreseqs))))
1036 (do* ((ready nil) ;flag: return when t
1037 (result t) ;resulting value
1038 (applyval nil) ;result of applying pred once
1040 (cdr remaining)) ;remaining argument sets
1041 (current (car remaining) ;current argument set
1043 ((or ready (endp remaining)) result)
1044 (setq applyval (apply pred current))
1047 (setq result nil)))))
1049 (defun notevery (pred seq &rest moreseqs)
1050 "Test PREDICATE on each element of SEQUENCE; is it sometimes nil?
1051 Extra args are additional sequences; PREDICATE gets one arg from each
1052 sequence and we advance down all the sequences together in lock-step.
1053 A sequence means either a list or a vector."
1054 (let ((args (reassemble-argslists (list* seq moreseqs))))
1055 (do* ((ready nil) ;flag: return when t
1056 (result nil) ;resulting value
1057 (applyval nil) ;result of applying pred once
1059 (cdr remaining)) ;remaining argument sets
1060 (current (car remaining) ;current argument set
1062 ((or ready (endp remaining)) result)
1063 (setq applyval (apply pred current))
1068 ;;; More sequence functions that don't need keyword arguments
1070 (defun concatenate (type &rest sequences)
1071 "(concatenate TYPE &rest SEQUENCES) => a sequence
1072 The sequence returned is of type TYPE (must be 'list, 'string, or 'vector) and
1073 contains the concatenation of the elements of all the arguments, in the order
1075 (let ((sequences (append sequences '(()))))
1078 (apply (function append) sequences))
1080 (apply (function concat) sequences))
1082 (apply (function vector) (apply (function append) sequences)))
1084 (error "type for concatenate `%s' not 'list, 'string or 'vector"
1085 (prin1-to-string type))))))
1087 (defun map (type function &rest sequences)
1088 "(map TYPE FUNCTION &rest SEQUENCES) => a sequence
1089 The FUNCTION is called on each set of elements from the SEQUENCES \(stopping
1090 when the shortest sequence is terminated\) and the results are possibly
1091 returned in a sequence of type TYPE \(one of 'list, 'vector, 'string, or nil\)
1092 giving NIL for TYPE gets rid of the values."
1093 (if (not (memq type (list 'list 'string 'vector nil)))
1094 (error "type for map `%s' not 'list, 'string, 'vector or nil"
1095 (prin1-to-string type)))
1096 (let ((argslists (reassemble-argslists sequences))
1099 (while argslists ;don't bother accumulating
1100 (apply function (car argslists))
1101 (setq argslists (cdr argslists)))
1102 (setq results (mapcar (function (lambda (args) (apply function args)))
1108 (funcall (function concat) results))
1110 (apply (function vector) results))))))
1112 ;;; an inverse of elt is needed for setf purposes
1114 (defun setelt (seq n newval)
1115 "In SEQUENCE, set the Nth element to NEWVAL. Returns NEWVAL.
1116 A sequence means either a list or a vector."
1117 (let ((l (length seq)))
1118 (if (or (< n 0) (>= n l))
1119 (error "N(%d) should be between 0 and %d" n l)
1120 ;; only two cases need be considered valid, as strings are arrays
1122 (setnth n seq newval))
1124 (aset seq n newval))
1126 (error "SEQ should be a sequence, not `%s'"
1127 (prin1-to-string seq)))))))
1129 ;;; Testing with keyword arguments.
1131 ;;; Many of the sequence functions use keywords to denote some stylized
1132 ;;; form of selecting entries in a sequence. The involved arguments
1133 ;;; are collected with a &rest marker (as Emacs Lisp doesn't have a &key
1134 ;;; marker), then they are passed to build-klist, who
1135 ;;; constructs an association list. That association list is used to
1136 ;;; test for satisfaction and matching.
1138 ;;; DON'T USE MEMBER, NOR ANY FUNCTION THAT COULD TAKE KEYWORDS HERE!!!
1140 (defun build-klist (argslist acceptable &optional allow-other-keys)
1141 "Decode a keyword argument list ARGSLIST for keywords in ACCEPTABLE.
1142 ARGSLIST is a list, presumably the &rest argument of a call, whose
1143 even numbered elements must be keywords.
1144 ACCEPTABLE is a list of keywords, the only ones that are truly acceptable.
1145 The result is an alist containing the arguments named by the keywords
1146 in ACCEPTABLE, or an error is signalled, if something failed.
1147 If the third argument (an optional) is non-nil, other keys are acceptable."
1148 ;; check legality of the arguments, then destructure them
1149 (unless (and (listp argslist)
1150 (evenp (length argslist)))
1151 (error "build-klist: odd number of keyword-args"))
1152 (unless (and (listp acceptable)
1153 (every 'keywordp acceptable))
1154 (error "build-klist: second arg should be a list of keywords"))
1155 (multiple-value-bind
1157 (unzip-list argslist)
1158 (unless (every 'keywordp keywords)
1159 (error "build-klist: expected keywords, found `%s'"
1160 (prin1-to-string keywords)))
1161 (unless (or allow-other-keys
1162 (every (function (lambda (keyword)
1163 (memq keyword acceptable)))
1165 (error "bad keyword[s]: %s not in %s"
1166 (prin1-to-string (mapcan (function (lambda (keyword)
1167 (if (memq keyword acceptable)
1171 (prin1-to-string acceptable)))
1172 (do* ;;pick up the pieces
1173 ((auxlist ;auxiliary a-list, may
1174 (pairlis keywords forms)) ;contain repetitions and junk
1175 (ptr acceptable (cdr ptr)) ;pointer in acceptable
1176 (this (car ptr) (car ptr)) ;current acceptable keyword
1177 (auxval nil) ;used to move values around
1178 (alist '())) ;used to build the result
1180 ;; if THIS appears in auxlist, use its value
1181 (when (setq auxval (assq this auxlist))
1182 (setq alist (cons auxval alist))))))
1185 (defun extract-from-klist (klist key &optional default)
1186 "(extract-from-klist KLIST KEY [DEFAULT]) => value of KEY or DEFAULT
1187 Extract value associated with KEY in KLIST (return DEFAULT if nil)."
1188 (let ((retrieved (cdr (assq key klist))))
1189 (or retrieved default)))
1191 (defun keyword-argument-supplied-p (klist key)
1192 "(keyword-argument-supplied-p KLIST KEY) => nil or something
1193 NIL if KEY (a keyword) does not appear in the KLIST."
1196 (defun add-to-klist (key item klist)
1197 "(ADD-TO-KLIST KEY ITEM KLIST) => new KLIST
1198 Add association (KEY . ITEM) to KLIST."
1199 (setq klist (acons key item klist)))
1201 (defun elt-satisfies-test-p (item elt klist)
1202 "(elt-satisfies-test-p ITEM ELT KLIST) => t or nil
1203 KLIST encodes a keyword-arguments test, as in CH. 14 of CLtL.
1204 True if the given ITEM and ELT satisfy the test."
1205 (let ((test (extract-from-klist klist :test))
1206 (test-not (extract-from-klist klist :test-not))
1207 (keyfn (extract-from-klist klist :key 'identity)))
1209 (funcall test item (funcall keyfn elt)))
1211 (not (funcall test-not item (funcall keyfn elt))))
1212 (t ;should never happen
1213 (error "neither :test nor :test-not in `%s'"
1214 (prin1-to-string klist))))))
1216 (defun elt-satisfies-if-p (item klist)
1217 "(elt-satisfies-if-p ITEM KLIST) => t or nil
1218 True if an -if style function was called and ITEM satisfies the
1219 predicate under :predicate in KLIST."
1220 (let ((predicate (extract-from-klist klist :predicate))
1221 (keyfn (extract-from-klist klist :key 'identity)))
1222 (funcall predicate (funcall keyfn item))))
1224 (defun elt-satisfies-if-not-p (item klist)
1225 "(elt-satisfies-if-not-p ITEM KLIST) => t or nil
1226 KLIST encodes a keyword-arguments test, as in CH. 14 of CLtL.
1227 True if an -if-not style function was called and ITEM does not satisfy
1228 the predicate under :predicate in KLIST."
1229 (let ((predicate (extract-from-klist klist :predicate))
1230 (keyfn (extract-from-klist klist :key 'identity)))
1231 (not (funcall predicate (funcall keyfn item)))))
1233 (defun elts-match-under-klist-p (e1 e2 klist)
1234 "(elts-match-under-klist-p E1 E2 KLIST) => t or nil
1235 KLIST encodes a keyword-arguments test, as in CH. 14 of CLtL.
1236 True if elements E1 and E2 match under the tests encoded in KLIST."
1237 (let ((test (extract-from-klist klist :test))
1238 (test-not (extract-from-klist klist :test-not))
1239 (keyfn (extract-from-klist klist :key 'identity)))
1240 (if (and test test-not)
1241 (error "both :test and :test-not in `%s'"
1242 (prin1-to-string klist)))
1244 (funcall test (funcall keyfn e1) (funcall keyfn e2)))
1246 (not (funcall test-not (funcall keyfn e1) (funcall keyfn e2))))
1247 (t ;should never happen
1248 (error "neither :test nor :test-not in `%s'"
1249 (prin1-to-string klist))))))
1251 ;;; This macro simplifies using keyword args. It is less clumsy than using
1252 ;;; the primitives build-klist, etc... For instance, member could be written
1255 ;;; (defun member (item list &rest kargs)
1256 ;;; (with-keyword-args kargs (test test-not (key 'identity))
1259 ;;; Suggested by Robert Potter (potter@cs.rochester.edu, 15 Nov 1989)
1261 (defmacro with-keyword-args (keyargslist vardefs &rest body)
1262 "(WITH-KEYWORD-ARGS KEYARGSLIST VARDEFS . BODY)
1263 KEYARGSLIST can be either a symbol or a list of one or two symbols.
1264 In the second case, the second symbol is either T or NIL, indicating whether
1265 keywords other than the mentioned ones are tolerable.
1267 VARDEFS is a list. Each entry is either a VAR (symbol) or matches
1268 \(VAR [DEFAULT [KEYWORD]]). Just giving VAR is the same as giving
1271 The BODY is executed in an environment where each VAR (a symbol) is bound to
1272 the value present in the KEYARGSLIST provided, or to the DEFAULT. The value
1273 is searched by using the keyword form of VAR (i.e., :VAR) or the optional
1274 keyword if provided.
1276 Notice that this macro doesn't distinguish between a default value given
1277 explicitly by the user and one provided by default. See also the more
1278 primitive functions build-klist, add-to-klist, extract-from-klist,
1279 keyword-argument-supplied-p, elt-satisfies-test-p, elt-satisfies-if-p,
1280 elt-satisfies-if-not-p, elts-match-under-klist-p. They provide more complete,
1281 if clumsier, control over this feature."
1282 (let (allow-other-keys)
1283 (if (listp keyargslist)
1284 (if (> (length keyargslist) 2)
1286 "`%s' should be SYMBOL, (SYMBOL), or (SYMBOL t-OR-nil)"
1287 (prin1-to-string keyargslist))
1288 (setq allow-other-keys (cadr keyargslist)
1289 keyargslist (car keyargslist))
1291 (symbolp keyargslist)
1292 (memq allow-other-keys '(t nil))))
1294 "first subform should be SYMBOL, (SYMBOL), or (SYMBOL t-OR-nil)"
1296 (if (symbolp keyargslist)
1297 (setq allow-other-keys nil)
1299 "first subform should be SYMBOL, (SYMBOL), or (SYMBOL t-OR-nil)")))
1300 (let (vars defaults keywords forms
1301 (klistname (gensym "KLIST_")))
1302 (mapcar (function (lambda (entry)
1303 (if (symbolp entry) ;defaulty case
1304 (setq entry (list entry nil (keyword-of entry))))
1305 (let* ((l (length entry))
1309 (if (or (< l 1) (> l 3))
1311 "`%s' must match (VAR [DEFAULT [KEYWORD]])"
1312 (prin1-to-string entry)))
1313 (if (or (null v) (not (symbolp v)))
1315 "bad variable `%s': must be non-null symbol"
1316 (prin1-to-string v)))
1317 (setq vars (cons v vars))
1318 (setq defaults (cons d defaults))
1320 (setq k (keyword-of v)))
1323 (not (keywordp k))))
1325 "bad keyword `%s'" (prin1-to-string k)))
1326 (setq keywords (cons k keywords))
1327 (setq forms (cons (list v (list 'extract-from-klist
1334 (list 'let* (nconc (list (list klistname
1335 (list 'build-klist keyargslist
1336 (list 'quote keywords)
1340 (put 'with-keyword-args 'lisp-indent-hook 1)
1344 ;;; It is here mostly as an example of how to use KLISTs.
1346 ;;; First of all, you need to declare the keywords (done elsewhere in this
1348 ;;; (defkeyword :from-end "syntax of sequence functions")
1349 ;;; (defkeyword :start "syntax of sequence functions")
1352 ;;; Then, you capture all the possible keyword arguments with a &rest
1353 ;;; argument. You can pass that list downward again, of course, but
1354 ;;; internally you need to parse it into a KLIST (an alist, really). One uses
1355 ;;; (build-klist REST-ARGS ACCEPTABLE-KEYWORDS [ALLOW-OTHER]). You can then
1356 ;;; test for presence by using (keyword-argument-supplied-p KLIST KEY) and
1357 ;;; extract a value with (extract-from-klist KLIST KEY [DEFAULT]).
1359 (defun reduce (function sequence &rest kargs)
1360 "Apply FUNCTION (a function of two arguments) to succesive pairs of elements
1361 from SEQUENCE. Some keyword arguments are valid after FUNCTION and SEQUENCE:
1362 :from-end If non-nil, process the values backwards
1363 :initial-value If given, prefix it to the SEQUENCE. Suffix, if :from-end
1364 :start Restrict reduction to the subsequence from this index
1365 :end Restrict reduction to the subsequence BEFORE this index.
1366 If the sequence is empty and no :initial-value is given, the FUNCTION is
1367 called on zero (not two) arguments. Otherwise, if there is exactly one
1368 element in the combination of SEQUENCE and the initial value, that element is
1370 (let* ((klist (build-klist kargs '(:from-end :start :end :initial-value)))
1371 (length (length sequence))
1372 (from-end (extract-from-klist klist :from-end))
1373 (initial-value-given (keyword-argument-supplied-p
1374 klist :initial-value))
1375 (start (extract-from-klist kargs :start 0))
1376 (end (extract-from-klist kargs :end length)))
1377 (setq sequence (cl$subseq-as-list sequence start end))
1379 (setq sequence (reverse sequence)))
1380 (if initial-value-given
1381 (setq sequence (cons (extract-from-klist klist :initial-value)
1384 (funcall function) ;only use of 0 arguments
1385 (let* ((result (car sequence))
1386 (sequence (cdr sequence)))
1388 (setq result (if from-end
1389 (funcall function (car sequence) result)
1390 (funcall function result (car sequence)))
1391 sequence (cdr sequence)))
1394 (defun cl$subseq-as-list (sequence start end)
1395 "(cl$subseq-as-list SEQUENCE START END) => a list"
1396 (let ((list (append sequence nil))
1397 (length (length sequence))
1400 (error "start should be >= 0, not %d" start))
1402 (error "end should be <= %d, not %d" length end))
1403 (if (and (zerop start) (= end length))
1406 (vector (apply 'vector list)))
1408 (setq result (cons (elt vector i) result))
1410 (nreverse result)))))
1412 ;;;; end of cl-sequences.el
1414 ;;;; Some functions with keyword arguments
1416 ;;;; Both list and sequence functions are considered here together. This
1417 ;;;; doesn't fit any more with the original split of functions in files.
1419 (defun member (item list &rest kargs)
1420 "Look for ITEM in LIST; return first tail of LIST the car of whose first
1421 cons cell tests the same as ITEM. Admits arguments :key, :test, and
1423 (if (null kargs) ;treat this fast for efficiency
1425 (let* ((klist (build-klist kargs '(:test :test-not :key)))
1426 (test (extract-from-klist klist :test))
1427 (testnot (extract-from-klist klist :test-not))
1428 (key (extract-from-klist klist :key 'identity)))
1429 ;; another workaround allegedly for speed, BLAH
1430 (if (and (or (eq test 'eq) (eq test 'eql)
1431 (eq test (symbol-function 'eq))
1432 (eq test (symbol-function 'eql)))
1434 (or (eq key 'identity) ;either by default or so given
1435 (eq key (function identity)) ;could this happen?
1436 (eq key (symbol-function 'identity)) ;sheer paranoia
1439 (if (and test testnot)
1440 (error ":test and :test-not both specified for member"))
1441 (if (not (or test testnot))
1443 ;; final hack: remove the indirection through the function names
1445 (if (symbolp testnot)
1446 (setq testnot (symbol-function testnot)))
1448 (setq test (symbol-function test))))
1450 (setq key (symbol-function key)))
1456 (while (not (or done (endp ptr)))
1457 (cond ((not (funcall testnot item (funcall key (car ptr))))
1460 (setq ptr (cdr ptr)))
1461 (while (not (or done (endp ptr)))
1462 (cond ((funcall test item (funcall key (car ptr)))
1465 (setq ptr (cdr ptr))))
1468 ;;;; MULTIPLE VALUES
1469 ;;;; This package approximates the behavior of the multiple-values
1470 ;;;; forms of Common Lisp.
1472 ;;;; Cesar Quiroz @ UofR DofCSc - Dec. 1986
1473 ;;;; (quiroz@cs.rochester.edu)
1475 ;;; Lisp indentation information
1476 (put 'multiple-value-bind 'lisp-indent-hook 2)
1477 (put 'multiple-value-setq 'lisp-indent-hook 2)
1478 (put 'multiple-value-list 'lisp-indent-hook nil)
1479 (put 'multiple-value-call 'lisp-indent-hook 1)
1480 (put 'multiple-value-prog1 'lisp-indent-hook 1)
1482 ;;; Global state of the package is kept here
1483 (defvar *mvalues-values* nil
1484 "Most recently returned multiple-values")
1485 (defvar *mvalues-count* nil
1486 "Count of multiple-values returned, or nil if the mechanism was not used")
1488 ;;; values is the standard multiple-value-return form. Must be the
1489 ;;; last thing evaluated inside a function. If the caller is not
1490 ;;; expecting multiple values, only the first one is passed. (values)
1491 ;;; is the same as no-values returned (unaware callers see nil). The
1492 ;;; alternative (values-list <list>) is just a convenient shorthand
1493 ;;; and complements multiple-value-list.
1495 (defun values (&rest val-forms)
1496 "Produce multiple values (zero or more). Each arg is one value.
1497 See also `multiple-value-bind', which is one way to examine the
1498 multiple values produced by a form. If the containing form or caller
1499 does not check specially to see multiple values, it will see only
1501 (setq *mvalues-values* val-forms)
1502 (setq *mvalues-count* (length *mvalues-values*))
1503 (car *mvalues-values*))
1505 (defun values-list (&optional val-forms)
1506 "Produce multiple values (zero or more). Each element of LIST is one value.
1507 This is equivalent to (apply 'values LIST)."
1508 (cond ((nlistp val-forms)
1509 (error "Argument to values-list must be a list, not `%s'"
1510 (prin1-to-string val-forms))))
1511 (setq *mvalues-values* val-forms)
1512 (setq *mvalues-count* (length *mvalues-values*))
1513 (car *mvalues-values*))
1515 ;;; Callers that want to see the multiple values use these macros.
1517 (defmacro multiple-value-list (form)
1518 "Execute FORM and return a list of all the (multiple) values FORM produces.
1519 See `values' and `multiple-value-bind'."
1521 (list 'setq '*mvalues-count* nil)
1522 (list 'let (list (list 'it '(gensym)))
1523 (list 'set 'it form)
1524 (list 'if '*mvalues-count*
1525 (list 'copy-sequence '*mvalues-values*)
1527 (list 'setq '*mvalues-count* 1)
1528 (list 'setq '*mvalues-values*
1529 (list 'list (list 'symbol-value 'it)))
1530 (list 'copy-sequence '*mvalues-values*))))))
1532 (defmacro multiple-value-call (function &rest args)
1533 "Call FUNCTION on all the values produced by the remaining arguments.
1534 (multiple-value-call '+ (values 1 2) (values 3 4)) is 10."
1535 (let* ((result (gentemp))
1537 (list 'apply (list 'function (eval function))
1538 (list 'let* (list (list result '()))
1539 (list 'dolist (list arg (list 'quote args) result)
1543 (list 'multiple-value-list
1544 (list 'eval arg)))))))))
1546 (defmacro multiple-value-bind (vars form &rest body)
1547 "Bind VARS to the (multiple) values produced by FORM, then do BODY.
1548 VARS is a list of variables; each is bound to one of FORM's values.
1549 If FORM doesn't make enough values, the extra variables are bound to nil.
1550 (Ordinary forms produce only one value; to produce more, use `values'.)
1551 Extra values are ignored.
1552 BODY (zero or more forms) is executed with the variables bound,
1553 then the bindings are unwound."
1554 (let* ((vals (gentemp)) ;name for intermediate values
1555 (clauses (mv-bind-clausify ;convert into clauses usable
1556 vars vals))) ; in a let form
1558 (cons (list vals (list 'multiple-value-list form))
1562 (defmacro multiple-value-setq (vars form)
1563 "Set VARS to the (multiple) values produced by FORM.
1564 VARS is a list of variables; each is set to one of FORM's values.
1565 If FORM doesn't make enough values, the extra variables are set to nil.
1566 (Ordinary forms produce only one value; to produce more, use `values'.)
1567 Extra values are ignored."
1568 (let* ((vals (gentemp)) ;name for intermediate values
1569 (clauses (mv-bind-clausify ;convert into clauses usable
1570 vars vals))) ; in a setq (after append).
1572 (list (list vals (list 'multiple-value-list form)))
1573 (cons 'setq (apply (function append) clauses)))))
1575 (defmacro multiple-value-prog1 (form &rest body)
1576 "Evaluate FORM, then BODY, then produce the same values FORM produced.
1577 Thus, (multiple-value-prog1 (values 1 2) (foobar)) produces values 1 and 2.
1578 This is like `prog1' except that `prog1' would produce only one value,
1579 which would be the first of FORM's values."
1580 (let* ((heldvalues (gentemp)))
1582 (cons (list (list heldvalues (list 'multiple-value-list form)))
1583 (append body (list (list 'values-list heldvalues)))))))
1585 ;;; utility functions
1587 ;;; mv-bind-clausify makes the pairs needed to have the variables in
1588 ;;; the variable list correspond with the values returned by the form.
1589 ;;; vals is a fresh symbol that intervenes in all the bindings.
1591 (defun mv-bind-clausify (vars vals)
1592 "MV-BIND-CLAUSIFY VARS VALS => Auxiliary list
1593 Forms a list of pairs `(,(nth i vars) (nth i vals)) for i from 0 to
1594 the length of VARS (a list of symbols). VALS is just a fresh symbol."
1595 (if (or (nlistp vars)
1596 (notevery 'symbolp vars))
1597 (error "expected a list of symbols, not `%s'"
1598 (prin1-to-string vars)))
1599 (let* ((nvars (length vars))
1601 (dotimes (n nvars clauses)
1602 (setq clauses (cons (list (nth n vars)
1603 (list 'nth n vals)) clauses)))))
1605 ;;;; end of cl-multiple-values.el
1608 ;;;; This file provides integer arithmetic extensions. Although
1609 ;;;; Emacs Lisp doesn't really support anything but integers, that
1610 ;;;; has still to be made to look more or less standard.
1613 ;;;; Cesar Quiroz @ UofR DofCSc - Dec. 1986
1614 ;;;; (quiroz@cs.rochester.edu)
1617 (defsubst plusp (number)
1618 "True if NUMBER is strictly greater than zero."
1621 (defsubst minusp (number)
1622 "True if NUMBER is strictly less than zero."
1625 (defsubst oddp (number)
1626 "True if INTEGER is not divisible by 2."
1627 (/= (% number 2) 0))
1629 (defsubst evenp (number)
1630 "True if INTEGER is divisible by 2."
1633 (defsubst abs (number)
1634 "Return the absolute value of NUMBER."
1639 (defsubst signum (number)
1640 "Return -1, 0 or 1 according to the sign of NUMBER."
1648 (defun gcd (&rest integers)
1649 "Return the greatest common divisor of all the arguments.
1650 The arguments must be integers. With no arguments, value is zero."
1651 (let ((howmany (length integers)))
1652 (cond ((= howmany 0)
1655 (abs (car integers)))
1657 (apply (function gcd)
1658 (cons (gcd (nth 0 integers) (nth 1 integers))
1659 (nthcdr 2 integers))))
1661 ;; essentially the euclidean algorithm
1662 (when (zerop (* (nth 0 integers) (nth 1 integers)))
1663 (error "a zero argument is invalid for `gcd'"))
1664 (do* ((absa (abs (nth 0 integers))) ; better to operate only
1665 (absb (abs (nth 1 integers))) ;on positives.
1666 (dd (max absa absb)) ; setup correct order for the
1667 (ds (min absa absb)) ;succesive divisions.
1668 ;; intermediate results
1672 (done nil) ; flag: end of iterations
1673 (result 0)) ; final value
1677 (cond ((zerop r) (setq done t) (setq result ds))
1678 (t (setq dd ds) (setq ds r))))))))
1680 (defun lcm (integer &rest more)
1681 "Return the least common multiple of all the arguments.
1682 The arguments must be integers and there must be at least one of them."
1683 (let ((howmany (length more))
1686 prod ; intermediate product
1687 (yetmore (nthcdr 1 more)))
1688 (cond ((zerop howmany)
1690 ((> howmany 1) ; recursive case
1691 (apply (function lcm)
1692 (cons (lcm a b) yetmore)))
1693 (t ; base case, just 2 args
1699 (/ (abs prod) (gcd a b))))))))
1701 (defun isqrt (number)
1702 "Return the integer square root of NUMBER.
1703 NUMBER must not be negative. Result is largest integer less than or
1704 equal to the real square root of the argument."
1705 ;; The method used here is essentially the Newtonian iteration
1706 ;; x[n+1] <- (x[n] + Number/x[n]) / 2
1707 ;; suitably adapted to integer arithmetic.
1708 ;; Thanks to Philippe Schnoebelen <phs@lifia.imag.fr> for suggesting the
1709 ;; termination condition.
1710 (cond ((minusp number)
1711 (error "argument to `isqrt' (%d) must not be negative"
1715 (t ;so (>= number 0)
1716 (do* ((approx 1) ;any positive integer will do
1717 (new 0) ;init value irrelevant
1719 (done (if (> (* approx approx) number)
1722 (setq new (/ (+ approx (/ number approx)) 2)
1723 done (or (= new approx) (= new (+ approx 1)))
1726 (defun floor (number &optional divisor)
1727 "Divide DIVIDEND by DIVISOR, rounding toward minus infinity.
1728 DIVISOR defaults to 1. The remainder is produced as a second value."
1729 (cond ((and (null divisor) ; trivial case
1732 (t ; do the division
1733 (multiple-value-bind
1735 (safe-idiv number divisor)
1740 (t ;opposite-signs case
1743 (let ((q (- (+ q 1))))
1744 (values q (- number (* q divisor)))))))))))
1746 (defun ceiling (number &optional divisor)
1747 "Divide DIVIDEND by DIVISOR, rounding toward plus infinity.
1748 DIVISOR defaults to 1. The remainder is produced as a second value."
1749 (cond ((and (null divisor) ; trivial case
1752 (t ; do the division
1753 (multiple-value-bind
1755 (safe-idiv number divisor)
1759 (values (+ q 1) (- r divisor)))
1761 (values (- q) (+ number (* q divisor)))))))))
1763 (defun truncate (number &optional divisor)
1764 "Divide DIVIDEND by DIVISOR, rounding toward zero.
1765 DIVISOR defaults to 1. The remainder is produced as a second value."
1766 (cond ((and (null divisor) ; trivial case
1769 (t ; do the division
1770 (multiple-value-bind
1772 (safe-idiv number divisor)
1775 ((plusp s) ;same as floor
1778 (values (- q) (+ number (* q divisor)))))))))
1780 (defun round (number &optional divisor)
1781 "Divide DIVIDEND by DIVISOR, rounding to nearest integer.
1782 DIVISOR defaults to 1. The remainder is produced as a second value."
1783 (cond ((and (null divisor) ; trivial case
1786 (t ; do the division
1787 (multiple-value-bind
1789 (safe-idiv number divisor)
1791 ;; adjust magnitudes first, and then signs
1792 (let ((other-r (- (abs divisor) r)))
1793 (cond ((> r other-r)
1797 ;; round to even is mandatory
1800 (setq r (- number (* q divisor)))
1803 ;;; These two functions access the implementation-dependent representation of
1804 ;;; the multiple value returns.
1806 (defun mod (number divisor)
1807 "Return remainder of X by Y (rounding quotient toward minus infinity).
1808 That is, the remainder goes with the quotient produced by `floor'.
1810 If you know that both arguments are positive, use `%' instead for speed."
1811 (floor number divisor)
1812 (cadr *mvalues-values*))
1814 (defun rem (number divisor)
1815 "Return remainder of X by Y (rounding quotient toward zero).
1816 That is, the remainder goes with the quotient produced by `truncate'.
1818 If you know that both arguments are positive, use `%' instead for speed."
1819 (truncate number divisor)
1820 (cadr *mvalues-values*))
1822 ;;; internal utilities
1824 ;;; safe-idiv performs an integer division with positive numbers only.
1825 ;;; It is known that some machines/compilers implement weird remainder
1826 ;;; computations when working with negatives, so the idea here is to
1827 ;;; make sure we know what is coming back to the caller in all cases.
1829 ;;; Signum computation fixed by mad@math.keio.JUNET (MAEDA Atusi)
1831 (defun safe-idiv (a b)
1832 "SAFE-IDIV A B => Q R S
1833 Q=|A|/|B|, S is the sign of A/B, R is the rest A - S*Q*B."
1834 ;; (unless (and (numberp a) (numberp b))
1835 ;; (error "arguments to `safe-idiv' must be numbers"))
1837 ;; (error "cannot divide %d by zero" a))
1838 (let* ((q (/ (abs a) (abs b)))
1839 (s (* (signum a) (signum b)))
1840 (r (- a (* s q b))))
1843 ;;;; end of cl-arith.el
1846 ;;;; This file provides the setf macro and friends. The purpose has
1847 ;;;; been modest, only the simplest defsetf forms are accepted.
1848 ;;;; Use it and enjoy.
1850 ;;;; Cesar Quiroz @ UofR DofCSc - Dec. 1986
1851 ;;;; (quiroz@cs.rochester.edu)
1854 (defkeyword :setf-update-fn
1855 "Property, its value is the function setf must invoke to update a
1856 generalized variable whose access form is a function call of the
1857 symbol that has this property.")
1859 (defkeyword :setf-update-doc
1860 "Property of symbols that have a `defsetf' update function on them,
1861 installed by the `defsetf' from its optional third argument.")
1863 (defmacro setf (&rest pairs)
1864 "Generalized `setq' that can set things other than variable values.
1865 A use of `setf' looks like (setf {PLACE VALUE}...).
1866 The behavior of (setf PLACE VALUE) is to access the generalized variable
1867 at PLACE and store VALUE there. It returns VALUE. If there is more
1868 than one PLACE and VALUE, each PLACE is set from its VALUE before
1869 the next PLACE is evaluated."
1870 (let ((nforms (length pairs)))
1871 ;; check the number of subforms
1872 (cond ((/= (% nforms 2) 0)
1873 (error "odd number of arguments to `setf'"))
1877 ;; this is the recursive case
1879 (do* ;collect the place-value pairs
1880 ((args pairs (cddr args))
1881 (place (car args) (car args))
1882 (value (cadr args) (cadr args))
1884 ((endp args) (nreverse result))
1886 (cons (list 'setf place value)
1889 ;; this is the base case (SETF PLACE VALUE)
1890 (let* ((place (car pairs))
1891 (value (cadr pairs))
1894 ;; dispatch on the type of the PLACE
1895 (cond ((symbolp place)
1896 (list 'setq place value))
1898 (setq head (car place))
1900 (setq updatefn (get head :setf-update-fn)))
1901 ;; dispatch on the type of update function
1902 (cond ((and (consp updatefn) (eq (car updatefn) 'lambda))
1904 (cons (list 'function updatefn)
1905 (append (cdr place) (list value)))))
1906 ((and (symbolp updatefn)
1908 (let ((defn (symbol-function updatefn)))
1911 (or (eq (car defn) 'lambda)
1912 (eq (car defn) 'macro))))))
1913 (cons updatefn (append (cdr place) (list value))))
1915 (multiple-value-bind
1918 (append (cdr place) (list value)))
1919 ;; this let gets new symbols to ensure adequate
1920 ;; order of evaluation of the subforms.
1923 (cons updatefn newsyms))))))
1925 (error "no `setf' update-function for `%s'"
1926 (prin1-to-string place)))))))))
1928 (defmacro defsetf (accessfn updatefn &optional docstring)
1929 "Define how `setf' works on a certain kind of generalized variable.
1930 A use of `defsetf' looks like (defsetf ACCESSFN UPDATEFN [DOCSTRING]).
1931 ACCESSFN is a symbol. UPDATEFN is a function or macro which takes
1932 one more argument than ACCESSFN does. DEFSETF defines the translation
1933 of (SETF (ACCESFN . ARGS) NEWVAL) to be a form like (UPDATEFN ARGS... NEWVAL).
1934 The function UPDATEFN must return its last arg, after performing the
1935 updating called for."
1936 ;; reject ill-formed requests. too bad one can't test for functionp
1938 (when (not (symbolp accessfn))
1939 (error "first argument of `defsetf' must be a symbol, not `%s'"
1940 (prin1-to-string accessfn)))
1941 ;; update properties
1943 (list 'eval-and-compile
1944 (list 'put (list 'quote accessfn)
1945 :setf-update-fn (list 'function updatefn)))
1946 (list 'put (list 'quote accessfn) :setf-update-doc docstring)
1947 ;; any better thing to return?
1948 (list 'quote accessfn)))
1950 ;;; This section provides the "default" setfs for Common-Emacs-Lisp
1951 ;;; The user will not normally add anything to this, although
1952 ;;; defstruct will introduce new ones as a matter of fact.
1954 ;;; Apply is a special case. The Common Lisp
1955 ;;; standard makes the case of apply be useful when the user writes
1956 ;;; something like (apply #'name ...), Emacs Lisp doesn't have the #
1957 ;;; stuff, but it has (function ...). Notice that V18 includes a new
1958 ;;; apply: this file is compatible with V18 and pre-V18 Emacses.
1960 ;;; INCOMPATIBILITY: the SETF macro evaluates its arguments in the
1961 ;;; (correct) left to right sequence *before* checking for apply
1962 ;;; methods (which should really be an special case inside setf). Due
1963 ;;; to this, the lambda expression defsetf'd to apply will succeed in
1964 ;;; applying the right function even if the name was not quoted, but
1965 ;;; computed! That extension is not Common Lisp (nor is particularly
1966 ;;; useful, I think).
1969 (lambda (&rest args)
1970 ;; dissasemble the calling form
1971 ;; "(((quote fn) x1 x2 ... xn) val)" (function instead of quote, too)
1972 (let* ((fnform (car args)) ;functional form
1973 (applyargs (append ;arguments "to apply fnform"
1974 (apply 'list* (butlast (cdr args)))
1976 (newupdater nil)) ; its update-fn, if any
1977 (if (and (symbolp fnform)
1978 (setq newupdater (get fnform :setf-update-fn)))
1979 (apply newupdater applyargs)
1980 (error "can't `setf' to `%s'"
1981 (prin1-to-string fnform)))))
1982 "`apply' is a special case for `setf'")
1987 "`setf' inversion for `aref'")
1991 "`setf' inversion for `nth'")
1995 "`setf' inversion for `nthcdr'")
1999 "`setf' inversion for `elt'")
2002 (lambda (list val) (setnth 0 list val))
2003 "`setf' inversion for `first'")
2006 (lambda (list val) (setnth 1 list val))
2007 "`setf' inversion for `second'")
2010 (lambda (list val) (setnth 2 list val))
2011 "`setf' inversion for `third'")
2014 (lambda (list val) (setnth 3 list val))
2015 "`setf' inversion for `fourth'")
2018 (lambda (list val) (setnth 4 list val))
2019 "`setf' inversion for `fifth'")
2022 (lambda (list val) (setnth 5 list val))
2023 "`setf' inversion for `sixth'")
2026 (lambda (list val) (setnth 6 list val))
2027 "`setf' inversion for `seventh'")
2030 (lambda (list val) (setnth 7 list val))
2031 "`setf' inversion for `eighth'")
2034 (lambda (list val) (setnth 8 list val))
2035 "`setf' inversion for `ninth'")
2038 (lambda (list val) (setnth 9 list val))
2039 "`setf' inversion for `tenth'")
2042 (lambda (list val) (setcdr list val))
2043 "`setf' inversion for `rest'")
2045 (defsetf car setcar "Replace the car of a cons")
2047 (defsetf cdr setcdr "Replace the cdr of a cons")
2050 (lambda (list val) (setcar (nth 0 list) val))
2051 "`setf' inversion for `caar'")
2054 (lambda (list val) (setcar (cdr list) val))
2055 "`setf' inversion for `cadr'")
2058 (lambda (list val) (setcdr (car list) val))
2059 "`setf' inversion for `cdar'")
2062 (lambda (list val) (setcdr (cdr list) val))
2063 "`setf' inversion for `cddr'")
2066 (lambda (list val) (setcar (caar list) val))
2067 "`setf' inversion for `caaar'")
2070 (lambda (list val) (setcar (cadr list) val))
2071 "`setf' inversion for `caadr'")
2074 (lambda (list val) (setcar (cdar list) val))
2075 "`setf' inversion for `cadar'")
2078 (lambda (list val) (setcdr (caar list) val))
2079 "`setf' inversion for `cdaar'")
2082 (lambda (list val) (setcar (cddr list) val))
2083 "`setf' inversion for `caddr'")
2086 (lambda (list val) (setcdr (cadr list) val))
2087 "`setf' inversion for `cdadr'")
2090 (lambda (list val) (setcdr (cdar list) val))
2091 "`setf' inversion for `cddar'")
2094 (lambda (list val) (setcdr (cddr list) val))
2095 "`setf' inversion for `cdddr'")
2098 (lambda (list val) (setcar (caaar list) val))
2099 "`setf' inversion for `caaaar'")
2102 (lambda (list val) (setcar (caadr list) val))
2103 "`setf' inversion for `caaadr'")
2106 (lambda (list val) (setcar (cadar list) val))
2107 "`setf' inversion for `caadar'")
2110 (lambda (list val) (setcar (cdaar list) val))
2111 "`setf' inversion for `cadaar'")
2114 (lambda (list val) (setcdr (caar list) val))
2115 "`setf' inversion for `cdaaar'")
2118 (lambda (list val) (setcar (caddr list) val))
2119 "`setf' inversion for `caaddr'")
2122 (lambda (list val) (setcar (cdadr list) val))
2123 "`setf' inversion for `cadadr'")
2126 (lambda (list val) (setcdr (caadr list) val))
2127 "`setf' inversion for `cdaadr'")
2130 (lambda (list val) (setcar (cddar list) val))
2131 "`setf' inversion for `caddar'")
2134 (lambda (list val) (setcdr (cadar list) val))
2135 "`setf' inversion for `cdadar'")
2138 (lambda (list val) (setcdr (cdaar list) val))
2139 "`setf' inversion for `cddaar'")
2142 (lambda (list val) (setcar (cdddr list) val))
2143 "`setf' inversion for `cadddr'")
2146 (lambda (list val) (setcdr (cdadr list) val))
2147 "`setf' inversion for `cddadr'")
2150 (lambda (list val) (setcdr (caddr list) val))
2151 "`setf' inversion for `cdaddr'")
2154 (lambda (list val) (setcdr (cddar list) val))
2155 "`setf' inversion for `cdddar'")
2158 (lambda (list val) (setcdr (cddr list) val))
2159 "`setf' inversion for `cddddr'")
2161 (defsetf get put "`setf' inversion for `get' is `put'")
2163 (defsetf symbol-function fset
2164 "`setf' inversion for `symbol-function' is `fset'")
2166 (defsetf symbol-plist setplist
2167 "`setf' inversion for `symbol-plist' is `setplist'")
2169 (defsetf symbol-value set
2170 "`setf' inversion for `symbol-value' is `set'")
2172 (defsetf point goto-char
2173 "To set (point) to N, use (goto-char N)")
2175 ;; how about defsetfing other Emacs forms?
2179 ;;; It could be nice to implement define-modify-macro, but I don't
2180 ;;; think it really pays.
2182 (defmacro incf (ref &optional delta)
2183 "(incf REF [DELTA]) -> increment the g.v. REF by DELTA (default 1)"
2186 (list 'setf ref (list '+ ref delta)))
2188 (defmacro decf (ref &optional delta)
2189 "(decf REF [DELTA]) -> decrement the g.v. REF by DELTA (default 1)"
2192 (list 'setf ref (list '- ref delta)))
2194 (defmacro push (item ref)
2195 "(push ITEM REF) -> cons ITEM at the head of the g.v. REF (a list)"
2196 (list 'setf ref (list 'cons item ref)))
2198 (defmacro pushnew (item ref)
2199 "(pushnew ITEM REF): adjoin ITEM at the head of the g.v. REF (a list)"
2200 (list 'setf ref (list 'adjoin item ref)))
2203 "(pop REF) -> (prog1 (car REF) (setf REF (cdr REF)))"
2204 (let ((listname (gensym)))
2205 (list 'let (list (list listname ref))
2207 (list 'car listname)
2208 (list 'setf ref (list 'cdr listname))))))
2212 ;;; Psetf is the generalized variable equivalent of psetq. The right
2213 ;;; hand sides are evaluated and assigned (via setf) to the left hand
2214 ;;; sides. The evaluations are done in an environment where they
2215 ;;; appear to occur in parallel.
2217 (defmacro psetf (&rest body)
2218 "(psetf {var value }...) => nil
2219 Like setf, but all the values are computed before any assignment is made."
2220 (let ((length (length body)))
2221 (cond ((/= (% length 2) 0)
2222 (error "psetf needs an even number of arguments, %d given"
2229 (bodyforms (reverse body)))
2231 (let* ((value (car bodyforms))
2232 (place (cadr bodyforms)))
2233 (setq bodyforms (cddr bodyforms))
2235 (setq setfs (list 'setf place value))
2236 (setq setfs (list 'setf place
2241 ;;; SHIFTF and ROTATEF
2244 (defmacro shiftf (&rest forms)
2245 "(shiftf PLACE1 PLACE2... NEWVALUE)
2246 Set PLACE1 to PLACE2, PLACE2 to PLACE3...
2247 Each PLACE is set to the old value of the following PLACE,
2248 and the last PLACE is set to the value NEWVALUE.
2249 Returns the old value of PLACE1."
2250 (unless (> (length forms) 1)
2251 (error "`shiftf' needs more than one argument"))
2252 (let ((places (butlast forms))
2253 (newvalue (car (last forms))))
2254 ;; the places are accessed to fresh symbols
2255 (multiple-value-bind
2257 (pair-with-newsyms places)
2261 (append (cdr newsyms) (list newvalue))))
2264 (defmacro rotatef (&rest places)
2265 "(rotatef PLACE...) sets each PLACE to the old value of the following PLACE.
2266 The last PLACE is set to the old value of the first PLACE.
2267 Thus, the values rotate through the PLACEs. Returns nil."
2270 (multiple-value-bind
2272 (pair-with-newsyms places)
2277 (append (cdr newsyms) (list (car newsyms)))))
2280 ;;; GETF, REMF, and REMPROP
2283 (defun getf (place indicator &optional default)
2284 "Return PLACE's PROPNAME property, or DEFAULT if not present."
2285 (while (and place (not (eq (car place) indicator)))
2286 (setq place (cdr (cdr place))))
2291 (defmacro getf$setf$method (place indicator default &rest newval)
2292 "SETF method for GETF. Not for public use."
2293 (case (length newval)
2294 (0 (setq newval default default nil))
2295 (1 (setq newval (car newval)))
2296 (t (error "Wrong number of arguments to (setf (getf ...)) form")))
2297 (let ((psym (gentemp)) (isym (gentemp)) (vsym (gentemp)))
2298 (list 'let (list (list psym place)
2299 (list isym indicator)
2304 (list 'eq (list 'car psym) isym)))
2305 (list 'setq psym (list 'cdr (list 'cdr psym))))
2307 (list 'setcar (list 'cdr psym) vsym)
2309 (list 'nconc place (list 'list isym newval))))
2315 (defmacro remf (place indicator)
2316 "Remove from the property list at PLACE its PROPNAME property.
2317 Returns non-nil if and only if the property existed."
2318 (let ((psym (gentemp)) (isym (gentemp)))
2319 (list 'let (list (list psym place) (list isym indicator))
2321 (list (list 'eq isym (list 'car psym))
2322 (list 'setf place (list 'cdr (list 'cdr psym)))
2325 (list 'setq psym (list 'cdr psym))
2327 (list 'and (list 'cdr psym)
2329 (list 'eq (list 'car (list 'cdr psym))
2331 (list 'setq psym (list 'cdr (list 'cdr psym))))
2333 (list (list 'cdr psym)
2336 (list 'cdr (list 'cdr psym))))
2339 (defun remprop (symbol indicator)
2340 "Remove SYMBOL's PROPNAME property, returning non-nil if it was present."
2341 (remf (symbol-plist symbol) indicator))
2345 ;;;; This file provides the structures mechanism. See the
2346 ;;;; documentation for Common-Lisp's defstruct. Mine doesn't
2347 ;;;; implement all the functionality of the standard, although some
2348 ;;;; more could be grafted if so desired. More details along with
2352 ;;;; Cesar Quiroz @ UofR DofCSc - Dec. 1986
2353 ;;;; (quiroz@cs.rochester.edu)
2356 (defkeyword :include "Syntax of `defstruct'")
2357 (defkeyword :named "Syntax of `defstruct'")
2358 (defkeyword :conc-name "Syntax of `defstruct'")
2359 (defkeyword :copier "Syntax of `defstruct'")
2360 (defkeyword :predicate "Syntax of `defstruct'")
2361 (defkeyword :print-function "Syntax of `defstruct'")
2362 (defkeyword :type "Syntax of `defstruct'")
2363 (defkeyword :initial-offset "Syntax of `defstruct'")
2365 (defkeyword :structure-doc "Documentation string for a structure.")
2366 (defkeyword :structure-slotsn "Number of slots in structure")
2367 (defkeyword :structure-slots "List of the slot's names")
2368 (defkeyword :structure-indices "List of (KEYWORD-NAME . INDEX)")
2369 (defkeyword :structure-initforms "List of (KEYWORD-NAME . INITFORM)")
2370 (defkeyword :structure-includes
2371 "() or list of a symbol, that this struct includes")
2372 (defkeyword :structure-included-in
2373 "List of the structs that include this")
2376 (defmacro defstruct (&rest args)
2377 "(defstruct NAME [DOC-STRING] . SLOTS) define NAME as structure type.
2378 NAME must be a symbol, the name of the new structure. It could also
2379 be a list (NAME . OPTIONS).
2381 Each option is either a symbol, or a list of a keyword symbol taken from the
2382 list \{:conc-name, :copier, :constructor, :predicate, :include,
2383 :print-function, :type, :initial-offset\}. The meanings of these are as in
2384 CLtL, except that no BOA-constructors are provided, and the options
2385 \{:print-fuction, :type, :initial-offset\} are ignored quietly. All these
2386 structs are named, in the sense that their names can be used for type
2389 The DOC-STRING is established as the `structure-doc' property of NAME.
2391 The SLOTS are one or more of the following:
2392 SYMBOL -- meaning the SYMBOL is the name of a SLOT of NAME
2393 list of SYMBOL and VALUE -- meaning that VALUE is the initial value of
2395 `defstruct' defines functions `make-NAME', `NAME-p', `copy-NAME' for the
2396 structure, and functions with the same name as the slots to access
2397 them. `setf' of the accessors sets their values."
2398 (multiple-value-bind
2399 (name options docstring slotsn slots initlist)
2400 (parse$defstruct$args args)
2401 ;; Names for the member functions come from the options. The
2402 ;; slots* stuff collects info about the slots declared explicitly.
2403 (multiple-value-bind
2404 (conc-name constructor copier predicate
2405 moreslotsn moreslots moreinits included)
2406 (parse$defstruct$options name options slots)
2407 ;; The moreslots* stuff refers to slots gained as a consequence
2408 ;; of (:include clauses). -- Oct 89: Only one :include tolerated
2409 (when (and (numberp moreslotsn)
2411 (setf slotsn (+ slotsn moreslotsn))
2412 (setf slots (append moreslots slots))
2413 (setf initlist (append moreinits initlist)))
2414 (unless (> slotsn 0)
2415 (error "%s needs at least one slot"
2416 (prin1-to-string name)))
2417 (let ((dups (duplicate-symbols-p slots)))
2419 (error "`%s' are duplicates"
2420 (prin1-to-string dups))))
2421 (setq initlist (simplify$inits slots initlist))
2422 (let (properties functions keywords accessors alterators returned)
2423 ;; compute properties of NAME
2427 (list 'put (list 'quote name) :structure-doc
2429 (list 'put (list 'quote name) :structure-slotsn
2431 (list 'put (list 'quote name) :structure-slots
2432 (list 'quote slots))
2433 (list 'put (list 'quote name) :structure-initforms
2434 (list 'quote initlist))
2435 (list 'put (list 'quote name) :structure-indices
2436 (list 'quote (extract$indices initlist))))
2437 ;; If this definition :includes another defstruct,
2438 ;; modify both property lists.
2444 (list 'quote included))
2447 (list 'get (list 'quote (car included))
2448 :structure-included-in))))
2451 (let ((old (gensym)))
2457 :structure-includes))))
2461 :structure-included-in
2464 ;; careful with destructive
2471 :structure-included-in)
2478 ;; If this definition used to be :included in another, warn
2479 ;; that things make break. On the other hand, the redefinition
2480 ;; may be trivial, so don't call it an error.
2481 (let ((old (gensym)))
2484 (list (list old (list 'get
2486 :structure-included-in)))
2489 "`%s' redefined. Should redefine `%s'?"
2491 (list 'prin1-to-string old))))))))
2493 ;; Compute functions associated with NAME. This is not
2494 ;; handling BOA constructors yet, but here would be the place.
2497 (list 'fset (list 'quote constructor)
2499 (list 'lambda (list '&rest 'args)
2500 (list 'make$structure$instance
2503 (list 'fset (list 'quote copier)
2504 (list 'function 'copy-sequence))
2505 (let ((typetag (gensym)))
2506 (list 'fset (list 'quote predicate)
2510 'lambda (list 'thing)
2512 (list 'vectorp 'thing)
2515 (list 'elt 'thing 0)))
2523 (list 'length 'thing)
2530 :structure-included-in))))))
2532 ;; compute accessors for NAME's slots
2533 (multiple-value-setq
2534 (accessors alterators keywords)
2535 (build$accessors$for name conc-name predicate slots slotsn))
2536 ;; generate returned value -- not defined by the standard
2541 (function (lambda (x) (list 'quote x)))
2542 (cons name slots)))))
2545 (nconc properties functions keywords
2546 accessors alterators returned))))))
2548 (defun parse$defstruct$args (args)
2549 "(parse$defstruct$args ARGS) => NAME OPTIONS DOCSTRING SLOTSN SLOTS INITLIST
2550 NAME=symbol, OPTIONS=list of, DOCSTRING=string, SLOTSN=count of slots,
2551 SLOTS=list of their names, INITLIST=alist (keyword . initform)."
2552 (let (name ;args=(symbol...) or ((symbol...)...)
2553 options ;args=((symbol . options) ...)
2554 (docstring "") ;args=(head docstring . slotargs)
2555 slotargs ;second or third cdr of args
2556 (slotsn 0) ;number of slots
2557 (slots '()) ;list of slot names
2558 (initlist '())) ;list of (slot keyword . initform)
2559 ;; extract name and options
2560 (cond ((symbolp (car args)) ;simple name
2561 (setq name (car args)
2563 ((and (listp (car args)) ;(name . options)
2564 (symbolp (caar args)))
2565 (setq name (caar args)
2566 options (cdar args)))
2568 (error "first arg to `defstruct' must be symbol or (symbol ...)")))
2569 (setq slotargs (cdr args))
2570 ;; is there a docstring?
2571 (when (stringp (car slotargs))
2572 (setq docstring (car slotargs)
2573 slotargs (cdr slotargs)))
2574 ;; now for the slots
2575 (multiple-value-bind
2576 (slotsn slots initlist)
2577 (process$slots slotargs)
2578 (values name options docstring slotsn slots initlist))))
2580 (defun process$slots (slots)
2581 "(process$slots SLOTS) => SLOTSN SLOTSLIST INITLIST
2582 Converts a list of symbols or lists of symbol and form into the last 3
2583 values returned by PARSE$DEFSTRUCT$ARGS."
2584 (let ((slotsn (length slots)) ;number of slots
2585 slotslist ;(slot1 slot2 ...)
2586 initlist) ;((:slot1 . init1) ...)
2588 ((ptr slots (cdr ptr))
2589 (this (car ptr) (car ptr)))
2591 (cond ((symbolp this)
2592 (setq slotslist (cons this slotslist))
2593 (setq initlist (acons (keyword-of this) nil initlist)))
2595 (symbolp (car this)))
2596 (let ((name (car this))
2598 ;; this silently ignores any slot options. bad...
2599 (setq slotslist (cons name slotslist))
2600 (setq initlist (acons (keyword-of name) form initlist))))
2602 (error "slot should be symbol or (symbol ...), not `%s'"
2603 (prin1-to-string this)))))
2604 (values slotsn (nreverse slotslist) (nreverse initlist))))
2606 (defun parse$defstruct$options (name options slots)
2607 "(parse$defstruct$options name OPTIONS SLOTS) => many values
2608 A defstruct named NAME, with options list OPTIONS, has already slots SLOTS.
2609 Parse the OPTIONS and return the updated form of the struct's slots and other
2610 information. The values returned are:
2612 CONC-NAME is the string to use as prefix/suffix in the methods,
2613 CONST is the name of the official constructor,
2614 COPIER is the name of the structure copier,
2615 PRED is the name of the type predicate,
2616 MORESLOTSN is the number of slots added by :include,
2617 MORESLOTS is the list of slots added by :include,
2618 MOREINITS is the list of initialization forms added by :include,
2619 INCLUDED is nil, or the list of the symbol added by :include"
2620 (let* ((namestring (symbol-name name))
2621 ;; to build the return values
2622 (conc-name (concat namestring "-"))
2623 (const (intern (concat "make-" namestring)))
2624 (copier (intern (concat "copy-" namestring)))
2625 (pred (intern (concat namestring "-p")))
2630 option-head ;When an option is not a plain
2631 option-second ; keyword, it must be a list of
2632 option-rest ; the form (head second . rest)
2633 these-slotsn ;When :include is found, the
2634 these-slots ; info about the included
2635 these-inits ; structure is added here.
2636 included ;NIL or (list INCLUDED)
2638 ;; Values above are the defaults. Now we read the options themselves
2639 (dolist (option options)
2640 ;; 2 cases arise, as options must be a keyword or a list
2647 (error "can't recognize option `%s'"
2648 (prin1-to-string option)))))
2649 ((and (listp option)
2650 (keywordp (setq option-head (car option))))
2651 (setq option-second (second option))
2652 (setq option-rest (nthcdr 2 option))
2657 ((stringp option-second)
2659 ((null option-second)
2662 (error "`%s' is invalid as `conc-name'"
2663 (prin1-to-string option-second))))))
2667 ((and (symbolp option-second)
2671 (error "can't recognize option `%s'"
2672 (prin1-to-string option))))))
2674 (:constructor ;no BOA-constructors allowed
2677 ((and (symbolp option-second)
2681 (error "can't recognize option `%s'"
2682 (prin1-to-string option))))))
2686 ((and (symbolp option-second)
2690 (error "can't recognize option `%s'"
2691 (prin1-to-string option))))))
2693 (unless (symbolp option-second)
2694 (error "arg to `:include' should be a symbol, not `%s'"
2695 (prin1-to-string option-second)))
2696 (setq these-slotsn (get option-second :structure-slotsn)
2697 these-slots (get option-second :structure-slots)
2698 these-inits (get option-second :structure-initforms))
2699 (unless (and (numberp these-slotsn)
2701 (error "`%s' is not a valid structure"
2702 (prin1-to-string option-second)))
2704 (error "`%s' already includes `%s', can't include `%s' too"
2705 name (car included) option-second)
2706 (push option-second included))
2707 (multiple-value-bind
2708 (xtra-slotsn xtra-slots xtra-inits)
2709 (process$slots option-rest)
2710 (when (> xtra-slotsn 0)
2711 (dolist (xslot xtra-slots)
2712 (unless (memq xslot these-slots)
2713 (error "`%s' is not a slot of `%s'"
2714 (prin1-to-string xslot)
2715 (prin1-to-string option-second))))
2716 (setq these-inits (append xtra-inits these-inits)))
2717 (setq moreslotsn (+ moreslotsn these-slotsn))
2718 (setq moreslots (append these-slots moreslots))
2719 (setq moreinits (append these-inits moreinits))))
2720 ((:print-function :type :initial-offset)
2723 (error "can't recognize option `%s'"
2724 (prin1-to-string option)))))
2726 (error "can't recognize option `%s'"
2727 (prin1-to-string option)))))
2728 ;; Return values found
2729 (values conc-name const copier pred
2730 moreslotsn moreslots moreinits
2733 (defun simplify$inits (slots initlist)
2734 "(simplify$inits SLOTS INITLIST) => new INITLIST
2735 Removes from INITLIST - an ALIST - any shadowed bindings."
2736 (let ((result '()) ;built here
2739 (dolist (slot slots)
2740 (setq key (keyword-of slot))
2741 (setq result (acons key (cdr (assoc key initlist)) result)))
2744 (defun extract$indices (initlist)
2745 "(extract$indices INITLIST) => indices list
2746 Kludge. From a list of pairs (keyword . form) build a list of pairs
2747 of the form (keyword . position in list from 0). Useful to precompute
2748 some of the work of MAKE$STRUCTURE$INSTANCE."
2751 (dolist (entry initlist (nreverse result))
2752 (setq result (acons (car entry) index result)
2753 index (+ index 1)))))
2755 (defun build$accessors$for (name conc-name predicate slots slotsn)
2756 "(build$accessors$for NAME PREDICATE SLOTS SLOTSN) => FSETS DEFSETFS KWDS
2757 Generate the code for accesors and defsetfs of a structure called
2758 NAME, whose slots are SLOTS. Also, establishes the keywords for the
2764 (canonic "")) ;slot name with conc-name prepended
2767 (nreverse accessors) (nreverse alterators) (nreverse keywords)))
2768 (setq canonic (intern (concat conc-name (symbol-name (nth i slots)))))
2771 (list 'fset (list 'quote canonic)
2773 (list 'lambda (list 'object)
2775 (list (list predicate 'object)
2776 (list 'aref 'object (1+ i)))
2779 "`%s' is not a struct %s"
2780 (list 'prin1-to-string
2782 (list 'prin1-to-string
2788 (list 'defsetf canonic
2789 (list 'lambda (list 'object 'newval)
2791 (list (list predicate 'object)
2792 (list 'aset 'object (1+ i) 'newval))
2796 (list 'prin1-to-string
2798 (list 'prin1-to-string
2803 (cons (list 'defkeyword (keyword-of (nth i slots)))
2806 (defun make$structure$instance (name args)
2807 "(make$structure$instance NAME ARGS) => new struct NAME
2808 A struct of type NAME is created, some slots might be initialized
2809 according to ARGS (the &rest argument of MAKE-name)."
2810 (unless (symbolp name)
2811 (error "`%s' is not a possible name for a structure"
2812 (prin1-to-string name)))
2813 (let ((initforms (get name :structure-initforms))
2814 (slotsn (get name :structure-slotsn))
2815 (indices (get name :structure-indices))
2816 initalist ;pairlis'd on initforms
2817 initializers ;definitive initializers
2819 ;; check sanity of the request
2820 (unless (and (numberp slotsn)
2822 (error "`%s' is not a defined structure"
2823 (prin1-to-string name)))
2824 (unless (evenp (length args))
2825 (error "slot initializers `%s' not of even length"
2826 (prin1-to-string args)))
2827 ;; analyze the initializers provided by the call
2828 (multiple-value-bind
2829 (speckwds specvals) ;keywords and values given
2830 (unzip-list args) ; by the user
2831 ;; check that all the arguments are introduced by keywords
2832 (unless (every (function keywordp) speckwds)
2833 (error "all of the names in `%s' should be keywords"
2834 (prin1-to-string speckwds)))
2835 ;; check that all the keywords are known
2836 (dolist (kwd speckwds)
2837 (unless (numberp (cdr (assoc kwd indices)))
2838 (error "`%s' is not a valid slot name for %s"
2839 (prin1-to-string kwd) (prin1-to-string name))))
2843 (do* ;;protect values from further evaluation
2844 ((ptr specvals (cdr ptr))
2845 (val (car ptr) (car ptr))
2847 ((endp ptr) (nreverse result))
2849 (cons (list 'quote val)
2851 (copy-sequence initforms)))
2852 ;; compute definitive initializers
2854 (do* ;;gather the values of the most definitive forms
2855 ((ptr indices (cdr ptr))
2856 (key (caar ptr) (caar ptr))
2858 ((endp ptr) (nreverse result))
2860 (cons (eval (cdr (assoc key initalist))) result))))
2861 ;; do real initialization
2862 (apply (function vector)
2863 (cons name initializers)))))
2865 ;;;; end of cl-structs.el
2867 ;;; For lisp-interaction mode, so that multiple values can be seen when passed
2868 ;;; back. Lies every now and then...
2870 (defvar - nil "form currently under evaluation")
2871 (defvar + nil "previous -")
2872 (defvar ++ nil "previous +")
2873 (defvar +++ nil "previous ++")
2874 (defvar / nil "list of values returned by +")
2875 (defvar // nil "list of values returned by ++")
2876 (defvar /// nil "list of values returned by +++")
2877 (defvar * nil "(first) value of +")
2878 (defvar ** nil "(first) value of ++")
2879 (defvar *** nil "(first) value of +++")
2881 (defun cl-eval-print-last-sexp ()
2882 "Evaluate sexp before point; print value\(s\) into current buffer.
2883 If the evaled form returns multiple values, they are shown one to a line.
2884 The variables -, +, ++, +++, *, **, ***, /, //, /// have their usual meaning.
2886 It clears the multiple-value passing mechanism, and does not pass back
2887 multiple values. Use this only if you are debugging cl.el and understand well
2888 how the multiple-value stuff works, because it can be fooled into believing
2889 that multiple values have been returned when they actually haven't, for
2891 \(identity \(values nil 1\)\)
2892 However, even when this fails, you can trust the first printed value to be
2893 \(one of\) the returned value\(s\)."
2895 ;; top level call, can reset mvalues
2896 (setq *mvalues-count* nil
2897 *mvalues-values* nil)
2898 (setq - (car (read-from-string
2900 (let ((stab (syntax-table)))
2903 (set-syntax-table emacs-lisp-mode-syntax-table)
2906 (set-syntax-table stab)))
2917 (cond ((or (null *mvalues-count*) ;mvalues mechanism not used
2918 (not (eq * (car *mvalues-values*))))
2919 (print * (current-buffer)))
2920 ((null /) ;no values returned
2921 (terpri (current-buffer)))
2922 (t ;more than zero mvalues
2923 (terpri (current-buffer))
2924 (mapcar (function (lambda (value)
2925 (prin1 value (current-buffer))
2926 (terpri (current-buffer))))
2928 (setq *mvalues-count* nil ;make sure
2929 *mvalues-values* nil))
2931 ;;;; More LISTS functions
2934 ;;; Some mapping functions on lists, commonly useful.
2935 ;;; They take no extra sequences, to go along with Emacs Lisp's MAPCAR.
2937 (defun mapc (function list)
2938 "(MAPC FUNCTION LIST) => LIST
2939 Apply FUNCTION to each element of LIST, return LIST.
2940 Like mapcar, but called only for effect."
2943 (funcall function (car args))
2944 (setq args (cdr args))))
2947 (defun maplist (function list)
2948 "(MAPLIST FUNCTION LIST) => list'ed results of FUNCTION on cdrs of LIST
2949 Apply FUNCTION to successive sublists of LIST, return the list of the results"
2953 (setq results (cons (funcall function args) results)
2955 (nreverse results)))
2957 (defun mapl (function list)
2958 "(MAPL FUNCTION LIST) => LIST
2959 Apply FUNCTION to successive cdrs of LIST, return LIST.
2960 Like maplist, but called only for effect."
2963 (funcall function args)
2964 (setq args (cdr args)))
2967 (defun mapcan (function list)
2968 "(MAPCAN FUNCTION LIST) => nconc'd results of FUNCTION on LIST
2969 Apply FUNCTION to each element of LIST, nconc the results.
2970 Beware: nconc destroys its first argument! See copy-list."
2974 (setq results (nconc (funcall function (car args)) results)
2976 (nreverse results)))
2978 (defun mapcon (function list)
2979 "(MAPCON FUNCTION LIST) => nconc'd results of FUNCTION on cdrs of LIST
2980 Apply FUNCTION to successive sublists of LIST, nconc the results.
2981 Beware: nconc destroys its first argument! See copy-list."
2985 (setq results (nconc (funcall function args) results)
2987 (nreverse results)))
2991 (defsubst copy-list (list)
2992 "Build a copy of LIST"
2995 (defun copy-tree (tree)
2996 "Build a copy of the tree of conses TREE
2997 The argument is a tree of conses, it is recursively copied down to
2998 non conses. Circularity and sharing of substructure are not
2999 necessarily preserved."
3001 (cons (copy-tree (car tree))
3002 (copy-tree (cdr tree)))
3005 ;;; reversals, and destructive manipulations of a list's spine
3007 (defun revappend (x y)
3008 "does what (append (reverse X) Y) would, only faster"
3011 (revappend (cdr x) (cons (car x) y))))
3013 (defun nreconc (x y)
3014 "does (nconc (nreverse X) Y) would, only faster
3015 Destructive on X, be careful."
3018 ;; reuse the first cons of x, making it point to y
3019 (nreconc (cdr x) (prog1 x (rplacd x y)))))
3021 (defun nbutlast (list &optional n)
3022 "Side-effected LIST truncated N+1 conses from the end.
3023 This is the destructive version of BUTLAST. Returns () and does not
3024 modify the LIST argument if the length of the list is not at least N."
3025 (when (null n) (setf n 1))
3026 (let ((length (list-length list)))
3027 (cond ((null length)
3032 (setnthcdr (- length n) list nil)
3037 (defun subst (new old tree)
3038 "NEW replaces OLD in a copy of TREE
3039 Uses eql for the test."
3040 (subst-if new (function (lambda (x) (eql x old))) tree))
3042 (defun subst-if-not (new test tree)
3043 "NEW replaces any subtree or leaf that fails TEST in a copy of TREE"
3044 ;; (subst-if new (function (lambda (x) (not (funcall test x)))) tree)
3045 (cond ((not (funcall test tree))
3050 (let ((head (subst-if-not new test (car tree)))
3051 (tail (subst-if-not new test (cdr tree))))
3052 ;; If nothing changed, return originals. Else use the new
3053 ;; components to assemble a new tree.
3054 (if (and (eql head (car tree))
3055 (eql tail (cdr tree)))
3057 (cons head tail))))))
3059 (defun subst-if (new test tree)
3060 "NEW replaces any subtree or leaf that satisfies TEST in a copy of TREE"
3061 (cond ((funcall test tree)
3066 (let ((head (subst-if new test (car tree)))
3067 (tail (subst-if new test (cdr tree))))
3068 ;; If nothing changed, return originals. Else use the new
3069 ;; components to assemble a new tree.
3070 (if (and (eql head (car tree))
3071 (eql tail (cdr tree)))
3073 (cons head tail))))))
3075 (defun sublis (alist tree)
3076 "Use association list ALIST to modify a copy of TREE
3077 If a subtree or leaf of TREE is a key in ALIST, it is replaced by the
3078 associated value. Not exactly Common Lisp, but close in spirit and
3079 compatible with the native Emacs Lisp ASSOC, which uses EQUAL."
3080 (let ((toplevel (assoc tree alist)))
3081 (cond (toplevel ;Bingo at top
3083 ((atom tree) ;Give up on this
3086 (let ((head (sublis alist (car tree)))
3087 (tail (sublis alist (cdr tree))))
3088 (if (and (eql head (car tree))
3089 (eql tail (cdr tree)))
3091 (cons head tail)))))))
3093 (defun member-if (predicate list)
3094 "PREDICATE is applied to the members of LIST. As soon as one of them
3095 returns true, that tail of the list if returned. Else NIL."
3096 (catch 'found-member-if
3097 (while (not (endp list))
3098 (if (funcall predicate (car list))
3099 (throw 'found-member-if list)
3100 (setq list (cdr list))))
3103 (defun member-if-not (predicate list)
3104 "PREDICATE is applied to the members of LIST. As soon as one of them
3105 returns false, that tail of the list if returned. Else NIL."
3106 (catch 'found-member-if-not
3107 (while (not (endp list))
3108 (if (funcall predicate (car list))
3109 (setq list (cdr list))
3110 (throw 'found-member-if-not list)))
3113 (defun tailp (sublist list)
3114 "(tailp SUBLIST LIST) => True if SUBLIST is a sublist of LIST."
3116 (while (not (endp list))
3117 (if (eq sublist list)
3118 (throw 'tailp-found t)
3119 (setq list (cdr list))))
3122 ;;; Suggestion of phr%widow.Berkeley.EDU@lilac.berkeley.edu
3124 (defmacro declare (&rest decls)
3125 "Ignore a Common-Lisp declaration."
3126 "declarations are ignored in this implementation")
3128 (defun proclaim (&rest decls)
3129 "Ignore a Common-Lisp proclamation."
3130 "declarations are ignored in this implementation")
3132 (defmacro the (type form)
3133 "(the TYPE FORM) macroexpands to FORM
3134 No checking is even attempted. This is just for compatibility with
3138 ;;; Due to Aaron Larson (alarson@src.honeywell.com, 26 Jul 91)
3139 (put 'progv 'common-lisp-indent-hook '(4 4 &body))
3140 (defmacro progv (vars vals &rest body)
3141 "progv vars vals &body forms
3142 bind vars to vals then execute forms.
3143 If there are more vars than vals, the extra vars are unbound, if
3144 there are more vals than vars, the extra vals are just ignored."
3145 (` (progv$runtime (, vars) (, vals) (function (lambda () (,@ body))))))
3147 ;;; To do this efficiently, it really needs to be a special form...
3148 (defun progv$runtime (vars vals body)
3149 (eval (let ((vars-n-vals nil)
3151 (do ((r vars (cdr r))
3154 (push (list (car r) (list 'quote (car l))) vars-n-vals)
3156 (push (` (makunbound '(, (car r)))) unbind-forms)))
3157 (` (let (, vars-n-vals) (,@ unbind-forms) (funcall '(, body)))))))