How would I write a custom key binding or plugin for HTML language that would add enter
after the tag?
Example
Currently Sublime Text does this upon auto complete
<table></table>
I would like to have this
<table>
</table>
I hope you guys can help. Thanks in advance :)
These snippet-completions are hard coded in the HTML package.
I think the easiest way to archive this, is to write a simple plugin on your own. To do this open your User
folder (or an other subfolder of Packages) and create a python file (e.g. html_complete_tag.py
).
Then open the python file and just paste the following code:
import sublime, sublime_plugin
class HtmlCompleteTagCommand(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
view.run_command("commit_completion")
for sel in view.sel():
if not sel.empty(): continue
pos = sel.begin()
# check we are inside a tag
if view.substr(sublime.Region(pos-1, pos+1)) == "><":
# we have: <tag>|<tag/>
# insert \n< one position after the cursor
# => <tag>|<\n<tag/>
view.insert(edit, pos+1, "\n<")
# remove the char after the cursor
# => <tag>|\n<tag/>
view.replace(edit, sublime.Region(pos, pos+1), "")
# insert a newline and a tab at the cursor
# => <tag>\n\t|\n<tag/>
view.insert(edit, pos, "\n\t")
This will commit the completion and if inside a tag insert the newlines. The actions are a little bit weird, because we want the cursor to be at the desired position after inserting \n\t\n
.
To use the keybinding in html just add the following lines to your keymap:
{ "keys": ["tab"], "command": "html_complete_tag", "context":
[
{ "key": "auto_complete_visible" },
{ "key": "selector", "operator": "equal", "operand": "text.html" }
]
},
If you confirm the autocompletion with enter
, then replace tab
by enter
or keep both keybindings.