You don’t have to replace the entire buffer, but you do have to search it. I did a plugin, RegReplace, where you can specify custom searches you can string together, and like FichteFoll mentioned, I had to use re on the view’s buffer. I basically wrote a function that would search the buffer and return the regions and the extractions (modified text after replace); like the Sublime API does. Then I could just iterate backwards through my sublime regions, tracking the index so I could access the corresponding extractions, and replace backwards. I don’t know if you lose all of your selections when you replace the entire buffer…I didn’t want to lose my selections, so I opted for replacing the regions in reverse order.
[pre=#232628] def regex_findall(self, find, flags, replace, extractions, literal=False, sel=None):
regions = ]
offset = 0
if sel is not None:
offset = sel.begin()
bfr = self.view.substr(sublime.Region(offset, sel.end()))
else:
bfr = self.view.substr(sublime.Region(0, self.view.size()))
flags |= re.MULTILINE
if literal:
find = re.escape(find)
for m in re.compile(find, flags).finditer(bfr):
regions.append(sublime.Region(offset + m.start(0), offset + m.end(0)))
extractions.append(m.expand(replace))
return regions[/pre]
replace corresponds to extractions (I’m cutting out unrelated code here):
[pre=#232628] def greedy_replace(self, find, replace, regions, scope_filter):
# Initialize replace
…
count = len(regions) - 1
…
for region in reversed(regions):
…
replaced += 1
…
self.view.replace(self.edit, region, replacecount])
count -= 1
return replaced[/pre]
Anyways, just showing a way to approach it.