Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manage undo/redo stack in VSPackage?

Tags:

c#

vsx

vspackage

I have created VSPackage that provides certain functionality in Visual Studio code window context menu. This action consists of several code edits plus some stuff around.

The problem is, each of these code edits get added to the undo stack separately. What I want is to handle this action as one atomic unit, i.e. pressing CTRL+Z rollbacks all code edits and everything else (plus of course, places the unit on top of redo stack).

Documentation regarding this topic is extremely poor, the only thing I found is something about IOleParentUndo unit - but I wasn't succesfull in implementing it.

I use

IVsTextLines.GetUndoManager()

to get the undo manager - that appears to be a good start.

like image 597
cre8or Avatar asked Dec 30 '25 19:12

cre8or


1 Answers

I encapsulated below code to undo couple of actions.

public class VSUndo : IDisposable
{
    public static UndoContext undoContext;

    public static VSUndo StartUndo()
    {
        undoContext = ((DTE2)Package.GetGlobalService(typeof(DTE))).UndoContext; 
        undoContext.Open(Guid.NewGuid().ToString());
        // return new instance for calling dispose to close current undocontext
        return new VSUndo(); 
    }

    public void Dispose()
    {
        undoContext.Close();
    }

}

then, you can just use:

using (VSUndo.StartUndo())
{
   // couple of actions that may need to undo together
}
like image 100
scott Avatar answered Jan 02 '26 10:01

scott



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!