Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VS for Mac extension - null Editor in ActiveWindow

I'm trying to get into developing an extension for Visual Studio for Mac. I'm using this tutorial. Everything had been going well until I tried to run my extension. In my case "Insert date" in Edit submenu is disabled. While debugging I've noticed that IdeApp.Workbench.ActiveDocument.Editor is null despite I have an open document. Here's my code

using System;
using MonoDevelop.Components.Commands;
using MonoDevelop.Ide;

namespace ExampleIDEExtension
{
    public class InsertDateHandler : CommandHandler
    {
        protected override void Run()
        {
            var editor = IdeApp.Workbench.ActiveDocument.Editor;
            var currentTime = DateTime.Now.ToString();
            editor.InsertAtCaret(currentTime);
        }

        protected override void Update(CommandInfo info)
        {
            info.Enabled = IdeApp.Workbench.ActiveDocument.Editor != null;
        }
    }
}

I have no idea why Editor is null despite having an open document.

like image 249
Wolen Avatar asked Sep 22 '19 11:09

Wolen


1 Answers

The editor is null, as Monodevelop is using Microsoft.VisualStudio.Text.Editor and it mentions that the API has been obsolete in the below link.

https://github.com/mono/monodevelop/blob/50fbe0a7e65c5439e3313c6b50e7ef927f5f1fe9/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Editor/TextEditor.cs

Anyways, to answer your question, this is what I had to do to achieve the insert date handler demo addin

    protected override void Run()
    {
        var textBuffer = IdeApp.Workbench.ActiveDocument.GetContent<ITextBuffer>();
        var date = DateTime.Now.ToString();
        var textView = IdeApp.Workbench.ActiveDocument.GetContent<ITextView>();
        var caretPosition = textView.Caret.Position;
        textBuffer.Insert(caretPosition.BufferPosition.Position,date);
    }

    protected override void Update(CommandInfo info)
    {
        var textBuffer = IdeApp.Workbench.ActiveDocument.GetContent<ITextBuffer>();
        if (textBuffer != null && textBuffer.AsTextContainer() is SourceTextContainer container)
        {
            var document = container.GetTextBuffer();
            if (document != null)
            {
                info.Enabled = true;
            }
        }
    }
like image 160
vin Avatar answered Oct 21 '22 12:10

vin