# -*- coding: iso-8859-1 -*-
"""
= AgelSrc.py =
  Simple source code highlighting parser.

== Install ==
 1. `$ easy_install Pygments`
  This parser uses highlighting facility of Pygments library.
  Thanks to [http://pygments.pocoo.org/docs/authors/ authors].
  So you must install this great library with EasyInstall (or install manually)
 2. download and install `AgelSrc.py` file to your `wiki/data/plugin/parser/`.
  You may need to restart your MoinMoin processes. (Recommended)
 3. Enjoy! :-)

== Usage ==
 {{{#!AgelSrc filetype=python
 print 'hello, world!'
 }}}

 ...or...

 {{{#!AgelSrc
 #!/usr/bin/env python
 print 'hello, world!'
 }}}

 Second method may can fail if you didn't supply enough information for
 Pygments to //guess// syntax for your source code. (use 1st usage.)

== Author ==
 * Jonghyouk Yun <ageldama@gmail.com> 2007Jan23Tue0200 KST

== License ==
 * GNU GPL, http://www.gnu.org/copyleft/gpl.html for details.
 

"""

from MoinMoin import wikiutil

from pygments import highlight
from pygments.lexers import get_lexer_by_name, guess_lexer
from pygments.formatters import HtmlFormatter

### correction for multilingual sources...
import sys; reload(sys)
sys.setdefaultencoding('utf8')


class Parser:
    extensions = '*'
    Dependencies = []

    def __init__(self, raw, request, **kw):
        self.raw = raw
        self.request = request
        self.form = request.form
        self._ = request.getText
        ## bind `format_args` to self.*
        ## 'format_args':'a=1,b=2' => self.a=1; self.b=2
        for arg in kw.get('format_args', '').split(','):
            if arg.find('=') > -1:
                key, value = arg.split('=')
                setattr(self, key, wikiutil.escape(value.strip(), quote=1))

    def format(self, formatter):
        ## select lexer
        l= None
        if hasattr(self, 'filetype'):
            l= get_lexer_by_name(self.filetype)#, stripall=True)
        else:
            l= guess_lexer(self.raw)
        f= HtmlFormatter(linenos=True)#, cssclass="source")
        r= highlight(self.raw, l, f)
        ## printout stylesheet... dumb...
        self.request.write(u'<style>')
        self.request.write(f.get_style_defs())
        self.request.write(u'</style>')
        ## write result htmlcode
        self.request.write(r.expandtabs())
#EOF
