Home Download Buy Blog Forum Support

Keeping Selection After Edits

Keeping Selection After Edits

Postby pyparadigm on Thu Sep 15, 2011 8:00 am

This is sort of a feature request, and also explaining a problem to see if there is a better way to do this, I am creating a plugin that runs JS Beautify on source code and noticed that after the edit, it erases your current selection and moves the cursor. So I set upon a way to preserve the selection and came up with a solution.

Code: Select all
# Clone all the regions in view.sel()
# and put them in a list called old_selection
old_selection = []
for region in view.sel():
   old_selection.append(region)

{{ DO EDIT, and now the cursor positions/selections changed :( }}

# Remove new positions then add all the old regions
# back and its the same as before the edit
view.sel().clear()
for region in old_selection:
   view.sel().add(region)


I noticed this logic could be much easier if there was a constructor for sublime.RegionSet() that if you pass it a RegionSet it will clone it

Code: Select all
# Wouldn't it be nice?
old_selection = sublime.RegionSet(view.sel())

{{ DO EDIT, and now the cursor positions/selections changed }}

view.sel().clear()
view.sel().add_all(old_selection)


Further you could allow sublime.RegionSet() to return an empty Region Set.

Also to make it easier optionally you can pass a Region Set to view.sel(RegionSet) to update selection, this makes it easier to discover how to change the selection and maybe instead of above you can make view.sel() return the clone by default. Then it would be as easy as:

Code: Select all
old_selection = view.sel()
Do edits...
view.sel(old_selection)
pyparadigm
 
Posts: 23
Joined: Thu Aug 04, 2011 8:15 am

Re: Keeping Selection After Edits

Postby pyparadigm on Thu Sep 15, 2011 11:21 am

sublimator wrote:Rereading what you said it looks like a good place for a context manager actually eh?

Code: Select all
with saved_sels(view):
    do_stuff()


Code: Select all
class FirmSelection():
   def __init__(self, view):
      self.view = view
   def __enter__(self):
      self.old_selection = []
      for region in self.view.sel():
         self.old_selection.append(region)
   def __exit__(self, type, value, traceback):
      self.view.sel().clear()
      for region in self.old_selection:
         self.view.sel().add(region)


Then you can just:
Code: Select all
with FirmSelection(view):
   Do edit...
pyparadigm
 
Posts: 23
Joined: Thu Aug 04, 2011 8:15 am

Re: Keeping Selection After Edits

Postby MSch on Wed Jan 25, 2012 1:21 pm

I'm wondering the same right now. Can we please create new instances of RegionSet?
MSch
 
Posts: 15
Joined: Fri Jan 13, 2012 11:46 pm


Return to Plugin Development

Who is online

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