2

Is there a way to add a code in a specific point with Roslyn (also without roslyn)? This is my problem: I develop a vspackage that add a command in the context menu (in CODE WINDOW). When I right click and I select this command it should add some code in that point. How can I resolve this problem?

blinkettaro
  • 341
  • 6
  • 18
  • Some time has passed since you asked for help, but I'm curious; did my solution below work for you? – wobuntu Mar 03 '18 at 13:26

1 Answers1

1

You have to:

  • receive the current text window of visual studio
  • get the position in the textbuffer (clicking the right mouse button will set the caret position)
  • insert your text

First things first; receive the text view:

public static IWpfTextView GetCurrentTextView(Package package)
{
    try
    {
        var serviceProvider = package as IServiceProvider;
        IVsTextManager textManager = (IVsTextManager)serviceProvider.GetService(typeof(SVsTextManager));

        IVsTextView textView;
        textManager.GetActiveView(1, null, out textView);

        IComponentModel componentModel = (IComponentModel)serviceProvider.GetService(typeof(SComponentModel));
        var factoryService = componentModel.GetService<IVsEditorAdaptersFactoryService>();

        return factoryService.GetWpfTextView(textView);
    }
    catch
    {
        return null;
    }
}

Get the caret position from that and insert your text:

IWpfTextView textView = GetCurrentTextView(package);
SnapshotPoint caretPosition = textView.Caret.Position.BufferPosition;
textView.TextBuffer.Insert(caretPosition, "HELLO WORLD");

Don't forget to add error handling.

wobuntu
  • 422
  • 5
  • 12