summaryrefslogtreecommitdiffstats
path: root/plugins/snippets/snippets/substitutionparser.py
blob: 8469dd33317511bbb3c11fde01c79a01e6ddf3b7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
#    Gedit snippets plugin
#    Copyright (C) 2006-2007  Jesse van den Kieboom <jesse@icecrew.nl>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

import re

class ParseError(Exception):
    def __str__(self):
        return 'Parse error, resume next'

class Modifiers:
    def _first_char(s):
        first = (s != '' and s[0]) or ''
        rest = (len(s) > 1 and s[1:]) or ''

        return first, rest

    def upper_first(s):
        first, rest = Modifiers._first_char(s)

        return '%s%s' % (first.upper(), rest)

    def upper(s):
        return s.upper()

    def lower_first(s):
        first, rest = Modifiers._first_char(s)

        return '%s%s' % (first.lower(), rest)

    def lower(s):
        return s.lower()

    def title(s):
        return s.title()

    upper_first = staticmethod(upper_first)
    upper = staticmethod(upper)
    lower_first = staticmethod(lower_first)
    lower = staticmethod(lower)
    title = staticmethod(title)
    _first_char = staticmethod(_first_char)

class SubstitutionParser:
    REG_ID = '[0-9]+'
    REG_NAME = '[a-zA-Z_]+'
    REG_MOD = '[a-zA-Z]+'
    REG_ESCAPE = '\\\\|\\(\\?|,|\\)'

    REG_GROUP = '(?:(%s)|<(%s|%s)(?:,(%s))?>)' % (REG_ID, REG_ID, REG_NAME, REG_MOD)

    def __init__(self, pattern, groups = {}, modifiers = {}):
        self.pattern = pattern
        self.groups = groups

        self.modifiers = {'u': Modifiers.upper_first,
                  'U': Modifiers.upper,
                  'l': Modifiers.lower_first,
                  'L': Modifiers.lower,
                  't': Modifiers.title}

        for k, v in modifiers.items():
            self.modifiers[k] = v

    def parse(self):
        result, tokens = self._parse(self.pattern, None)

        return result

    def _parse(self, tokens, terminator):
        result = ''

        while tokens != '':
            if self._peek(tokens) == '' or self._peek(tokens) == terminator:
                tokens = self._remains(tokens)
                break

            try:
                res, tokens = self._expr(tokens, terminator)
            except ParseError:
                res, tokens = self._text(tokens)

            result += res

        return result, tokens

    def _peek(self, tokens, num = 0):
        return (num < len(tokens) and tokens[num])

    def _token(self, tokens):
        if tokens == '':
            return '', '';

        return tokens[0], (len(tokens) > 1 and tokens[1:]) or ''

    def _remains(self, tokens, num = 1):
        return (num < len(tokens) and tokens[num:]) or ''

    def _expr(self, tokens, terminator):
        if tokens == '':
            return ''

        try:
            return {'\\': self._escape,
                '(': self._condition}[self._peek(tokens)](tokens, terminator)
        except KeyError:
            raise ParseError

    def _text(self, tokens):
        return self._token(tokens)

    def _substitute(self, group, modifiers = ''):
        result = (self.groups.has_key(group) and self.groups[group]) or ''

        for modifier in modifiers:
            if self.modifiers.has_key(modifier):
                result = self.modifiers[modifier](result)

        return result

    def _match_group(self, tokens):
        match = re.match('\\\\%s' % self.REG_GROUP, tokens)

        if not match:
            return None, tokens

        return self._substitute(match.group(1) or match.group(2), match.group(3) or ''), tokens[match.end():]

    def _escape(self, tokens, terminator):
        # Try to match a group
        result, tokens = self._match_group(tokens)

        if result != None:
            return result, tokens

        s = self.REG_GROUP

        if terminator:
            s += '|%s' % re.escape(terminator)

        match = re.match('\\\\(\\\\%s|%s)' % (s, self.REG_ESCAPE), tokens)

        if not match:
            raise ParseError

        return match.group(1), tokens[match.end():]

    def _condition_value(self, tokens):
        match = re.match('\\\\?%s\s*' % self.REG_GROUP, tokens)

        if not match:
            return None, tokens

        groups = match.groups()
        name = groups[0] or groups[1]

        return self.groups.has_key(name) and self.groups[name] != None, tokens[match.end():]

    def _condition(self, tokens, terminator):
        # Match ? after (
        if self._peek(tokens, 1) != '?':
            raise ParseError

        # Remove initial (? token
        tokens = self._remains(tokens, 2)
        condition, tokens = self._condition_value(tokens)

        if condition is None or self._peek(tokens) != ',':
            raise ParseError

        truepart, tokens = self._parse(self._remains(tokens), ',')

        if truepart is None:
            raise ParseError

        falsepart, tokens = self._parse(tokens, ')')

        if falsepart is None:
            raise ParseError

        if condition:
            return truepart, tokens
        else:
            return falsepart, tokens

    @staticmethod
    def escape_substitution(substitution):
        return re.sub('(%s|%s)' % (SubstitutionParser.REG_GROUP, SubstitutionParser.REG_ESCAPE), '\\\\\\1', substitution)

# ex:ts=4:et: