Sublime Forum

Find backwards

#1

Hello. I have the following Python code to find the previous occurrence of a word:

new_regions = self.view.find_all(prev_wd, sublime.LITERAL) new_region = None for r in reversed(new_regions): if r.begin() < prev_pt: new_region = r break if new_region:
where prev_pt is the begin-point of the word I’m looking for (prev_wd).

Well, it works, but I’m assuming there is a neater, more efficient, way of doing this?

An alternative, but messier approach, might be to keep subtracting some number (10) for a value x, using find() forward from this x-point. But perhaps a single call to find_all will always be more efficient than repeated calls to find? Andy.

0 Likes

#2

No worries :wink: :sunglasses:

new_regions = (r for r in reversed(self.view.find_all(prev_wd, sublime.LITERAL)) if r.begin() < prev_pt) try: new_region = new_regions.next() except StopIteration: new_region = None if new_region:

Added: A beautiful piece of code… if I say so myself :laughing:

0 Likes