Add code to the current editor window in visual studio package / extention

How to add / remove code in the code editor from the extension?

For example:
I created an extension that modifies code from an incoming socket. This example uses Microsoft.VisualStudio.Text.Editor

Tried to use:

<code> IWpfTextView textView; // received from the "Create" visual studio event Change ITextChange; // Received from a network socket or other source

ITextEdit edit = textView.TextBuffer.CreateEdit (); // Throws a "Not Owner" exception edit.Delete (change.OldSpan); edit.Insert (change.NewPosition, change.NewText); Code>

But I assume that there is another way, because the CrateEdit () function does not work

+3
source share
2 answers

The problem is that you are trying to edit ITextBufferfrom a stream other than the one that owns it. It is simply not possible. ITextBufferinstances are affinity to a specific stream after the first editing, and after this point they cannot be edited from another stream. The method TakeThreadOwnershipwill also fail after being ITextBufferaffinity. Most other methods without editing ( CurrentSnapshotfor example) can be called from any thread.

ITextBuffer Visual Studio. SynchronizationContext.Current Dispatcher.CurrentDispatcher , , .

+3

,

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();
        }));
0

Source: https://habr.com/ru/post/1777953/


All Articles