Search code examples
c#autocompleteintellisenseroslyncode-editor

Obtaining a list of keywords at the current position using Roslyn


I'm implementing Intellisense for a Web-based .Net editor, and I need it to display, among others, a list of matching keywords. For example, in the C# flavor, if a user presses "u", I need it to display both local symbols and keywords starting with "u" (e.g., "using").

Questions:

  1. Is it possible to retrieve all keywords that exist in the language (including the built-in type names, like "int")?
  2. Is it possible to retrieve only keywords that are valid in the current context (e.g., "using" doesn't fit after "public")?
  3. If not, can I get the context via Roslyn and manually pick the fitting keywords?

Solution

  • Figured it.

    var memberInfos = typeof (SyntaxKind).GetMembers(BindingFlags.Public | BindingFlags.Static);
    var keywords = from memberInfo in memberInfos
                   where memberInfo.Name.EndsWith("Keyword") 
                   orderby memberInfo.Name
                   select memberInfo.Name.CutoffEnd("Keyword").ToLower();
    

    I'm getting some extra keywords for compiler directives, like pragma, but it's a good start.