pb_lull
pb_lull

Reputation: 43

Is there a way to enable keyboard shortcuts only when specific file types are opened

I have a custom keyboard shortcut shift + R + enter which I only want to be enabled when working on .sql files. Is it possible to disable the shortcut when any other file type is open

Upvotes: 3

Views: 1148

Answers (2)

M Kim
M Kim

Reputation: 11

I thank @Mark for his nice answers with examples. However, his last example with

"when": "editorTextFocus && resourceExtname =~ /\\.(html|css|scss)"  

or

 "when": "editorTextFocus && resourceExtname =~ /\\.sql"  

was not working.

Later, I've learned that the regular expression should have / at both ends. In addition, you might want it case-insensitive. Then, the revised example would be

"when": "editorTextFocus && resourceExtname =~ /\\.(html|css|scss)/i" 

or

 "when": "editorTextFocus && resourceExtname =~ /\\.sql/i"  

Upvotes: 0

Mark
Mark

Reputation: 180915

There is a context clause for language IDs. For example:

{
  "key": "alt+c",
  "command": "extension.multiCommand.execute",
  "args": { "command": "multiCommand.newComponentFolderAndFiles" },
  "when": "editorTextFocus && editorLangId == sql"
}

So it is enabled for sql files (if that is the language ID) only. To see the language it click on the language mode in the lower right-hand corner of the vscode window. You use the version that is in parens, like SQL (sql). Use the version as it appears in the parens: sql.

To enable for multiple filetypes you can do this:

"when": "editorTextFocus && resourceExtname =~ /\\.(html|css|scss)"

See conditional operators for when clauses.

Upvotes: 5

Related Questions