Converted the HTML-generator to Python3.
authorFredrik Tolf <fredrik@dolda2000.com>
Sun, 13 May 2012 02:10:40 +0000 (04:10 +0200)
committerFredrik Tolf <fredrik@dolda2000.com>
Sun, 13 May 2012 02:10:40 +0000 (04:10 +0200)
wrw/sp/cons.py
wrw/sp/util.py
wrw/sp/xhtml.py

index 5341b20..9e81677 100644 (file)
@@ -5,14 +5,14 @@ class node(object):
         doc = xml.dom.minidom.Document()
         return self.__todom__(doc).toxml()
 
-class text(node, unicode):
+class text(node, str):
     def __todom__(self, doc):
         return doc.createTextNode(self)
 
 class element(node):
     def __init__(self, ns, name, ctx):
         self.ns = ns
-        self.name = unicode(name)
+        self.name = str(name)
         self.ctx = ctx
         self.attrs = {}
         self.children = []
@@ -20,13 +20,13 @@ class element(node):
     def __call__(self, *children, **attrs):
         for child in children:
             self.children.append(self.ctx.nodefrom(child))
-        for k, v in attrs.iteritems():
-            self.attrs[unicode(k)] = unicode(v)
+        for k, v in attrs.items():
+            self.attrs[str(k)] = str(v)
         return self
 
     def __todom__(self, doc):
         el = doc.createElementNS(self.ns, self.name)
-        for k, v in self.attrs.iteritems():
+        for k, v in self.attrs.items():
             el.setAttribute(k, v)
         for child in self.children:
             el.appendChild(child.__todom__(doc))
@@ -35,10 +35,9 @@ class element(node):
 class context(object):
     def __init__(self):
         self.nodeconv = {}
-        self.nodeconv[str] = lambda ob: text(ob, "utf-8")
-        self.nodeconv[unicode] = text
+        self.nodeconv[bytes] = lambda ob: text(ob, "utf-8")
+        self.nodeconv[str] = text
         self.nodeconv[int] = text
-        self.nodeconv[long] = text
         self.nodeconv[float] = text
 
     def nodefrom(self, ob):
index 96e9880..c9f9401 100644 (file)
@@ -1,4 +1,4 @@
-import cons
+from . import cons
 
 def findnsnames(el):
     names = {}
@@ -6,7 +6,7 @@ def findnsnames(el):
     def proc(el):
         if isinstance(el, cons.element):
             if el.ns not in names:
-                names[el.ns] = u"n" + unicode(nid[0])
+                names[el.ns] = "n" + str(nid[0])
                 nid[:] = [nid[0] + 1]
             for ch in el.children:
                 proc(ch)
@@ -32,12 +32,12 @@ class formatter(object):
 
     def quotewrite(self, buf):
         for ch in buf:
-            if ch == u'&':
-                self.write(u"&amp;")
-            elif ch == u'<':
-                self.write(u"&lt;")
-            elif ch == u'>':
-                self.write(u"&gt;")
+            if ch == '&':
+                self.write("&amp;")
+            elif ch == '<':
+                self.write("&lt;")
+            elif ch == '>':
+                self.write("&gt;")
             else:
                 self.write(ch)
 
@@ -45,15 +45,15 @@ class formatter(object):
         self.quotewrite(el)
 
     def attrval(self, buf):
-        qc, qt = (u"'", u"&apos;") if u'"' in buf else (u'"', u"&quot;")
+        qc, qt = ("'", "&apos;") if '"' in buf else ('"', "&quot;")
         self.write(qc)
         for ch in buf:
-            if ch == u'&':
-                self.write(u"&amp;")
-            elif ch == u'<':
-                self.write(u"&lt;")
-            elif ch == u'>':
-                self.write(u"&gt;")
+            if ch == '&':
+                self.write("&amp;")
+            elif ch == '<':
+                self.write("&lt;")
+            elif ch == '>':
+                self.write("&gt;")
             elif ch == qc:
                 self.write(qt)
             else:
@@ -62,38 +62,38 @@ class formatter(object):
 
     def attr(self, k, v):
         self.write(k)
-        self.write(u'=')
+        self.write('=')
         self.attrval(v)
 
     def shorttag(self, el, **extra):
-        self.write(u'<' + self.elname(el))
-        for k, v in el.attrs.iteritems():
-            self.write(u' ')
+        self.write('<' + self.elname(el))
+        for k, v in el.attrs.items():
+            self.write(' ')
             self.attr(k, v)
-        for k, v in extra.iteritems():
-            self.write(u' ')
+        for k, v in extra.items():
+            self.write(' ')
             self.attr(k, v)
-        self.write(u" />")
+        self.write(" />")
 
     def elname(self, el):
         ns = self.nsnames[el.ns]
         if ns is None:
             return el.name
         else:
-            return ns + u':' + el.name
+            return ns + ':' + el.name
 
     def starttag(self, el, **extra):
-        self.write(u'<' + self.elname(el))
-        for k, v in el.attrs.iteritems():
-            self.write(u' ')
+        self.write('<' + self.elname(el))
+        for k, v in el.attrs.items():
+            self.write(' ')
             self.attr(k, v)
