"""
    MoinMoin wiki - Parser for Excel data copy/pasted into the edit window. 
    copied partly from CSV.py

Installation:

Copy ExcelPastedTable.py into your data/plugin/parser directory and
restart your MoinMoin. 

Use:

put 

{{{#!ExcelPastedTable

}}}

into your editing page

then copy/paste data from excel in there like this:

{{{#!ExcelPastedTable
a    b    c
d    e    f
}}}


Note:

This only works if you modify Lib/site-packages/MoinMoin/parser/wiki.py 

do a search for 'expandtabs' in that file and then replace the line:

        rawtext = self.raw.expandtabs()

with this line:

        rawtext = self.raw

I consider this a bug in MoinMoin because whatever is inside {{{#!blah }}} is not supposed
to be touched except by your own parser you write. However wiki.py is getting in there
and expanding the tabs. For excel-pasted data this wont work because it relies on tabs
as separators. 

Peace Out

"""

class Parser:

    def __init__(self, raw, request, **kw):
        """ save incoming data """
        self.raw = raw
        self.request = request
        self.kw = kw

    def format(self, formatter):
        """ write html to the request object. When you do copy/
        paste from Excel its format is like this:
        a<tab>b<tab>c<tab><end of line> 
        d<tab>e<tab>f<tab><end of line>

        so i take that and use the formatter.table functions and
        write it out to html """

        lines = self.raw.replace('\r','').split('\n')

        self.request.write(formatter.table(1))
        for line in lines:
            if line.strip()!='':
                self.request.write(formatter.table_row(1))
                cells = line.split('\t')
                for cell in cells:
                    self.request.write(formatter.table_cell(1))
                    self.request.write(formatter.text(cell))
                    self.request.write(formatter.table_cell(0))
                self.request.write(formatter.table_row(0))
        self.request.write(formatter.table(0))


if __name__=='__main__':
    # this is used to test this parser

    # fake the request object
    import StringIO
    class FakeReq(StringIO.StringIO):
        getText,user,cfg,current_lang,content_lang='','','','',''
    fakereq=FakeReq()

    # get a formatter object
    import MoinMoin.formatter.text_html
    testformatter = MoinMoin.formatter.text_html.Formatter(fakereq)

    # fake some tables as pasted from excel
    testtables = ['a\tb\tc\r\n' + 'd\te\tf\r\n']
    testtables += ['1\t2\t3\r\n' + 'd\t\t\r\n']

    for table in testtables:
        # try out the parser
        test = Parser(table,fakereq)
        test.format(testformatter)
        # print out result
        print test.request.getvalue()

