Sublime Forum

Expand selection backward

#1

I have added the underscore character to the list of word delimiters and implemented the following code to be able to press ctrl+w several times to expand to the next word part:

class IntelligentExpandSelection(sublime_plugin.TextCommand):
  def run(self, edit, args=None):
    after = self.view.substr(self.view.sel()[0].end())
    if after == "_":
      self.view.run_command("move", {"by": "characters", "forward": True, "extend": True})
    self.view.run_command("expand_selection", {"to": "word"})

This works well for expanding forward. However, when I include code to expand backward too, by setting “forward” to False like so

    before = self.view.substr(self.view.sel()[0].begin() - 1)
    if before == "_":
      self.view.run_command("move", {"by": "characters", "forward": False, "extend": True})

the selection shrinks by one character at the rightmost part of the selection, not by extending to the left, as I had hoped. How can I extend the selection by one character to the left?

0 Likes

#2

Never mind, I figured it out. It was as simple as adding a region to the selection. Here is the finished command, if anyone is interested.

class IntelligentExpandSelection(sublime_plugin.TextCommand):
  def run(self, edit, args=None):
    start_pos = self.view.sel()[0].begin()
    end_pos = self.view.sel()[0].end()
    before = self.view.substr(start_pos - 1)
    after = self.view.substr(end_pos)
    if after == "_":
      self.view.sel().add(sublime.Region(end_pos, end_pos + 1))
    if before == "_":
      self.view.sel().add(sublime.Region(start_pos - 1, start_pos))
    self.view.run_command("expand_selection", {"to": "word"})
0 Likes