Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Key Binding when condition for multiple languages

I want to bind a command that triggers only when I'm in a javascript or javascript react (jsx) file.

This is ideally something along what I want:

   {
        "key": "f9",
        "command": "sortImports.sort",
        "when": "editorTextFocus && (editorLangId == 'javascriptreact' && editorLangId == 'javascript')"
    }

I have tried with (editorLangId == 'javascriptreact' || editorLangId == 'javascript') but that fails.

I can get it to work by doing 2 key bindings (one with javascript and one with javascript react).

I'm not quite sure what the 'when' condition really supports? Maybe a startsWith...but I couldn't get that to work though.

like image 765
Johan Leino Avatar asked Nov 01 '25 11:11

Johan Leino


2 Answers

If it's a snippet, adding the snippet in a global snippets file with multiple languages in the scope property seems to work for me. (Type "User snippets" in help and click on "New Global Snippets file"). Then add your snippet to the file.

"myFavSnippet": {
    "scope": "javascript,javascriptreact",
    "prefix": "console.log",
    "body": [
        "console.log(${1:}$SELECTION)${0};"
    ],
    "description": "console.log"
},

This is what I put in the keybindings.json file:

 {
    "key": "shift+cmd+l",
    "command": "editor.action.insertSnippet",
    "when": "editorTextFocus",
    "args": {
      "name": "myFavSnippet"
    }  
  },

Despite what is written in the documentation, it seems to work without adding the langId property to args. This works for me even when the snippet is put in a language specific snippets file.

like image 157
sam-m Avatar answered Nov 03 '25 17:11

sam-m


What worked for me was:

{
    "key": "f9",
    "command": "sortImports.sort",
    "when": "editorTextFocus && editorLangId == 'javascriptreact' || editorLangId == 'javascript'"
}
like image 32
Anil kumar Avatar answered Nov 03 '25 18:11

Anil kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!