Keep in mind that in order to get text into the buffer, you need to use view.replace()
(since you’re trying to replace some piece of text with another). That call requires you to provide the region that’s going to be replaced and the text as well.
If you want to use re.sub()
to do all the replacements at once, then you need to:
- Grab the entire contents of the buffer all at once as a string
- Run your
re.sub()
to perform the replacements
- Put the entire contents of the buffer (with replacements) back into the buffer.
That’s certainly possible; roughly something like this:
# 1
region = sublime.Region(0, self.view.size())
content = self.view.substr(region)
# 2
new_content = re.sub(somethingorother)
# 3
self.view.replace(edit, region, new_content)
Extracting the entire contents of a file is wasteful unless you know that it’s primarily text that you need to perform replacements on though. For example, if your file was 5MB and the word North
appears once, this is akin to driving in a nail by ramming it with a speeding pickup truck.
On the other hand, you can also do something like this using find_all
; it has the power to extract the matched text and give it to you (leaving the rest alone) and the ability to format the strings on the way through.
A modified example of the plugin @ThomSmith posted above might be:
import sublime
import sublime_plugin
class TestCommand(sublime_plugin.TextCommand):
def run(self, edit):
result = []
regions = self.view.find_all(r'^((?:This|That) .*) North', 0,
r"\1 South", result)
for idx,region in enumerate(reversed(regions)):
self.view.replace(edit, region, result[-idx - 1])
This tells the find_all
call to put the matched text into the result
array along with telling you the region that it was found in, and also modifies the text as it’s extracting it so that it’s ready for replacement later.
Input:
This is North Carolina
Where is North Dakota
That was North Korea
Output:
This is South Carolina
Where is North Dakota
That was South Korea
Not all of the instances of the word North
are replaced, only those on lines that start with This
or That
.