MiB_Coder
MiB_Coder

Reputation: 915

VSIX Extension: how to make atomic undo upon text replacement

I am writing an Visual Studio Extension module (VSIX ), which allows the user to select text and upon a menu command, the selected text is replaced with a new text:

var document = ProjectHelpers.DTE.ActiveDocument;
var selection = (TextSelection)document.Selection;
var text = selection.Text;
string newText = doSomethingWith(text);
selection.Text = newText; 

Now the problem is, when I wish to undo the operation (e.g. via Ctrl-Z), only one line at a time of the new text is removed and finally the original text is restored (need to use Ctrl-Z many times).

How can I implement an atomic undo, where only one Ctrl-Z command un-does the whole process?

In case it matters, I am writing for VS2017.

Upvotes: 2

Views: 208

Answers (1)

MiB_Coder
MiB_Coder

Reputation: 915

The solution is to create an undo context, in which all changes can be collected, which should appear as a single transaction:

try
{
   ProjectHelpers.DTE.UndoContext.Open("Description of operation");
   selection.Text = newText;
}
finally
{
   ProjectHelpers.DTE.UndoContext.Close();
}

Upvotes: 2

Related Questions