Saturday, February 11, 2012

VS Spell Check Extension - using Roslyn


A couple of months ago Microsoft published the Roslyn CTP which gives us an inside view on the Compilers view to our code. This also comes with project templates for creating CodeIssues and CodeActions (These are code suggestiongs/actions that are available to the coder in the IDE).

Since I read about this it interested me a little, and wanted to play around with this. Since I've been programming in java at home lately due to a course i'm taking at the university, I realized that one of the nice features that IntelliJ has is that it gives you suggestions on spelling mistakes you made on variable names (because this is one of the most annoying things i see in code and i truly believe makes it harder to maintain), so I thought i'd try to implement this in VS as an extension.

It was really simple to do so -

I just created a CodeIssue project :


With the ExportSyntaxNodeCodeIssueProvider attribute, you can tell it to execute the code only on variable declarations :


Split each variable name into separate words (most variables, at least when I write code looks like this "var myReceivedFilesList" so i separate them by case) :
public IEnumerable<CodeIssue> GetIssues(IDocument document, CommonSyntaxNode node, CancellationToken cancellationToken = new CancellationToken())
{
    var variable = node as VariableDeclarationSyntax;
    if (variable != null)
    {
        var nodes = variable.ChildNodes().Where(x => x.Kind == SyntaxKind.VariableDeclarator);

        foreach (var syntaxNode in nodes)
        {
            var fullVariableName = syntaxNode.GetFirstToken().ValueText;

            var wordsInVariableName = fullVariableName.SplitToWords();
  
            if (wordsInVariableName != null)
            {
                var correctSpelling = CheckAndCorrectSpelling(wordsInVariableName);

                if (correctSpelling != null)
                    yield return new CodeIssue(CodeIssue.Severity.Info, syntaxNode.GetFirstToken().Span, "Possible Typo ?\nMaybe you meant : " + correctSpelling);
            }
        }
    }
}


And viola!
You have the spell check feature on variable names in your VS IDE :



For the spell check I used the NHunspell project (This is the .net wrapper to the OpenOffice dictionary).

I put the code up on google code so you can take a look at it, and who knows, maybe even contribute to it... :)
https://code.google.com/p/gb-coding-extension/

I don't know if this is production-worthy code, I didn't even check performance or if it slows down the IDE. This was just a small learning experience for me.
Maybe if I have some more free time, and good ideas, I'll add to it more features in the future...

5 comments:

  1. I am happy to find this post Very useful for me. as it contains lot of information. I Always prefer to read The Quality and glad I found this thing in you post Secrailway

    ReplyDelete