Sublime Forum

Keybinding based on file type or extension

#1

On Dev Build 3140

I am trying to bind a key only when file type is jsx I prefer my formatting keybindings to be consistent across file types, I am using the following snippet with extensions, I tried using operand but jsx-babel uses the same scope as js file type so not helpful

    "keys": [
      "super+shift+h"
    ],
    "command": "js_prettier",
    "args": {
      "extensions": [
        "jsx"
      ]
    }
  }

I get the following error message

Traceback (most recent call last):
  File "/Applications/Sublime Text.app/Contents/MacOS/sublime_plugin.py", line 812, in run_
    return self.run(edit, **args)
TypeError: run() got an unexpected keyword argument 'extensions'
1 Like

#2

You can try to create a context listener:

import os

import sublime_plugin

class JsxContextListener(sublime_plugin.EventListener):
    def on_query_context(self, view, key, operator, operand, match_all):
        if key != "has_extension":
            return
        file_name = view.file_name()
        if not file_name:
            return False
        return os.path.splitext(file_name)[1][1:] == operand

and then add ey context to your keybinding

{
    "keys": ["super+shift+h"],"command": "js_prettier",
    "context": 
    [
        { "key": "has_extension", "operand": "jsx" }
    ]
}
3 Likes

#3

Thanks a lot, that worked.

0 Likes