Skip to content

Instantly share code, notes, and snippets.

@OdatNurd
Created December 28, 2020 17:31
Show Gist options
  • Select an option

  • Save OdatNurd/a70b74e10d0688a915e1859cd4cd4f57 to your computer and use it in GitHub Desktop.

Select an option

Save OdatNurd/a70b74e10d0688a915e1859cd4cd4f57 to your computer and use it in GitHub Desktop.
Plugin 101 Lesson 20 examples
import sublime
import sublime_plugin
class DoFindReplaceCommand(sublime_plugin.TextCommand):
"""
Find all instances of the search text and replace it with the replacement
text provided. The arguments allow you to decide if the command should be a
regular expression (the default) or just plain text, and whether or not
case should be ignored or not (by default it is not).
The replacement string may contain the standard regex replacement text,
should the command be told to do a regex replace.
"""
def run(self, edit, search, replace, is_regex=True, ignore_case=False):
flags = 0
if not is_regex: flags |= sublime.LITERAL
if ignore_case: flags |= sublime.IGNORECASE
replacements = []
regions = self.view.find_all(search, flags, replace, replacements)
adjust = 0
for idx, searched in enumerate(regions):
replaced = sublime.Region(searched.a - adjust, searched.b - adjust)
adjust += (replaced.size() - len(replacements[idx]))
self.view.replace(edit, replaced, replacements[idx])
if not regions:
sublime.status_message("Search term was not found")
else:
sublime.status_message("Replaced %d matches" % len(regions))
import sublime
import sublime_plugin
class CaseChangeCommand(sublime_plugin.TextCommand):
"""
A more complete example of this can be found in Default/transform.py, which
contains the built in commands that do this.
"""
def run(self, edit):
# Iterate over all selections in this file (could be more than one)
for s in self.view.sel():
# Use the word under the cursor if this selection is empty.
if s.empty():
s = self.view.word(s)
# Gather the text, then transform it and put it back
txt = self.view.substr(s)
self.view.replace(edit, s, txt.upper())
class TerminateLineCommand(sublime_plugin.TextCommand):
def run(self, edit, character):
# Iterate over all selections in this file (could be more than one)
for s in self.view.sel():
# Get the region indicating the line the cursor is in
line = self.view.line(s.b)
# If the line doesn't end with the given character, insert it now
if self.view.substr(line.end() - 1) != character:
self.view.insert(edit, line.end(), character)
# Use the default macro to go to the next line
self.view.run_command("run_macro_file", {
"file": "res://Packages/Default/Add Line.sublime-macro"
});
@OdatNurd

Copy link
Copy Markdown
Author

These plugin examples are from Plugin 101 Lesson 20 on my YouTube Channel, covering some examples of plugin commands that modify the buffer as well as a sample command that can perform a find and replace operation in a macro,

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment