Reimplemented the SP output formatters to hopefully work better and faster.
[wrw.git] / wrw / sp / xhtml.py
CommitLineData
ff79cdbf
FT
1import xml.dom.minidom, StringIO
2import cons as _cons
3import util
4dom = xml.dom.minidom.getDOMImplementation()
5
6ns = u"http://www.w3.org/1999/xhtml"
7doctype = u"-//W3C//DTD XHTML 1.1//EN"
8dtd = u"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"
9
10class htmlelement(_cons.element):
11 def __todoc__(self):
12 doc = dom.createDocument(None, None, None)
13 doc.appendChild(dom.createDocumentType("html", doctype, dtd))
14 doc.appendChild(self.__todom__(doc))
15 return doc
16
a573465e
FT
17class xhtmlcontext(_cons.context):
18 attrmap = {u"klass": u"class"}
19
20 def addattr(self, node, k, v):
21 k = unicode(k)
4c4dcf7a 22 super(xhtmlcontext, self).addattr(node, self.attrmap.get(k, k), v)
a573465e 23
ff79cdbf 24def cons(ctx=None):
a573465e 25 if ctx is None: ctx = xhtmlcontext()
ff79cdbf
FT
26 return _cons.constructor(ns, htmlelement, ctx)
27
28def head(title=None, css=None):
29 h = cons()
30 head = h.head
31 if title:
32 head(h.title(title))
33 if isinstance(css, str) or isinstance(css, unicode):
34 head(h.link(rel="stylesheet", type="text/css", href=css))
35 elif css:
36 for ss in css:
37 head(h.link(rel="stylesheet", type="text/css", href=ss))
38 return head
39
40class htmlformatter(util.formatter):
d11a27e2 41 allowshort = set([u"br", u"hr", u"img", u"input", u"meta", u"link"])
fb5f9f27 42 def shorttag(self, el):
ff79cdbf 43 if el.name in self.allowshort:
fb5f9f27 44 super(htmlformatter, self).shorttag(el)
ff79cdbf 45 else:
fb5f9f27
FT
46 self.starttag(el)
47 self.endtag(el)
ff79cdbf 48
fb5f9f27 49class htmlindenter(util.textindenter, htmlformatter):
ff79cdbf
FT
50 pass
51
52def forreq(req, tree):
53 # XXX: Use proper Content-Type for clients accepting it.
54 req.ohead["Content-Type"] = "text/html; charset=utf-8"
55 buf = StringIO.StringIO()
56 htmlindenter.output(buf, tree, doctype=(doctype, dtd), charset="utf-8")
a7b35f84
FT
57 ret = buf.getvalue()
58 req.ohead["Content-Length"] = len(ret)
59 return [ret]
ff79cdbf
FT
60
61def xhtmlresp(callable):
62 def wrapper(req):
63 return forreq(req, callable(req))
d22f3483 64 wrapper.__wrapped__ = callable
ff79cdbf 65 return wrapper