forked from facelessuser/RegReplace
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrr_extended.py
More file actions
294 lines (251 loc) · 8.55 KB
/
rr_extended.py
File metadata and controls
294 lines (251 loc) · 8.55 KB
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
import sre_parse
import traceback
CAP_TOKEN = set("lLcCE")
DEF_BACK_REF = set("abfnrtvAbBdDsSwWZuxg")
class ReplaceTemplate(object):
def __init__(self, pattern, template):
self.__original = template
self.__back_ref = set()
self.__add_back_references(CAP_TOKEN)
self.__template = self.__escape_template(template)
self.groups, self.literals = sre_parse.parse_template(self.__template, pattern)
def get_base_template(self):
"""
Return the unmodified template before expansion.
"""
return self.__original
def __escape_template(self, template):
"""
Because the new backreferences are recognized by python
we need to escape them so they come out okay.
"""
new_template = []
slash_count = 0
for c in template:
if c == "\\":
slash_count += 1
elif c in self.__back_ref:
if slash_count != 0 and (slash_count % 2) == 0:
new_template.append("\\")
slash_count = 0
else:
slash_count = 0
new_template.append(c)
return "".join(new_template)
def __add_back_references(self, args):
"""
Add new backreferences, but not if they
interfere with existing ones.
"""
for arg in args:
if isinstance(arg, str) and len(arg) == 1:
if arg not in DEF_BACK_REF and arg not in self.__back_ref:
self.__back_ref.add(arg)
def get_group_index(self, index):
"""
Find and return the appropriate group index
"""
g_index = None
for group in self.groups:
if group[0] == index:
g_index = group[1]
break
return g_index
class Tokens(object):
def __init__(self, string):
self.string = string
self.max_index = len(string) - 1
self.index = 0
self.current = None
def __iter__(self):
return self
def __next__(self):
"""
Iterate through characters of the string.
Count \l, \L, \c, \C and \\ as a single char.
"""
if self.index > self.max_index:
raise StopIteration
char = self.string[self.index]
if char == "\\":
try:
c = self.string[self.index + 1]
if c in CAP_TOKEN:
char += c
elif c == "\\":
try:
ref = self.string[self.index + 2]
if ref in CAP_TOKEN:
self.index += 1
else:
char += c
except:
char += c
pass
except:
pass
self.index += len(char)
self.current = char
return self.current
class BackReferencs(object):
def __init__(self, match, template):
self.template = template
self.upper = False
self.lower = False
self.span = False
self._expand_string(match)
def next_group_boundary(self, index):
"""
Return the next match group boundaries
in relation to the index. Return 'None'
if there are no more boundaries.
"""
bound = None
for b in self.group_boundaries:
if index < b[1]:
bound = b
break
return bound
def ignore_index(self, boundary, index):
"""
If the index falls within the current group boundary,
return that it should be ignored.
"""
return boundary is not None and index >= boundary[0] and index < boundary[1]
def out_of_boundary(self, boundary, index):
"""
Return if the index has exceeded the right boundary.
"""
return boundary is not None and index >= boundary[1]
def span_upper(self, i):
"""
Uppercase the next range of characters until end marker is found.
Ignore \E if found in a group bondary.
"""
try:
boundary = self.next_group_boundary(i.index)
index = i.index
char = next(i)
while char != "\\E" or self.ignore_index(boundary, index):
self.result.append(char.upper())
char = next(i)
index = i.index
if self.out_of_boundary(boundary, index):
boundary = self.next_group_boundary(i.index)
except StopIteration:
pass
def span_lower(self, i):
"""
Lowercase the next range of characters until end marker is found.
Ignore \E if found in a group bondary.
"""
try:
boundary = self.next_group_boundary(i.index)
index = i.index
char = next(i)
while char != "\\E" or self.ignore_index(boundary, index):
self.result.append(char.lower())
char = next(i)
index = i.index
if self.out_of_boundary(boundary, index):
boundary = self.next_group_boundary(i.index)
except StopIteration:
pass
def single_lower(self, i):
"""
Lowercase the next character.
If none found, allow spanning to the next group.
"""
try:
t = next(i)
if len(t) > 1:
# Excaped char; just append.
self.result.append(t)
else:
self.result.append(t.lower())
except StopIteration:
pass
def single_upper(self, i):
"""
Uppercase the next character.
If none found, allow spanning to the next group.
"""
try:
t = next(i)
if len(t) > 1:
# Excaped char; just append.
self.result.append(t)
else:
self.result.append(t.upper())
except StopIteration:
pass
def _expand_string(self, match):
"""
Using the template, expand the string.
Keep track of the match group bondaries for later.
"""
self.sep = match.string[:0]
self.text = []
self.result = []
self.group_boundaries = []
# Expand string
char_index = 0
for x in range(0, len(self.template.literals)):
index = x
l = self.template.literals[x]
if l is None:
g_index = self.template.get_group_index(index)
l = match.group(g_index)
start = char_index
char_index += len(l)
self.group_boundaries.append((start, char_index))
self.text.append(l)
else:
start = char_index
char_index += len(l)
self.text.append(l)
def expand_titles(self):
"""
Walk the expanded template string and process
the new added backreferences and apply the associated
action.
"""
# Handle backreferences
i = Tokens(self.sep.join(self.text))
for t in i:
if t is None:
break
# Backreference has been found
# This is for the neutral state
# (currently applying no title cases)
if len(t) > 1:
c = t[1]
if c == "\\":
self.result.append(t)
elif c == "E":
self.result.append(t)
elif c == "l":
self.single_lower(i)
elif c == "L":
self.span_lower(i)
elif c == "c":
self.single_upper(i)
elif c == "C":
self.span_upper(i)
else:
self.result.append(t)
return self.sep.join(self.result)
def replace(m, template):
"""
Replace event. Using the template, scan for (\c | \C.*?\E | \l | \L.*?\E).
(c|C) are capital/upper case. (l|L) is lower case.
\c and \l are applied to the next character. While \C and \L are applied to
all characters until either the end of the string is found, or the end marker \E
is found. Actual group content is not scanned for markers.
"""
assert isinstance(template, ReplaceTemplate), "Not a valid template!"
try:
return BackReferencs(m, template).expand_titles()
except:
print(str(traceback.format_exc()))
return m.expand(template.get_base_template())