Files
nx_post_support/server/src/common/formatter.py
T
2025-07-21 09:12:36 +02:00

64 lines
2.2 KiB
Python

import re
def format_tcl(src: str, indent_str=" ") -> str:
"""
Simple Tcl formatter with special handling for:
1) Single-line 'if {cond} {action}' blocks remain on one line.
2) Combined closing-and-opening lines like '} else {' dedent then re-indent.
3) Lines like '} Tag' stay on the same line: '} Tag'.
4) Standard multi-line blocks for 'if', 'elseif', 'else', '{', '}'.
"""
level = 0
out_lines = []
for raw_line in src.splitlines():
stripped = raw_line.strip()
# Comments are ignored
if stripped.startswith("#"):
out_lines.append(indent_str * level + stripped)
continue
# Single-line 'if {cond} {action}' → no indent change
if re.match(r"^(if|elseif)\s*\{[^}]+\}\s*\{[^}]+\}$", stripped):
out_lines.append(indent_str * level + stripped)
continue
# Combined '} else {' → dedent, print, then indent
if re.match(r"^\}\s*(elseif|else)\b.*\{$", stripped):
level = max(level - 1, 0)
out_lines.append(indent_str * level + stripped)
level += 1
continue
# SPECIAL: closing brace plus tag on same line: '} Tag'
m = re.match(r"^\}\s+(.+)", stripped)
if m and not stripped.startswith("#"):
# close one block
level = max(level - 1, 0)
# stay on one line: "} Tag"
out_lines.append(f"{indent_str * level}}} {m.group(1)}")
continue
# Pure '}' → dedent then print
if stripped == "}":
level = max(level - 1, 0)
out_lines.append(f"{indent_str * level}{stripped}")
continue
# 'elseif' or 'else' alone → align with matching 'if'
if re.match(r"^(elseif|else)\b(?!.*\{)", stripped):
level = max(level - 1, 0)
out_lines.append(f"{indent_str * level}{stripped}")
continue
# Default: print at current indent
out_lines.append(f"{indent_str * level}{stripped}")
# Open a new block on lines ending with '{'
if re.match(r"^(if|elseif)\b.*\{$", stripped) or stripped.endswith("{"):
level += 1
return "\n".join(out_lines)