SublimeText / sublime_lib

Utility library for frequently used functionality in Sublime Text and convenience functions or classes
https://sublimetext.github.io/sublime_lib
MIT License
52 stars 4 forks source link

A "maintainer" or "owner" class for view.add_regions #141

Open rwols opened 3 years ago

rwols commented 3 years ago

Decorated regions in a view can be regarded as a resource. Resources must be cleaned up when they are no longer needed.

It is too easy to forget this in a large plugin (or even a small plugin). For instance, one tends to forget to clean up regions when a plugin gets disabled.

It'd be nice to have a class that maintains this resource. Something like this (just an idea):

class AddRegionsMaintainer:

    def __init__(self, view: sublime.View, key: str, *args: Any, **kwargs: Any) -> None:
        self._view = view
        self._key = key
        self(*args, **kwargs)

    def __call__(self, *args: Any, **kwargs: Any) -> None:
        self._view.add_regions(self._key, *args, **kwargs)

    def __del__(self) -> None:
        self._view.erase_regions(self._key)
Thom1729 commented 3 years ago

@rwols The linked PR uses the following interface:

class RegionManager:
    def __init__(
        self,
        view: sublime.View,
        key: Optional[str] = None,
        *,
        scope: Optional[str] = None,
        icon: Optional[str] = None,
        flags: Optional[RegionOption] = None
    ): ...

    def __del__(self) -> None: ...

    def set(
        self,
        regions: Collection[sublime.Region],
        *,
        scope: Optional[str] = None,
        icon: Optional[str] = None,
        flags: Optional[RegionOption] = None
    ) -> None: ...

    def get(self) -> List[sublime.Region]: ...

    def erase(self) -> None: ...

Is it actually useful to override the scope/icon/flags in set()?

rwols commented 3 years ago

I would say yes. If for instance the icon is determined by a package setting, you can just load that setting when updating the regions.