Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VS Code - highlight some variables with TextMate

VS Code 1.15 added support for TextMate grammar rules. I want to highlight some variables in JavaScript with these rules: self, me. How can I do this?

like image 893
spyke Avatar asked Aug 11 '17 09:08

spyke


2 Answers

Short answer: you can't.

I'm assuming you're referring to the new editor.tokenColorCustomizations setting. This setting only allows you to change the colors associated with specific scopes that the TextMate grammar already defines. self and me are not treated specially by the JS gramar, they use the same variable.other.readwrite.js scope as any other variable:

Contrast this with the this keyword: It has its own unique variable.language.this.js scope, so we could use the setting to color this red:

"editor.tokenColorCustomizations": {
    "textMateRules": [
        {
            "scope": "variable.language.this.js",
            "settings": {
                "foreground": "#FF0000"
            }
        }
    ]
}

like image 197
Gama11 Avatar answered Sep 19 '22 07:09

Gama11


As @Gama11 said, you can't do it with the editor.tokenColorCustomizations but you could do it with the extension TODO Highlight. It is not the intended use but it would easily work for what you want. The only problem being that 'self' and 'me' would be highlighted if they appeared within any text as well with a default implementation, but that could be fixed using a regexp with word boundaries. Here is a sample implementation:

"todohighlight.keywords": [
    "DEBUG:",
    "REVIEW:",
    {
        "text": "NOTE:",
        "color": "#ff0000",
        "backgroundColor": "yellow",
        "overviewRulerColor": "grey"
    },
    {
        "text": "HACK:",
        "color": "#000",
        "isWholeLine": false
    },
    {
        "text": "TODO:",
        "color": "red",
        "borderRadius":"0px",
        "backgroundColor": "rgba(0,0,0,.2)"
    }
],

You could just replace with your 'self' and 'me'. I use an interesting pattern:

  //  highlight `TODO:`,`FIXME:` and 'HACK:' and content between parentheses

  // "todohighlight.keywordsPattern": "((\\s\\sTODO\\s*:\\s{0,5})|(\\s\\sFIXME\\s*:\\s{0,5})|(\\s\\sHACK\\s*:\\s{0,5}))(\\(.*\\)\\s)*",

It highlights TODO:, FIXME: and HACK: if they are preceded by some spaces as well as any content that follows that is in parens.

But I don't see why this extension couldn't be used to highlight any particular text you want but you'll probably want to include a space before and maybe after 'me' and 'self' in case they may also appear embedded within other text such as 'varmetoo'.

like image 38
Mark Avatar answered Sep 18 '22 07:09

Mark