(chapter-start 'html-help “Utilities for generating html-formatted help from 'dox data”)

(def helpful/type (thing)

(if (no thing)
    "nil"
    (let type (type-of thing)
      (if (string-match type "ruby/Hash")
          'ruby-hash
          (string-match type "ruby/")
          'object
          type))))

(def helpful/keys (thing)

; return a string with one line per key
; to describe the corresponding value
(map (fn (k) (%div.keyhelp
                   (%div.key k)
                   "->"
                   (%div.keyvalue (helpful/type thing.,k))))
     (sort:hash-keys thing)))

(def helpful/info (thing)

; tries to say something useful about the thing
(if (no thing)
    "nil"
    (pair? thing)
    "list with ~(len thing) elements, first is a ~(helpful/type:car thing)"
    (with (mytype (helpful/type thing)
           mykeys (hash-keys thing))
          "is a ~|mytype|~(helpful/keys thing)")))

(def helpful/index ()

; return the names and types of all the things that are documented
(joinstr "\n"
         (map (curry inspect:firstn 2)
              (collect dox-with-documentation (dox-all-items)))))

(mac helpful/dox (name)

; finds documentation for the named thing
`(let infos (dox-lookup ',name)
   (if (no infos)
       (joinstr " : " ,(pp name) (helpful/info ,name))
       (joinstr "\n\n"
                (map λi(dox-show-info i.name i.what i.texts i.args i.src)
                     infos)))))

(def helpful/show-examples (name examples)

(if examples
    (%div.helpful-examples
          (%h2 "Examples for "
               (%span.example-name name))
          (map λk(map λx(%pre.helpful-example
                              (dox-show-one-example name x))
                      k)
               examples))))

(def helpful/examples (name)

; finds examples that have been defined for the given 'name
(helpful/show-examples name
                       (dox-examples name)))

(mac help (thing)

; returns helpful information about the thing
; if thing is nil, show what help is available for
`(%pre.helpful ,(if (no thing)
                    `(helpful/index)
                    `(joinstr "\n\n"
                              (helpful/dox ,thing)
                              (helpful/examples ',thing)))))

(def-colon-syntax help names

(let target (cadr names)
  `(help ,(if (eq? target '||)
              nil
              target))))