reformat tabs

This commit is contained in:
Elan Ruusamäe 2012-09-23 14:27:30 +02:00
parent 7abbf81733
commit 591cf09756

View file

@ -1,10 +1,11 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# Setup VIM: ex: noet ts=2 sw=2 :
""" """
MoinMoin - Dokuwiki Formatter MoinMoin - Dokuwiki Formatter
@copyright: 2000, 2001, 2002 by Jürgen Hermann <jh@web.de> @copyright: 2000, 2001, 2002 by Jürgen Hermann <jh@web.de>
@copyright: 2011-2012 Elan Ruusamäe <glen@delfi.ee> @copyright: 2011-2012 Elan Ruusamäe <glen@delfi.ee>
@license: GNU GPL, see COPYING for details. @license: GNU GPL, see COPYING for details.
""" """
from xml.sax import saxutils from xml.sax import saxutils
@ -16,330 +17,330 @@ from types import *
# TODO: let base class MoinMoin/formatter/base.py handle not implemented methods # TODO: let base class MoinMoin/formatter/base.py handle not implemented methods
class Formatter(FormatterBase): class Formatter(FormatterBase):
""" """
Send Dokuwiki formatted data. Send Dokuwiki formatted data.
""" """
hardspace = '&nbsp;' hardspace = '&nbsp;'
# hardspace = ' ' # hardspace = ' '
def __init__(self, request, **kw): def __init__(self, request, **kw):
apply(FormatterBase.__init__, (self, request), kw) apply(FormatterBase.__init__, (self, request), kw)
self._current_depth = 1 self._current_depth = 1
self._base_depth = 0 self._base_depth = 0
self.in_pre = 0 self.in_pre = 0
self.in_table = 0 self.in_table = 0
self._text = None # XXX does not work with links in headings!!!!! self._text = None # XXX does not work with links in headings!!!!!
self.list_depth = 0 self.list_depth = 0
self.list_type = ' ' self.list_type = ' '
def _escape(self, text, extra_mapping={"'": "&apos;", '"': "&quot;"}): def _escape(self, text, extra_mapping={"'": "&apos;", '"': "&quot;"}):
return saxutils.escape(text, extra_mapping) return saxutils.escape(text, extra_mapping)
def startDocument(self, pagename): def startDocument(self, pagename):
encoding = config.charset encoding = config.charset
return '<?xml version="1.0" encoding="%s"?>\n<s1 title="%s">' % ( return '<?xml version="1.0" encoding="%s"?>\n<s1 title="%s">' % (
encoding, self._escape(pagename)) encoding, self._escape(pagename))
def endDocument(self): def endDocument(self):
result = "" result = ""
while self._current_depth > 1: while self._current_depth > 1:
result += "</s%d>" % self._current_depth result += "</s%d>" % self._current_depth
self._current_depth -= 1 self._current_depth -= 1
return result + '</s1>' return result + '</s1>'
def lang(self, on, lang_name): def lang(self, on, lang_name):
return ('<div lang="">' % lang_name, '</div>')[not on] return ('<div lang="">' % lang_name, '</div>')[not on]
def sysmsg(self, on, **kw): def sysmsg(self, on, **kw):
return ('<sysmsg>', '</sysmsg>')[not on] return ('<sysmsg>', '</sysmsg>')[not on]
def rawHTML(self, markup): def rawHTML(self, markup):
return '<html>' + markup + '</html>' return '<html>' + markup + '</html>'
def pagelink(self, on, pagename='', page=None, **kw): def pagelink(self, on, pagename='', page=None, **kw):
if on: if on:
return '[[:' + ":".join(pagename.split("/")) + "|" return '[[:' + ":".join(pagename.split("/")) + "|"
else: else:
return ']]' return ']]'
def interwikilink(self, on, interwiki='', pagename='', **kw): def interwikilink(self, on, interwiki='', pagename='', **kw):
if on: if on:
if interwiki == 'Self': if interwiki == 'Self':
return self.pagelink(on, pagename, **kw) return self.pagelink(on, pagename, **kw)
return '[[%s>%s|' % (interwiki, pagename) return '[[%s>%s|' % (interwiki, pagename)
else: else:
return ']]' return ']]'
def url(self, on, url='', css=None, **kw): def url(self, on, url='', css=None, **kw):
return ('[[%s|' % (self._escape(url)), ']]')[not on] return ('[[%s|' % (self._escape(url)), ']]')[not on]
def attachment_link(self, url, text, **kw): def attachment_link(self, url, text, **kw):
return '{{%s|%s}}' % (url, text) return '{{%s|%s}}' % (url, text)
def attachment_image(self, url, **kw): def attachment_image(self, url, **kw):
return '{{%s|}}' % (url,) return '{{%s|}}' % (url,)
def attachment_drawing(self, url, text, **kw): def attachment_drawing(self, url, text, **kw):
return '{{%s|%s}}' % (url, text) return '{{%s|%s}}' % (url, text)
def text(self, text, **kw): def text(self, text, **kw):
self._did_para = 0 self._did_para = 0
if self._text is not None: if self._text is not None:
self._text.append(text) self._text.append(text)
return text return text
def rule(self, size=0, **kw): def rule(self, size=0, **kw):
# size not supported # size not supported
if size >= 4: if size >= 4:
return '----\n' return '----\n'
else: else:
return '-' * size + '\n' return '-' * size + '\n'
def icon(self, type): def icon(self, type):
return '<icon type="%s" />' % type return '<icon type="%s" />' % type
def strong(self, on, **kw): def strong(self, on, **kw):
return ['**', '**'][not on] return ['**', '**'][not on]
def emphasis(self, on, **kw): def emphasis(self, on, **kw):
return ['//', '//'][not on] return ['//', '//'][not on]
def highlight(self, on, **kw): def highlight(self, on, **kw):
return ['**', '**'][not on] return ['**', '**'][not on]
def number_list(self, on, type=None, start=None, **kw): def number_list(self, on, type=None, start=None, **kw):
# list type not supported # list type not supported
if on: if on:
self.list_depth += 1 self.list_depth += 1
self.list_type = '-' self.list_type = '-'
else: else:
self.list_depth -= 1 self.list_depth -= 1
self.list_type = ' ' self.list_type = ' '
return ['', '\n'][on] return ['', '\n'][on]
def bullet_list(self, on, **kw): def bullet_list(self, on, **kw):
if on: if on:
self.list_depth += 1 self.list_depth += 1
self.list_type = '*' self.list_type = '*'
else: else:
self.list_depth -= 1 self.list_depth -= 1
self.list_type = ' ' self.list_type = ' '
return ['', '\n'][on] return ['', '\n'][on]
def listitem(self, on, **kw): def listitem(self, on, **kw):
# somewhy blockquote uses "listitem" call # somewhy blockquote uses "listitem" call
return [(' ' * self.list_depth * 2) + self.list_type + ' ', '\n'][not on] return [(' ' * self.list_depth * 2) + self.list_type + ' ', '\n'][not on]
def code(self, on, **kw): def code(self, on, **kw):
""" `typewriter` or {{{typerwriter}}, for code blocks i hope codeblock works """ """ `typewriter` or {{{typerwriter}}, for code blocks i hope codeblock works """
return ["''", "''"][not on] return ["''", "''"][not on]
def sup(self, on, **kw): def sup(self, on, **kw):
return ['<sup>', '</sup>'][not on] return ['<sup>', '</sup>'][not on]
def sub(self, on, **kw): def sub(self, on, **kw):
return ['<sub>', '</sub>'][not on] return ['<sub>', '</sub>'][not on]
def strike(self, on, **kw): def strike(self, on, **kw):
return ['<del>', '</del>'][not on] return ['<del>', '</del>'][not on]
def preformatted(self, on, **kw): def preformatted(self, on, **kw):
FormatterBase.preformatted(self, on) FormatterBase.preformatted(self, on)
result = '' result = ''
if self.in_p: if self.in_p:
result = self.paragraph(0) result = self.paragraph(0)
return result + ['<file>', '</file>\n'][not on] return result + ['<file>', '</file>\n'][not on]
def paragraph(self, on, **kw): def paragraph(self, on, **kw):
FormatterBase.paragraph(self, on) FormatterBase.paragraph(self, on)
if self.in_table or self.list_depth: if self.in_table or self.list_depth:
return '' return ''
return ['', '\n\n'][not on] return ['', '\n\n'][not on]
def linebreak(self, preformatted=1): def linebreak(self, preformatted=1):
return ['\n', '\\\n'][not preformatted] return ['\n', '\\\n'][not preformatted]
def heading(self, on, depth, **kw): def heading(self, on, depth, **kw):
# heading depth reversed in dokuwiki # heading depth reversed in dokuwiki
heading_depth = 7 - depth heading_depth = 7 - depth
if on: if on:
return u'%s ' % (u'=' * heading_depth) return u'%s ' % (u'=' * heading_depth)
else: else:
return u' %s\n' % (u'=' * heading_depth) return u' %s\n' % (u'=' * heading_depth)
def table(self, on, attrs={}, **kw): def table(self, on, attrs={}, **kw):
if on: if on:
self.in_table = 1 self.in_table = 1
else: else:
self.in_table = 0 self.in_table = 0
return '' return ''
def table_row(self, on, attrs={}, **kw): def table_row(self, on, attrs={}, **kw):
return ['\n', '|'][not on] return ['\n', '|'][not on]
def table_cell(self, on, attrs={}, **kw): def table_cell(self, on, attrs={}, **kw):
return ['|', ''][not on] return ['|', ''][not on]
def anchordef(self, id): def anchordef(self, id):
# not supported # not supported
return '' return ''
def anchorlink(self, on, name='', **kw): def anchorlink(self, on, name='', **kw):
# kw.id not supported, we hope the anchor matches existing heading on page # kw.id not supported, we hope the anchor matches existing heading on page
return ('[[#', ']]') [not on] return ('[[#', ']]') [not on]
def underline(self, on, **kw): def underline(self, on, **kw):
return ['__', '__'][not on] return ['__', '__'][not on]
def definition_list(self, on, **kw): def definition_list(self, on, **kw):
result = '' result = ''
if self.in_p: if self.in_p:
result = self.paragraph(0) result = self.paragraph(0)
return result + ['<gloss>', '</gloss>'][not on] return result + ['<gloss>', '</gloss>'][not on]
def definition_term(self, on, compact=0, **kw): def definition_term(self, on, compact=0, **kw):
return ['<label>', '</label>'][not on] return ['<label>', '</label>'][not on]
def definition_desc(self, on, **kw): def definition_desc(self, on, **kw):
return ['<item>', '</item>'][not on] return ['<item>', '</item>'][not on]
def image(self, src=None, **kw): def image(self, src=None, **kw):
valid_attrs = ['src', 'width', 'height', 'alt', 'title'] valid_attrs = ['src', 'width', 'height', 'alt', 'title']
url = src url = src
if '?' in url: if '?' in url:
url += '&' url += '&'
else: else:
url += '?' url += '?'
attrs = {} attrs = {}
for key, value in kw.items(): for key, value in kw.items():
if key in valid_attrs: if key in valid_attrs:
attrs[key] = value attrs[key] = value
# TODO: finish this # TODO: finish this
if attrs.has_key('width'): if attrs.has_key('width'):
url += attrs['width'] url += attrs['width']
return '{{' + url + '}}' return '{{' + url + '}}'
def code_area(self, on, code_id, code_type='code', show=0, start=-1, step=-1): def code_area(self, on, code_id, code_type='code', show=0, start=-1, step=-1):
syntax = '' syntax = ''
# switch for Python: http://simonwillison.net/2004/may/7/switch/ # switch for Python: http://simonwillison.net/2004/may/7/switch/
try: try:
syntax = { syntax = {
'ColorizedPython': 'python', 'ColorizedPython': 'python',
'ColorizedPascal': 'pascal', 'ColorizedPascal': 'pascal',
'ColorizedJava': 'java', 'ColorizedJava': 'java',
'ColorizedCPlusPlus': 'cpp', 'ColorizedCPlusPlus': 'cpp',
}[code_type] }[code_type]
except KeyError: except KeyError:
pass pass
return ('<code %s>' % syntax , '</code>')[not on] return ('<code %s>' % syntax , '</code>')[not on]
def code_line(self, on): def code_line(self, on):
return ('', '\n')[on] return ('', '\n')[on]
def code_token(self, on, tok_type): def code_token(self, on, tok_type):
# not supported # not supported
return '' return ''
def comment(self, text): def comment(self, text):
# real comments (lines with two hash marks) # real comments (lines with two hash marks)
if text[0:2] == '##': if text[0:2] == '##':
return "/* %s */\n" % text[2:].strip() return "/* %s */\n" % text[2:].strip()
# Some kind of Processing Instruction # Some kind of Processing Instruction
# http://moinmo.in/HelpOnProcessingInstructions # http://moinmo.in/HelpOnProcessingInstructions
tokens = text.lstrip('#').split(None, 1) tokens = text.lstrip('#').split(None, 1)
if tokens[0] in ('language', 'format', 'refresh'): if tokens[0] in ('language', 'format', 'refresh'):
return '' return ''
if tokens[0] == 'acl': if tokens[0] == 'acl':
# TODO: fill acl.auth.php # TODO: fill acl.auth.php
return '' return ''
if tokens[0] == 'deprecated': if tokens[0] == 'deprecated':
return '<note warning>This page is deprecated</note>\n' return '<note warning>This page is deprecated</note>\n'
if tokens[0] == 'redirect': if tokens[0] == 'redirect':
return text + "\n" return text + "\n"
if tokens[0] == 'pragma': if tokens[0] == 'pragma':
# TODO: can do 'description' via 'meta' dokuwiki plugin # TODO: can do 'description' via 'meta' dokuwiki plugin
return "/* pragma: %s */\n" % " ".join(tokens[1:]) return "/* pragma: %s */\n" % " ".join(tokens[1:])
return "/* %s */\n" % text.lstrip('#') return "/* %s */\n" % text.lstrip('#')
def macro(self, macro_obj, name, args): def macro(self, macro_obj, name, args):
def email(args): def email(args):
mail = args.replace(' AT ', '@') mail = args.replace(' AT ', '@')
mail = mail.replace(' DOT ', '.') mail = mail.replace(' DOT ', '.')
return '[[%s|%s]]' % (mail, args) return '[[%s|%s]]' % (mail, args)
# function which will just do what parent class would # function which will just do what parent class would
def inherit(args): def inherit(args):
return apply(FormatterBase.macro, (self, macro_obj, name, args)) return apply(FormatterBase.macro, (self, macro_obj, name, args))
try: try:
lookup = { lookup = {
'BR' : '\\\\', 'BR' : '\\\\',
'MailTo' : email, 'MailTo' : email,
'GetText' : args, 'GetText' : args,
'ShowSmileys' : inherit, 'ShowSmileys' : inherit,
}[name] }[name]
except KeyError: except KeyError:
lookup = '/* UndefinedMacro: %s(%s) */' % (name, args) lookup = '/* UndefinedMacro: %s(%s) */' % (name, args)
if type(lookup) == FunctionType: if type(lookup) == FunctionType:
text = lookup(args) text = lookup(args)
else: else:
text = lookup text = lookup
return text return text
def smiley(self, text): def smiley(self, text):
try: try:
# https://www.dokuwiki.org/devel:smileys.conf # https://www.dokuwiki.org/devel:smileys.conf
return { return {
# note: reverse sorted so that longer smileys get matched first # note: reverse sorted so that longer smileys get matched first
'X-(' : ':-X', 'X-(' : ':-X',
'{X}' : ':!:', '{X}' : ':!:',
'{*}' : '<ubu>', '{*}' : '<ubu>',
'(./)' : u'', '(./)' : u'',
':))' : ':-P', ':))' : ':-P',
':-))' : ':-P', ':-))' : ':-P',
':-?' : ':-P', ':-?' : ':-P',
':o' : ':-o', ':o' : ':-o',
'{OK}' : ':!:', '{OK}' : ':!:',
'{o}' : '<circ>', '{o}' : '<circ>',
'{i}' : ':!:', '{i}' : ':!:',
':D' : ':-D', ':D' : ':-D',
'B)' : '8-)', 'B)' : '8-)',
'B-)' : '8-)', 'B-)' : '8-)',
'{3}' : '<3>', '{3}' : '<3>',
'{2}' : '<2>', '{2}' : '<2>',
'{1}' : '<1>', '{1}' : '<1>',
'(!)' : ':!:', '(!)' : ':!:',
'/!\\' : ':!:', '/!\\' : ':!:',
':\\' : ':-\\', ':\\' : ':-\\',
':))' : ':-)', ':))' : ':-)',
':)' : ':-)', ':)' : ':-)',
':(' : ':-(', ':(' : ':-(',
':-))' : ':-)', ':-))' : ':-)',
':-)' : ':-)', ':-)' : ':-)',
':-(' : ':-(', ':-(' : ':-(',
';)' : ';-)', ';)' : ';-)',
'|)' : ':-|', '|)' : ':-|',
'|-)' : ':-|', '|-)' : ':-|',
'>:>' : '^_^', '>:>' : '^_^',
'<!>' : ':!:', '<!>' : ':!:',
'<:(' : ':-?', '<:(' : ':-?',
}[text] }[text]
except KeyError: except KeyError:
return text return text