I am working on an extension that uses an external program to format code inside Visual Studio.
If I replace the contents of the file using ITextEdit.Replace(...) the caret will be put at the end of the document, which is wrong.
What I'm trying to do is saving a snapshot of the current caret position in the textbuffer before replacing the contents of the file, and then setting the caret position to where it previously was in the textbuffer before replacing content.
However, ITextEdit.Apply() is generating a new snapshot causing _textView.Caret.MoveTo(point) to throw an exception:
System.ArgumentException: The supplied SnapshotPoint is on an incorrect snapshot.
Parameter name: bufferPosition
at Microsoft.VisualStudio.Text.Editor.Implementation.CaretElement.InternalMoveTo(VirtualSnapshotPoint bufferPosition, PositionAffinity caretAffinity, Boolean captureHorizontalPosition, Boolean captureVerticalPosition, Boolean raiseEvent)
at Microsoft.VisualStudio.Text.Editor.Implementation.CaretElement.MoveTo(SnapshotPoint bufferPosition)
I have also tried creating a new snapshot point instead of using _textView.Caret.Position.BufferPosition, like so:
var point = new SnapshotPoint(_textView.TextSnapshot, 0);
throwing the same "The supplied SnapshotPoint is on an incorrect snapshot." exception.
public class MyCommand
{
private readonly IWpfTextView _textView;
private readonly MyFormatter _formatter;
private readonly ITextDocument _document;
public MyCommand(IWpfTextView textView, MyFormatter formatter, ITextDocument document)
{
_textView = textView;
_formatter = formatter;
_document = document;
}
public void Format()
{
var input = _document.TextBuffer.CurrentSnapshot.GetText();
var output = _formatter.format(input);
// get caret snapshot point
var point = _textView.Caret.Position.BufferPosition;
using (var edit = _document.TextBuffer.CreateEdit())
{
edit.Replace(0, _document.TextBuffer.CurrentSnapshot.Length, output);
edit.Apply();
}
// set caret position
_textView.Caret.MoveTo(point);
}
}
I don't want to implement some custom caret "history", I want to do it the way it is meant to be. Also I would like the moving caret to be considered part of the edit, keeping the "ctrl+z" functionality intact.
As always, any help is greatly appreciated!