Source

codeaide / snippet.py

Full commit
  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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
# -*- coding: utf-8 -*-
import re
import os
# for loading snippet definitions:
from xml.etree import ElementTree 



digits = "0123456789"
lowercase_letters = "abcdefghijklmnopqrstuvwxyz"
uppercase_letters = lowercase_letters.upper()
letters = uppercase_letters + lowercase_letters
whitespace = " \t\r\n"
punct = re.escape(".-,;!?") # XXX: Any more?


character_classes = {
  "alpha": letters,
  "alnum": letters + digits,
  "ascii": re.escape("".join([chr(i) for i in range(128)])),
  "cntrl": re.escape("".join([chr(i) for i in range(32)])),
  "digit": digits,
  "graph": letters + digits + punct,
  "lower": lowercase_letters,
  "print": letters + digits + punct + whitespace,
  "punct": punct,
  "space": whitespace,
  "upper": uppercase_letters,
  "word" : letters + digits + "_",
  "xdigit": "0-9a-fA-F"
  }



class PerlRegEx(object):
    """
    This class can search and replace with a single string like sed or Perl.
    Additionally support for Posix character classes was added for compatibily reasons.
    
    Full syntax documented at http://perldoc.perl.org/perlre.html
    XXX: Make tests with http://blazonry.com/perl/regexp_exs.php
    
    >>> pre = PerlRegEx(r"/(:alpha:)/'$1'/g")
    >>> pre.search
    '([ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz])'
    
    >>> print pre.replace
    '\\1'
    
    >>> pre("a+1*b")
    "'a'+1*'b'"
    
    """

    def __init__(self, pattern):
        self.pattern = pattern
        self.length = len(pattern)
        self.pos = -1
        self.search = []
        self.replace = []
        self.modifiers = []
        self.target = self.search
        self.next_char()
        self.parse()


    def next_char(self):
        self.pos += 1
        if self.pos < self.length:
            self.char = self.pattern[self.pos]
        else:
            self.char = None
        return self.char


    def emit(self, char):
        self.target.append(char)


    def _parse_word(self, allowed=letters):
        word = ""
        while self.char:
            if not self.char in allowed:
                break
            word += self.char
            self.next_char()
        return word


    def parse_character_class(self):
        # Currently not supported by Python:
        # http://bugs.python.org/issue433029
        # Will hopefully be added besides other goodies:
        # http://bugs.python.org/issue2636
        self.next_char()
        if self.char == "^":
            negate = True
            self.next_char()
        else:
            negate = False
        if self.char in letters:
            name = self._parse_word()
            if self.char == ":":
                self.next_char()
                found = character_classes.get(name)
                if not found:
                    raise ValueError, ":%s: unknown posix character class" % name
                self.emit("[")
                if negate:
                    self.emit("^")
                self.emit(found)
                self.emit("]")
            else:
                self.emit(":")
                self.emit(name)
        else:
            self.emit(self.char)
            if negate:
                self.emit("^")


    def parse(self):
        while self.char:
            if self.char == "/":
                if self.pos == 0:
                    pass # skip
                elif self.target == self.search:
                    self.target = self.replace
                elif self.target == self.replace:
                    self.target = self.modifiers
                elif self.target == self.modifiers:
                    raise ValueError, "Third unescaped '/' found in regex"
                self.next_char()

            elif self.char == ":" and self.target == self.search:
                self.parse_character_class()

            elif self.char == "$" and self.target == self.replace:
                # Python uses \1 and Perl uses $1
                # XXX: Perl's \1 would mean chr(1)
                self.next_char()
                if self.char in digits:
                    self.emit("\\")
                    while self.char:
                        if not self.char in digits:
                            break
                        self.emit(self.char)
                        self.next_char()
                else:
                    self.emit("$")

            elif self.char == "\\":
                # This makes sure that nexxxt char is not handled 
                # above by accident
                self.next_char()
                self.emit("\\")
                self.emit(self.char)
                self.next_char()

            else:
                self.emit(self.char)
                self.next_char()

        if self.target == self.replace:
            self.replace, self.modifiers = self.modifiers, self.replace
        self.search = "".join(self.search)
        self.replace = "".join(self.replace)
        self.global_mode = False
        self.re_options = 0
        processed = []
        for char in self.modifiers:
            if char in processed:
                raise ValueError, "More than one occurence of same modifier %r" % m
            elif char == "g":
                self.global_mode = True
            elif char == "i":
                self.re_options |= re.I
            elif char == "m":
                self.re_options |= re.M
            elif char == "s":
                self.re_options |= re.S
            elif char == "x":
                self.re_optons |= re.X
            else:
                raise ValueError, "Unknown modifier %r" % char
            processed.append(char)
        self.search_re = re.compile(self.search, self.re_options)
        self.search_match = self.search_re.match

        
    def __call__(self, s):
        if self.replace:
            if self.global_mode:
                count = 0
            else:
                count = 1
            return re.sub(self.search_re, self.replace, s, count)
        else:
            found = self.search_match(s)
            if found:
                return found.groups()



class Environ(dict):


    def __init__(self, filename, selection=None):
        dict.__init__(self)
        self.filename = os.path.abspath(filename)
        self.path, self.name = os.path.split(self.filename)
        self.selection = selection
        self.populate()


    def populate(self):
        pass



class GEditEnviron(Environ):


    def populate(self):
        # http://live.gnome.org/Gedit/Plugins/Snippets
        v = dict(
            GEDIT_SELECTED_TEXT=self.selection,
            GEDIT_FILENAME=self.filename,
            GEDIT_BASENAME=self.name,
            )
        self.update(v)





class TextmateEnviron(Environ):


    def populate(self):
        filename = os.path.abspath(filename)
        v = dict(
            TM_FILENAME=self.name,
            TM_FILEPATH=self.filename, 
            TM_DIRECTORY=self.path,
    #         TM_CURRENT_WORD 	
    #         TM_CURRENT_LINE 	
    #         TM_LINE_NUMBER 	
    #         TM_LINE_INDEX 	
    #         TM_COLUMN_NUMBER 	
    #         TM_TAB_SIZE 	
    #         TM_SOFT_TABS 	
    #         TM_SCOPE 	
    #         TM_MODE 	
    #         TM_CARET_XPOS 	
    #         TM_CARET_YPOS 	
    #         TM_PROJECT_DIRECTORY 	
    #         TM_SELECTED_FILE 	
    #         TM_SELECTED_FILES 	
    #         TM_BUNDLE_PATH 	
    #         TM_BUNDLE_SUPPORT
    #         TM_SUPPORT_PATH  
            )
        if self.selection:
            v.update(TM_SELECTED_TEXT=self.selection) 
        self.update(v)



class TabStop(object):


    def __init__(self, number):
        self.number = number


    def __repr__(self):
        return "<%s object at 0x%x %r>" % (
            self.__class__.__name__, id(self), self.__dict__)



class SimpleTabStop(TabStop):
    pass


class ExtendedTabStop(TabStop):


    def __init__(self, number, value=None, transform=None):
        TabStop.__init__(self, number)
        self.value = value # initial
        self.transform = transform


    def __call__(self, value):
        if self.transform:
            pre = PerlRegEx(self.transform)
            return pre(value)
        else:
            return value

    
    def __str__(self):
        value = self.value
        if self.transform:
            pass # XXX
        return value



class SnippetParser(object):
    """
    Simple recursive decent LL(1) parser
    """


    def __init__(self, s):
        self.parts = []
        self.s = s
        self.pos = -1
        self.length = len(self.s)
        self.parse()


    def next_char(self):
        self.pos += 1
        if self.pos < self.length:
            self.char = self.s[self.pos]
        else:
            self.char = None
        return self.char


    def emit(self, item):
        if isinstance(item, basestring) and \
                len(self.parts) and \
                isinstance(self.parts[-1], basestring):
            self.parts[-1] += item
            return
        self.parts.append(item)


    def parse_number(self):
        num = int(self.char)
        self.next_char()
        while self.char:
            if not self.char in digits:
                break
            num = 10 * num + int(self.char)
            self.next_char()
        return num

    
    def _parse_escaped(self, escape_chars=None):
        result = ""
        while self.char:
            if not self.char == "\\":
                break
            self.next_char()
            if self.char in escape_chars or not escape_chars:
                result += self.char
                self.next_char()
                continue
            else:
                result += "\\"
                continue
        return result


    def __iter__(self):
        return iter(self.parts)


    def __len__(self):
        return len(self.parts)



class TextmateSnippetParser(SnippetParser):
    

    def parse_simple_tabstop(self):
        number = self.parse_number()
        self.parts.append(SimpleTabStop(number))


    def parse_tabstop(self):
        self.next_char()
        if self.char in digits:
            number = self.parse_number()
        else:
            raise ValueError(
                "Number expected after '{' at position %s" % self.pos)
        value = transform = code = ""
        if self.char ==  ":":
            self.next_char()
            while self.char:
                if self.char == "}":
                    self.next_char()
                    break
                elif self.char == "\\":
                    value += self._parse_escaped("}")
                    continue
                value += self.char
                self.next_char()
        if self.char == "/":
            self.next_char()
            while self.char:
                if self.char == "}":
                    self.next_char()
                    break
                elif self.char == "\\":
                    transform += self._parse_escaped("}")
                    continue
                transform += self.char
                self.next_char()
        elif self.char == "`":
            self.next_char()
            while self.char:
                if self.char == "}":
                    self.next_char()
                    break
                elif self.char == "\\":
                    code += self._parse_escaped("`")
                    continue
                code += self.char
                self.next_char()
        ts = ExtendedTabStop(number, value, transform)
        return ts


    def parse(self):
        self.next_char()
        while self.char:
            if self.char == "$":
                self.next_char()
                if self.char in digits:
                    ts = self.parse_simple_tabstop()
                    self.emit(ts)
                elif self.char == "{":
                    ts = self.parse_tabstop()
                    self.emit(ts)
                else:
                    self.emit("$")
            elif self.char == "\\":
                self.emit(self._parse_escaped("{"))
            else:
                self.emit(self.char)
                self.next_char()




