Sublime Forum

Regex Find Replace Plugin Selected Text [SOLVED]

#1

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 [https://www.youtube.com/watch?v=be4jVjZsnJk&t=1115s]

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))

and a macro

[
{
	"command":"do_find_replace",
	"args":{
		"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 (https://stackoverflow.com/questions/38632861/sublime-text-plugin-how-to-find-all-regions-in-selection) with someething like:

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

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

0 Likes

#2

How about https://packagecontrol.io/packages/RegReplace if you don’t want to ST’s find and replace functionality?

1 Like

#3

Thanks for that. Perfect. Solved.

0 Likes