1.0.37.2.: document UNLOAD-SHARED-OBJECT in the manual
[sbcl.git] / doc / manual / docstrings.lisp
1 ;;; -*- lisp -*-
2
3 ;;;; A docstring extractor for the sbcl manual.  Creates
4 ;;;; @include-ready documentation from the docstrings of exported
5 ;;;; symbols of specified packages.
6
7 ;;;; This software is part of the SBCL software system. SBCL is in the
8 ;;;; public domain and is provided with absolutely no warranty. See
9 ;;;; the COPYING file for more information.
10 ;;;;
11 ;;;; Written by Rudi Schlatte <rudi@constantly.at>, mangled
12 ;;;; by Nikodemus Siivola.
13
14 ;;;; TODO
15 ;;;; * Verbatim text
16 ;;;; * Quotations
17 ;;;; * Method documentation untested
18 ;;;; * Method sorting, somehow
19 ;;;; * Index for macros & constants?
20 ;;;; * This is getting complicated enough that tests would be good
21 ;;;; * Nesting (currently only nested itemizations work)
22 ;;;; * doc -> internal form -> texinfo (so that non-texinfo format are also
23 ;;;;   easily generated)
24
25 ;;;; FIXME: The description below is no longer complete. This
26 ;;;; should possibly be turned into a contrib with proper documentation.
27
28 ;;;; Formatting heuristics (tweaked to format SAVE-LISP-AND-DIE sanely):
29 ;;;;
30 ;;;; Formats SYMBOL as @code{symbol}, or @var{symbol} if symbol is in
31 ;;;; the argument list of the defun / defmacro.
32 ;;;;
33 ;;;; Lines starting with * or - that are followed by intented lines
34 ;;;; are marked up with @itemize.
35 ;;;;
36 ;;;; Lines containing only a SYMBOL that are followed by indented
37 ;;;; lines are marked up as @table @code, with the SYMBOL as the item.
38
39 (eval-when (:compile-toplevel :load-toplevel :execute)
40   (require 'sb-introspect))
41
42 (defpackage :sb-texinfo
43   (:use :cl :sb-mop)
44   (:shadow #:documentation)
45   (:export #:generate-includes #:document-package)
46   (:documentation
47    "Tools to generate TexInfo documentation from docstrings."))
48
49 (in-package :sb-texinfo)
50
51 ;;;; various specials and parameters
52
53 (defvar *texinfo-output*)
54 (defvar *texinfo-variables*)
55 (defvar *documentation-package*)
56
57 (defparameter *undocumented-packages* '(sb-pcl sb-int sb-kernel sb-sys sb-c))
58
59 (defparameter *documentation-types*
60   '(compiler-macro
61     function
62     method-combination
63     setf
64     ;;structure  ; also handled by `type'
65     type
66     variable)
67   "A list of symbols accepted as second argument of `documentation'")
68
69 (defparameter *character-replacements*
70   '((#\* . "star") (#\/ . "slash") (#\+ . "plus")
71     (#\< . "lt") (#\> . "gt"))
72   "Characters and their replacement names that `alphanumize' uses. If
73 the replacements contain any of the chars they're supposed to replace,
74 you deserve to lose.")
75
76 (defparameter *characters-to-drop* '(#\\ #\` #\')
77   "Characters that should be removed by `alphanumize'.")
78
79 (defparameter *texinfo-escaped-chars* "@{}"
80   "Characters that must be escaped with #\@ for Texinfo.")
81
82 (defparameter *itemize-start-characters* '(#\* #\-)
83   "Characters that might start an itemization in docstrings when
84   at the start of a line.")
85
86 (defparameter *symbol-characters* "ABCDEFGHIJKLMNOPQRSTUVWXYZ*:-+&#'"
87   "List of characters that make up symbols in a docstring.")
88
89 (defparameter *symbol-delimiters* " ,.!?;")
90
91 (defparameter *ordered-documentation-kinds*
92   '(package type structure condition class macro))
93
94 ;;;; utilities
95
96 (defun flatten (list)
97   (cond ((null list)
98          nil)
99         ((consp (car list))
100          (nconc (flatten (car list)) (flatten (cdr list))))
101         ((null (cdr list))
102          (cons (car list) nil))
103         (t
104          (cons (car list) (flatten (cdr list))))))
105
106 (defun whitespacep (char)
107   (find char #(#\tab #\space #\page)))
108
109 (defun setf-name-p (name)
110   (or (symbolp name)
111       (and (listp name) (= 2 (length name)) (eq (car name) 'setf))))
112
113 (defgeneric specializer-name (specializer))
114
115 (defmethod specializer-name ((specializer eql-specializer))
116   (list 'eql (eql-specializer-object specializer)))
117
118 (defmethod specializer-name ((specializer class))
119   (class-name specializer))
120
121 (defun ensure-class-precedence-list (class)
122   (unless (class-finalized-p class)
123     (finalize-inheritance class))
124   (class-precedence-list class))
125
126 (defun specialized-lambda-list (method)
127   ;; courtecy of AMOP p. 61
128   (let* ((specializers (method-specializers method))
129          (lambda-list (method-lambda-list method))
130          (n-required (length specializers)))
131     (append (mapcar (lambda (arg specializer)
132                       (if  (eq specializer (find-class 't))
133                            arg
134                            `(,arg ,(specializer-name specializer))))
135                     (subseq lambda-list 0 n-required)
136                     specializers)
137            (subseq lambda-list n-required))))
138
139 (defun string-lines (string)
140   "Lines in STRING as a vector."
141   (coerce (with-input-from-string (s string)
142             (loop for line = (read-line s nil nil)
143                while line collect line))
144           'vector))
145
146 (defun indentation (line)
147   "Position of first non-SPACE character in LINE."
148   (position-if-not (lambda (c) (char= c #\Space)) line))
149
150 (defun docstring (x doc-type)
151   (cl:documentation x doc-type))
152
153 (defun flatten-to-string (list)
154   (format nil "~{~A~^-~}" (flatten list)))
155
156 (defun alphanumize (original)
157   "Construct a string without characters like *`' that will f-star-ck
158 up filename handling. See `*character-replacements*' and
159 `*characters-to-drop*' for customization."
160   (let ((name (remove-if (lambda (x) (member x *characters-to-drop*))
161                          (if (listp original)
162                              (flatten-to-string original)
163                              (string original))))
164         (chars-to-replace (mapcar #'car *character-replacements*)))
165     (flet ((replacement-delimiter (index)
166              (cond ((or (< index 0) (>= index (length name))) "")
167                    ((alphanumericp (char name index)) "-")
168                    (t ""))))
169       (loop for index = (position-if #'(lambda (x) (member x chars-to-replace))
170                                      name)
171          while index
172          do (setf name (concatenate 'string (subseq name 0 index)
173                                     (replacement-delimiter (1- index))
174                                     (cdr (assoc (aref name index)
175                                                 *character-replacements*))
176                                     (replacement-delimiter (1+ index))
177                                     (subseq name (1+ index))))))
178     name))
179
180 ;;;; generating various names
181
182 (defgeneric name (thing)
183   (:documentation "Name for a documented thing. Names are either
184 symbols or lists of symbols."))
185
186 (defmethod name ((symbol symbol))
187   symbol)
188
189 (defmethod name ((cons cons))
190   cons)
191
192 (defmethod name ((package package))
193   (package-name package))
194
195 (defmethod name ((method method))
196   (list
197    (generic-function-name (method-generic-function method))
198    (method-qualifiers method)
199    (specialized-lambda-list method)))
200
201 ;;; Node names for DOCUMENTATION instances
202
203 (defgeneric name-using-kind/name (kind name doc))
204
205 (defmethod name-using-kind/name (kind (name string) doc)
206   (declare (ignore kind doc))
207   name)
208
209 (defmethod name-using-kind/name (kind (name symbol) doc)
210   (declare (ignore kind))
211   (format nil "~A:~A" (package-name (get-package doc)) name))
212
213 (defmethod name-using-kind/name (kind (name list) doc)
214   (declare (ignore kind))
215   (assert (setf-name-p name))
216   (format nil "(setf ~A:~A)" (package-name (get-package doc)) (second name)))
217
218 (defmethod name-using-kind/name ((kind (eql 'method)) name doc)
219   (format nil "~A~{ ~A~} ~A"
220           (name-using-kind/name nil (first name) doc)
221           (second name)
222           (third name)))
223
224 (defun node-name (doc)
225   "Returns TexInfo node name as a string for a DOCUMENTATION instance."
226   (let ((kind (get-kind doc)))
227     (format nil "~:(~A~) ~(~A~)" kind (name-using-kind/name kind (get-name doc) doc))))
228
229 (defun short-package-name (package)
230   (car (sort (copy-list (cons (package-name package) (package-nicknames package)))
231              #'< :key #'length)))
232
233 ;;; Definition titles for DOCUMENTATION instances
234
235 (defgeneric title-using-kind/name (kind name doc))
236
237 (defmethod title-using-kind/name (kind (name string) doc)
238   (declare (ignore kind doc))
239   name)
240
241 (defmethod title-using-kind/name (kind (name symbol) doc)
242   (declare (ignore kind))
243   (format nil "~A:~A" (short-package-name (get-package doc)) name))
244
245 (defmethod title-using-kind/name (kind (name list) doc)
246   (declare (ignore kind))
247   (assert (setf-name-p name))
248   (format nil "(setf ~A:~A)" (short-package-name (get-package doc)) (second name)))
249
250 (defmethod title-using-kind/name ((kind (eql 'method)) name doc)
251   (format nil "~{~A ~}~A"
252           (second name)
253           (title-using-kind/name nil (first name) doc)))
254
255 (defun title-name (doc)
256   "Returns a string to be used as name of the definition."
257   (string-downcase (title-using-kind/name (get-kind doc) (get-name doc) doc)))
258
259 (defun include-pathname (doc)
260   (let* ((kind (get-kind doc))
261          (name (nstring-downcase
262                 (if (eq 'package kind)
263                     (format nil "package-~A" (alphanumize (get-name doc)))
264                     (format nil "~A-~A-~A"
265                             (case (get-kind doc)
266                               ((function generic-function) "fun")
267                               (structure "struct")
268                               (variable "var")
269                               (otherwise (symbol-name (get-kind doc))))
270                             (alphanumize (package-name (get-package doc)))
271                             (alphanumize (get-name doc)))))))
272     (make-pathname :name name  :type "texinfo")))
273
274 ;;;; documentation class and related methods
275
276 (defclass documentation ()
277   ((name :initarg :name :reader get-name)
278    (kind :initarg :kind :reader get-kind)
279    (string :initarg :string :reader get-string)
280    (children :initarg :children :initform nil :reader get-children)
281    (package :initform *documentation-package* :reader get-package)))
282
283 (defmethod print-object ((documentation documentation) stream)
284   (print-unreadable-object (documentation stream :type t)
285     (princ (list (get-kind documentation) (get-name documentation)) stream)))
286
287 (defgeneric make-documentation (x doc-type string))
288
289 (defmethod make-documentation ((x package) doc-type string)
290   (declare (ignore doc-type))
291   (make-instance 'documentation
292                  :name (name x)
293                  :kind 'package
294                  :string string))
295
296 (defmethod make-documentation (x (doc-type (eql 'function)) string)
297   (declare (ignore doc-type))
298   (let* ((fdef (and (fboundp x) (fdefinition x)))
299          (name x)
300          (kind (cond ((and (symbolp x) (special-operator-p x))
301                       'special-operator)
302                      ((and (symbolp x) (macro-function x))
303                       'macro)
304                      ((typep fdef 'generic-function)
305                       (assert (or (symbolp name) (setf-name-p name)))
306                       'generic-function)
307                      (fdef
308                       (assert (or (symbolp name) (setf-name-p name)))
309                       'function)))
310          (children (when (eq kind 'generic-function)
311                      (collect-gf-documentation fdef))))
312     (make-instance 'documentation
313                    :name (name x)
314                    :string string
315                    :kind kind
316                    :children children)))
317
318 (defmethod make-documentation ((x method) doc-type string)
319   (declare (ignore doc-type))
320   (make-instance 'documentation
321                  :name (name x)
322                  :kind 'method
323                  :string string))
324
325 (defmethod make-documentation (x (doc-type (eql 'type)) string)
326   (make-instance 'documentation
327                  :name (name x)
328                  :string string
329                  :kind (etypecase (find-class x nil)
330                          (structure-class 'structure)
331                          (standard-class 'class)
332                          (sb-pcl::condition-class 'condition)
333                          ((or built-in-class null) 'type))))
334
335 (defmethod make-documentation (x (doc-type (eql 'variable)) string)
336   (make-instance 'documentation
337                  :name (name x)
338                  :string string
339                  :kind (if (constantp x)
340                            'constant
341                            'variable)))
342
343 (defmethod make-documentation (x (doc-type (eql 'setf)) string)
344   (declare (ignore doc-type))
345   (make-instance 'documentation
346                  :name (name x)
347                  :kind 'setf-expander
348                  :string string))
349
350 (defmethod make-documentation (x doc-type string)
351   (make-instance 'documentation
352                  :name (name x)
353                  :kind doc-type
354                  :string string))
355
356 (defun maybe-documentation (x doc-type)
357   "Returns a DOCUMENTATION instance for X and DOC-TYPE, or NIL if
358 there is no corresponding docstring."
359   (let ((docstring (docstring x doc-type)))
360     (when docstring
361       (make-documentation x doc-type docstring))))
362
363 (defun lambda-list (doc)
364   (case (get-kind doc)
365     ((package constant variable type structure class condition nil)
366      nil)
367     (method
368      (third (get-name doc)))
369     (t
370      ;; KLUDGE: Eugh.
371      ;;
372      ;; believe it or not, the above comment was written before CSR
373      ;; came along and obfuscated this.  (2005-07-04)
374      (when (symbolp (get-name doc))
375        (labels ((clean (x &key optional key)
376                   (typecase x
377                     (atom x)
378                     ((cons (member &optional))
379                      (cons (car x) (clean (cdr x) :optional t)))
380                     ((cons (member &key))
381                      (cons (car x) (clean (cdr x) :key t)))
382                     ((cons cons)
383                      (cons
384                       (cond (key (if (consp (caar x))
385                                      (caaar x)
386                                      (caar x)))
387                             (optional (caar x))
388                             (t (clean (car x))))
389                       (clean (cdr x) :key key :optional optional)))
390                     (cons
391                      (cons
392                       (cond ((or key optional) (car x))
393                             (t (clean (car x))))
394                       (clean (cdr x) :key key :optional optional))))))
395          (clean (sb-introspect:function-lambda-list (get-name doc))))))))
396
397 (defun get-string-name (x)
398   (let ((name (get-name x)))
399     (cond ((symbolp name)
400            (symbol-name name))
401           ((and (consp name) (eq 'setf (car name)))
402            (symbol-name (second name)))
403           ((stringp name)
404            name)
405           (t
406            (error "Don't know which symbol to use for name ~S" name)))))
407
408 (defun documentation< (x y)
409   (let ((p1 (position (get-kind x) *ordered-documentation-kinds*))
410         (p2 (position (get-kind y) *ordered-documentation-kinds*)))
411     (if (or (not (and p1 p2)) (= p1 p2))
412         (string< (get-string-name x) (get-string-name y))
413         (< p1 p2))))
414
415 ;;;; turning text into texinfo
416
417 (defun escape-for-texinfo (string &optional downcasep)
418   "Return STRING with characters in *TEXINFO-ESCAPED-CHARS* escaped
419 with #\@. Optionally downcase the result."
420   (let ((result (with-output-to-string (s)
421                   (loop for char across string
422                         when (find char *texinfo-escaped-chars*)
423                         do (write-char #\@ s)
424                         do (write-char char s)))))
425     (if downcasep (nstring-downcase result) result)))
426
427 (defun empty-p (line-number lines)
428   (and (< -1 line-number (length lines))
429        (not (indentation (svref lines line-number)))))
430
431 ;;; line markups
432
433 (defvar *not-symbols* '("ANSI" "CLHS"))
434
435 (defun locate-symbols (line)
436   "Return a list of index pairs of symbol-like parts of LINE."
437   ;; This would be a good application for a regex ...
438   (let (result)
439     (flet ((grab (start end)
440              (unless (member (subseq line start end) '("ANSI" "CLHS"))
441                (push (list start end) result))))
442       (do ((begin nil)
443            (maybe-begin t)
444            (i 0 (1+ i)))
445           ((= i (length line))
446            ;; symbol at end of line
447            (when (and begin (or (> i (1+ begin))
448                                 (not (member (char line begin) '(#\A #\I)))))
449              (grab begin i))
450            (nreverse result))
451         (cond
452           ((and begin (find (char line i) *symbol-delimiters*))
453            ;; symbol end; remember it if it's not "A" or "I"
454            (when (or (> i (1+ begin)) (not (member (char line begin) '(#\A #\I))))
455              (grab begin i))
456            (setf begin nil
457                  maybe-begin t))
458           ((and begin (not (find (char line i) *symbol-characters*)))
459            ;; Not a symbol: abort
460            (setf begin nil))
461           ((and maybe-begin (not begin) (find (char line i) *symbol-characters*))
462            ;; potential symbol begin at this position
463            (setf begin i
464                  maybe-begin nil))
465           ((find (char line i) *symbol-delimiters*)
466            ;; potential symbol begin after this position
467            (setf maybe-begin t))
468           (t
469            ;; Not reading a symbol, not at potential start of symbol
470            (setf maybe-begin nil)))))))
471
472 (defun texinfo-line (line)
473   "Format symbols in LINE texinfo-style: either as code or as
474 variables if the symbol in question is contained in symbols
475 *TEXINFO-VARIABLES*."
476   (with-output-to-string (result)
477     (let ((last 0))
478       (dolist (symbol/index (locate-symbols line))
479         (write-string (subseq line last (first symbol/index)) result)
480         (let ((symbol-name (apply #'subseq line symbol/index)))
481           (format result (if (member symbol-name *texinfo-variables*
482                                      :test #'string=)
483                              "@var{~A}"
484                              "@code{~A}")
485                   (string-downcase symbol-name)))
486         (setf last (second symbol/index)))
487       (write-string (subseq line last) result))))
488
489 ;;; lisp sections
490
491 (defun lisp-section-p (line line-number lines)
492   "Returns T if the given LINE looks like start of lisp code --
493 ie. if it starts with whitespace followed by a paren or
494 semicolon, and the previous line is empty"
495   (let ((offset (indentation line)))
496     (and offset
497          (plusp offset)
498          (find (find-if-not #'whitespacep line) "(;")
499          (empty-p (1- line-number) lines))))
500
501 (defun collect-lisp-section (lines line-number)
502   (flet ((maybe-line (index)
503            (and (< index (length lines)) (svref lines index))))
504     (let ((lisp (loop for index = line-number then (1+ index)
505                       for line = (maybe-line index)
506                       while (or (indentation line)
507                                 ;; Allow empty lines in middle of lisp sections.
508                                 (let ((next (1+ index)))
509                                   (lisp-section-p (maybe-line next) next lines)))
510                       collect line)))
511      (values (length lisp) `("@lisp" ,@lisp "@end lisp")))))
512
513 ;;; itemized sections
514
515 (defun maybe-itemize-offset (line)
516   "Return NIL or the indentation offset if LINE looks like it starts
517 an item in an itemization."
518   (let* ((offset (indentation line))
519          (char (when offset (char line offset))))
520     (and offset
521          (member char *itemize-start-characters* :test #'char=)
522          (char= #\Space (find-if-not (lambda (c) (char= c char))
523                                      line :start offset))
524          offset)))
525
526 (defun collect-maybe-itemized-section (lines starting-line)
527   ;; Return index of next line to be processed outside
528   (let ((this-offset (maybe-itemize-offset (svref lines starting-line)))
529         (result nil)
530         (lines-consumed 0))
531     (loop for line-number from starting-line below (length lines)
532        for line = (svref lines line-number)
533        for indentation = (indentation line)
534        for offset = (maybe-itemize-offset line)
535        do (cond
536             ((not indentation)
537              ;; empty line -- inserts paragraph.
538              (push "" result)
539              (incf lines-consumed))
540             ((and offset (> indentation this-offset))
541              ;; nested itemization -- handle recursively
542              ;; FIXME: tables in itemizations go wrong
543              (multiple-value-bind (sub-lines-consumed sub-itemization)
544                  (collect-maybe-itemized-section lines line-number)
545                (when sub-lines-consumed
546                  (incf line-number (1- sub-lines-consumed)) ; +1 on next loop
547                  (incf lines-consumed sub-lines-consumed)
548                  (setf result (nconc (nreverse sub-itemization) result)))))
549             ((and offset (= indentation this-offset))
550              ;; start of new item
551              (push (format nil "@item ~A"
552                            (texinfo-line (subseq line (1+ offset))))
553                    result)
554              (incf lines-consumed))
555             ((and (not offset) (> indentation this-offset))
556              ;; continued item from previous line
557              (push (texinfo-line line) result)
558              (incf lines-consumed))
559             (t
560              ;; end of itemization
561              (loop-finish))))
562     ;; a single-line itemization isn't.
563     (if (> (count-if (lambda (line) (> (length line) 0)) result) 1)
564         (values lines-consumed `("@itemize" ,@(reverse result) "@end itemize"))
565         nil)))
566
567 ;;; table sections
568
569 (defun tabulation-body-p (offset line-number lines)
570   (when (< line-number (length lines))
571     (let ((offset2 (indentation (svref lines line-number))))
572       (and offset2 (< offset offset2)))))
573
574 (defun tabulation-p (offset line-number lines direction)
575   (let ((step  (ecase direction
576                  (:backwards (1- line-number))
577                  (:forwards (1+ line-number)))))
578     (when (and (plusp line-number) (< line-number (length lines)))
579       (and (eql offset (indentation (svref lines line-number)))
580            (or (when (eq direction :backwards)
581                  (empty-p step lines))
582                (tabulation-p offset step lines direction)
583                (tabulation-body-p offset step lines))))))
584
585 (defun maybe-table-offset (line-number lines)
586   "Return NIL or the indentation offset if LINE looks like it starts
587 an item in a tabulation. Ie, if it is (1) indented, (2) preceded by an
588 empty line, another tabulation label, or a tabulation body, (3) and
589 followed another tabulation label or a tabulation body."
590   (let* ((line (svref lines line-number))
591          (offset (indentation line))
592          (prev (1- line-number))
593          (next (1+ line-number)))
594     (when (and offset (plusp offset))
595       (and (or (empty-p prev lines)
596                (tabulation-body-p offset prev lines)
597                (tabulation-p offset prev lines :backwards))
598            (or (tabulation-body-p offset next lines)
599                (tabulation-p offset next lines :forwards))
600            offset))))
601
602 ;;; FIXME: This and itemization are very similar: could they share
603 ;;; some code, mayhap?
604
605 (defun collect-maybe-table-section (lines starting-line)
606   ;; Return index of next line to be processed outside
607   (let ((this-offset (maybe-table-offset starting-line lines))
608         (result nil)
609         (lines-consumed 0))
610     (loop for line-number from starting-line below (length lines)
611           for line = (svref lines line-number)
612           for indentation = (indentation line)
613           for offset = (maybe-table-offset line-number lines)
614           do (cond
615                ((not indentation)
616                 ;; empty line -- inserts paragraph.
617                 (push "" result)
618                 (incf lines-consumed))
619                ((and offset (= indentation this-offset))
620                 ;; start of new item, or continuation of previous item
621                 (if (and result (search "@item" (car result) :test #'char=))
622                     (push (format nil "@itemx ~A" (texinfo-line line))
623                           result)
624                     (progn
625                       (push "" result)
626                       (push (format nil "@item ~A" (texinfo-line line))
627                             result)))
628                 (incf lines-consumed))
629                ((> indentation this-offset)
630                 ;; continued item from previous line
631                 (push (texinfo-line line) result)
632                 (incf lines-consumed))
633                (t
634                 ;; end of itemization
635                 (loop-finish))))
636      ;; a single-line table isn't.
637     (if (> (count-if (lambda (line) (> (length line) 0)) result) 1)
638         (values lines-consumed
639                 `("" "@table @emph" ,@(reverse result) "@end table" ""))
640         nil)))
641
642 ;;; section markup
643
644 (defmacro with-maybe-section (index &rest forms)
645   `(multiple-value-bind (count collected) (progn ,@forms)
646     (when count
647       (dolist (line collected)
648         (write-line line *texinfo-output*))
649       (incf ,index (1- count)))))
650
651 (defun write-texinfo-string (string &optional lambda-list)
652   "Try to guess as much formatting for a raw docstring as possible."
653   (let ((*texinfo-variables* (flatten lambda-list))
654         (lines (string-lines (escape-for-texinfo string nil))))
655       (loop for line-number from 0 below (length lines)
656             for line = (svref lines line-number)
657             do (cond
658                  ((with-maybe-section line-number
659                     (and (lisp-section-p line line-number lines)
660                          (collect-lisp-section lines line-number))))
661                  ((with-maybe-section line-number
662                     (and (maybe-itemize-offset line)
663                          (collect-maybe-itemized-section lines line-number))))
664                  ((with-maybe-section line-number
665                     (and (maybe-table-offset line-number lines)
666                          (collect-maybe-table-section lines line-number))))
667                  (t
668                   (write-line (texinfo-line line) *texinfo-output*))))))
669
670 ;;;; texinfo formatting tools
671
672 (defun hide-superclass-p (class-name super-name)
673   (let ((super-package (symbol-package super-name)))
674     (or
675      ;; KLUDGE: We assume that we don't want to advertise internal
676      ;; classes in CP-lists, unless the symbol we're documenting is
677      ;; internal as well.
678      (and (member super-package #.'(mapcar #'find-package *undocumented-packages*))
679           (not (eq super-package (symbol-package class-name))))
680      ;; KLUDGE: We don't generally want to advertise SIMPLE-ERROR or
681      ;; SIMPLE-CONDITION in the CPLs of conditions that inherit them
682      ;; simply as a matter of convenience. The assumption here is that
683      ;; the inheritance is incidental unless the name of the condition
684      ;; begins with SIMPLE-.
685      (and (member super-name '(simple-error simple-condition))
686           (let ((prefix "SIMPLE-"))
687             (mismatch prefix (string class-name) :end2 (length prefix)))
688           t ; don't return number from MISMATCH
689           ))))
690
691 (defun hide-slot-p (symbol slot)
692   ;; FIXME: There is no pricipal reason to avoid the slot docs fo
693   ;; structures and conditions, but their DOCUMENTATION T doesn't
694   ;; currently work with them the way we'd like.
695   (not (and (typep (find-class symbol nil) 'standard-class)
696             (docstring slot t))))
697
698 (defun texinfo-anchor (doc)
699   (format *texinfo-output* "@anchor{~A}~%" (node-name doc)))
700
701 ;;; KLUDGE: &AUX *PRINT-PRETTY* here means "no linebreaks please"
702 (defun texinfo-begin (doc &aux *print-pretty*)
703   (let ((kind (get-kind doc)))
704     (format *texinfo-output* "@~A {~:(~A~)} ~(~A~@[ ~{~A~^ ~}~]~)~%"
705             (case kind
706               ((package constant variable)
707                "defvr")
708               ((structure class condition type)
709                "deftp")
710               (t
711                "deffn"))
712             (map 'string (lambda (char) (if (eql char #\-) #\Space char)) (string kind))
713             (title-name doc)
714             ;; &foo would be amusingly bold in the pdf thanks to TeX/Texinfo
715             ;; interactions,so we escape the ampersand -- amusingly for TeX.
716             ;; sbcl.texinfo defines macros that expand @&key and friends to &key.
717             (mapcar (lambda (name)
718                       (if (member name lambda-list-keywords)
719                           (format nil "@~A" name)
720                           name))
721                     (lambda-list doc)))))
722
723 (defun texinfo-index (doc)
724   (let ((title (title-name doc)))
725     (case (get-kind doc)
726       ((structure type class condition)
727        (format *texinfo-output* "@tindex ~A~%" title))
728       ((variable constant)
729        (format *texinfo-output* "@vindex ~A~%" title))
730       ((compiler-macro function method-combination macro generic-function)
731        (format *texinfo-output* "@findex ~A~%" title)))))
732
733 (defun texinfo-inferred-body (doc)
734   (when (member (get-kind doc) '(class structure condition))
735     (let ((name (get-name doc)))
736       ;; class precedence list
737       (format *texinfo-output* "Class precedence list: @code{~(~{@lw{~A}~^, ~}~)}~%~%"
738               (remove-if (lambda (class)  (hide-superclass-p name class))
739                          (mapcar #'class-name (ensure-class-precedence-list (find-class name)))))
740       ;; slots
741       (let ((slots (remove-if (lambda (slot) (hide-slot-p name slot))
742                               (class-direct-slots (find-class name)))))
743         (when slots
744           (format *texinfo-output* "Slots:~%@itemize~%")
745           (dolist (slot slots)
746             (format *texinfo-output*
747                     "@item ~(@code{~A}~#[~:; --- ~]~
748                       ~:{~2*~@[~2:*~A~P: ~{@code{@w{~S}}~^, ~}~]~:^; ~}~)~%~%"
749                     (slot-definition-name slot)
750                     (remove
751                      nil
752                      (mapcar
753                       (lambda (name things)
754                         (if things
755                             (list name (length things) things)))
756                       '("initarg" "reader"  "writer")
757                       (list
758                        (slot-definition-initargs slot)
759                        (slot-definition-readers slot)
760                        (slot-definition-writers slot)))))
761             ;; FIXME: Would be neater to handler as children
762             (write-texinfo-string (docstring slot t)))
763           (format *texinfo-output* "@end itemize~%~%"))))))
764
765 (defun texinfo-body (doc)
766   (write-texinfo-string (get-string doc)))
767
768 (defun texinfo-end (doc)
769   (write-line (case (get-kind doc)
770                 ((package variable constant) "@end defvr")
771                 ((structure type class condition) "@end deftp")
772                 (t "@end deffn"))
773               *texinfo-output*))
774
775 (defun write-texinfo (doc)
776   "Writes TexInfo for a DOCUMENTATION instance to *TEXINFO-OUTPUT*."
777   (texinfo-anchor doc)
778   (texinfo-begin doc)
779   (texinfo-index doc)
780   (texinfo-inferred-body doc)
781   (texinfo-body doc)
782   (texinfo-end doc)
783   ;; FIXME: Children should be sorted one way or another
784   (mapc #'write-texinfo (get-children doc)))
785
786 ;;;; main logic
787
788 (defun collect-gf-documentation (gf)
789   "Collects method documentation for the generic function GF"
790   (loop for method in (generic-function-methods gf)
791         for doc = (maybe-documentation method t)
792         when doc
793         collect doc))
794
795 (defun collect-name-documentation (name)
796   (loop for type in *documentation-types*
797         for doc = (maybe-documentation name type)
798         when doc
799         collect doc))
800
801 (defun collect-symbol-documentation (symbol)
802   "Collects all docs for a SYMBOL and (SETF SYMBOL), returns a list of
803 the form DOC instances. See `*documentation-types*' for the possible
804 values of doc-type."
805   (nconc (collect-name-documentation symbol)
806          (collect-name-documentation (list 'setf symbol))))
807
808 (defun collect-documentation (package)
809   "Collects all documentation for all external symbols of the given
810 package, as well as for the package itself."
811   (let* ((*documentation-package* (find-package package))
812          (docs nil))
813     (check-type package package)
814     (do-external-symbols (symbol package)
815       (setf docs (nconc (collect-symbol-documentation symbol) docs)))
816     (let ((doc (maybe-documentation *documentation-package* t)))
817       (when doc
818         (push doc docs)))
819     docs))
820
821 (defmacro with-texinfo-file (pathname &body forms)
822   `(with-open-file (*texinfo-output* ,pathname
823                                     :direction :output
824                                     :if-does-not-exist :create
825                                     :if-exists :supersede)
826     ,@forms))
827
828 (defun generate-includes (directory &rest packages)
829   "Create files in `directory' containing Texinfo markup of all
830 docstrings of each exported symbol in `packages'. `directory' is
831 created if necessary. If you supply a namestring that doesn't end in a
832 slash, you lose. The generated files are of the form
833 \"<doc-type>_<packagename>_<symbol-name>.texinfo\" and can be included
834 via @include statements. Texinfo syntax-significant characters are
835 escaped in symbol names, but if a docstring contains invalid Texinfo
836 markup, you lose."
837   (handler-bind ((warning #'muffle-warning))
838     (let ((directory (merge-pathnames (pathname directory))))
839       (ensure-directories-exist directory)
840       (dolist (package packages)
841         (dolist (doc (collect-documentation (find-package package)))
842           (with-texinfo-file (merge-pathnames (include-pathname doc) directory)
843             (write-texinfo doc))))
844       directory)))
845
846 (defun document-package (package &optional filename)
847   "Create a file containing all available documentation for the
848 exported symbols of `package' in Texinfo format. If `filename' is not
849 supplied, a file \"<packagename>.texinfo\" is generated.
850
851 The definitions can be referenced using Texinfo statements like
852 @ref{<doc-type>_<packagename>_<symbol-name>.texinfo}. Texinfo
853 syntax-significant characters are escaped in symbol names, but if a
854 docstring contains invalid Texinfo markup, you lose."
855   (handler-bind ((warning #'muffle-warning))
856     (let* ((package (find-package package))
857            (filename (or filename (make-pathname
858                                    :name (string-downcase (package-name package))
859                                    :type "texinfo")))
860            (docs (sort (collect-documentation package) #'documentation<)))
861       (with-texinfo-file filename
862         (dolist (doc docs)
863           (write-texinfo doc)))
864       filename)))