Created
May 9, 2019 19:16
-
-
Save kodo-pp/89cefb17a8772cd9fd7b875d94fd29c7 to your computer and use it in GitHub Desktop.
Pretty-print multiple levels of nested braces
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 | |
import sys | |
linechar = '\x1b[92m|\x1b[0m' if sys.stdout.isatty() else '|' | |
def indent(nest): | |
sys.stdout.write('{} '.format(linechar) * nest) | |
def main(): | |
s = sys.stdin.read() | |
nest = 0 | |
comma = False | |
for c in s: | |
if c != ' ': | |
if comma: | |
comma = False | |
sys.stdout.write('\n') | |
indent(nest) | |
if c in '[({<': | |
sys.stdout.write(c + '\n') | |
nest += 1 | |
indent(nest) | |
elif c in '])}>': | |
sys.stdout.write('\n') | |
nest -= 1 | |
indent(nest) | |
sys.stdout.write(c) | |
elif c == ',': | |
comma = True | |
sys.stdout.write(',') | |
elif c != ' ': | |
sys.stdout.write(c) | |
elif c == ' ': | |
if not comma or nest <= 0: | |
sys.stdout.write(c) | |
if __name__ == '__main__': | |
main() |
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
$ cat test.txt | |
foo: {bar, (baz, abc, def, d[a, b, ccc]), [13, 24, f(24)]} | |
$ bracefilter < test.txt | |
foo: { | |
| bar, | |
| ( | |
| | baz, | |
| | abc, | |
| | def, | |
| | d[ | |
| | | a, | |
| | | b, | |
| | | ccc | |
| | ] | |
| ), | |
| [ | |
| | 13, | |
| | 24, | |
| | f( | |
| | | 24 | |
| | ) | |
| ] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment