|
| 1 | +import sublime, sublime_plugin |
| 2 | +import tokenize |
| 3 | +from io import BytesIO |
| 4 | + |
| 5 | + |
| 6 | +class PythonOutputFormatCommand(sublime_plugin.TextCommand): |
| 7 | + indentation_level = 0 |
| 8 | + |
| 9 | + def indent(self): |
| 10 | + return (tokenize.INDENT, ' ' * 4 * self.indentation_level) |
| 11 | + |
| 12 | + def run(self, edit): |
| 13 | + NEWLINE = (tokenize.NL, '\n') |
| 14 | + result = [] |
| 15 | + entire_document = sublime.Region(0, self.view.size()) |
| 16 | + data_input = tokenize.tokenize(BytesIO(self.view.substr(entire_document).encode('utf-8')).readline) |
| 17 | + |
| 18 | + for token in data_input: |
| 19 | + if token.type == tokenize.OP: |
| 20 | + if token.exact_type in [tokenize.LBRACE, tokenize.LSQB]: |
| 21 | + result.append(self.indent()) |
| 22 | + result.append((token.exact_type, token.string)) |
| 23 | + result.append(NEWLINE) |
| 24 | + self.indentation_level += 1 |
| 25 | + elif token.exact_type in [tokenize.RBRACE, tokenize.RSQB]: |
| 26 | + if result[-1] != NEWLINE: |
| 27 | + result.append(NEWLINE) |
| 28 | + self.indentation_level -= 1 |
| 29 | + result.append(self.indent()) |
| 30 | + result.append((token.exact_type, token.string)) |
| 31 | + elif token.exact_type == tokenize.COLON: |
| 32 | + result.append((token.exact_type, token.string)) |
| 33 | + result.append((tokenize.STRING, ' ')) |
| 34 | + elif token.exact_type == tokenize.COMMA: |
| 35 | + result.append((token.exact_type, token.string)) |
| 36 | + result.append(NEWLINE) |
| 37 | + else: |
| 38 | + result.append((token.exact_type, token.string)) |
| 39 | + elif token.type != tokenize.NL: |
| 40 | + result.append(self.indent()) |
| 41 | + result.append((token.exact_type, token.string)) |
| 42 | + |
| 43 | + result.append(NEWLINE) |
| 44 | + self.view.replace(edit, entire_document, tokenize.untokenize(result).decode('utf-8')) |
0 commit comments