Sublime Forum

Keeping Selection After Edits

#1

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.

# 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]# 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)[/code]

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:

old_selection = view.sel() Do edits... view.sel(old_selection)

0 Likes

#2

[quote=“sublimator”]Rereading what you said it looks like a good place for a context manager actually eh?

with saved_sels(view): do_stuff()[/quote]

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:

with FirmSelection(view): Do edit...

0 Likes

#3

I’m wondering the same right now. Can we please create new instances of RegionSet?

0 Likes