Skip to content

Instantly share code, notes, and snippets.

@spdskatr
Created March 3, 2019 11:30
Show Gist options
  • Save spdskatr/39df3b5a88110447d956410eac456449 to your computer and use it in GitHub Desktop.
Save spdskatr/39df3b5a88110447d956410eac456449 to your computer and use it in GitHub Desktop.
Makes your C++ code look a whole lot prettier. Usage: `./cpp_formatter.py (L|R|J) <width>`
#!/usr/bin/env python2
# "Justifies" your C++ code
# Warning: It might split some strings in half :P
import sys
inp = sys.stdin
out = sys.stdout
tp = sys.argv[1]
w = int(sys.argv[2])
l, wl = '', []
tt = inp.read()
wl = tt.strip().split("\n")
limit = 0
ll = [[0, []]]
for l in wl:
if l.strip().startswith("#") or l.strip().startswith("//"):
ll.append([len(l.split()) + len([c for c in l if not c.isspace()]), l.split()])
ll.append([0, []])
limit = max(limit, len(l))
continue
for wd in l.split():
ln = len(wd)
limit = max(limit, ln)
if ll[-1][0] + ln > w:
ll.append([ln+1, [wd]])
else:
ll[-1][0] += ln+1
ll[-1][1].append(wd)
if tp == 'L':
for le in ll:
if le[0] == 0: continue
out.write(" ".join(le[1]) + "\n")
if tp == 'R':
for le in ll:
if le[0] == 0: continue
out.write(" " * (w - le[0] + 1) + " ".join(le[1]) + "\n")
if tp == 'J':
if w < limit:
sys.stderr.write("Warning: width %d is smaller than required limit %d\n" % (w, limit))
for i, le in enumerate(ll):
if le[0] == 0: continue
if len(le[1]) == 1:
out.write(le[1][0] + "\n")
continue
#if i == len(ll) - 1:
# out.write(" ".join(le[1]) + "\n")
# continue
s, dv = "", (w - le[0] + len(le[1]))
qu, rm = dv // (len(le[1]) - 1), dv % (len(le[1]) - 1)
for i, wd in enumerate(le[1]):
if i < rm:
s += wd + " " * (qu+1)
else:
s += wd + " " * qu
assert(len(s.strip()) == w)
out.write(s.strip() + "\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment