Created
August 18, 2024 02:38
-
-
Save andydude/50c81f693cc74c366070be62149aad02 to your computer and use it in GitHub Desktop.
indent-sexpr
This file contains hidden or 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
#!/usr/bin/env python3 | |
import hy | |
import io | |
TAB = " " | |
class Writer: | |
indent: int = -1 | |
def __init__(self): | |
self.indent = 0 | |
def visit(self, obj): | |
if isinstance(obj, hy.models.Expression): | |
s = self.visit_list(obj) | |
s2 = self.visit_atom(obj) | |
if len(s2) < 40: | |
s = s2 | |
return s | |
else: | |
return self.visit_atom(obj) | |
def visit_atom(self, obj): | |
s = hy.repr(obj) | |
s = s.replace('\t', ' ') | |
s = s.replace('\n', ' ') | |
for j in range(5): | |
s = s.replace(' ', ' ') | |
if s.startswith("'"): | |
s = s[1:] | |
return s | |
def visit_list(self, ls): | |
o = io.StringIO() | |
self.on_indent(1) | |
o.write("(") | |
nhead = self.get_head(ls) | |
for k, i in enumerate(ls): | |
if k > 0: | |
if k < nhead: | |
o.write(" ") | |
else: | |
o.write(self.get_newline()) | |
s = self.visit(i) | |
o.write(s) | |
o.write(")") | |
self.on_dedent(1) | |
return o.getvalue() | |
def get_head(self, ls): | |
# TODO add special processing | |
# for define, case, etc... | |
return 2 | |
def get_newline(self): | |
global TAB | |
return "\n" + (TAB * self.indent) | |
def on_indent(self, n=1): | |
self.indent += n | |
def on_dedent(self, n=1): | |
self.indent -= n | |
if __name__ == '__main__': | |
import sys | |
writer = Writer() | |
ins = "(list " + sys.stdin.read() + ")" | |
ins = ins.replace("#t", "True") | |
ins = ins.replace("#f", "False") | |
obj = hy.read(ins) | |
for k, i in enumerate(obj[1:]): | |
if k > 0: | |
print("") | |
outs = writer.visit(i) | |
outs = outs.replace("True", "#t") | |
outs = outs.replace("False", "#f") | |
print(outs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment