Skip to content

Instantly share code, notes, and snippets.

@cb109
Last active October 15, 2018 06:45
Show Gist options
  • Select an option

  • Save cb109/983f0d6b6a9b254c629f780dc3256b33 to your computer and use it in GitHub Desktop.

Select an option

Save cb109/983f0d6b6a9b254c629f780dc3256b33 to your computer and use it in GitHub Desktop.
Allow two word selection behaviours at the same time in Sublime.
[
{
"button": "button1",
"modifiers": ["alt"],
"command": "select_underscored_word",
},
]
import re
import sublime
import sublime_plugin
class SelectUnderscoredWordCommand(sublime_plugin.TextCommand):
"""Select whole word udner cursor, even if containing underscores.
That is actually Sublime's default, but is e.g. overriden when
adding a '_' to the word_separators setting. Best illustrated with
an example:
Selecting word under cursor (the '|'):
'_my_variab|le_name'
'variab|le'
With this command it would be:
'_my_variab|le_name'
'_my_variab|le_name'
So this can be used to make use of both selection behaviours in
parallel. With the keyboard, you may use the 'select single word
without underscore' behaviour, while e.g. an Alt-mouseclick
(preferred to a doubleclick as that would overwrite things like
jump-to-next-search-result) could bind to this command to trigger
the 'select entire word including underscores' behaviour.
/Packages/User/Default (Linux).sublime-mousemap
[
{
"button": "button1",
"modifiers": ["alt"],
"command": "select_underscored_word",
},
]
"""
def run(self, edit):
view = self.view
cursors = view.sel()
if len(cursors) != 1:
return
region = cursors[0]
line = view.line(region)
region_begin, region_end = region.begin(), region.end()
if region_begin == region_end:
# Nothing selected, let's assume we selected the next char.
region_end = region_begin + 1
fixed_region = sublime.Region(region_begin, region_end)
start = fixed_region.begin() - line.begin()
end = start + fixed_region.end() - fixed_region.begin() - 1
line_text = view.substr(line)
before = line_text[:start]
after = line_text[end:]
pattern = r"[\w]"
select_next_n_chars = 0
for char in after:
if not re.match(pattern, char):
break
select_next_n_chars += 1
select_prev_n_chars = 0
for char in reversed(before):
if not re.match(pattern, char):
break
select_prev_n_chars += 1
new_region = sublime.Region(
fixed_region.begin() - select_prev_n_chars,
fixed_region.end() + select_next_n_chars - 1,
)
self.view.sel().clear()
self.view.sel().add(new_region)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment