formatter.py: stuff more logic into variables

This commit is contained in:
gregorni 2023-09-17 12:18:22 +02:00
parent 025f2d4dae
commit aac03a02d9

View file

@ -60,6 +60,7 @@ class Format:
watch_parentheses = False watch_parentheses = False
parentheses_balance = 0 parentheses_balance = 0
bracket_tracker = [None] bracket_tracker = [None]
last_added_char = ""
def another_newline(one_indent_less=False): def another_newline(one_indent_less=False):
nonlocal end_str nonlocal end_str
@ -75,23 +76,26 @@ class Format:
def commit_current_line( def commit_current_line(
two_newlines=False, line_type=prev_line_type, indent_decrease=False two_newlines=False, line_type=prev_line_type, indent_decrease=False
): ):
nonlocal end_str, current_line, prev_line_type nonlocal end_str, current_line, prev_line_type, last_added_char
whitespace_to_add = "\n" + (indent_levels * indent_item)
if indent_decrease: if indent_decrease:
end_str = end_str.strip() + "\n" + (indent_levels * indent_item) end_str = end_str.strip() + whitespace_to_add
if two_newlines: if two_newlines:
another_newline( another_newline(
not ( not (
current_line[-1] == ";" current_line[-1] == ";"
and end_str.strip()[-1] in CLOSING_TOKENS and last_added_char in CLOSING_TOKENS
) )
) )
end_str += current_line + "\n" + (indent_levels * indent_item) end_str += current_line + whitespace_to_add
current_line = "" current_line = ""
prev_line_type = line_type prev_line_type = line_type
last_added_char = end_str.strip()[-1]
for item in tokens: for item in tokens:
if item.type != tokenizer.TokenType.WHITESPACE: if item.type != tokenizer.TokenType.WHITESPACE:
@ -139,7 +143,7 @@ class Format:
commit_current_line( commit_current_line(
not ( not (
prev_line_type == LineType.CHILD_TYPE prev_line_type == LineType.CHILD_TYPE
or end_str.strip()[-1] in OPENING_TOKENS or last_added_char in OPENING_TOKENS
), ),
LineType.BLOCK_OPEN, LineType.BLOCK_OPEN,
) )
@ -190,7 +194,7 @@ class Format:
if len(bracket_tracker) > 0: if len(bracket_tracker) > 0:
if bracket_tracker[-1] == "[" and str_item == ",": if bracket_tracker[-1] == "[" and str_item == ",":
if end_str.strip()[-1] not in ["[", ","]: if last_added_char not in ["[", ","]:
end_str = end_str.strip() end_str = end_str.strip()
commit_current_line() commit_current_line()