How to Set a Key Binding in Sublime Text Based on the File Type the Command Is Running on

In my Sublime Text 3, I use JsFormat to format my javascript source code. Its key binding follows:

I have noticed that the JsFormat used the selector context operand to make sure that the js_format command would only run on file types “.js”, “.json” or “.html”. This is to avoid key clashes with other commands such as the SublimeAStyleFormatter which is used to format my C family source code.

Now I want to add another command that uses a python script called tidy_xml.py to format my XML source code. At the same time, I want to use the same key binding, i.e. the “ctrl+alt+i”, to run the formatting command. Actually, the “ctrl+alt+i” is my universal formatting shortcut. So I set the following binding which followed the idea from JsFormat:

Unfortunately, this doesn’t work. But why did the JsFormat one work? Believe me, I asked myself a lot about this and I also googled a lot. Finally, I found that the scope for XML is not “source.xml”, but “text.xml”. WTF! So this works:

Here are the steps I used to find out the scope of XML type (other types also apply):

  1. Right click your “Applications/Sublime Text.app”, and select the “Show Package Contents”.
  2. Copy and paste the file “Contents/MacOS/Packages/XML.sublime-package” to somewhere else, says Downloads.
  3. Rename XML.sublime-package to XML.zip, and double click it to unzip
  4. Open XML-Processing-Instruction.sublime-snippet in the unzipped folder XML, and then you will find the scope value

Hope this work out for you too If anyone of you managed to make the regex_match work so that we don’t have to manually check the scope for each file type in the future, please let me know.