Last active
February 23, 2021 18:52
-
-
Save mwchase/a2da63e1f81f3ee5b1c5117c1f162105 to your computer and use it in GitHub Desktop.
Better reindenting for Sublime Text
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Excerpt | |
{ "keys": ["tab"], "command": "sane_reindent", "context": | |
[ | |
{ "key": "setting.auto_indent", "operator": "equal", "operand": true }, | |
{ "key": "selection_empty", "operator": "equal", "operand": true, "match_all": true }, | |
{ "key": "preceding_text", "operator": "regex_match", "operand": "^$", "match_all": true }, | |
{ "key": "following_text", "operator": "regex_match", "operand": "^$", "match_all": true } | |
] | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sublime | |
import sublime_plugin | |
class SaneReindentCommand(sublime_plugin.TextCommand): | |
def run(self, edit): | |
view = self.view | |
max_index = view.size() | |
to_reindent = {} | |
sel = view.sel() | |
regions = sorted(sel, key=lambda r: r.a, reverse=True) | |
for region in regions: | |
if not region.empty(): | |
return # Don't have a spec for non-empty selections | |
cursor = region.a | |
cur_line = view.line(cursor) | |
if not cur_line.empty(): | |
return # Don't have a spec for non-empty lines | |
index = cursor | |
next_line = cur_line | |
while next_line.empty() and index < max_index: | |
index += 1 | |
next_line = view.line(index) | |
if index == max_index: | |
continue | |
length = view.find_by_class( | |
index - 1, # Using the index itself seemed to act weird. | |
True, | |
# Just get anything, I don't care | |
sublime.CLASS_WORD_START | |
| sublime.CLASS_WORD_END | |
| sublime.CLASS_PUNCTUATION_START | |
| sublime.CLASS_PUNCTUATION_END | |
| sublime.CLASS_SUB_WORD_START | |
| sublime.CLASS_SUB_WORD_END | |
| sublime.CLASS_LINE_END | |
) - index | |
if length: | |
to_reindent[cursor] = length * " " | |
for region in regions: | |
cursor = region.a | |
view.insert(edit, cursor, to_reindent.get(cursor, "\t")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I don't even use Sublime Text much any more. I just pinned this to flex on the builtin reindent logic, at least as far as Python development goes.