Sublime Forum

Regex Find Replace Plugin Selected Text [SOLVED]


Hoping this is the right place to ask this. I am new to both ST and to python, but am trying to write a small plugin to search and replace a regex. A sample plugin from this (great) youtube series []

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")
            sublime.status_message("Replaced %d matches" % len(regions))

and a macro

		"search": "\\s+",
		"replace": "\",\""

put me in the right direction.

But it only works on the entire view/file. Is there a way to limit the action to just the selected text? I’m really only interested in a single block of selected text. The find_all method doesn’t work with .sel()

I’ve tried limiting the view with something like:

sel = self.view.sel()[0]
selected = self.view.substr(sel)

but that breaks the code no matter where I seem to put it.

I’ve also tried finding all the regions in the view, then somehow restricting to just the selection as suggested here ( with someething like:

for idx, searched in enumerate(regions):
    if view.sel().contains(regions):

But also not working. Any help would be most gratefully appreciated.



How about if you don’t want to ST’s find and replace functionality?

1 Like


Thanks for that. Perfect. Solved.