class SnippetField(object):
    
    def __init__(self, pos, length, tabstop):
        self.pos = pos
        self.length = length
        self.tabstop = tabstop


    def __repr__(self):
        return "<%s object at 0x%x %r>" % (
            self.__class__.__name__, id(self), self.__dict__)



class SnippetTemplate(object):

    """
    >>> example = "if (${1:condition}) { $2 }"
    >>> t = SnippetTemplate(example)
    >>> t.template
    'if (condition) {  }'
    """

    def __init__(self, s, Parser=TextmateSnippetParser):
        self.parser = Parser(s)
        self.reset()


    def reset(self):
        self.values = {}
        for part in self.parser:
            if isinstance(part, TabStop):
                self.values.setdefault(part.number, []).append(part)
        for number in self.values.keys():
            value = ""
            for ts in self.values[number]:
                if isinstance(ts, ExtendedTabStop):
                    if ts.value:
                        value = ts.value
                        break
            self.values[number] = value
        self.render()
        self.field_count = len(self.values)
        self.tab_count = len(self.parser)
        self.tab_index = 1


    def render(self):
        fields = {}
        template = ""
        for part in self.parser:
            pos = len(template)
            if isinstance(part, basestring):
                template += part
            elif isinstance(part, TabStop):
                if isinstance(part, ExtendedTabStop):
                    value = part(self.values[part.number])
                else:
                    value = self.values[part.number]
                f = SnippetField(pos, len(value), part)
                fields.setdefault(part.number, []).append(f)
                template += value
        self.length = len(template)
        if not self.values.get(0):
            ts = SimpleTabStop(0)
            f = SnippetField(len(template), 0, ts)
            fields.setdefault(0, []).append(f)
        self.fields = fields
        self.template = template


    def __str__(self):
        return self.template


    def set(self, tab_number, value):
        """
        >>> example = "if (${1:condition}) { $2 }"
        >>> t = SnippetTemplate(example)
        >>> t.set(1, "FOOBAR")
        >>> t.template
        'if (FOOBAR) {  }'
        """
        self.values[tab_number] = value
        self.render()


    def insert_chars(self, tab_number, pos, chars):
        """
        >>> example = "if (${1:condition}) { $2 }"
        >>> t = SnippetTemplate(example)
        >>> t.set(1, "FOO")
        >>> t.insert_chars(1, 3, "BAZ")
        >>> t.template
        'if (FOOBAZ) {  }'
        """
        value = self.values[tab_number]
        value = value[:pos] +  chars + value[pos:]
        self.values[tab_number] = value
        self.render()


    def remove_chars(self, tab_number, pos, count=1):
        """
        >>> example = "if (${1:condition}) { $2 }"
        >>> t = SnippetTemplate(example)
        >>> t.set(1, "FOOBAR")
        >>> t.remove_chars(1, 1, 2)
        >>> t.template
        'if (FBAR) {  }'
        """
        value = self.values[tab_number]
        value = value[:pos] + value[pos+count:]
        self.values[tab_number] = value
        self.render()


    def iter_fields(self):
        return iter(self.fields.get(self.tab_index, []))


    def next_tab(self):
        self.tab_index += 1
        if self.tab_index > len(self.values):
            self.tab_index = 1
        return self.tab_index


    def previous_tab(self):
        self.tab_index -= 1
        if self.tab_index < 1:
            self.tab_index = len(self.values)
        return self.tab_index
    

    def field_pos(self, cursor_pos):
        found = None
        for field in self.fields.get(self.tab_index, []):
            if cursor_pos >= field.pos and cursor_pos <= field.pos + field.length:
                found = field
                break
        if not found:
            #raise ValueError, "Field not found. This should not happen!"
            return -1
        return cursor_pos - field.pos


    def field_value_length(self):
        return len(self.values.get(self.tab_index, ""))


    def find_tab(self, cursor_pos, assign=True):
        length = self.field_value_length()
        distances = []
        for tab_index in range(1, self.tab_count):
            for field in self.fields.get(tab_index, []):
                if cursor_pos  >= field.pos and cursor_pos <= field.pos + length:
                    if tab_index != self.tab_index:
                        # inside other tabstop
                        return tab_index
                    else:
                        # inside old tabstop
                        return tab_index
                else:
                    # outside tabstop
                    if tab_index != self.tab_index:
                        if not getattr(field, "transform", ""):
                            distances.append((abs(cursor_pos - field.pos), tab_index))
        if assign and distances:
            distances.sort(cmp=lambda a, b: cmp(a[0], b[0]))
            return distances[0][1]
        return -1




if __name__ == "__main__":
    import doctest
    doctest.testmod()