import commands, os.path, sets, string, sys, traceback
import color, completer, default, mode, method, regex, tab
from point import Point
from lex import Grammar, PatternRule, RegionRule, OverridePatternRule
import mode.lisp

class SchemeGrammar(Grammar):
    rules = [
        PatternRule(r'comment', r';.*$'),
        PatternRule(r'delimiter', r'[()]'),
        RegionRule(r'string', r'"', mode.lisp.StringGrammar, r'"'),
        PatternRule(r'spaces', r' +'),
        PatternRule(r'eol', r'\n'),
        PatternRule(r'abbrev', r"'|`|,\@|,"),

        # from r5rs
        PatternRule(r'scheme_keyword', r'(?:=>|unquote-splicing|unquote|syntax-rules|set!|quote|quasiquote|or|map|loop|letrec-syntax|letrec|let-syntax|let\*|let|lambda|if|for-each|else|dynamic-wind|do|delay|define-syntax|define-macro|define|cond|case|call-with-output-file|call-with-input-file|call-with-current-continuation|begin|and)(?![^\n )])'),

        PatternRule(r'scheme_boolean', r'#[tf]'),
        PatternRule(r'scheme_char', r'#\\space|#\\newline|#\\.'),
        PatternRule(r'scheme_number', '[+-]?[0-9][^ ()\n]+'),
        PatternRule(r'scheme_number', '#[bodx][ie]?[^ ()\n]+'),
        PatternRule(r'scheme_number', '#[ie][bodx]?[^ ()\n]+'),

        PatternRule(r'variable', r'[a-zA-Z!$%&*/:<=>?\^_~][-a-zA-Z0-9!$%&*/:<=>?^_~+.@]*|\+|-|\.\.\.'),
    ]

class SchemeCheckSyntax(method.Method):
    '''Check the syntax of a scheme file'''
    def _execute(self, w, **vargs):
        app = w.application
        cmd = "guile -s %r" % (w.buffer.path)
        (status, output) = commands.getstatusoutput(cmd)
        if status == 0:
            app.set_error("Syntax OK")
            app.data_buffer("*Scheme-Check-Syntax*", output, switch_to=False)
        else:
            app.data_buffer("*Scheme-Check-Syntax*", output)

class Scheme(mode.Fundamental):
    modename    = 'Scheme'
    extensions  = ['.scm']
    tabwidth    = 2
    tabbercls   = mode.lisp.LispTabber
    grammar     = SchemeGrammar
    opentokens  = ('delimiter',)
    opentags    = {'(': ')'}
    closetokens = ('delimiter',)
    closetags   = {')': '('}
    colors      = {
        'scheme_keyword': ('cyan', 'default', 'bold'),
        'scheme_char':    ('green', 'default', 'bold'),
        'scheme_boolean': ('magenta', 'default', 'bold'),
        'scheme_number':  ('default', 'default', 'bold'),
    }
    actions = [SchemeCheckSyntax]
    def __init__(self, w):
        mode.Fundamental.__init__(self, w)
        self.add_bindings('close-paren', (')',))
        self.add_bindings('close-brace', ('}',))
        self.add_bindings('close-bracket', (']',))
        self.add_bindings('scheme-check-syntax', ('C-c s',))

install = Scheme.install