Sublime Forum

Automatically Unindent in Python

#1

Hello! I am new to Sublime. I wanted to ask whether there’s a way I can have new lines automatically unindent after a line starting with “return”, “break”, “raise”, or “continue”, since there’s no reason I’d be writing on the same indentation level afterwards.

I couldn’t find anything like this in settings, so I was wondering if I missed it, if there’s a package for it, or if it would be easy to create such a package.

0 Likes

#2

That’s not possible using indentation rules. It would require an indentation rule like unindentNextLinePattern or something like that.

It can be achieved with a key binding, calling a macro.

Packages/User/Default.sublime-keymap

[
    { "keys": ["enter"], "command": "run_macro_file", "args": {"file": "Packages/User/NewLineUnindent.sublime-macro"}, "context":
        [
            { "key": "selector", "operand": "source.python - string.quoted.double" },
            { "key": "selection_empty", "match_all": true },
            { "key": "preceding_text", "operator": "regex_contains", "operand": "\\b(?:break|continue|pass|return\\b.*)$", "match_all": true },
        ],
    },
]

Packages/User/NewLineUnindent.sublime-macro

[
	{"command": "insert_snippet", "args": {"contents": "\n"}},
	{"command": "unindent"}
]
1 Like

#3

Thank you so much! When I put in these settings however, it makes is so that nothing happens (no newline is written) when upon pressing the return key on a line starting with “return” or the line. Do you know how I could fix this?

Edit: nevermind, I was being dumb and put the NewLineUnindent.sublime-macro file in the wrong folder.

0 Likes