import color, mode
from lex import Grammar, PatternRule, RegionRule, PatternGroupRule
from mode.sh import ShGrammar, Sh

class StringGrammar1(Grammar):
    rules = [
        PatternRule(r'escaped', r'\\.'),
        PatternRule(r'escaped', r'\$\$'),
        PatternRule(r'variable', r"\$\([a-zA-Z0-9_]+\)"),
        PatternRule(r'data', r"[^\\']+"),
    ]
class StringGrammar2(Grammar):
    rules = [
        PatternRule(r'escaped', r'\\.'),
        PatternRule(r'escaped', r'\$\$'),
        PatternRule(r'variable', r"\$\([a-zA-Z0-9_]+\)"),
        PatternRule(r'data', r'[^\\"]+'),
    ]

class MakeGrammar(Grammar):
    rules = [
        PatternRule(r'comment', r'#.*\n$'),
        PatternRule(r'spaces', r' +$'),
        PatternRule(r'continuation', r'\\\n$'),
        PatternRule(r'targets', r'^[^:= ]+(?= *:)'),
        RegionRule(r'assignment', r'^[^:= ]+ *=', ShGrammar, r'\n'),
        RegionRule(r'actions', r'^    ', ShGrammar, r'\n'),
        PatternRule(r'make_variable', r'\$\([a-zA-Z0-9_]+\)'),
        PatternRule(r'make_variable', r'\${[a-zA-Z0-9_]+}'),
        RegionRule(r'make_string', r'"', StringGrammar2, r'"'),
        RegionRule(r'make_string', r"'", StringGrammar1, r"'"),
        PatternRule(r'eol', r'\n$'),
    ]

class Make(mode.Fundamental):
    modename  = 'Make'
    basenames = ['Makefile']
    grammar   = MakeGrammar
    savetabs  = True
    colors    = {
        'targets.start':        ('cyan', 'default', 'bold'),
        'assignment.start':     ('yellow', 'default', 'bold'),
        'make_variable':        ('yellow', 'default', 'bold'),
        'make_string.start':    ('green', 'default', 'bold'),
        'make_string.variable': ('yellow', 'default', 'bold'),
        'make_string.escaped':  ('magenta', 'default', 'bold'),
        'make_string.null':     ('green', 'default', 'bold'),
        'make_string.end':      ('green', 'default', 'bold'),
    }

install = Make.install