Sublime Forum

Python syntax: position of cursor after (⏎

#1

I’m using Sublime Text build 4143. In a JSON document, if I press return between a pair of curly braces, like {⏎}, the cursor is placed on a new indented line and the closing brace’s indentation depth matches the opening one: (:mouse: is my cursor)

{
    🐭
}

In a Python document, doing the same thing within a pair of parenthesis (⏎) results in this:

foo(
    🐭)

What I would like is

foo(
    🐭
)

Is there a way to make this happen? It’s bothered me for literally years but I’m just now trying to find a solution. :laughing:

0 Likes

#2

Could be achieved via key binding, which inserts a snippet.

	{ "keys": ["enter"], "command": "insert_snippet", "args": {"contents": "\n\t$0\n"}, "context":
		[
			{ "key": "setting.auto_indent", "operator": "equal", "operand": true },
			{ "key": "selection_empty", "operator": "equal", "operand": true, "match_all": true },
			{ "key": "preceding_text", "operator": "regex_contains", "operand": "\\($", "match_all": true },
			{ "key": "following_text", "operator": "regex_contains", "operand": "^\\)", "match_all": true }
		]
	},

An alternative would be to use the default macro which is used for braces, but it also indents closing parens in function definitions, which might be unwanted.

	{ "keys": ["enter"], "command": "run_macro_file", "args": {"file": "res://Packages/Default/Add Line in Braces.sublime-macro"}, "context":
		[
			{ "key": "setting.auto_indent", "operand": true },
			{ "key": "selection_empty", "operand": true, "match_all": true },
			{ "key": "preceding_text", "operator": "regex_contains", "operand": "\\($", "match_all": true },
			{ "key": "following_text", "operator": "regex_contains", "operand": "^\\)", "match_all": true }
		]
	},
1 Like

#3

Awesome! Thank you. I added a selector for the specific Python scope:

    {
        "keys": [ "enter" ],
        "command": "insert_snippet",
        "args": {
            "contents": "\n\t$0\n"
        },
        "context": [
            { "key": "selector",            "operator": "equal",          "operand": "meta.function.parameters.python" },
            { "key": "setting.auto_indent", "operator": "equal",          "operand": true                              },
            { "key": "selection_empty",     "operator": "equal",          "operand": true,   "match_all": true         },
            { "key": "preceding_text",      "operator": "regex_contains", "operand": "\\($", "match_all": true         },
            { "key": "following_text",      "operator": "regex_contains", "operand": "^\\)", "match_all": true         }
        ]
    },
0 Likes