-
Notifications
You must be signed in to change notification settings - Fork 23
/
expand_to_semantic_unit.py
93 lines (76 loc) · 2.57 KB
/
expand_to_semantic_unit.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
85
86
87
88
89
90
91
92
93
import re
try:
# Block it from trying to import something which should not be on the python sys.path
# https://github.com/hktonylee/SublimeNumberKing/issues/4
import expand_region_handler
import utils
except:
from . import utils
# This function definitely sucks and needs a serious rework. Finding semantic
# units is not that easy. Maybe a parser is needed?
def expand_to_semantic_unit(string, startIndex, endIndex):
symbols = "([{)]}"
breakSymbols = ",;=&|\n"
lookBackBreakSymbols = breakSymbols + "([{"
lookForwardBreakSymbols = breakSymbols + ")]}"
symbolsRe = re.compile(r'(['+re.escape(symbols)+re.escape(breakSymbols)+'])')
counterparts = {
"(":")",
"{":"}",
"[":"]",
")":"(",
"}":"{",
"]":"["
}
symbolStack = []
searchIndex = startIndex - 1;
while True:
if(searchIndex < 0):
newStartIndex = searchIndex + 1
break
char = string[searchIndex:searchIndex+1]
result = symbolsRe.match(char)
if result:
symbol = result.group()
if(symbol in lookBackBreakSymbols and len(symbolStack) == 0):
newStartIndex = searchIndex + 1
break
if symbol in symbols:
if len(symbolStack) > 0 and symbolStack[len(symbolStack) - 1] == counterparts[symbol]:
symbolStack.pop()
else:
symbolStack.append(symbol)
# print("ExpandRegion, expand_to_semantic_unit.py, " + char + " " + symbolStack)
searchIndex -= 1
searchIndex = endIndex;
while True:
char = string[searchIndex:searchIndex+1]
result = symbolsRe.match(char)
if result:
symbol = result.group()
if len(symbolStack) == 0 and symbol in lookForwardBreakSymbols:
newEndIndex = searchIndex;
break
if symbol in symbols:
if len(symbolStack) > 0 and symbolStack[len(symbolStack) - 1] == counterparts[symbol]:
symbolStack.pop()
else:
symbolStack.append(symbol)
if searchIndex >= len(string) - 1:
return None
# print("ExpandRegion, latex.py, " + char + " " + symbolStack + " " + searchIndex)
searchIndex += 1
s = string[newStartIndex:newEndIndex]
# print( utils )
trimResult = utils.trim(s)
if trimResult:
newStartIndex = newStartIndex + trimResult["start"];
newEndIndex = newEndIndex - (len(s) - trimResult["end"]);
try:
if newStartIndex == startIndex and newEndIndex == endIndex:
return None
if newStartIndex > startIndex or newEndIndex < endIndex:
return None
return utils.create_return_obj(newStartIndex, newEndIndex, string, "semantic_unit")
except NameError:
return None