-        for k, v in extra.iteritems():
-            self.write(u' ')
+        for k, v in extra.items():
+            self.write(' ')
             self.attr(k, v)
-        self.write(u'>')
+        self.write('>')
 
     def endtag(self, el):
-        self.write(u'</' + self.elname(el) + u'>')
+        self.write('</' + self.elname(el) + '>')
 
     def longtag(self, el):
         self.starttag(el, **extra)
@@ -116,19 +116,19 @@ class formatter(object):
             raise Exception("Unknown object in element tree: " + el)
 
     def start(self):
-        self.write(u'<?xml version="1.0" encoding="' + self.charset + u'" ?>\n')
+        self.write('<?xml version="1.0" encoding="' + self.charset + '" ?>\n')
         if self.doctype:
-            self.write(u'<!DOCTYPE %s PUBLIC "%s" "%s">\n' % (self.root.name,
-                                                              self.doctype[0],
-                                                              self.doctype[1]))
+            self.write('<!DOCTYPE %s PUBLIC "%s" "%s">\n' % (self.root.name,
+                                                             self.doctype[0],
+                                                             self.doctype[1]))
         extra = {}
-        for uri, nm in self.nsnames.iteritems():
+        for uri, nm in self.nsnames.items():
             if uri is None:
                 continue
             if nm is None:
-                extra[u"xmlns"] = uri
+                extra["xmlns"] = uri
             else:
-                extra[u"xmlns:" + nm] = uri
+                extra["xmlns:" + nm] = uri
         self.element(self.root, **extra)
 
     @classmethod
@@ -148,8 +148,9 @@ class iwriter(object):
         self.col = 0
 
     def write(self, buf):
-        for c in buf:
-            if c == '\n':
+        for i in range(len(buf)):
+            c = buf[i:i + 1]
+            if c == b'\n':
                 self.col = 0
             else:
                 self.col += 1
@@ -160,16 +161,16 @@ class iwriter(object):
         if self.atbol:
             return
         if self.col != 0:
-            self.write('\n')
+            self.write(b'\n')
         self.write(indent)
         self.atbol = True
 
 class indenter(formatter):
-    def __init__(self, indent=u"  ", *args, **kw):
+    def __init__(self, indent="  ", *args, **kw):
         super(indenter, self).__init__(*args, **kw)
         self.out = iwriter(self.out)
         self.indent = indent
-        self.curind = u""
+        self.curind = ""
 
     def simple(self, el):
         for ch in el.children:
@@ -183,18 +184,21 @@ class indenter(formatter):
         reind = False
         if not self.simple(el):
             sub = self.update(curind=self.curind + self.indent)
-            sub.out.indent(sub.curind)
+            sub.reindent()
             reind = True
         for ch in el.children:
             sub.node(ch)
         if reind:
-            self.out.indent(self.curind)
+            self.reindent()
         self.endtag(el)
 
     def element(self, el, **extra):
         super(indenter, self).element(el, **extra)
         if self.out.col > 80 and self.simple(el):
-            self.out.indent(self.curind)
+            self.reindent()
+
+    def reindent(self):
+        self.out.indent(self.curind.encode(self.charset))
 
     def start(self):
         super(indenter, self).start()
index abf4b96..7058138 100644 (file)
@@ -1,11 +1,11 @@
-import xml.dom.minidom, StringIO
-import cons as _cons
-import util
+import xml.dom.minidom, io
+from . import cons as _cons
+from . import util
 dom = xml.dom.minidom.getDOMImplementation()
 
-ns = u"http://www.w3.org/1999/xhtml"
-doctype = u"-//W3C//DTD XHTML 1.1//EN"
-dtd = u"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"
+ns = "http://www.w3.org/1999/xhtml"
+doctype = "-//W3C//DTD XHTML 1.1//EN"
+dtd = "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"
 
 class htmlelement(_cons.element):
     def __todoc__(self):
@@ -22,7 +22,7 @@ def head(title=None, css=None):
     head = h.head
     if title:
         head(h.title(title))
-    if isinstance(css, str) or isinstance(css, unicode):
+    if isinstance(css, str) or isinstance(css, bytes):
         head(h.link(rel="stylesheet", type="text/css", href=css))
     elif css:
         for ss in css:
@@ -30,7 +30,7 @@ def head(title=None, css=None):
     return head
 
 class htmlformatter(util.formatter):
-    allowshort = set([u"br", u"hr", u"img", u"input"])
+    allowshort = set(["br", "hr", "img", "input"])
     def element(self, el, **extra):
         if el.name in self.allowshort:
             super(htmlformatter, self).element(el, **extra)
@@ -43,7 +43,7 @@ class htmlindenter(util.indenter, htmlformatter):
 def forreq(req, tree):
     # XXX: Use proper Content-Type for clients accepting it.
     req.ohead["Content-Type"] = "text/html; charset=utf-8"
-    buf = StringIO.StringIO()
+    buf = io.StringIO()
     htmlindenter.output(buf, tree, doctype=(doctype, dtd), charset="utf-8")
     return [buf.getvalue()]