views:

18

answers:

1

Hiya,

I have a Visual Studio (2010) package that combines multiple text operations, e.g. it inserts custom properties into my csharp files.

These inserts can become quite numerous and I would like to be able to reverse the effect of the Command with a single click of the undo button. Is there a way of doing this?

Steve

A: 

Yes. Assuming you have a valid

ITextBuffer buffer;

You just need to get an ITextEdit, like this:

var textEdit = buffer.CreateEdit();

Then you can:

textEdit.Delete(...)
textEdit.Insert(....)

and when you are done, you must

textEdit.Apply();

or

textEdit.Cancel();

If you don't apply or cancel your changes, other changes will not be allowed on the buffer.... so you probably want to wrap your changes in a try...finally so an exception doesn't shut down your editor. All your changes will be grouped and a single undo will reverse them all.

Hope this helps.

Cameron Peters
ITextEdit is disposable, so you should put it in a `using` block. If you leave the `using` block without calling `Apply()`, then it will auto-cancel.So it will look something like: `using (var textEdit = buffer.CreateEdit()) { //doStuff and then textEdit.Apply(); }`
Noah Richards
Also, this approach won't completely fix the issue if you are making edits in multiple files at once. If you are doing that, you'll need to manually create an undo transaction (if you could clarify the question, that will help)
Noah Richards
@Noah - that's cool... and a nice way to get rid of the try...finally. Thanks! It's possible to create an Undo that covers multiple files?? ... sounds like a future blog post to me!
Cameron Peters

related questions