import commands
import color, mode2, tab2
from lex3 import Grammar, PatternRule, RegionRule
from method import Method

class StringGrammar(Grammar):
    rules = [
        PatternRule(r'escaped', r'\\.'),
        PatternRule(r'variable', r"\${(?:[a-zA-Z0-9_]+|\?\$)}"),
        PatternRule(r"variable", r"\$[^({][a-zA-Z0-9_]*"),
        PatternRule(r'variable', r"\$(?=\()"),
    ]

class ShGrammar(Grammar):
    rules = [
        PatternRule(r'function', r'[a-zA-Z_][a-zA-Z0-9_]*(?= *\(\))'),
        PatternRule(r'reserved', r"(?:case|done|do|elif|else|esac|fi|for|function|if|in|select|then|until|while|time)(?![a-zA-Z0-9_=/])"),
        PatternRule(r'builtin', r"(?:source|alias|bg|bind|break|builtin|cd|command|compgen|complete|declare|dirs|disown|echo|enable|eval|exec|exit|export|fc|fg|getops|hash|help|history|jobs|kill|let|local|logout|popd|printf|pushd|pwd|readonly|read|return|set|shift|shopt|suspend|test|times|trap|type|ulimit|umask|unalias|unset|wait)(?![a-zA-Z0-9_=/])"),
        PatternRule(r'operator', r"(?:-eq|-ne|-gt|-lt|-ge|-le| = | != )"),
        PatternRule(r'delimiter', r";;|[\[\]\(\);\{\}|&><]"),
        RegionRule(r'eval', '`', StringGrammar, '`'),
        RegionRule(r'neval', r'\$\(', StringGrammar, r'\)'),
        PatternRule(r'variable', r"(?:^|(?<= ))[a-zA-Z_][a-zA-Z0-9_]*(?==)"),
        PatternRule(r'variable', r"\${(?:[a-zA-Z0-9_]+|\?\$)}"),
        PatternRule(r"variable", r"\$[^({][a-zA-Z0-9_]*"),
        PatternRule(r'variable', r"\$(?=\()"),
        RegionRule(r'string', "'", Grammar, "'"),
        RegionRule(r'string', '"', StringGrammar, '"'),
        PatternRule(r'comment', r'#.*$'),
        PatternRule(r'bareword', r'[a-zA-Z0-9_-]+'),
        PatternRule(r'continuation', r'\\\n$'),
        PatternRule(r'eol', r'\n$'),
    ]

class ShTabber(tab2.StackTabber):
    def is_base(self, y):
        if y == 0:
            return True
        highlighter = self.mode.window.buffer.highlights[self.mode.name()]
        if not highlighter.tokens[y]:
            return False
        t = highlighter.tokens[y][0]
        return t.name == 'function'
    def _handle_close_token(self, currlvl, y, i):
        s = self.get_token(y, i).string
        if s == ')' and self.markers and self._peek_name() == "case":
            # we have to ignore ) when used in "case" statements.
            return currlvl
        else:
            return tab2.StackTabber._handle_close_token(self, currlvl, y, i)
    def _handle_other_token(self, currlvl, y, i):
        token  = self.get_token(y, i)
        fqname = token.fqname()
        if token.name == 'continuation':
            self._opt_append("cont", currlvl + 4)
        elif token.name == 'eol':
            self._opt_pop("cont")
        return currlvl

class Sh(mode2.Fundamental):
    grammar     = ShGrammar
    tabbercls   = ShTabber
    opentokens  = ('delimiter', 'reserved',)
    opentags    = {'(': ')', '[': ']', '{': '}',
                   'do': 'done', 'then': 'fi', 'case': 'esac'}
    closetokens = ('delimiter', 'reserved',)
    closetags   = {')': '(', ']': '[', '}': '{',
                   'done': 'do', 'fi': 'then', 'esac': 'case'}
    colors = {
        'builtin':         ('cyan', 'default', 'bold'),
        'function':        ('magenta', 'default', 'bold'),
        'reserved':        ('magenta', 'default', 'bold'),
        'variable':        ('yellow', 'default', 'bold'),

        'delimiter':       ('default', 'default', 'bold'),
        'operator':        ('magenta', 'default', 'bold'),

        'string.start':    ('green', 'default'),
        'string.variable': ('yellow', 'default'),
        'string.escaped':  ('magenta', 'default'),
        'string.null':     ('green', 'default'),
        'string.end':      ('green', 'default'),

        'eval.start':      ('cyan', 'default'),
        'eval.variable':   ('yellow', 'default'),
        'eval.null':       ('cyan', 'default'),
        'eval.end':        ('cyan', 'default'),

        #'neval.start':      ('cyan', 'default'),
        #'neval.end':        ('cyan', 'default'),
        'neval.start':      ('yellow', 'default'),
        'neval.variable':   ('yellow', 'default'),
        'neval.null':       ('cyan', 'default'),
        'neval.end':        ('yellow', 'default'),

        'comment':         ('red', 'default'),
        'continuation':    ('red', 'default'),
    }
    def __init__(self, w):
        mode2.Fundamental.__init__(self, w)
        self.add_action_and_bindings(ShCheckSyntax(), ('C-c s',))

class ShCheckSyntax(Method):
    '''Check the syntax of a shell script'''
    def _execute(self, w, **vargs):
        app = w.application
        cmd = "bash -n %r" % w.buffer.path
        (status, output) = commands.getstatusoutput(cmd)
        if status == 0:
            app.set_error("Syntax OK")
            app.data_buffer("*Sh-Check-Syntax*", output, switch_to=False)
        else:
            app.data_buffer("*Sh-Check-Syntax*", output)