Skip to content

Instantly share code, notes, and snippets.

@mwchase
Last active February 23, 2021 18:52
Show Gist options
  • Save mwchase/a2da63e1f81f3ee5b1c5117c1f162105 to your computer and use it in GitHub Desktop.
Save mwchase/a2da63e1f81f3ee5b1c5117c1f162105 to your computer and use it in GitHub Desktop.
Better reindenting for Sublime Text
// 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 }
]
}
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"))
@mwchase
Copy link
Author

mwchase commented Feb 23, 2021

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment