*** empty log message ***
[bpt/emacs.git] / lisp / emacs-lisp / cust-print.el
CommitLineData
ecb4184d
ER
1;; cus-print.el -- handles print-level and print-circle.
2
e5167999
ER
3;; Author: Daniel LaLiberte <liberte@cs.uiuc.edu>
4;; Version: 1.0
5;; Last-Modified: 17 Mar 1992
6;; Adapted-By: ESR
ecb4184d
ER
7
8;; Copyright (C) 1992 Free Software Foundation, Inc.
9
10;; This file is part of GNU Emacs.
11
12;; GNU Emacs is free software; you can redistribute it and/or modify
13;; it under the terms of the GNU General Public License as published by
e5167999 14;; the Free Software Foundation; either version 2, or (at your option)
ecb4184d
ER
15;; any later version.
16
17;; GNU Emacs is distributed in the hope that it will be useful,
18;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20;; GNU General Public License for more details.
21
22;; You should have received a copy of the GNU General Public License
23;; along with GNU Emacs; see the file COPYING. If not, write to
24;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
25
e5167999
ER
26;;; Commentary:
27
ecb4184d
ER
28;; This package provides a general print handler for prin1 and princ
29;; that supports print-level and print-circle, and by the way,
30;; print-length since the standard routines are being replaced. Also,
31;; to print custom types constructed from lists and vectors, use
32;; custom-print-list and custom-print-vector. See the documentation
33;; strings of these variables for more details.
34
35;; If the results of your expressions contain circular references to
36;; other parts of the same structure, the standard Emacs print
37;; subroutines may fail to print with an untrappable error,
38;; "Apparently circular structure being printed". If you only use cdr
39;; circular lists (where cdrs of lists point back; what is the right
40;; term here?), you can limit the length of printing with
41;; print-length. But car circular lists and circular vectors generate
42;; the above mentioned untrappable error in Emacs version 18. Version
43;; 19 will support print-level, but it is often useful to get a better
44;; print representation of circular structures; the print-circle
45;; option may be used to print more concise representations.
46
47;; There are two main ways to use this package. First, you may
48;; replace prin1, princ, and some subroutines that use them by calling
49;; install-custom-print-funcs so that any use of these functions in
50;; lisp code will be affected. Second, you could call the custom
51;; routines directly, thus only affecting the printing that requires
52;; them.
53
54;; Note that subroutines which call print subroutines directly will not
55;; use the custom print functions. In particular, the evaluation
56;; functions like eval-region call the print subroutines directly.
57;; Therefore, evaluating (aref circ-list 0), which calls error
58;; directly (because circ-list is not an array), will jump to the top
59;; level instead of printing the circular list.
60
61;; Obviously the right way to implement this custom-print facility
62;; is in C. Please volunteer since I don't have the time or need.
63
64;; Implementation design: we want to use the same list and vector
65;; processing algorithm for all versions of prin1 and princ, since how
66;; the processing is done depends on print-length, print-level, and
67;; print-circle. For circle printing, a preprocessing step is
68;; required before the final printing. Thanks to Jamie Zawinski
69;; for motivation and algorithms.
70
71;;=========================================================
72;; export list:
73
74;; print-level
75;; print-circle
76
77;; custom-print-list
78;; custom-print-vector
79;; add-custom-print-list
80;; add-custom-print-vector
81
82;; install-custom-print-funcs
83;; uninstall-custom-print-funcs
84
85;; custom-prin1
86;; custom-princ
87;; custom-prin1-to-string
88;; custom-print
89;; custom-format
90;; custom-message
91;; custom-error
92
e5167999 93;;; Code:
ecb4184d
ER
94
95(provide 'custom-print)
96;; Abbreviated package name: "CP"
97
98;;(defvar print-length nil
99;; "*Controls how many elements of a list, at each level, are printed.
100;;This is defined by emacs.")
101
102(defvar print-level nil
103 "*Controls how many levels deep a nested data object will print.
104
105If nil, printing proceeds recursively and may lead to
106max-lisp-eval-depth being exceeded or an untrappable error may occur:
107\"Apparently circular structure being printed.\" Also see
108print-length and print-circle.
109
110If non-nil, components at levels equal to or greater than print-level
111are printed simply as \"#\". The object to be printed is at level 0,
112and if the object is a list or vector, its top-level components are at
113level 1.")
114
115
116(defvar print-circle nil
117 "*Controls the printing of recursive structures.
118
119If nil, printing proceeds recursively and may lead to
120max-lisp-eval-depth being exceeded or an untrappable error may occur:
121\"Apparently circular structure being printed.\" Also see
122print-length and print-level.
123
124If non-nil, shared substructures anywhere in the structure are printed
125with \"#n=\" before the first occurance (in the order of the print
126representation) and \"#n#\" in place of each subsequent occurance,
127where n is a positive decimal integer.
128
129Currently, there is no way to read this representation in Emacs.")
130
131
132(defconst custom-print-list
133 nil
134 ;; e.g. '((floatp . float-to-string))
135 "If non-nil, an alist for printing of custom list objects.
136Pairs are of the form (pred . converter). If the predicate is true
137for an object, the converter is called with the object and should
138return a string which will be printed with princ.
139Also see custom-print-vector.")
140
141(defconst custom-print-vector
142 nil
143 "If non-nil, an alist for printing of custom vector objects.
144Pairs are of the form (pred . converter). If the predicate is true
145for an object, the converter is called with the object and should
146return a string which will be printed with princ.
147Also see custom-print-list.")
148
149
150(defun add-custom-print-list (pred converter)
151 "Add the pair, a PREDICATE and a CONVERTER, to custom-print-list.
152Any pair that has the same PREDICATE is first removed."
153 (setq custom-print-list (cons (cons pred converter)
154 (delq (assq pred custom-print-list)
155 custom-print-list))))
156;; e.g. (add-custom-print-list 'floatp 'float-to-string)
157
158
159(defun add-custom-print-vector (pred converter)
160 "Add the pair, a PREDICATE and a CONVERTER, to custom-print-vector.
161Any pair that has the same PREDICATE is first removed."
162 (setq custom-print-vector (cons (cons pred converter)
163 (delq (assq pred custom-print-vector)
164 custom-print-vector))))
165
166
167;;====================================================
168;; Saving and restoring internal printing routines.
169
170(defun CP::set-function-cell (symbol-pair)
171 (fset (car symbol-pair)
172 (symbol-function (car (cdr symbol-pair)))))
173
174
175(if (not (fboundp 'CP::internal-prin1))
176 (mapcar 'CP::set-function-cell
177 '((CP::internal-prin1 prin1)
178 (CP::internal-princ princ)
179 (CP::internal-print print)
180 (CP::internal-prin1-to-string prin1-to-string)
181 (CP::internal-format format)
182 (CP::internal-message message)
183 (CP::internal-error error))))
184
185
186(defun install-custom-print-funcs ()
187 "Replace print functions with general, customizable, lisp versions.
188The internal subroutines are saved away and may be recovered with
189uninstall-custom-print-funcs."
190 (interactive)
191 (mapcar 'CP::set-function-cell
192 '((prin1 custom-prin1)
193 (princ custom-princ)
194 (print custom-print)
195 (prin1-to-string custom-prin1-to-string)
196 (format custom-format)
197 (message custom-message)
198 (error custom-error)
199 )))
200
201(defun uninstall-custom-print-funcs ()
202 "Reset print functions to their internal subroutines."
203 (interactive)
204 (mapcar 'CP::set-function-cell
205 '((prin1 CP::internal-prin1)
206 (princ CP::internal-princ)
207 (print CP::internal-print)
208 (prin1-to-string CP::internal-prin1-to-string)
209 (format CP::internal-format)
210 (message CP::internal-message)
211 (error CP::internal-error)
212 )))
213
214
215;;===============================================================
216;; Lisp replacements for prin1 and princ and for subrs that use prin1
217;; (or princ) -- so far only the printing and formatting subrs.
218
219(defun custom-prin1 (object &optional stream)
220 "Replacement for standard prin1 that uses the appropriate
221printer depending on the values of print-level and print-circle (which see).
222
223Output the printed representation of OBJECT, any Lisp object.
224Quoting characters are printed when needed to make output that `read'
225can handle, whenever this is possible.
226Output stream is STREAM, or value of `standard-output' (which see)."
227 (CP::top-level object stream 'CP::internal-prin1))
228
229
230(defun custom-princ (object &optional stream)
231 "Same as custom-prin1 except no quoting."
232 (CP::top-level object stream 'CP::internal-princ))
233
234(defun custom-prin1-to-string-func (c)
235 "Stream function for custom-prin1-to-string."
236 (setq prin1-chars (cons c prin1-chars)))
237
238(defun custom-prin1-to-string (object)
239 "Replacement for standard prin1-to-string."
240 (let ((prin1-chars nil))
241 (custom-prin1 object 'custom-prin1-to-string-func)
242 (concat (nreverse prin1-chars))))
243
244
245(defun custom-print (object &optional stream)
246 "Replacement for standard print."
247 (CP::internal-princ "\n")
248 (custom-prin1 object stream)
249 (CP::internal-princ "\n"))
250
251
252(defun custom-format (fmt &rest args)
253 "Replacement for standard format.
254
255Calls format after first making strings for list or vector args.
256The format specification for such args should be %s in any case, so a
257string argument will also work. The string is generated with
258custom-prin1-to-string, which quotes quotable characters."
259 (apply 'CP::internal-format fmt
260 (mapcar (function (lambda (arg)
261 (if (or (listp arg) (vectorp arg))
262 (custom-prin1-to-string arg)
263 arg)))
264 args)))
265
266
267
268(defun custom-message (fmt &rest args)
269 "Replacement for standard message that works like custom-format."
270 ;; It doesnt work to princ the result of custom-format
271 ;; because the echo area requires special handling
272 ;; to avoid duplicating the output. CP::internal-message does it right.
273 ;; (CP::internal-princ (apply 'custom-format fmt args))
274 (apply 'CP::internal-message fmt
275 (mapcar (function (lambda (arg)
276 (if (or (listp arg) (vectorp arg))
277 (custom-prin1-to-string arg)
278 arg)))
279 args)))
280
281
282(defun custom-error (fmt &rest args)
283 "Replacement for standard error that uses custom-format"
284 (signal 'error (list (apply 'custom-format fmt args))))
285
286
287;;=========================================
288;; Support for custom prin1 and princ
289
290(defun CP::top-level (object stream internal-printer)
291 "Set up for printing."
292 (let ((standard-output (or stream standard-output))
293 (circle-table (and print-circle (CP::preprocess-circle-tree object)))
294 (level (or print-level -1))
295 )
296
297 (fset 'CP::internal-printer internal-printer)
298 (fset 'CP::low-level-prin
299 (cond
300 ((or custom-print-list
301 custom-print-vector
302 print-level ; comment out for version 19
303 )
304 'CP::custom-object)
305 (circle-table
306 'CP::object)
307 (t 'CP::internal-printer)))
308 (fset 'CP::prin (if circle-table 'CP::circular 'CP::low-level-prin))
309
310 (CP::prin object)
311 object))
312
313
314(defun CP::object (object)
315 "Test object type and print accordingly."
316 ;; Could be called as either CP::low-level-prin or CP::prin.
317 (cond
318 ((null object) (CP::internal-printer object))
319 ((consp object) (CP::list object))
320 ((vectorp object) (CP::vector object))
321 ;; All other types, just print.
322 (t (CP::internal-printer object))))
323
324
325(defun CP::custom-object (object)
326 "Test object type and print accordingly."
327 ;; Could be called as either CP::low-level-prin or CP::prin.
328 (cond
329 ((null object) (CP::internal-printer object))
330
331 ((consp object)
332 (or (and custom-print-list
333 (CP::custom-object1 object custom-print-list))
334 (CP::list object)))
335
336 ((vectorp object)
337 (or (and custom-print-vector
338 (CP::custom-object1 object custom-print-vector))
339 (CP::vector object)))
340
341 ;; All other types, just print.
342 (t (CP::internal-printer object))))
343
344
345(defun CP::custom-object1 (object alist)
346 "Helper for CP::custom-object.
347Print the custom OBJECT using the custom type ALIST.
348For the first predicate that matches the object, the corresponding
349converter is evaluated with the object and the string that results is
350printed with princ. Return nil if no predicte matches the object."
351 (while (and alist (not (funcall (car (car alist)) object)))
352 (setq alist (cdr alist)))
353 ;; If alist is not null, then something matched.
354 (if alist
355 (CP::internal-princ
356 (funcall (cdr (car alist)) object) ; returns string
357 )))
358
359
360(defun CP::circular (object)
361 "Printer for prin1 and princ that handles circular structures.
362If OBJECT appears multiply, and has not yet been printed,
363prefix with label; if it has been printed, use #n# instead.
364Otherwise, print normally."
365 (let ((tag (assq object circle-table)))
366 (if tag
367 (let ((id (cdr tag)))
368 (if (> id 0)
369 (progn
370 ;; Already printed, so just print id.
371 (CP::internal-princ "#")
372 (CP::internal-princ id)
373 (CP::internal-princ "#"))
374 ;; Not printed yet, so label with id and print object.
375 (setcdr tag (- id)) ; mark it as printed
376 (CP::internal-princ "#")
377 (CP::internal-princ (- id))
378 (CP::internal-princ "=")
379 (CP::low-level-prin object)
380 ))
381 ;; Not repeated in structure.
382 (CP::low-level-prin object))))
383
384
385;;================================================
386;; List and vector processing for print functions.
387
388(defun CP::list (list)
389 "Print a list using print-length, print-level, and print-circle."
390 (if (= level 0)
391 (CP::internal-princ "#")
392 (let ((level (1- level)))
393 (CP::internal-princ "(")
394 (let ((length (or print-length 0)))
395
396 ;; Print the first element always (even if length = 0).
397 (CP::prin (car list))
398 (setq list (cdr list))
399 (if list (CP::internal-princ " "))
400 (setq length (1- length))
401
402 ;; Print the rest of the elements.
403 (while (and list (/= 0 length))
404 (if (and (listp list)
405 (not (assq list circle-table)))
406 (progn
407 (CP::prin (car list))
408 (setq list (cdr list)))
409
410 ;; cdr is not a list, or it is in circle-table.
411 (CP::internal-princ ". ")
412 (CP::prin list)
413 (setq list nil))
414
415 (setq length (1- length))
416 (if list (CP::internal-princ " ")))
417
418 (if (and list (= length 0)) (CP::internal-princ "..."))
419 (CP::internal-princ ")"))))
420 list)
421
422
423(defun CP::vector (vector)
424 "Print a vector using print-length, print-level, and print-circle."
425 (if (= level 0)
426 (CP::internal-princ "#")
427 (let ((level (1- level))
428 (i 0)
429 (len (length vector)))
430 (CP::internal-princ "[")
431
432 (if print-length
433 (setq len (min print-length len)))
434 ;; Print the elements
435 (while (< i len)
436 (CP::prin (aref vector i))
437 (setq i (1+ i))
438 (if (< i (length vector)) (CP::internal-princ " ")))
439
440 (if (< i (length vector)) (CP::internal-princ "..."))
441 (CP::internal-princ "]")
442 ))
443 vector)
444
445
446;;==================================
447;; Circular structure preprocessing
448
449(defun CP::preprocess-circle-tree (object)
450 ;; Fill up the table.
451 (let (;; Table of tags for each object in an object to be printed.
452 ;; A tag is of the form:
453 ;; ( <object> <nil-t-or-id-number> )
454 ;; The id-number is generated after the entire table has been computed.
455 ;; During walk through, the real circle-table lives in the cdr so we
456 ;; can use setcdr to add new elements instead of having to setq the
457 ;; variable sometimes (poor man's locf).
458 (circle-table (list nil)))
459 (CP::walk-circle-tree object)
460
461 ;; Reverse table so it is in the order that the objects will be printed.
462 ;; This pass could be avoided if we always added to the end of the
463 ;; table with setcdr in walk-circle-tree.
464 (setcdr circle-table (nreverse (cdr circle-table)))
465
466 ;; Walk through the table, assigning id-numbers to those
467 ;; objects which will be printed using #N= syntax. Delete those
468 ;; objects which will be printed only once (to speed up assq later).
469 (let ((rest circle-table)
470 (id -1))
471 (while (cdr rest)
472 (let ((tag (car (cdr rest))))
473 (cond ((cdr tag)
474 (setcdr tag id)
475 (setq id (1- id))
476 (setq rest (cdr rest)))
477 ;; Else delete this object.
478 (t (setcdr rest (cdr (cdr rest))))))
479 ))
480 ;; Drop the car.
481 (cdr circle-table)
482 ))
483
484
485
486(defun CP::walk-circle-tree (object)
487 (let (read-equivalent-p tag)
488 (while object
489 (setq read-equivalent-p (or (numberp object) (symbolp object))
490 tag (and (not read-equivalent-p)
491 (assq object (cdr circle-table))))
492 (cond (tag
493 ;; Seen this object already, so note that.
494 (setcdr tag t))
495
496 ((not read-equivalent-p)
497 ;; Add a tag for this object.
498 (setcdr circle-table
499 (cons (list object)
500 (cdr circle-table)))))
501 (setq object
502 (cond
503 (tag ;; No need to descend since we have already.
504 nil)
505
506 ((consp object)
507 ;; Walk the car of the list recursively.
508 (CP::walk-circle-tree (car object))
509 ;; But walk the cdr with the above while loop
510 ;; to avoid problems with max-lisp-eval-depth.
511 ;; And it should be faster than recursion.
512 (cdr object))
513
514 ((vectorp object)
515 ;; Walk the vector.
516 (let ((i (length object))
517 (j 0))
518 (while (< j i)
519 (CP::walk-circle-tree (aref object j))
520 (setq j (1+ j))))))))))
521
522
523
524;;=======================================
525
526(quote
527 examples
528
529 (progn
530 ;; Create some circular structures.
531 (setq circ-sym (let ((x (make-symbol "FOO"))) (list x x)))
532 (setq circ-list (list 'a 'b (vector 1 2 3 4) 'd 'e 'f))
533 (setcar (nthcdr 3 circ-list) circ-list)
534 (aset (nth 2 circ-list) 2 circ-list)
535 (setq dotted-circ-list (list 'a 'b 'c))
536 (setcdr (cdr (cdr dotted-circ-list)) dotted-circ-list)
537 (setq circ-vector (vector 1 2 3 4 (list 'a 'b 'c 'd) 6 7))
538 (aset circ-vector 5 (make-symbol "-gensym-"))
539 (setcar (cdr (aref circ-vector 4)) (aref circ-vector 5))
540 nil)
541
542 (install-custom-print-funcs)
543 ;; (setq print-circle t)
544
545 (let ((print-circle t))
546 (or (equal (prin1-to-string circ-list) "#1=(a b [1 2 #1# 4] #1# e f)")
547 (error "circular object with array printing")))
548
549 (let ((print-circle t))
550 (or (equal (prin1-to-string dotted-circ-list) "#1=(a b c . #1#)")
551 (error "circular object with array printing")))
552
553 (let* ((print-circle t)
554 (x (list 'p 'q))
555 (y (list (list 'a 'b) x 'foo x)))
556 (setcdr (cdr (cdr (cdr y))) (cdr y))
557 (or (equal (prin1-to-string y) "((a b) . #1=(#2=(p q) foo #2# . #1#))"
558 )
559 (error "circular list example from CL manual")))
560
561 ;; There's no special handling of uninterned symbols in custom-print.
562 (let ((print-circle nil))
563 (or (equal (prin1-to-string circ-sym) "(#:FOO #:FOO)")
564 (error "uninterned symbols in list")))
565 (let ((print-circle t))
566 (or (equal (prin1-to-string circ-sym) "(#1=FOO #1#)")
567 (error "circular uninterned symbols in list")))
568
569 (uninstall-custom-print-funcs)
570 )
571
572;;; cus-print.el ends here