Skip to content

Instantly share code, notes, and snippets.

@greyblue9
Created June 11, 2022 19:35
Show Gist options
  • Save greyblue9/fae65af97ff1dbfd54cec8ef4b1d5396 to your computer and use it in GitHub Desktop.
Save greyblue9/fae65af97ff1dbfd54cec8ef4b1d5396 to your computer and use it in GitHub Desktop.
Format brainfuck code listings using nested indentation
#!/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
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, end = "", file=output)
if(prog[i] == "]"):
# print() # remove lf after ']'
# print(ich * ilv, end = "")
ilv -= 1
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