Home Download Buy Blog Forum Support

Expand selection backward

Expand selection backward

Postby stiang on Sat Feb 12, 2011 1:45 pm

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:
Code: Select all
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
Code: Select all
    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?
stiang
 
Posts: 39
Joined: Sat Jan 29, 2011 12:34 pm

Re: Expand selection backward

Postby stiang on Sat Feb 12, 2011 6:27 pm

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.

Code: Select all
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"})
stiang
 
Posts: 39
Joined: Sat Jan 29, 2011 12:34 pm


Return to Plugin Development

Who is online

Users browsing this forum: Google [Bot] and 11 guests