~divmod-dev/divmod.org/compressed-resources-2747

« back to all changes in this revision

Viewing changes to Imaginary/pottery/unc.py

  • Committer: exarkun
  • Date: 2006-02-26 02:37:39 UTC
  • Revision ID: svn-v4:866e43f7-fbfc-0310-8f2a-ec88d1da2979:trunk:4991
Merge move-pottery-to-trunk

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
def getInt(i):
 
2
    d = ''
 
3
    for c in i:
 
4
        if not c.isdigit():
 
5
            return d, c
 
6
        d = d+c
 
7
 
 
8
ss = '\x1b[31;42;4mhello\x1b[0;31;42m \x1b[0;31mworld\x1b[0m'
 
9
BEGIN, END, ADD, NUMBER, CHAR, ATTS, STR = range(7)
 
10
 
 
11
def tokenize(s):
 
12
    s = iter(s)
 
13
    for c in s:
 
14
        if c != '\x1b':
 
15
            yield CHAR, c
 
16
            continue
 
17
        c = s.next()
 
18
        if c != '[':
 
19
            yield CHAR, '\x1b'
 
20
            yield CHAR, c
 
21
            continue
 
22
        yield BEGIN, c
 
23
        while 1:
 
24
            d, c = getInt(s)
 
25
            yield NUMBER, d
 
26
            if c == 'm':
 
27
                yield END, c
 
28
                break
 
29
 
 
30
def parser(tokens):
 
31
    tokens = iter(tokens)
 
32
    sofar = ''
 
33
    for tp, token in tokens:
 
34
        if tp == CHAR:
 
35
            sofar += token
 
36
        if tp == BEGIN:
 
37
            if sofar:
 
38
                yield STR, sofar
 
39
                sofar = ''
 
40
            atts = []
 
41
            for tp, token in tokens:
 
42
                if tp == END:
 
43
                    break
 
44
                atts.append(int(token))
 
45
            yield ATTS, atts
 
46
    if sofar:
 
47
        yield STR, sofar
 
48
        sofar = ''
 
49
 
 
50
def prettylist(l):
 
51
    res = []
 
52
    for tp, data in l:
 
53
        if tp == ATTS:
 
54
            res.append('COLOR('+', '.join(map(str, data))+')\n')
 
55
        else:
 
56
            res.append(repr(data)+'\n')
 
57
    return ''.join(res)
 
58
 
 
59
def prettystring(s):
 
60
    return prettylist((parser(tokenize(s))))
 
61
 
 
62
def _test():
 
63
    print prettystring(ss)
 
64
 
 
65
if __name__ == '__main__':
 
66
    _test()