# -*- coding: iso-8859-1 -*-
"""MoinMoin - Cite Macro

A macro to insert citations from a bibliography into the text.

Syntax:
    [[Cite(key[, "before"[, "after"]])]]

Parameters:
    key    -- key of the entry in the bibtex database
    before -- text appearing before the reference link, needs to be
              wrapped in single- or double-quotes
    after  -- text appearing after the reference link, needs to be
              wrapped in single- or double-quotes

Notes:
This macro is intended to be used with the Bibliography macro.

$Id: Cite.py,v 1.1.1.1 2007-06-07 20:36:15 gber Exp $
Copyright 2007 by Guido Berhoerster <guido+moinmoin@berhoerster.name>
Licensed under the GNU GPL, see COPYING for details.

$Log: Cite.py,v $
Revision 1.1.1.1  2007-06-07 20:36:15  gber
initial import into CVS


"""

import re

Dependencies = []

class Cite:
    """
    A citation in the text with a link to a (possible) corresponding
    bibliography entry.

    """
    def __init__(self, macro, args):
        args_re = re.compile(r'''
^(?P<key>[^,]+) # citation key (mandatory)
(
(,\s*((?P<bquote>[\'"])(?P<before>.*?)(?P=bquote))?\s*)? # text before citation
(,\s*((?P<aquote>[\'"])(?P<after>.*?)(?P=aquote))?\s*)?  # text after citation
)?''', re.UNICODE|re.VERBOSE)
        self.macro = macro
        self.args = args
        self.request = self.macro.request
        self._ = self.request.getText
        self.args_match = args_re.match(self.args)

    def run(self):
        _ = self._
        output = []
        if not self.args_match:
            output.append(self.macro.formatter.span(1, css_class="error"))
            output.append(self.macro.formatter.escapedText(
                         _('Error: Invalid Cite arguments: "%(args)s"') %
                         {"args": self.args}))
            output.append(self.macro.formatter.span(0))
            return "".join(output)

        if self.args_match.group("before"):
            output.append(self.macro.formatter.escapedText(\
                    self.args_match.group("before")))
        output.append(self.macro.formatter.anchorlink(1, name="ref:%s" %
                                                self.args_match.group("key")))
        output.append(self.macro.formatter.escapedText(self.args_match.group(
                                                                       "key")))
        output.append(self.macro.formatter.anchorlink(0))
        if self.args_match.group("after"):
            output.append(self.macro.formatter.escapedText(
                                               self.args_match.group("after")))

        return "".join(output)


def execute(macro, args):
    cite = Cite(macro, args)
    return cite.run()
