"If non-nil, try and make sure the result can be `read'.")
(defvar cl-print--number-table nil)
+(defvar cl-print--currently-printing nil)
;;;###autoload
(cl-defgeneric cl-print-object (object stream)
(princ "(" stream)
(cl-print-object car stream)
(while (and (consp object)
- (not (and cl-print--number-table
- (numberp (gethash object cl-print--number-table)))))
+ (not (if cl-print--number-table
+ (numberp (gethash object cl-print--number-table))
+ (memq object cl-print--currently-printing))))
(princ " " stream)
(cl-print-object (pop object) stream))
(when object
(cl-defmethod cl-print-object :around (object stream)
;; FIXME: Only put such an :around method on types where it's relevant.
- (let ((n (if cl-print--number-table (gethash object cl-print--number-table))))
- (if (not (numberp n))
- (cl-call-next-method)
- (if (> n 0)
- ;; Already printed. Just print a reference.
- (progn (princ "#" stream) (princ n stream) (princ "#" stream))
- (puthash object (- n) cl-print--number-table)
- (princ "#" stream) (princ (- n) stream) (princ "=" stream)
- (cl-call-next-method)))))
+ (cond
+ (print-circle
+ (let ((n (gethash object cl-print--number-table)))
+ (if (not (numberp n))
+ (cl-call-next-method)
+ (if (> n 0)
+ ;; Already printed. Just print a reference.
+ (progn (princ "#" stream) (princ n stream) (princ "#" stream))
+ (puthash object (- n) cl-print--number-table)
+ (princ "#" stream) (princ (- n) stream) (princ "=" stream)
+ (cl-call-next-method)))))
+ ((let ((already-printing (memq object cl-print--currently-printing)))
+ (when already-printing
+ ;; Currently printing, just print reference to avoid endless
+ ;; recursion.
+ (princ "#" stream)
+ (princ (length (cdr already-printing)) stream))))
+ (t (let ((cl-print--currently-printing
+ (cons object cl-print--currently-printing)))
+ (cl-call-next-method)))))
(defvar cl-print--number-index nil)
"\\`(#1=#s(foo 1 2 3) #1#)\\'"
(cl-prin1-to-string (list x x)))))))
+(ert-deftest cl-print-circle ()
+ (let ((x '(#1=(a . #1#) #1#)))
+ (let ((print-circle nil))
+ (should (string-match "\\`((a . #[0-9]) (a . #[0-9]))\\'"
+ (cl-prin1-to-string x))))
+ (let ((print-circle t))
+ (should (equal "(#1=(a . #1#) #1#)" (cl-prin1-to-string x))))))
+
;;; cl-print-tests.el ends here.