-
Notifications
You must be signed in to change notification settings - Fork 0
/
bracketmatch.py
84 lines (77 loc) · 1.79 KB
/
bracketmatch.py
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
# -*- coding: utf-8 -*-
import cgi, re
MISMATCH_DISTANCE=100
escape_table = {
"[": "[",
"]": "]",
"|": "|",
"{": "{",
"}": "}"
}
#print(str(ord('|')))
def getmismatches(text):
rs,ss,cs,ns,ae=[],[],[],[],[]
for i in range(len(text)):
ch=text[i]
if ch=='(': rs.append(i)
elif ch=='[': ss.append(i)
elif ch=='{': cs.append(i)
elif ch=='<': ns.append(i)
try:
if ch==')': rs.pop()
elif ch==']': ss.pop()
elif ch=='}': cs.pop()
elif ch=='>': ns.pop()
except IndexError:
ae.append(i)
mismatches=[]
mismatches.extend(rs)
mismatches.extend(ss)
mismatches.extend(cs)
mismatches.extend(ns)
mismatches.extend(ae)
mismatches.sort()
ret=""
while mismatches:
highlighted,started=False,False
i=mismatches[0]-MISMATCH_DISTANCE
if i<0: i=0
cur="<p>"
mismatches,ret,cur,i,highlighted,started=_getnextmismatch(text,mismatches,ret,cur,i,highlighted,started)
#
#if ret.startswith(['[[','{{']):
for repl in escape_table:
ret = ret.replace(repl, escape_table[repl])
#ret = cgi.escape( ret )
return ret or "None"
pre='<span style="color:red;font-weight:bold;">'
post="</span>"
def _getnextmismatch(text,mismatches,ret,cur,i,highlighted,started):
while i<len(text):
ch=text[i]
if ch=="\n":
if highlighted:
cur+=cgi.escape(ch)
break
else:
cur=""
elif len(mismatches)>1 and i==mismatches[1]:
mismatches.pop(0)
cur+=pre+"&#"+str(ord(ch))+";"+post
elif i==mismatches[0]:
cur+=pre+"&#"+str(ord(ch))+";"+post
highlighted=True
else:
if started:
cur+=cgi.escape(ch)
elif not ch.isalnum():
started=True
if i==mismatches[0]+MISMATCH_DISTANCE:
break
i+=1
cur=cur.replace(post+pre,"")
while cur[-1].isalnum():
cur=cur[:-1]
ret+=cur.strip()+""
mismatches.pop(0)
return mismatches,ret,cur,i,highlighted,started