Sublime Forum

How to create a new rule for auto-completing matching brackets that are in templating systems like jinja2

#1

I have been using sublime text for almost 4 years now and have always struggled with jinja2 brackets that are in this format

{% if expression %}

Is there a way i can create a rule for this kind of autocomplate.

0 Likes

#2

You mean the behavior like with automatically adding closing parentheses, brackets and braces?

These functions use normal keybindings which you can copy and customize. Here is an example.

	// Auto-pair jinja brackets
	{
		// ctrl+% (german layout)
		"keys": ["ctrl+shift+5"],
		"command": "insert_snippet",
		"args": {"contents": "{% $0 %}"},
		"context": [
			{ "key": "setting.auto_match_enabled", "operator": "equal", "operand": true },
			{ "key": "selection_empty", "operator": "equal", "operand": true, "match_all": true },
			{ "key": "following_text", "operator": "regex_contains", "operand": "^(?:\t| |\\)|]|;|\\}|$)", "match_all": true }
		]
	},
	{
		// ctrl+% (german layout)
		"keys": ["ctrl+shift+5"],
		"command": "insert_snippet",
		"args": {"contents": "{% ${0:$SELECTION} %}"},
		"context": [
			{ "key": "setting.auto_match_enabled", "operator": "equal", "operand": true },
			{ "key": "selection_empty", "operator": "equal", "operand": false, "match_all": true },
		]
	},
	{
		// ctrl+% (german layout)
		"keys": ["ctrl+shift+5"],
		"command": "move",
		"args": {"by": "characters", "forward": true},
		"context": [
			{ "key": "setting.auto_match_enabled", "operator": "equal", "operand": true },
			{ "key": "selection_empty", "operator": "equal", "operand": true, "match_all": true },
			{ "key": "following_text", "operator": "regex_contains", "operand": "^\\{%", "match_all": true }
		]
	},
1 Like

#3

You may also try this keybindings to insert them automatically as you type:

    {
        "keys": ["%"], "command": "insert_snippet",
        "args": {
            "contents": "% $1 %"
        },
        "context":
        [
            { "key": "setting.auto_match_enabled", "operator": "equal", "operand": true },
            { "key": "selector", "operand": "source" }, // your language
            { "key": "preceding_text", "operator": "regex_contains", "operand": "{$" },
        ],
    },
    {
        "keys": ["%"], "command": "insert_snippet",
        "args": {
            "contents": "% $1 %}"
        },
        "context":
        [
            { "key": "setting.auto_match_enabled", "operator": "equal", "operand": true },
            { "key": "selector", "operand": "source" }, // your language
            { "key": "preceding_text", "operator": "regex_contains", "operand": "{$" },
            { "key": "following_text", "operator": "not_regex_match", "operand": "}" },
        ],
    },

2 Likes

#4

Thanks It was great help :slight_smile:

0 Likes