Sublime Forum

Retrieve index of Region in view.sel()

#1

I am wondering about the most idiomatic way of checking the index of a region within view.sel().

Firstly, the following (idiomatic or not) doesn’t work, and I would like to ask why:

def index_within(thing, container):
    for i, t in enumerate(container):
        if t is thing:
            return i
    return -1

for r in view.sel():
    print("the index of region r with view.sel() is:", index_within(r, view.sel())

Apart from that, how else would one check the index of a region in view.sel(), except for replacing is by == in the above?

Thanks!

0 Likes

#2

It appears that Selection.__getitem__ creates a new Region object every time:

view.sel()[0] is view.sel()[0] // False

As you hint at above, using == instead of is will solve this. Myself, I’d do this:

def index_within(thing, container):
   return next((index for index, item in enumerate(container) if item == thing), -1)
1 Like