home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Source Code 1993 July / THE_SOURCE_CODE_CD_ROM.iso / languages / elisp / functions / custom-print.el < prev    next >
Encoding:
Text File  |  1992-03-23  |  19.3 KB  |  586 lines

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