# -*- coding: iso-8859-1 -*-
"""
    MoinMoin - "Literate Programming" Parser

    Format code fragments with anchors and links

    @version: 0.7
    @copyright: 2007 by Oleg Kobchenko <olegyk@yahoo.com>
    @web: http://moinmoin.wikiwikiweb.de/OlegKobchenko
    @license: GNU GPL, see COPYING for details.
"""

import re
from MoinMoin import wikiutil


Dependencies = []

class Parser:
    """
        Format code fragments with hypertext cross links.
    """

    Dependencies = []

    def __init__(self, raw, request, **kw):
        self.raw = raw
        self.request = request
        self.form = request.form
        self._ = request.getText
        self.litName = "untitled"
        self.litCaption = ""
        self.litFor = ""

        self.parse_args(request, kw.get('format_args',''))

    def parse_args(self, request, args):
        attrs, msg = wikiutil.parseAttributes(request, args)
        if not msg:
            try:
                self.litName = str(attrs.get('name','"untitled"')[1:-1])
            except ValueError:
                pass
            try:
                self.litCaption = str(attrs.get('caption','""')[1:-1])
            except ValueError:
                pass
            try:
                self.litFor = str(attrs.get('for','""')[1:-1])
            except ValueError:
                pass

    def format(self, formatter):
        """ Send the fragment. """
        frag = formatter.text(self.raw.expandtabs()) + '\n'
        for m in re.finditer(u'«([^»]+)»', frag):
            href = wikiutil.quoteWikinameURL(m.group(1))
            href = formatter.anchorlink(1, href, "backlink." + href) + m.group() + formatter.anchorlink(0)
            frag = frag.replace(m.group(), href)

        anchor = wikiutil.quoteWikinameURL(self.litName)
        url = self.litName.find(".") > 0 and "%s/%s?action=Literate&target=%s" % (
            self.request.getScriptname(), wikiutil.quoteWikinameURL(self.request.page.page_name),
            anchor) or ("#backlink." + anchor)
        self.request.write(''.join((
            formatter.open('div',0,{'class':'codearea'}),
                formatter.anchordef(anchor),
                formatter.url(1, url, css_class='codenumbers', title=len(self.litFor)and "for "+self.litFor or ""),
                    (u'«%s»=' % self.litName),
                formatter.anchorlink(0),
                self.litCaption and
                    ' ' + formatter.emphasis(1) + formatter.text(self.litCaption) + formatter.emphasis(0),
                formatter.preformatted(1),
                    frag,
                formatter.preformatted(0),
            formatter.close('div') )))
