Sublime Forum

View.add_regions to multiple regions?

#1

Can view.add_regions be used to write multiple regions to the view? I’m doing some tests with default/mark.py and I’m seeing any subsequent call to add_regions erases the previous regions. I’ve seen plugins have multiple regions so I know it’s possible but I don’t have any examples.

Thanks.

0 Likes

#2

As the API documentation mentions, view.add_regions() associates a set of regions with a given textual key, and if that key is already used the old set is overwritten with the new one.

As such, if you want to add more regions to the set using the same key, you need to use view.get_regions() to get the list of regions associated with the key and include that with your new regions when you add the new set.

Crudely, a version of the default set_mark command that does that would be something like the following:

import sublime
import sublime_plugin


class SetMultiMark(sublime_plugin.TextCommand):
    def run(self, edit):
        current_regions = self.view.get_regions("mark")
        new_marks = [s for s in self.view.sel()]

        mark = current_regions + new_marks
        self.view.add_regions("mark", mark, "mark", "dot", sublime.HIDDEN | sublime.PERSISTENT)

Here we ask the view for any regions already associated with the key mark, then create a list of extra regions the same way as the default does, and set the combination of both of them back as the list of views using the same key.

Now the existing set of regions is replaced with the new set, but since the new set also contains what used to be there, the net effect is to just add in the new regions.

Of course you may want to make sure that you don’t add a duplicate region (or test if Sublime silently ignores such a situation).

0 Likes

#3

Ok, I see now. Thanks again.

0 Likes