import commands
import color, mode, method, tab
from lex import Grammar, PatternRule, RegionRule, OverridePatternRule
from mode.python import StringGrammar1, StringGrammar2

class LuaGrammar(Grammar):
    rules = [
        PatternRule(r'comment', r'--.*$'),
        PatternRule(r'spaces', r' +'),
        PatternRule(r'eol', r'\n'),

        RegionRule(r'string', r"'", StringGrammar1, r"'"),
        RegionRule(r'string', r'"', StringGrammar2, r'"'),

        PatternRule(r'keyword', r'(?:while|until|true|then|return|repeat|or|not|nil|local|in|if|function|for|false|end|elseif|else|do|break|and)(?![a-zA-Z0-9_])'),
        #PatternRule(r'function', r'[a-zA-Z_][a-zA-Z0-9_]*(?= *\()'),
        PatternRule(r'function', r'(?<=function )[a-zA-Z_][a-zA-Z0-9_]*'),
        #PatternRule(r'identifier', r'[a-zA-Z_][a-zA-Z0-9_]*'),
        PatternRule(r'lua_identifier', r'[a-zA-Z_][a-zA-Z0-9_]*'),

        PatternRule(r'delimiter', r'(?:[=(){}\[\];:,.])'),
        PatternRule(r'operator', r'(?:\.\.\.|\.\.|==|~=|<=|>=|<|>)'),

        PatternRule(r"integer", r"(?<![\.0-9a-zA-Z_])(?:0|-?[1-9][0-9]*|0[0-7]+|0[xX][0-9a-fA-F]+)[lL]?(?![\.0-9a-zA-Z_])"),
        PatternRule(r"float", r"(?<![\.0-9a-zA-Z_])(?:-?[0-9]+\.[0-9]*|-?\.[0-9]+|(?:[0-9]|[0-9]+\.[0-9]*|-?\.[0-9]+)[eE][\+-]?[0-9]+)(?![\.0-9a-zA-Z_])"),
    ]

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

class Lua(mode.Fundamental):
    modename    = 'Lua'
    extensions  = ['.lua']
    #tabbercls   = mode.lisp.LispTabber
    grammar     = LuaGrammar
    opentokens  = ('delimiter',)
    opentags    = {'(': ')', '[': ']', '{': '}'}
    closetokens = ('delimiter',)
    closetags   = {')': '(', ']': '[', '}': '{'}
    colors      = {}
    actions = [LuaCheckSyntax]
    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('lua-check-syntax', ('C-c s',))

install = Lua.install