1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/moinformat/serialisers.py Sat Apr 29 17:47:03 2017 +0200
1.3 @@ -0,0 +1,108 @@
1.4 +#!/usr/bin/env python
1.5 +
1.6 +"""
1.7 +Moin wiki serialisers.
1.8 +
1.9 +Copyright (C) 2017 Paul Boddie <paul@boddie.org.uk>
1.10 +
1.11 +This program is free software; you can redistribute it and/or modify it under
1.12 +the terms of the GNU General Public License as published by the Free Software
1.13 +Foundation; either version 3 of the License, or (at your option) any later
1.14 +version.
1.15 +
1.16 +This program is distributed in the hope that it will be useful, but WITHOUT
1.17 +ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
1.18 +FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
1.19 +details.
1.20 +
1.21 +You should have received a copy of the GNU General Public License along with
1.22 +this program. If not, see <http://www.gnu.org/licenses/>.
1.23 +"""
1.24 +
1.25 +from cgi import escape
1.26 +
1.27 +class Serialiser:
1.28 +
1.29 + "General serialisation support."
1.30 +
1.31 + def __init__(self, out):
1.32 + self.out = out
1.33 +
1.34 +class MoinSerialiser(Serialiser):
1.35 +
1.36 + "Serialisation of the page."
1.37 +
1.38 + def start_region(self, level, indent, type):
1.39 + out = self.out
1.40 + if level:
1.41 + out(" " * indent + "{" * level)
1.42 + if type and level:
1.43 + out("#!%s\n" % type)
1.44 +
1.45 + def end_region(self, level, indent, type):
1.46 + out = self.out
1.47 + if level:
1.48 + out("}" * level)
1.49 +
1.50 + def start_block(self, final):
1.51 + pass
1.52 +
1.53 + def end_block(self, final):
1.54 + if not final:
1.55 + self.out("\n")
1.56 +
1.57 + def start_listitem(self):
1.58 + self.out(" *")
1.59 +
1.60 + def end_listitem(self):
1.61 + pass
1.62 +
1.63 + def text(self, s):
1.64 + self.out(s)
1.65 +
1.66 +class HTMLSerialiser(Serialiser):
1.67 +
1.68 + "Serialisation of the page."
1.69 +
1.70 + def start_region(self, level, indent, type):
1.71 + l = []
1.72 + out = l.append
1.73 + if level:
1.74 + out("level-%d" % level)
1.75 +
1.76 + if indent:
1.77 + out("indent-%d" % indent)
1.78 +
1.79 + # NOTE: Encode type details for CSS.
1.80 +
1.81 + if type:
1.82 + out("type-%s" % escape(type, True))
1.83 +
1.84 + self.out("<span class='%s'>" % " ".join(l))
1.85 +
1.86 + def end_region(self, level, indent, type):
1.87 + self.out("</span>")
1.88 +
1.89 + def start_block(self, final):
1.90 + self.out("<p>")
1.91 +
1.92 + def end_block(self, final):
1.93 + self.out("</p>")
1.94 +
1.95 + def start_listitem(self):
1.96 + self.out("<li>")
1.97 +
1.98 + def end_listitem(self):
1.99 + self.out("</li>")
1.100 +
1.101 + def text(self, s):
1.102 + self.out(escape(s))
1.103 +
1.104 +# Top-level functions.
1.105 +
1.106 +def serialise(doc, serialiser=MoinSerialiser):
1.107 + l = []
1.108 + doc.to_string(serialiser(l.append))
1.109 + return "".join(l)
1.110 +
1.111 +# vim: tabstop=4 expandtab shiftwidth=4