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 text(self, s): 61 self.out(s) 62 63 class HTMLSerialiser(Serialiser): 64 65 "Serialisation of the page." 66 67 def start_region(self, level, indent, type): 68 l = [] 69 out = l.append 70 if level: 71 out("level-%d" % level) 72 73 if indent: 74 out("indent-%d" % indent) 75 76 # NOTE: Encode type details for CSS. 77 78 if type: 79 out("type-%s" % escape(type, True)) 80 81 self.out("<span class='%s'>" % " ".join(l)) 82 83 def end_region(self, level, indent, type): 84 self.out("</span>") 85 86 def start_block(self, final): 87 self.out("<p>") 88 89 def end_block(self, final): 90 self.out("</p>") 91 92 def start_listitem(self): 93 self.out("<li>") 94 95 def end_listitem(self): 96 self.out("</li>") 97 98 def text(self, s): 99 self.out(escape(s)) 100 101 # Top-level functions. 102 103 def serialise(doc, serialiser=MoinSerialiser): 104 l = [] 105 doc.to_string(serialiser(l.append)) 106 return "".join(l) 107 108 # vim: tabstop=4 expandtab shiftwidth=4