Created
June 11, 2022 20:01
-
-
Save greyblue9/db38858652593172523ad7979637e726 to your computer and use it in GitHub Desktop.
Brainfuck formatter (aggressive linebreaks versiom)
This file contains 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 | |
# bf_format - format brainfuck code listings using nested indentation | |
# originally from https://pastebin.com/raw/FN1YMQ6r | |
# updated 2019-05-26-09:23 comment out the lf insertion for ']' | |
# I think it looks better this way, also results in shorter listing | |
# updated 2022-06-11 convert to use argv, add '-i' arg | |
# and indent every [ and ] | |
from io import StringIO | |
from pathlib import Path | |
from sys import argv, stdout | |
if not argv[1:]: | |
argv.append("-") | |
inplace = False | |
for arg in argv[1:]: | |
if arg == "-i": | |
inplace = True | |
continue | |
if arg == "-": | |
file = open(0, "rb") | |
else: | |
file = Path(arg).open("rb") | |
with file: | |
text = file.read() | |
output = stdout | |
if inplace: | |
output = Path(arg).open("w", encoding="utf-8") | |
with StringIO(text.decode("utf-8")) as f: | |
ilv = -1 | |
ich = " " # indent character - four regular spaces | |
prog = "" # store the whole program in a variable | |
command_set = "><+-,.[]" | |
# read file | |
while True: | |
nextch = f.read(1) | |
if(not nextch): | |
f.close() | |
break | |
if(nextch in command_set): | |
prog += (nextch) | |
# format | |
for i in range(len(prog)): | |
if(prog[i] == "["): | |
print(file=output) | |
ilv += 1 | |
# print(ich * ilv + ": indented block") | |
print(ich * ilv, end = "", file=output) | |
print("[", end="", file=output) | |
print(file=output) # remove lf after ']' | |
print(ich * (ilv+1), end="", file=output) | |
continue | |
if(prog[i] == "]"): | |
print(file=output) # remove lf after ']' | |
print(ich * (ilv), end="", file=output) | |
print("]", end="", file=output) | |
print(file=output) # remove lf after ']' | |
print(ich * (ilv), end="", file=output) | |
ilv -= 1 | |
continue | |
print(prog[i], end = "", file=output) | |
if inplace: | |
output.close() | |
inplace = False | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment