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