"""
    MoinMoin - Diff Parser

    Copyright (c) 2002 by Fabien Niņoles <fabien@tzone.org>
    Copyright (c) 2000, 2001, 2002 by Jürgen Hermann <jh@web.de>
    All rights reserved, see COPYING for details.

    $Id: $
"""

# Imports
import cgi, string, re, sys


#############################################################################
### Plain Text Parser
#############################################################################

# Currently, only work with diff -u output... other format
# should be easy to add.

_LINE_RE = [
        (re.compile('^(diff .*?)$', re.M), 'green'), # command line
        (re.compile('^(--- .*?)$', re.M), 'green'), # old file
        (re.compile('^(\+\+\+ .*?)$', re.M), 'green'), # new file
    (re.compile('^(@@ .*?)$', re.M), 'magenta'), # lines numbers
    (re.compile('^(- .*?)$', re.M), 'red'), # removed line
    (re.compile('^(\+ .*?)$', re.M), 'blue'), # added line
]

class _colorized_match:
    """Englobe the match with <font color="color">match</font>
    """
    def __init__(self, color):
        self.color = color

    def __call__(self, match):
        return '<font color="%s">%s</font>' % (self.color, match.group(0))

class Parser:
    """ Colorized diff output
    """

    def __init__(self, raw, request, **kw):
        self.raw = raw
        self.out = kw.get('out', sys.stdout)

    def format(self, form):
        """ Send the text.
        """

        text = '<font face="LucidaTypewriter,Courier New">'
        color_me = _colorized_match('grey')
        #!!! send each line via the usual formatter calls
        text = cgi.escape(self.raw)
        # text = color_me(text)
        text = string.expandtabs(text)
        for (regex, color) in _LINE_RE:
            color_me.color = color
            text = regex.sub(color_me, text)
        print >>self.out, '<pre class="code">' + text + '</font></pre>' 
