"Fossies" - the Fresh Open Source Software Archive 
Member "Tahchee-1.0.0/Sources/tahchee/plugins/_kiwi/kiwi2html.py" (22 Oct 2009, 12079 Bytes) of package /linux/privat/old/tahchee-1.0.0.tar.gz:
As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Python source code syntax highlighting (style:
standard) with prefixed line numbers.
Alternatively you can here
view or
download the uninterpreted source code file.
For more information about "kiwi2html.py" see the
Fossies "Dox" file reference documentation.
1 #!/usr/bin/env python
2 # Encoding: iso-8859-1
3 # vim: tw=80 ts=4 sw=4 noet
4 # -----------------------------------------------------------------------------
5 # Project : Kiwi
6 # -----------------------------------------------------------------------------
7 # Author : Sebastien Pierre <sebastien@type-z.org>
8 # -----------------------------------------------------------------------------
9 # Creation date : 07-Feb-2006
10 # Last mod. : 07-Oct-2009
11 # -----------------------------------------------------------------------------
12
13 import re, xml.dom
14 import sys
15 from formatting import *
16 import templates
17
18 #------------------------------------------------------------------------------
19 #
20 # Processing functions
21 #
22 #------------------------------------------------------------------------------
23
24 class Processor(templates.Processor):
25
26 def defaultProcessElement( self, element, selector ):
27 """We override this for elements with the 'html' attribute."""
28 if element.getAttributeNS(None, "_html"):
29 res = "<" + element.nodeName
30 att = element.attributes
31 for i in range(att.length):
32 a = att.item(i)
33 if a.name == "_html": continue
34 res += " %s='%s'" % (a.name, element.getAttributeNS(None, a.name))
35 if element.childNodes:
36 res += ">"
37 for e in element.childNodes:
38 res += self.processElement(e)
39 res += "</%s>" % (element.tagName)
40 else:
41 res += "/>"
42 return res
43 else:
44 return templates.Processor.defaultProcessElement(self,element,selector)
45
46 def generate( self, xmlDocument, bodyOnly=False, variables={} ):
47 node = xmlDocument.getElementsByTagName("Document")[0]
48 self.variables = variables
49 if bodyOnly:
50 for child in node.childNodes:
51 if child.nodeName == "Content":
52 return convertContent_bodyonly(child)
53 else:
54 return convertDocument(node)
55
56 #------------------------------------------------------------------------------
57 #
58 # Actual element processing
59 #
60 #------------------------------------------------------------------------------
61
62 def convertDocument(element):
63 return process(element, """\
64 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
65 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
66 <html xmlns="http://www.w3.org/1999/xhtml">
67 <head>
68 <meta http-equiv="Content-Type" content="text/html; charset=$(=ENCODING)" />
69 $(Header)$(=HEADER)
70 </head>
71 <body>
72 $(Header:title)
73 <div class="kiwiContent">$(Content)</div>
74 $(References)
75 </body>
76 </html>""")
77
78 def element_number( element ):
79 """Utility function that returns the element number (part of the element
80 offset attributes)"""
81 number = element.getAttributeNS(None, "_number")
82 if number: return int(number)
83 else: return None
84
85 def wdiv( element, text ):
86 """Wraps the given text in a DIV extended with offsets attributes if the
87 given element has offset attributes."""
88 number = element_number(element)
89 if number == None: return text
90 return "<div class='KIWI N%s' ostart='%s' oend='%s'>%s</div>" % (
91 element.getAttributeNS(None, '_number'),
92 element.getAttributeNS(None, '_start'),
93 element.getAttributeNS(None, '_end'),
94 text
95 )
96
97 def wspan( element, text ):
98 """Wraps the given text in a SPAN extended with offsets attributes if the
99 given element has offset attributes."""
100 number = element_number(element)
101 if number == None: return text
102 return "<div class='KIWI N%s' ostart='%s' oend='%s'>%s</div>" % (
103 element.getAttributeNS(None, '_number'),
104 element.getAttributeNS(None, '_start'),
105 element.getAttributeNS(None, '_end'),
106 text
107 )
108
109 def wattrs( element ):
110 """Returns the offset attributes of this element if it has any."""
111 res = ""
112 number = element_number(element)
113 if number != None:
114 res = " class='KIWI N%s' ostart='%s' oend='%s'" % (
115 element.getAttributeNS(None, '_number'),
116 element.getAttributeNS(None, '_start'),
117 element.getAttributeNS(None, '_end')
118 )
119 return res
120
121 def convertContent( element ):
122 return process(element, wdiv(element, """<div class='content'>$(*)</div>"""))
123
124 def convertContent_bodyonly( element ):
125 return process(element, wdiv(element, """$(*)"""))
126
127 def convertContent_table( element ):
128 return process(element, """<tbody%s>$(*)</tbody>""" % (wattrs(element)))
129
130 def convertHeader( element ):
131 return process(element, "<title%s>$(Title/title)</title>" % (wattrs(element)))
132
133 def convertHeading( element ):
134 return process(element, wspan(element, "$(*)"))
135
136 def getSectionNumberPrefix(element):
137 if not element:
138 return ""
139 if not element.nodeName in ("Chapter", "Section"):
140 return ""
141 parent = element.parentNode
142 section_count = 1
143 for child in parent.childNodes:
144 if child == element:
145 break
146 if child.nodeName in ("Chapter", "Section"):
147 section_count += 1
148 parent_number = getSectionNumberPrefix(parent.parentNode)
149 if parent_number:
150 return "%s.%s" % (parent_number, section_count)
151 else:
152 return str(section_count)
153
154 def formatSectionNumber(number):
155 number = str(number).split(".")
156 depth = 0
157 res = []
158 for n in number:
159 if depth == len(number) - 1:
160 res.append('<span class="level%s">%s<span class="lastDot dot">.</span></span>' % (depth,n))
161 else:
162 res.append('<span class="level%s">%s<span class="dot">.</span></span>' % (depth,n))
163 depth += 1
164 return "".join(res)
165
166 def convertSection( element ):
167 offset = element._processor.variables.get("LEVEL") or 0
168 level = int(element.getAttributeNS(None, "_depth")) + offset
169 return process(element,
170 '<div class="section" level="%d">' % (level)
171 + '<h%d class="heading"><span class="number">%s</span>$(Heading)</h%d>' % (level, formatSectionNumber(getSectionNumberPrefix(element)), level)
172 + '<div class="level%d">$(Content:section)</div></div>' % (level)
173 )
174
175 def convertReferences( element ):
176 return process(element, """<div class="kiwiReferences">$(Entry)</div>""")
177
178 def convertEntry( element ):
179 return process(element, """<div class="entry"><div class="name"><a name="%s">%s</a></div><div class="content">$(*)</div></div>""" %
180 (element.getAttributeNS(None, "id"), element.getAttributeNS(None, "id")))
181
182 def convertHeader_title( element ):
183 return process(element, """<div
184 class="title">$(Title/title:header)$(Title/subtitle:header)</div>$(Meta)""")
185
186 def converttitle_header( element ):
187 return process(element, """<h1%s>$(*)</h1>""" % (wattrs(element)))
188
189 def convertsubtitle_header( element ):
190 return process(element, """<h2%s>$(*)</h2>""" % (wattrs(element)))
191
192 def convertParagraph( element ):
193 return process(element, """<p%s>$(*)</p>""" % (wattrs(element)))
194
195 def convertParagraph_cell( element ):
196 return process(element, """$(*)<br />""")
197
198 def convertList( element ):
199 list_type = element.getAttributeNS(None, "type")
200 attrs = [""]
201 if list_type:
202 attrs.append('class="%s"' % (list_type))
203 if list_type == "ordered":
204 return process(element, """<ol%s%s>$(*)</ul>""" % (wattrs(element), " ".join(attrs)))
205 else:
206 return process(element, """<ul%s%s>$(*)</ul>""" % (wattrs(element), " ".join(attrs)))
207
208 def convertListItem( element ):
209 attrs = [""]
210 is_todo = element.getAttributeNS(None, "todo")
211 if is_todo:
212 if is_todo == "done":
213 attrs.append('class="todo done"')
214 return process(element, """<li%s%s><input type='checkbox' checked='true' readonly>$(*)</input></li>""" % (wattrs(element), " ".join(attrs)))
215 else:
216 attrs.append('class="todo"')
217 return process(element, """<li%s%s><input type='checkbox' readonly>$(*)</input></li>""" % (wattrs(element), " ".join(attrs)))
218 else:
219 return process(element, """<li%s%s>$(*)</li>""" % (wattrs(element), " ".join(attrs)))
220
221 def convertTable( element ):
222 tid = element.getAttributeNS(None, "id")
223 if tid: tid = ' id="%s"' % (tid)
224 else: tid = ""
225 return process(element, """<div class="table"%s><table cellpadding="0" cellspacing="0" align="center">$(Caption)$(Content:table)</table></div>""" % (tid))
226
227 def convertDefinition( element ):
228 return process(element, """<dl%s>$(*)</dl>""" % (wattrs(element)))
229
230 def convertDefinitionItem( element ):
231 return process(element, """<dt>$(Title)</dt><dd>$(Content)</dd>""")
232
233 def convertCaption( element ):
234 return process(element, """<caption%s>$(*)</caption>""" % (wattrs(element)))
235
236 def convertRow( element ):
237 try: index = element.parentNode.childNodes.index(element) % 2 + 1
238 except: index = 0
239 classes = ( "", "even", "odd" )
240 return process(element, """<tr class='%s'%s>$(*)</tr>""" % (classes[index], wattrs(element)))
241
242 def convertCell( element ):
243 cell_attrs = ""
244 node_type = element.getAttributeNS(None, "type")
245 if element.hasAttributeNS(None, "colspan"):
246 cell_attrs += " colspan='%s'" % (element.getAttributeNS(None, "colspan"))
247 if node_type == "header":
248 return process(element, """<th%s%s>$(*:cell)</th>""" % (cell_attrs,wattrs(element)))
249 else:
250 return process(element, """<td%s%s>$(*:cell)</td>""" % (cell_attrs,wattrs(element)))
251
252 def convertBlock( element ):
253 title = element.getAttributeNS(None,"title") or element.getAttributeNS(None, "type") or ""
254 css_class = ""
255 if title:
256 css_class=" class='ann%s'" % (element.getAttributeNS(None, "type").capitalize())
257 title = "<div class='title'>%s</div>" % (title)
258 div_type = "div"
259 elif not element.getAttributeNS(None, "type"):
260 div_type = "blockquote"
261 return process(element, """<%s%s>%s<div class='content'%s>$(*)</div></%s>""" % (div_type, css_class, title, wattrs(element), div_type))
262
263 def stringToTarget( text ):
264 return text.replace(" ", " ").strip().replace(" ", "_")
265
266 def convertlink( element ):
267 if element.getAttributeNS(None, "type") == "ref":
268 return process(element, """<a href="#%s" class="internal">$(*)</a>""" %
269 (stringToTarget(element.getAttributeNS(None, "target"))))
270 else:
271 # TODO: Support title
272 return process(element, """<a href="%s" class="external">$(*)</a>""" %
273 (element.getAttributeNS(None, "target")))
274
275 def converttarget( element ):
276 name = element.getAttributeNS(None, "name")
277 return process(element, """<a class="anchor" name="%s">$(*)</a>""" % (stringToTarget(name)))
278
279 def convertMeta( element ):
280 return process(element, "<table class='kiwiMeta'>$(*)</table>")
281
282 def convertmeta( element ):
283 return process(element,
284 "<tr><td width='0px' class='name'>%s</td><td width='100%%' class='value'>$(*)</td></tr>" %
285 (element.getAttributeNS(None, "name")))
286
287 def convertemail( element ):
288 mail = ""
289 for c in process(element, """$(*)"""):
290 mail += "&#%d;" % (ord(c))
291 return """<a href="mailto:%s">%s</a>""" % (mail, mail)
292
293 def converturl( element ):
294 return process(element, """<a href="$(*)" target="_blank">$(*)</a>""")
295
296 def converturl_header( element ):
297 return process(element, """<div class='url'>%s</div>""" % (
298 converturl(element)))
299
300 def convertterm( element ):
301 return process(element, """<span class='term'>$(*)</span>""")
302
303 def convertquote( element ):
304 return process(element, """“<span class='quote'>$(*)</span>”""")
305
306 def convertcitation( element ):
307 return process(element, """«<span class='citation'>$(*)</span>»""")
308
309 def convertstrong( element ):
310 return process(element, """<strong>$(*)</strong>""")
311
312 def convertpre( element ):
313 return process(element, """<pre%s>$(*)</pre>""" % (wattrs(element)))
314
315 def convertcode( element ):
316 return process(element, """<code>$(*)</code>""")
317
318 def convertemphasis( element ):
319 return process(element, """<em>$(*)</em>""")
320
321 def convertbreak( element ):
322 return process(element, """<br />""")
323
324 def convertnewline( element ):
325 return process(element, """<br />""")
326
327 def convertarrow( element ):
328 arrow = element.getAttributeNS(None, "type")
329 if arrow == "left":
330 return "←"
331 elif arrow == "right":
332 return "→"
333 else:
334 return "↔"
335
336 def convertdots( element ):
337 return "…"
338
339 def convertendash( element ):
340 return "–"
341
342 def convertemdash( element ):
343 return "—"
344
345 def convertentity( element ):
346 return "&%s;" % (element.getAttributeNS( None, "num"))
347
348 # We create the processor, register the rules and define the process variable
349 processor = Processor()
350 name2functions = {}
351 for symbol in filter(lambda x:x.startswith("convert"), dir()):
352 name2functions[symbol] = eval(symbol)
353 processor.register(name2functions)
354 process = processor.process
355
356 # EOF