Autocomplete React components to HTML Tags in Sublime Text 3

Problem: Babel syntax for sublime doesn’t provide native html autocomplete, that works in files with html syntax.

Solution: Sublime Text has a great Macro tool. Lets create a very simple macro, that converts entered word into the html tag and places it in the Packages/User folder with the name ‘Word to Tag.sublime-macro’

[
 {"args": {"by": "words", "forward": false }, "command": "move"},
 {"args": {"characters": "<"}, "command": "insert"},
 {"args": {"by": "wordends", "forward": true }, "command": "move"},
 {"args": {"characters": ">"}, "command": "insert"},
 {"args": null, "command": "close_tag"},
 {"args": {"by": "words", "forward": false }, "command": "move"},
 {"args": {"by": "characters", "forward": false }, "command": "move"},
 {"args": {"by": "characters", "forward": false }, "command": "move"}
]

Then we can bind macros with some key binding by adding next code to`User/Default (OSX).sublime-keymap`:

{ "keys": ["tab"], "command": "run_macro_file", "args": {"file": "res://Packages/User/Word to Tag.sublime-macro"}}

But if we leave it as it is we will have problem with tab hotkey. it will convert anything that we’ll write into tags by tab. It’s not very handy, so we need to add specific scope to our keybinding

[
  // Smart converting from component word to the tag
  { "keys": ["tab"], "command": "run_macro_file", "args": {"file": "res://Packages/User/Macroses/Word to Tag.sublime-macro"}, "context":
    [
      { "key": "selection_empty", "operator": "equal", "operand": true, "match_all": true },
      { "key": "preceding_text", "operator": "regex_match", "operand": ".*[a-zA-Z]$", "match_all": true },
      { "key": "selector", "operator": "equal", "operand": "meta.jsx.js", "match_all": true },
      { "key": "selector", "operator": "not_equal", "operand": "meta.embedded.expression.jsx", "match_all": false },
    ]
  }
]

You can read about keybindings scopes at Sublime Docs. But here is explanation of some of them:

  • auto_complete_visible — disable converting when we have suggestions
  • selection_emty — disable converting when we select some word
  • preceding_text — disable converting for non-words
  • selector — convert only when we are in jsx scope and not it curly braces area (babel syntax allows it)

So in a few minutes we have cool converting from component name to html tag in react jsx.