Skip to content

Instantly share code, notes, and snippets.

@sublimator
Created September 11, 2011 11:50
Show Gist options
  • Save sublimator/1209488 to your computer and use it in GitHub Desktop.
Save sublimator/1209488 to your computer and use it in GitHub Desktop.
Scope Commands
#coding: utf8
#################################### IMPORTS ###################################
# Sublime Libs
import sublime
import sublime_plugin
import bisect
################################### BINDINGS ###################################
[
{
"command": "select_scope",
"keys": [
"ctrl+alt+shift+s",
"ctrl+alt+shift+d"
]
},
{
"command": "show_scope_on_move",
"keys": [
"ctrl+alt+shift+s",
"ctrl+alt+shift+c"
]
}
]
#################################### HELPERS ###################################
def cursor(v):
return v.sel()[0].begin()
def set_sels(view, sels):
view.sel().clear()
for sel in sels: view.sel().add(sel)
################################### COMMANDS ###################################
class SelectScope(sublime_plugin.TextCommand):
last = ''
def run(self, edit):
view = self.view
window = view.window()
sels = start_sels = PyRegionSetLite(view.sel())
if not view.has_non_empty_selection_region():
view.sel().add(sublime.Region(0, view.size()))
sels = PyRegionSetLite(view.sel())
def on_cancel():
set_sels(view, start_sels)
def on_done(s):
self.last = s
def on_change(s):
if not s: return
runs = [s for s in view.find_by_selector(s) if sels.contains(s)]
try:
edit = view.begin_edit()
if runs:
view.sel().clear()
for sel in runs: view.sel().add(sel)
view.show(view.sel())
else:
set_sels(view, [])
finally:
view.end_edit(edit)
on_change(self.last)
window.show_input_panel (
'Enter Scope', self.last, on_done, on_change, on_cancel )
class ShowScopeOnMove(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
settings = view.settings()
settings.set('scopemode', not settings.get('scopemode'))
if not settings.get('scopemode'):
view.erase_status('scope')
class ShowScopeOnMoveListener(sublime_plugin.EventListener):
def on_selection_modified(self, view):
if view.sel() and view.settings().get('scopemode'):
scope = view.scope_name(cursor(view)).strip()
sublime.set_clipboard(scope)
view.set_status('scope', 'Scope %s' % scope)
class PyRegionSetLite(list):
def _bisect(self, r, bisector):
ix = min(bisector(self, r), len(self) -1)
reg = self[ix]
if r < reg and not (reg.contains(r) or reg.intersects(r)): ix -= 1
return max(0, ix)
def bisect(self, r):
return self._bisect(r, bisect.bisect)
def contains(self, r):
return self and self.closest_selection(r).contains(r)
def closest_selection(self, r):
return self[self.bisect(r)]
################################################################################
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment