Stefan Ram
2024-08-05 13:09:16 UTC
During my grub sesh today, I crushed out TeX's line breaking
in Python in like a hot minute - 36 to be exact. Tryna use
it for plain text, like, monospaced fonts and whatnot. Natch,
I stripped it down to the bare bones, but it's still hella
tight. Already got that "parshape" action goin' on (which
Knuth-Plass can't hang with, if I'm not trippin'). Next up,
I'm finna tackle those "discretionary items" - that's gonna be
gnarly! For sure there's some janky bugs in there, but peep this:
wrap.py
source = 'Ich habe das gebackene Profi-Bettuch bereits gesehen. '
active0 =[ 0, 0, 0, 0 ] # previous, position, quality, line_number
active =[ active0 ]
parshape =[ 10, 20, 20, 20, 20, 20, 20, 20 ]
p = 1
while p < len( source ):
ch = source[ p ]
if ch == ' ':
new_active = []
best_quality = -10000
best_act = active[ 0 ]
for act in active:
a = act[ 1 ]
line_number = act[ 3 ]
target_length = parshape[ line_number ]
this_length = p - a
if this_length > target_length:
pass
else:
quality = this_length - target_length
new_active.append( act )
if quality > best_quality:
best_quality = quality
best_act = act
new_active.append( [ best_act, p, best_quality, best_act[ 3 ]+1 ] )
active = new_active
p += 1
act = active[ -1 ]
buff = []
while act[ 0 ]:
prev = act[ 0 ]
buff.append( source[ prev[1]: act[1] ])
act = prev
for line in reversed( buff ):
print(line)
output
Ich habe das
gebackene Profi-Bettuch
bereits gesehen.
in Python in like a hot minute - 36 to be exact. Tryna use
it for plain text, like, monospaced fonts and whatnot. Natch,
I stripped it down to the bare bones, but it's still hella
tight. Already got that "parshape" action goin' on (which
Knuth-Plass can't hang with, if I'm not trippin'). Next up,
I'm finna tackle those "discretionary items" - that's gonna be
gnarly! For sure there's some janky bugs in there, but peep this:
wrap.py
source = 'Ich habe das gebackene Profi-Bettuch bereits gesehen. '
active0 =[ 0, 0, 0, 0 ] # previous, position, quality, line_number
active =[ active0 ]
parshape =[ 10, 20, 20, 20, 20, 20, 20, 20 ]
p = 1
while p < len( source ):
ch = source[ p ]
if ch == ' ':
new_active = []
best_quality = -10000
best_act = active[ 0 ]
for act in active:
a = act[ 1 ]
line_number = act[ 3 ]
target_length = parshape[ line_number ]
this_length = p - a
if this_length > target_length:
pass
else:
quality = this_length - target_length
new_active.append( act )
if quality > best_quality:
best_quality = quality
best_act = act
new_active.append( [ best_act, p, best_quality, best_act[ 3 ]+1 ] )
active = new_active
p += 1
act = active[ -1 ]
buff = []
while act[ 0 ]:
prev = act[ 0 ]
buff.append( source[ prev[1]: act[1] ])
act = prev
for line in reversed( buff ):
print(line)
output
Ich habe das
gebackene Profi-Bettuch
bereits gesehen.