Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the current filename from a Visual Studio text adornment extension

Tags:

c#

mef

I'm new to VS extension development. I'm currently working with the text adornment sample in VS 2015 and have been able to get coloured boxes showing correctly. Now I want to extend the sample so the adornment only appears on certain file names.

Googling has said I can use ITextDocumentFactoryService.TryGetTextDocument interface with the IWpfTextView.TextBuffer property to get a filename. This sounds great. But I can't seem to actually get the interface.

In my class I have:

    [Import]
    public ITextDocumentFactoryService TextDocumentFactoryService = null;

But it is always NULL.

How can I get ITextDocumentFactoryService?

namespace Test
{
    internal sealed class TestAdornment
    {
        [Import]
        public ITextDocumentFactoryService TextDocumentFactoryService = null;

        public TestAdornment(IWpfTextView view)
        {
        }

        /// <summary>
        /// Adds the scarlet box behind the 'a' characters within the given line
        /// </summary>
        /// <param name="line">Line to add the adornments</param>
        private void CreateVisuals(ITextViewLine line)
        {
            // TextDocumentFactoryService is NULL
        }
    }
}
like image 849
user3476571 Avatar asked Nov 25 '15 11:11

user3476571


1 Answers

TextAdornmentTextViewCreationListener.cs

[Export(typeof(IWpfTextViewCreationListener))]
[ContentType("text")]
[TextViewRole(PredefinedTextViewRoles.Document)]
internal sealed class TextAdornmentTextViewCreationListener : IWpfTextViewCreationListener
{
    [Import]
    public ITextDocumentFactoryService textDocumentFactory { get; set; }

    //...

    public void TextViewCreated(IWpfTextView textView)
    {
        new TextAdornment(textView, textDocumentFactory);
    }
}

TextAdornment.cs

internal sealed class TextAdornment
    {
        private readonly ITextDocumentFactoryService textDocumentFactory;
        private ITextDocument TextDocument;

        //...    

        public TextAdornment(IWpfTextView view, ITextDocumentFactoryService textDocumentFactory)
        {
            //...

            this.textDocumentFactory = textDocumentFactory;

            //...
        }

     internal void OnLayoutChanged(object sender, TextViewLayoutChangedEventArgs e)
        {
            var res = this.textDocumentFactory.TryGetTextDocument(this.view.TextBuffer, out this.TextDocument);
            if (res)
            {
                //this.TextDocument.FilePath;
            }
            else
            {
                //ERROR
            }
        }
    }
like image 169
rinatdobr Avatar answered Nov 04 '22 01:11

rinatdobr