Home Download Buy Blog Forum Support

Grouping edits outside of a TextCommand

Grouping edits outside of a TextCommand

Postby guillermooo on Thu Feb 03, 2011 10:12 pm

In Sublime Text 1 it wasn't possible to group edits outside of TextCommand objects, or rather, it was possible but either macros or undo wouldn't work correctly. Sometimes it seems cleaner to do operations on buffers in functions outside TextCommand objects.

Is this now possible in Sublime Text 2 with the Edit object?
guillermooo
 
Posts: 729
Joined: Thu Jul 23, 2009 9:06 am

Re: Grouping edits outside of a TextCommand

Postby jps on Thu Feb 03, 2011 10:22 pm

Yep.

The two functions of interest are view.begin_edit(), which takes an optional command name and an optional dictionary of arguments, and view.end_edit(), which finishes the edit.

All actions done within an edit are grouped as a single undo action. Callbacks such as on_modified() and on_selection_modified() are called when the edit is finished.

It's important to call view.end_edit() after each view.begin_edit(), otherwise the buffer will be in an inconsistent state. An attempt will be made to fix it automatically if the edit object gets collected, but that often doesn't happen when you expect, and will result in a warning printed to the console. In other words, you should always bracket an edit in a try..finally block.

The command name passed to begin_edit() is used for repeat, macro recording, and for describing the action when undoing/redoing it. If you're making an edit outside of a TextCommand, you should almost never supply a command name.

If you have created an edit object, and call a function that creates another one, that's fine: the edit is only considered finished when the outermost call to end_edit() runs.

As well as grouping modifications, you can use edit objects for grouping changes to the selection, so they're undone in a single step.
jps
Site Admin
 
Posts: 3077
Joined: Wed Mar 19, 2008 12:33 pm

Re: Grouping edits outside of a TextCommand

Postby guillermooo on Thu Feb 03, 2011 10:53 pm

Cool!

I had been pulling at my hair with decorators and sublime_plugin.text_command_classes to port a plugin and actually all's so much more simple!

So the "edit" object passed to every instance of TextCommand is for convenience only? Is there anything special about it? I mean, you can create a new one from self.view at any point.
guillermooo
 
Posts: 729
Joined: Thu Jul 23, 2009 9:06 am

Re: Grouping edits outside of a TextCommand

Postby jps on Thu Feb 03, 2011 11:07 pm

Yep, it's just a convenience thing, all it's doing is:

Code: Select all
edit = self.view.begin_edit(self.name())
try:
    return self.run(edit)
finally:
    self.view.end_edit(edit)


(from sublime_plugin.py)
jps
Site Admin
 
Posts: 3077
Joined: Wed Mar 19, 2008 12:33 pm


Return to Plugin Development

Who is online

Users browsing this forum: MarcusF and 6 guests