1.1 --- a/moinformat/output/common.py Sun Aug 05 18:07:02 2018 +0200
1.2 +++ b/moinformat/output/common.py Sun Aug 05 18:13:36 2018 +0200
1.3 @@ -19,6 +19,8 @@
1.4 this program. If not, see <http://www.gnu.org/licenses/>.
1.5 """
1.6
1.7 +import codecs
1.8 +
1.9 class Output:
1.10
1.11 "A common output context abstraction."
1.12 @@ -48,12 +50,57 @@
1.13
1.14 self.output.append(self.encode(text))
1.15
1.16 + # Serialisation methods.
1.17 +
1.18 def to_string(self):
1.19
1.20 "Return the output as a plain string."
1.21
1.22 return "".join(self.output)
1.23
1.24 + # Serialisation methods.
1.25 +
1.26 + def can_write(self):
1.27 +
1.28 + "Return whether this context supports page writing."
1.29 +
1.30 + return False
1.31 +
1.32 + def writefile(self, text, filename, encoding=None):
1.33 +
1.34 + """
1.35 + Write 'text' to the file having the given 'filename'. If the
1.36 + optional 'encoding' is specified, override the general encoding.
1.37 +
1.38 + Subclasses need to override this method for it to have an effect.
1.39 + """
1.40 +
1.41 + pass
1.42 +
1.43 + def writepage(self, text, pagename, encoding=None):
1.44 +
1.45 + """
1.46 + Write 'text' to the file having the given 'pagename' and optional
1.47 + 'encoding'.
1.48 + """
1.49 +
1.50 + return self.writefile(text, self.to_filename(pagename), encoding)
1.51 +
1.52 + # Output methods.
1.53 +
1.54 + def writepath(self, text, filename, encoding=None):
1.55 +
1.56 + """
1.57 + Write 'text' to the file having the given 'filename'. If the
1.58 + optional 'encoding' is specified, override the general encoding.
1.59 + """
1.60 +
1.61 + f = codecs.open(filename, "w", encoding=encoding or self.encoding)
1.62 + try:
1.63 + f.write(text)
1.64 + finally:
1.65 + f.close()
1.66 +
1.67 def encode(s, encoding):
1.68
1.69 "Encode 's' using 'encoding' if Unicode."