在Visual Studio包/扩展中将代码添加到当前编辑器窗口中
-
29-09-2019 - |
题
如何从扩展程序中添加/删除代码编辑器中的代码?
例如:
我创建了一个扩展女巫会从传入的插座修改代码
该示例使用microsoft.visualstudio.text.editor
尝试使用:
IWpfTextView textView; // got from visual studio "Create" event
ITextChange change; // Got from network socket or other source
ITextEdit edit = textView.TextBuffer.CreateEdit(); // Throws "Not Owner" Exception
edit.Delete(change.OldSpan);
edit.Insert(change.NewPosition, change.NewText);
但是我想还有另一种方法,因为crateedit()函数失败
解决方案
这里的问题是您正在尝试对 ITextBuffer
与拥有它的线程不同的线程。这根本是不可能的。 ITextBuffer
一旦第一个编辑发生,就将实例粘贴到特定线程中,此后无法从其他线程编辑它们。这 TakeThreadOwnership
方法也将在 ITextBuffer
已经被封闭。大多数其他非编辑方法(CurrentSnapshot
例如)可以从任何线程调用。
通常是 ITextBuffer
将被关联到Visual Studio UI线程。因此,要执行编辑使用原始 SynchronizationContext.Current
实例或 Dispatcher.CurrentDispatcher
从UI线程中返回UI线程,然后执行编辑。
其他提示
这是我发现的代码
Dispatcher.Invoke(new Action(() =>
{
ITextEdit edit = _view.TextBuffer.CreateEdit();
ITextSnapshot snapshot = edit.Snapshot;
int position = snapshot.GetText().IndexOf("text:");
edit.Delete(position, 5);
edit.Insert(position, "some text");
edit.Apply();
}));