Monday, 25 February 2008

Generating DocBook output using Common Lisp and SBCL

I've been a bit busy lately with Sohail 3.0 and an unexpected trip to Toronto (still here for a week) so I haven't had much time for much blogging.

Anyway, one of the things I've always wanted to learn was DocBook. Today I had a bit of down time so I downloaded the DocBook crash course. Oh boy. XML... If Java could be a markup language, it would be XML. If only I could get rid of the redundancy. Long story short, I thought of CL-WHO to generate the XML. Normally, CL-WHO is used to generate HTML, but it actually knows very little about HTML. To get CL-WHO to generate XML, all you need to do is set the prologue and mode to XML. To do this, execute the following at the REPL:

(setf (cl-who:html-mode) :xml)
;;; This is printed before anything else
(setf cl-who:*prologue* "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>")

For sample output, evaluate the following at the REPL:

(cl-who:with-html-output-to-string (s nil :indent t :prologue t)
    (:person :id "1" (:firstname "Sohail") (:surname "Somani"))
    (:person :id "2" (:firstname "Heinz") (:surname "Ketchup"))))

Which generates:

<?xml version=\"1.0\" encoding=\"UTF-8\" ?>
  <person id=\'1\'>
  <person id=\'2\'>

The workflow is pretty straighforward:

  1. Write CL-WHO document

  2. Convert document to XML

  3. Write to file

  4. Run through docbook2<target>

Here is a "real example" where by "real" I mean copied from the above mentioned ebook:

(defparameter *book*
  `(:book :lang "en"
           (:title "Hello, world!")
            (:author (:firstname "Sohail")
                     (:surname "Somani")))
            (:para (:application "twiddle")
                   "is an application specially designed to do nothing
                   you would ever want"))
            (:keyword "twiddle")
            (:keyword "sample application")))
          ,(docbook-part "introduction.lisp")
           (:title "Zomg")
            (:title "Testing")
              (:segtitle "Name")
              (:segtitle "Occupation")
              (:segtitle "Favourite food")
               (:seg "Tux")
               (:seg "Linux Mascot")
               (:seg "Herring")))
             (:ulink :url ""
                     "My favourite website"))))))

(docbook2pdf *book*) ;; actually also launches pdf reader :-D

So now, with Emacs and Slime (C-c C-l specifically!) I have a fully programmable DocBook IDE. Not to mention that I can use Lisp. Leave a comment if you are actually interested in the code :-)


Jason said...

I'm actually interested in the code!

How's that =)?

Rommel said...

In item #4 of the workflow, I think you meant:

4. Run through docbook2target

Sohail Somani said...

I believe you are right!