我正在开发一个扩展,它使用外部程序来格式化 Visual Studio 内的代码。
如果我使用ITextEdit.Replace(...)替换文件的内容,插入符号将放在文档的末尾,这是错误的。
我想做的是在替换文件的内容之前保存文本缓冲区中当前插入符号位置的快照,然后在替换内容之前将插入符号位置设置为文本缓冲区中之前的位置。
但是,ITextEdit.Apply()正在生成新快照,导致_textView.Caret.MoveTo(point)引发异常:
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)
Run Code Online (Sandbox Code Playgroud)
我还尝试创建一个新的快照点而不是使用 _textView.Caret.Position.BufferPosition,如下所示:
var point = new SnapshotPoint(_textView.TextSnapshot, 0);
Run Code Online (Sandbox Code Playgroud)
抛出相同的“提供的 SnapshotPoint 位于不正确的快照上。” 例外。
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 = …Run Code Online (Sandbox Code Playgroud)