Sublime Forum

View.find reverse

#1

Hi,

I use this code in sublime-text-2 to apply find-next operation to all cursors:

class MoveToNextCommand(sublime_plugin.TextCommand):
	saved_pattern = ""
	def run(self, edit):
		# cb = sublime.get_clipboard()
		def done(pattern):
			self.saved_pattern = pattern
			# we take end of selection for start point in search
			cursor_points = [x.b for x in self.view.sel()]
			# resulting_selection = []
			e = self.view.begin_edit()
			self.view.sel().clear()
			for point in cursor_points:
				region = self.view.find(pattern, point, sublime.LITERAL | sublime.IGNORECASE)
				if region != None:
					# resulting_selection.append(region)
					self.view.sel().add(region)
			self.view.end_edit(e)
		sublime.active_window().show_input_panel("move cursors to next pattern: ", self.saved_pattern, done, None, None)

I would like to create similar command that will find in reverse instead forward from each cursor. How can i accomplish this?

There is no direction in self.view.find signature.

Thanks,
Alex

0 Likes

#2

A worse workaround can be using Python re on a reversed string but that sounds quite expensive…

Or just get all results first and reverse them.

0 Likes

#3

Hi @jfcherng, Thanks for the response! Didn’t quite understand those 2 solutions, can you give me more details? It is ok if solution is not optimal.

0 Likes

#4

the 2nd is something like

import sublime
import sublime_plugin


def view_find_all_between_points(view, pattern, begin_point, end_point, flags=0):
    regions = []
    seek = begin_point

    while seek < end_point:
        region = view.find(pattern, seek, flags)

        # if found nothing, region will be (-1, -1)
        if region.begin() == -1:
            break

        regions.append(region)
        seek = region.end()

    return regions


class ExampleCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        pattern = r"def "
        point = 999
        flags = sublime.LITERAL | sublime.IGNORECASE

        regions = view_find_all_between_points(self.view, pattern, 0, point, flags)

        print(list(reversed(regions)))

It’s worse because you find all occurrences, which may be not necessary, before you actually do your logic. And if your logic will change text content in the searched region, you most likely has to re-do finding again… or do some math calculations to keep found regions correct.

0 Likes