如何在扩展程序中添加/删除代码编辑器中的代码?
例如:
我创建了一个扩展女巫修改来自插入的代码的代码
该示例使用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()函数失败
答案 0 :(得分:3)
这里的问题是您尝试从与拥有它的线程不同的线程对ITextBuffer
进行编辑。这根本不可能。第一次编辑发生后,ITextBuffer
个实例与特定线程相关联,在此之后,不能从不同的线程编辑它们。 TakeThreadOwnership
关联ITextBuffer
后,CurrentSnapshot
方法也会失败。大多数其他非编辑方法(例如ITextBuffer
)可以从任何线程调用。
通常,SynchronizationContext.Current
将与Visual Studio UI线程关联。因此,要执行编辑,请使用UI线程中的原始Dispatcher.CurrentDispatcher
实例或{{1}}来返回UI线程,然后执行编辑。
答案 1 :(得分:0)
这是我想出的代码
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();
}));