Skip to content

Instantly share code, notes, and snippets.

@webstrand
Created April 16, 2021 15:12
Show Gist options
  • Select an option

  • Save webstrand/787a750a2c76fc2b0f0645142217c3f3 to your computer and use it in GitHub Desktop.

Select an option

Save webstrand/787a750a2c76fc2b0f0645142217c3f3 to your computer and use it in GitHub Desktop.
Sublime Text 3 Plugin for iterating through selected regions
import sublime
import sublime_plugin
import weakref
from weakref import WeakValueDictionary
view_selection_iterators = WeakValueDictionary()
class ViewSelectionIterator(sublime_plugin.ViewEventListener):
current_item = None
def __init__(self, view):
super().__init__(view)
global view_selection_iterators
view_selection_iterators[self.view.id()] = self
@staticmethod
def find_by_view(view):
global view_selection_iterators
return view_selection_iterators.get(view.id())
def on_query_context(self, key, operator, operand, match_all):
if key == "has_selection_iterator":
return self.has_regions()
return False
def sel(self):
return self.view.get_regions("selection_iterator")
def has_regions(self):
return self.current_item is not None
def start(self, sel):
self.view.add_regions("selection_iterator", sel, "string", "", sublime.DRAW_EMPTY_AS_OVERWRITE)
self.current_item = 0
return sel[0]
def next(self):
n = self.current_item + 1
region = self.sel()[n]
self.current_item = n
return region
def clear(self):
self.view.erase_regions("selection_iterator")
self.current_item = None
class SelIterateCommand(sublime_plugin.TextCommand):
def run(self, edit):
iterator = ViewSelectionIterator.find_by_view(self.view)
sel = self.view.sel()
if iterator.has_regions():
sel.clear()
try:
region = iterator.next()
sel.add(region)
self.view.show(region)
except IndexError:
sel.add_all(iterator.sel())
iterator.clear()
else:
try:
region = iterator.start(sel)
sel.clear()
sel.add(region)
self.view.show(region)
except IndexError:
pass
class SelIterateCancelCommand(sublime_plugin.TextCommand):
def run(self, edit):
iterator = ViewSelectionIterator.find_by_view(self.view)
if iterator.has_regions():
sel = self.view.sel()
sel.clear()
sel.add_all(iterator.sel())
iterator.clear()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment