from mode import Fundamental
from lex import Grammar, PatternRule, RegionRule

class StringGrammar(Grammar):
    rules = [
        PatternRule('cheetah.placeholder', r'\${[a-zA-Z0-9_.\[\]]+}'),
        PatternRule('cheetah.placeholder', r'\$[a-zA-Z0-9_.\[\]]+'),
        PatternRule('octal', r'\\[0-7]{3}'),
        PatternRule('escaped', r'\\.'),
        PatternRule('data', r'[^\$\\]+'),
    ]

class TagGrammar(Grammar):
    rules = [
        PatternRule('cheetah.placeholder', r'\${[a-zA-Z0-9_.\[\]]+}'),
        PatternRule('cheetah.placeholder', r'\$[a-zA-Z0-9_.\[\]]+'),
        RegionRule('string', '"', StringGrammar, '"'),
        RegionRule('string', "'", StringGrammar, "'"),
        PatternRule('namespace', '[a-zA-Z_]+:'),
        PatternRule('attrname', r'[^ =>\n]+(?==)'),
        PatternRule('name', r'[^\[\] =>\n]+'),
    ]

class TemplateGrammar(Grammar):
    rules = [
        RegionRule('comment', r'#\*', Grammar, r'\*#'),
        PatternRule('comment', r'##.*\n'),
        PatternRule('cheetah.placeholder', r'\${[a-zA-Z0-9_.\[\]]+}'),
        PatternRule('cheetah.placeholder', r'\$[a-zA-Z0-9_.\[\]]+'),
        PatternRule('cheetah.directive', r'#.*?[#\n]'),
        RegionRule('cheetah.tag', '</?', TagGrammar, '/?>'),
    ]

class Template(Fundamental):
    name       = 'Cheetah'
    extensions = ['.tmpl']
    grammar    = TemplateGrammar
    commentc   = '##'
    colors     = {
        'cheetah.directive':        ('magenta', 'default', 'bold'),
        'cheetah.placeholder':      ('magenta', 'default', 'bold'),
        'cheetah.tag.start':        ('default', 'default', 'bold'),
        'cheetah.tag.namespace':    ('magenta', 'default', 'bold'),
        'cheetah.tag.name':         ('blue', 'default', 'bold'),
        'cheetah.tag.attrname':     ('cyan', 'default', 'bold'),
        'cheetah.tag.end':          ('default', 'default', 'bold'),
    }
    _bindings = {
        'close-paren':   (')',),
        'close-brace':   ('}',),
        'close-bracket': (']',),
    }

install = Template.install