1 #!/usr/bin/env python 2 3 """ 4 Moin wiki serialisers. 5 6 Copyright (C) 2017 Paul Boddie <paul@boddie.org.uk> 7 8 This program is free software; you can redistribute it and/or modify it under 9 the terms of the GNU General Public License as published by the Free Software 10 Foundation; either version 3 of the License, or (at your option) any later 11 version. 12 13 This program is distributed in the hope that it will be useful, but WITHOUT 14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 15 FOR A PARTICULAR PURPOSE. See the GNU General Public License for more 16 details. 17 18 You should have received a copy of the GNU General Public License along with 19 this program. If not, see <http://www.gnu.org/licenses/>. 20 """ 21 22 from cgi import escape 23 24 class Serialiser: 25 26 "General serialisation support." 27 28 def __init__(self, out): 29 self.out = out 30 31 class MoinSerialiser(Serialiser): 32 33 "Serialisation of the page." 34 35 def start_region(self, level, indent, type): 36 out = self.out 37 if level: 38 out(" " * indent + "{" * level) 39 if type and level: 40 out("#!%s\n" % type) 41 42 def end_region(self, level, indent, type): 43 out = self.out 44 if level: 45 out("}" * level) 46 47 def start_block(self, final): 48 pass 49 50 def end_block(self, final): 51 if not final: 52 self.out("\n") 53 54 def start_listitem(self): 55 self.out(" *") 56 57 def end_listitem(self): 58 pass 59 60 def rule(self, length): 61 self.out("-" * length) 62 63 def text(self, s): 64 self.out(s) 65 66 class HTMLSerialiser(Serialiser): 67 68 "Serialisation of the page." 69 70 def start_region(self, level, indent, type): 71 l = [] 72 out = l.append 73 if level: 74 out("level-%d" % level) 75 76 if indent: 77 out("indent-%d" % indent) 78 79 # NOTE: Encode type details for CSS. 80 81 if type: 82 out("type-%s" % escape(type, True)) 83 84 self.out("<span class='%s'>" % " ".join(l)) 85 86 def end_region(self, level, indent, type): 87 self.out("</span>") 88 89 def start_block(self, final): 90 self.out("<p>") 91 92 def end_block(self, final): 93 self.out("</p>") 94 95 def start_listitem(self): 96 self.out("<li>") 97 98 def end_listitem(self): 99 self.out("</li>") 100 101 def rule(self, length): 102 self.out("<hr style='height: %dpt' />" % min(length, 10)) 103 104 def text(self, s): 105 self.out(escape(s)) 106 107 # Top-level functions. 108 109 def serialise(doc, serialiser=MoinSerialiser): 110 l = [] 111 doc.to_string(serialiser(l.append)) 112 return "".join(l) 113 114 # vim: tabstop=4 expandtab shiftwidth=4