razorintellisensevisual-studio-extensions

How to create visual studio extension for .cshtml files?


I am trying to create a visual studio 2017 extension. More specifically, I want to extend IntelliSense to create light bulb suggestions and fixes. For that, I am trying to go through the syntax of .cshtml file (both markup and c# code), and parse it so that I can get stuff like values of the attributes and tag names, so that I know when to show the light bulbs.

I went through the documentation on MSDN site. I found out how I could get the light bulbs to show up at specific caret location using ITextBuffer and Snapshot for [ContentType = "text"]. But for my problem, I want the light bulb to show up based on values of attributes and like. So, I think I will have to work with [ContentType = 'code']. I couldn't find proper documentation for that. I found this article Writing a visual studio extension for code generation with roslyn

It tells how you can show a light bulb when your caret is on a method name and make a class file with that method name. Now, this is for a C# file and uses the Roslyn APIs to get the syntax tree and sementic model of the C# code.

Problem Comes down to this

I have a .cshtml file and I want to get the syntax tree of the markup and C# code in it. And, I think I should be able to get it because the editor higlights the markup and C# code of the file differently. Thus, it must be parsing it. But I am not able to do this.

So, for my approach I am trying to get the syntax tree. I want to know how this can be done. Please, tell me if this the wrong direction and what else I can do.

PS: This is my first question so please tell me if I have left any information and also I am new to Razor so maybe I am missing something there.

Thanks a lot for your time.


Solution

  • This might be useful:

    using System.Web.Razor;
    using System.Web.Razor.Parser.SyntaxTree;
    
    var host = new RazorEngineHost(new CSharpRazorCodeLanguage());
    var engine = new RazorTemplateEngine(host);
    
    var result = engine.ParseTemplate(new StringReader(<STRING>)));
    

    result.Document.Children provides detailed recursive tree structure.