# Text utilities: Myers diff with unified output, Levenshtein distance, and word wrap by display width. import Base import bend-kit-unicode@0.1.0.0/unicode.bend as Unicode import bend-kit-tty@0.1.0.1/text.bend as Tty # ---- edit scripts # Same pairs an old item with the new item it matched; before keeps old items, after keeps new ones. type Edit<-A: Data> is Data: Same{old: A, new: A} Del{old: A} Ins{new: A} type Move is Data: MSame{} MDel{} MIns{} def before(-A: Data, es: List<&2, Edit>) -> List<&2, A>: match es: case Nil{}: Nil{} case Con{Same{o, n}, t}: o <> before(A, t) case Con{Del{o}, t}: o <> before(A, t) case Con{Ins{n}, t}: before(A, t) def after(-A: Data, es: List<&2, Edit>) -> List<&2, A>: match es: case Nil{}: Nil{} case Con{Same{o, n}, t}: n <> after(A, t) case Con{Del{o}, t}: after(A, t) case Con{Ins{n}, t}: n <> after(A, t) def walk.ins(-A: Data, b: List<&2, A>) -> List<&2, Edit>: match b: case Nil{}: Nil{} case Con{y, t}: Ins{y} <> walk.ins(A, t) def walk.rest(-A: Data, a: List<&2, A>, b: List<&2, A>) -> List<&2, Edit>: match a: case Nil{}: walk.ins(A, b) case Con{x, t}: Del{x} <> walk.rest(A, t, b) # Replays moves over a and b. A move that does not fit is skipped, and leftovers become Del then Ins, # so before and after give a and b back for any moves. def walk(-A: Data, ms: List<&2, Move>, a: List<&2, A>, b: List<&2, A>) -> List<&2, Edit>: match ms a b: case Nil{} _ _: walk.rest(A, a, b) case Con{MSame{}, t} Con{x, xs} Con{y, ys}: Same{x, y} <> walk(A, t, xs, ys) case Con{MDel{}, t} Con{x, xs} _: Del{x} <> walk(A, t, xs, b) case Con{MIns{}, t} _ Con{y, ys}: Ins{y} <> walk(A, t, a, ys) case Con{_, t} _ _: walk(A, t, a, b) # ---- Myers O(ND) diff in linear space # The furthest point reached on one diagonal: x and y items consumed, a and b the rest. type Tip<-A: Data> is Data: Dead{} Tip{x: U32, y: U32, a: List<&2, A>, b: List<&2, A>} def heads(~A: Data, ~eq: A -> A -> Bool, +a: List<&2, A>, +b: List<&2, A>) -> Bool: match a b: case Con{x, _} Con{y, _}: eq(x, y) case _ _: False{} # more says whether the heads of a and b match. def snake(~A: Data, ~eq: A -> A -> Bool, a: List<&2, A>, more: Bool, b: List<&2, A>, +x: U32, +y: U32) -> Tip: match a more b: case Con{_, +t} True{} Con{_, +u}: snake(~A, ~eq, t, heads(~A, ~eq, t, u), u, (x + 1 : U32), (y + 1 : U32)) case _ _ _: Tip{x, y, a, b} def slide(~A: Data, ~eq: A -> A -> Bool, tip: Tip) -> Tip: match tip: case Dead{}: Dead{} case Tip{x, y, +a, +b}: snake(~A, ~eq, a, heads(~A, ~eq, a, b), b, x, y) def tip.del(-A: Data, tip: Tip) -> Tip: match tip: case Tip{x, y, Con{_, t}, b}: Tip{(x + 1 : U32), y, t, b} case _: Dead{} def tip.ins(-A: Data, tip: Tip) -> Tip: match tip: case Tip{x, y, a, Con{_, u}}: Tip{x, (y + 1 : U32), a, u} case _: Dead{} def tip.reach(-A: Data, +tip: Tip, +step: U32) -> U32: match tip: case Dead{}: 0 case Tip{x, _, _, _}: (x + step : U32) # The first tip, or the other one moved when the first is Dead. def choose.or(-A: Data, ins: Bool, first: Tip, other: Tip) -> Tip: match ins first: case True{} Dead{}: tip.ins(A, other) case False{} Dead{}: tip.del(A, other) case _ _: first def choose.pick(-A: Data, down: Bool, prev: Tip, next: Tip) -> Tip: match down: case True{}: choose.or(A, False{}, tip.ins(A, next), prev) case False{}: choose.or(A, True{}, tip.del(A, prev), next) # Myers' rule for diagonal k: go down from next (k+1) when V[k-1] < V[k+1], else right from prev (k-1). def choose(-A: Data, +prev: Tip, +next: Tip) -> Tip: choose.pick(A, U32.is_le(tip.reach(A, prev, 1), tip.reach(A, next, 0)), prev, next) def step.mid(~A: Data, ~eq: A -> A -> Bool, ts: List<&2, Tip>, +prev: Tip) -> List<&2, Tip>: match ts: case Nil{}: [slide(~A, ~eq, tip.del(A, prev))] case Con{+t, rest}: slide(~A, ~eq, choose(A, prev, t)) <> step.mid(~A, ~eq, rest, t) # Diagonals -d..d, low k first, become -(d+1)..d+1. def step(~A: Data, ~eq: A -> A -> Bool, ts: List<&2, Tip>) -> List<&2, Tip>: match ts: case Nil{}: Nil{} case Con{+t, rest}: slide(~A, ~eq, tip.ins(A, t)) <> step.mid(~A, ~eq, rest, t) # A point on a shortest path, and the items after it. type Split<-A: Data> is Data: Split{x: U32, y: U32, a: List<&2, A>, b: List<&2, A>} type Dec is Data: AdvF{} AdvR{} Hit{} End{} def decide.cmp(+l: U32, +r: U32, +reach: Bool) -> Dec: Bool.pick(Dec, U32.is_lt(l, r), AdvF{}, Bool.pick(Dec, U32.is_lt(r, l), AdvR{}, Bool.pick(Dec, reach, Hit{}, AdvF{}))) # f holds forward tips by ascending k = x - y. r holds reverse tips by ascending forward diagonal N - M - k'. # Both diagonals match when x1 - y1 = (n - m) - (x2 - y2), written without subtraction. def decide(-A: Data, +f: List<&2, Tip>, +r: List<&2, Tip>, +n: U32, +m: U32) -> Dec: match f r: case Con{Dead{}, _} _: AdvF{} case _ Con{Dead{}, _}: AdvR{} case Con{Tip{+x1, +y1, _, _}, _} Con{Tip{+x2, +y2, _, _}, _}: decide.cmp((x1 + x2 + m : U32), (y1 + y2 + n : U32), U32.is_le(n, (x1 + x2 : U32))) case _ _: End{} def overlap.hit(-A: Data, +f: List<&2, Tip>) -> Maybe<&2, Split>: match f: case Con{Tip{x, y, a, b}, _}: Some{Split{x, y, a, b}} case _: None{} def overlap.go(-A: Data, fuel: Nat, d: Dec, +f: List<&2, Tip>, +r: List<&2, Tip>, +n: U32, +m: U32) -> Maybe<&2, Split>: match fuel d: case 1n+p AdvF{}: +ft = List.tail(&2, Tip, f) overlap.go(A, p, decide(A, ft, r, n, m), ft, r, n, m) case 1n+p AdvR{}: +rt = List.tail(&2, Tip, r) overlap.go(A, p, decide(A, f, rt, n, m), f, rt, n, m) case _ Hit{}: overlap.hit(A, f) case _ _: None{} # The forward tip whose diagonal the reverse frontier has passed, if any. def overlap(-A: Data, +fuel: Nat, +f: List<&2, Tip>, +r: List<&2, Tip>, +n: U32, +m: U32) -> Maybe<&2, Split>: overlap.go(A, fuel, decide(A, f, r, n, m), f, r, n, m) def overlap.pick(-A: Data, odd: Bool, +fuel: Nat, +f: List<&2, Tip>, r0: List<&2, Tip>, r1: List<&2, Tip>, +n: U32, +m: U32) -> Maybe<&2, Split>: match odd: case True{}: overlap(A, fuel, f, r0, n, m) case False{}: overlap(A, fuel, f, r1, n, m) def step.desc.mid(~A: Data, ~eq: A -> A -> Bool, ts: List<&2, Tip>, +prev: Tip) -> List<&2, Tip>: match ts: case Nil{}: [slide(~A, ~eq, tip.ins(A, prev))] case Con{+t, rest}: slide(~A, ~eq, choose(A, t, prev)) <> step.desc.mid(~A, ~eq, rest, t) # step for a frontier kept high k first, so the reverse frontier lines up with the forward one. def step.desc(~A: Data, ~eq: A -> A -> Bool, ts: List<&2, Tip>) -> List<&2, Tip>: match ts: case Nil{}: Nil{} case Con{+t, rest}: slide(~A, ~eq, tip.del(A, t)) <> step.desc.mid(~A, ~eq, rest, t) # Myers' middle snake: grow d-paths from both ends. When N - M is odd, a forward d-path is checked # against the reverse (d-1)-paths; when even, against the reverse d-paths. def bisect(~A: Data, ~eq: A -> A -> Bool, fuel: Nat, found: Maybe<&2, Split>, +odd: Bool, +of: Nat, f: List<&2, Tip>, +r: List<&2, Tip>, +n: U32, +m: U32) -> Maybe<&2, Split>: match fuel found: case _ Some{s}: Some{s} case 0n None{}: None{} case 1n+p None{}: +f2 = step(~A, ~eq, f) +r2 = step.desc(~A, ~eq, r) bisect(~A, ~eq, p, overlap.pick(A, odd, of, f2, r, r2, n, m), odd, of, f2, r2, n, m) def middle(~A: Data, ~eq: A -> A -> Bool, +a: List<&2, A>, +b: List<&2, A>) -> Maybe<&2, Split>: +n = U32.from_nat(List.length(&2, A, a)) +m = U32.from_nat(List.length(&2, A, b)) +odd = U32.is_eq(((n + m : U32) .&. 1 : U32), 1) +size = Nat.add(List.length(&2, A, a), List.length(&2, A, b)) +of = Nat.add(Nat.mul(2n, size), 4n) +f = {[slide(~A, ~eq, Tip{0, 0, a, b})] : List<&2, Tip>} +r = {[slide(~A, ~eq, Tip{0, 0, List.reverse(&2, A, a), List.reverse(&2, A, b)})] : List<&2, Tip>} bisect(~A, ~eq, 1n+size, overlap.pick(A, odd, of, f, Nil{}, r, n, m), odd, of, f, r, n, m) def common(~A: Data, ~eq: A -> A -> Bool, a: List<&2, A>, more: Bool, b: List<&2, A>, +k: Nat) -> Nat: match a more b: case Con{_, +t} True{} Con{_, +u}: common(~A, ~eq, t, heads(~A, ~eq, t, u), u, 1n+k) case _ _ _: k def prefix(~A: Data, ~eq: A -> A -> Bool, +a: List<&2, A>, +b: List<&2, A>) -> Nat: common(~A, ~eq, a, heads(~A, ~eq, a, b), b, 0n) # A segment still to diff, or moves ready to emit. type Job<-A: Data> is Data: JSolve{a: List<&2, A>, b: List<&2, A>} JEmit{ms: List<&2, Move>} def plan.split(-A: Data, s: Maybe<&2, Split>, +a: List<&2, A>, +b: List<&2, A>) -> List<&2, Job>: match s: case Some{Split{x, y, sa, sb}}: [JSolve{sa, sb}, JSolve{List.take(&2, A, a, U32.to_nat(x)), List.take(&2, A, b, U32.to_nat(y))}] case None{}: [JEmit{List.append(&2, Move, List.replicate(Move, List.length(&2, A, a), MDel{}), List.replicate(Move, List.length(&2, A, b), MIns{}))}] def plan.mid(~A: Data, ~eq: A -> A -> Bool, +a: List<&2, A>, +b: List<&2, A>) -> List<&2, Job>: match a b: case Nil{} _: [JEmit{List.replicate(Move, List.length(&2, A, b), MIns{})}] case _ Nil{}: [JEmit{List.replicate(Move, List.length(&2, A, a), MDel{})}] case _ _: plan.split(A, middle(~A, ~eq, a, b), a, b) def plan.trim(~A: Data, ~eq: A -> A -> Bool, +p: Nat, +a: List<&2, A>, +b: List<&2, A>) -> List<&2, Job>: +k = prefix(~A, ~eq, List.reverse(&2, A, a), List.reverse(&2, A, b)) +a2 = List.take(&2, A, a, Nat.sub(List.length(&2, A, a), k)) +b2 = List.take(&2, A, b, Nat.sub(List.length(&2, A, b), k)) JEmit{List.replicate(Move, k, MSame{})} <> List.append(&2, Job, plan.mid(~A, ~eq, a2, b2), [JEmit{List.replicate(Move, p, MSame{})}]) # Jobs for one segment, last first: the common suffix, the middle, then the common prefix. def plan(~A: Data, ~eq: A -> A -> Bool, +a: List<&2, A>, +b: List<&2, A>) -> List<&2, Job>: +p = prefix(~A, ~eq, a, b) plan.trim(~A, ~eq, p, List.drop(&2, A, a, p), List.drop(&2, A, b, p)) # Runs jobs from the end of the script back to its start, so each emit prepends. def solve(~A: Data, ~eq: A -> A -> Bool, fuel: Nat, js: List<&2, Job>, acc: List<&2, Move>) -> List<&2, Move>: match fuel js: case 1n+f Con{JSolve{a, b}, t}: solve(~A, ~eq, f, List.append(&2, Job, plan(~A, ~eq, a, b), t), acc) case 1n+f Con{JEmit{ms}, t}: solve(~A, ~eq, f, t, List.append(&2, Move, ms, acc)) case _ _: acc def canon.flush(d: Nat, i: Nat, rest: List<&2, Move>) -> List<&2, Move>: List.append(&2, Move, List.replicate(Move, d, MDel{}), List.append(&2, Move, List.replicate(Move, i, MIns{}), rest)) # Each run of changes puts its deletes first, as diff does. def canon(ms: List<&2, Move>, +d: Nat, +i: Nat) -> List<&2, Move>: match ms: case Nil{}: canon.flush(d, i, Nil{}) case Con{MSame{}, t}: canon.flush(d, i, MSame{} <> canon(t, 0n, 0n)) case Con{MDel{}, t}: canon(t, 1n+d, i) case Con{MIns{}, t}: canon(t, d, 1n+i) # Each split leaves two smaller segments, and each segment plans at most 4 jobs. def moves(~A: Data, ~eq: A -> A -> Bool, +a: List<&2, A>, +b: List<&2, A>) -> List<&2, Move>: +size = Nat.add(List.length(&2, A, a), List.length(&2, A, b)) canon(solve(~A, ~eq, Nat.add(Nat.mul(8n, size), 8n), [JSolve{a, b}], Nil{}), 0n, 0n) # A shortest edit script from a to b. eq decides which items match. def diff(~A: Data, ~eq: A -> A -> Bool, +a: List<&2, A>, +b: List<&2, A>) -> List<&2, Edit>: walk(A, moves(~A, ~eq, a, b), a, b) def lines.push(c: Char, ls: List<&2, String>) -> List<&2, String>: match ls: case Nil{}: [SCon{c, SNil{}}] case Con{h, t}: SCon{c, h} <> t def lines.pick(nl: Bool, c: Char, ls: List<&2, String>) -> List<&2, String>: match nl: case True{}: SCon{c, SNil{}} <> ls case False{}: lines.push(c, ls) # Lines with their "\n". Only the last line can lack one, and joining the lines gives s back. def lines(s: String) -> List<&2, String>: match s: case SNil{}: Nil{} case SCon{+c, t}: lines.pick(Char.is_eq(c, '\n'), c, lines(t)) def diff_lines(a: String, b: String) -> List<&2, Edit>: diff(~String, ~String.eq, lines(a), lines(b)) def diff_chars(a: String, b: String) -> List<&2, Edit>: diff(~Char, ~Char.is_eq, String.to_list(a), String.to_list(b)) # ---- unified output def far() -> U32: 1000000000 def ahead.next(+r: List<&2, U32>) -> U32: match r: case Nil{}: far() case Con{d, _}: U32.min((d + 1 : U32), far()) def ahead.cons(+change: Bool, +r: List<&2, U32>) -> List<&2, U32>: Bool.pick(U32, change, 0, ahead.next(r)) <> r def is_change(-A: Data, e: Edit) -> Bool: match e: case Same{_, _}: False{} case _: True{} # For each edit, how many edits ahead the next change is: 0 for a change. def ahead(-A: Data, es: List<&2, Edit>) -> List<&2, U32>: match es: case Nil{}: Nil{} case Con{+e, t}: ahead.cons(is_change(A, e), ahead(A, t)) # A Gap is a Same line outside every hunk. dold and dnew count the old and new lines a row consumes. type Row is Data: Gap{} Line{text: String, dold: U32, dnew: U32} def rows(es: List<&2, Edit>, ds: List<&2, U32>, +ctx: U32, +back: U32) -> List<&2, Row>: match es ds: case Con{Same{_, n}, t} Con{+d, dt}: +b = U32.min((back + 1 : U32), far()) Bool.pick(Row, U32.is_le(b, ctx) || U32.is_le(d, ctx), Line{" " ++ n, 1, 1}, Gap{}) <> rows(t, dt, ctx, b) case Con{Del{o}, t} Con{_, dt}: Line{"-" ++ o, 1, 0} <> rows(t, dt, ctx, 0) case Con{Ins{n}, t} Con{_, dt}: Line{"+" ++ n, 0, 1} <> rows(t, dt, ctx, 0) case _ _: Nil{} type Hunk is Data: Hunk{o: U32, n: U32, ol: U32, nl: U32, body: List<&2, String>} # GNU form: an empty range names the line before it, and a one-line range drops ",1". def range.pick(empty: Bool, +start: U32, +len: U32) -> String: match empty: case True{}: U32.show(start) ++ ",0" case False{}: Bool.pick(String, U32.is_eq(len, 1), U32.show((start + 1 : U32)), U32.show((start + 1 : U32)) ++ "," ++ U32.show(len)) def range(+start: U32, +len: U32) -> String: range.pick(U32.is_eq(len, 0), start, len) def hunk.show(h: Hunk) -> String: match h: case Hunk{o, n, ol, nl, body}: "@@ -" ++ range(o, ol) ++ " +" ++ range(n, nl) ++ " @@\n" ++ String.concat(List.reverse(&2, String, body)) def close(cur: Maybe<&2, Hunk>, out: List<&2, String>) -> List<&2, String>: match cur: case None{}: out case Some{h}: hunk.show(h) <> out def open(cur: Maybe<&2, Hunk>, +o: U32, +n: U32) -> Hunk: match cur: case None{}: Hunk{o, n, 0, 0, Nil{}} case Some{h}: h # Text whose line lacks "\n" is the last line of its file, as diff -u marks it. def eol(+text: String) -> String: Bool.pick(String, String.ends_with(text, "\n"), "", "\n\\ No newline at end of file\n") def hunk.add(h: Hunk, +text: String, +dold: U32, +dnew: U32) -> Hunk: match h: case Hunk{o, n, ol, nl, body}: Hunk{o, n, (ol + dold : U32), (nl + dnew : U32), (text ++ eol(text)) <> body} # o and n count the old and new lines before the row. def emit(rs: List<&2, Row>, +o: U32, +n: U32, cur: Maybe<&2, Hunk>, out: List<&2, String>) -> List<&2, String>: match rs: case Nil{}: close(cur, out) case Con{Gap{}, t}: emit(t, (o + 1 : U32), (n + 1 : U32), None{}, close(cur, out)) case Con{Line{text, +dold, +dnew}, t}: emit(t, (o + dold : U32), (n + dnew : U32), Some{hunk.add(open(cur, o, n), text, dold, dnew)}, out) def unified.fin(hs: List<&2, String>, old_name: String, new_name: String) -> String: match hs: case Nil{}: "" case Con{_, _}: "--- " ++ old_name ++ "\n+++ " ++ new_name ++ "\n" ++ String.concat(List.reverse(&2, String, hs)) # Unified diff text with ctx lines of context around each change; "" when nothing changed. # Each line must end with "\n" except the last line of a file, as lines() gives them. def unified(old_name: String, new_name: String, +es: List<&2, Edit>, +ctx: U32) -> String: unified.fin(emit(rows(es, ahead(String, es), ctx, far()), 0, 0, None{}, Nil{}), old_name, new_name) # ---- Levenshtein distance def lev.row(~A: Data, ~eq: A -> A -> Bool, b: List<&2, A>, up: List<&2, U32>, +x: A, +diag: U32, +left: U32) -> List<&2, U32>: match b up: case Con{+y, bt} Con{+u, ut}: +v = U32.min(U32.min((u + 1 : U32), (left + 1 : U32)), (diag + Bool.pick(U32, eq(x, y), 0, 1) : U32)) v <> lev.row(~A, ~eq, bt, ut, x, u, v) case _ _: Nil{} def lev.last(xs: List<&2, U32>, +d: U32) -> U32: match xs: case Nil{}: d case Con{+h, t}: lev.last(t, h) def lev.init(n: Nat, +i: U32) -> List<&2, U32>: match n: case 0n: [i] case 1n+p: i <> lev.init(p, (i + 1 : U32)) def lev.go(~A: Data, ~eq: A -> A -> Bool, a: List<&2, A>, +b: List<&2, A>, prev: List<&2, U32>, +i: U32) -> U32: match a prev: case Con{+x, at} Con{+p0, pt}: +j = (i + 1 : U32) lev.go(~A, ~eq, at, b, j <> lev.row(~A, ~eq, b, pt, x, p0, j), j) case _ _: lev.last(prev, 0) # Fewest inserts, deletes, and substitutions that turn a into b. def edit_distance(~A: Data, ~eq: A -> A -> Bool, a: List<&2, A>, +b: List<&2, A>) -> U32: lev.go(~A, ~eq, a, b, lev.init(List.length(&2, A, b), 0), 0) # Levenshtein distance by code point. def distance(a: String, b: String) -> U32: edit_distance(~Char, ~Char.is_eq, String.to_list(a), String.to_list(b)) # ---- word wrap def words.flush(cur: String, out: List<&2, String>) -> List<&2, String>: match cur: case SNil{}: out case SCon{h, t}: String.reverse(SCon{h, t}) <> out # cur holds the word being read, reversed. def words.step(sp: Bool, +c: Char, st: String & List<&2, String>) -> String & List<&2, String>: match sp: case True{}: (cur, out) = st (SNil{}, words.flush(cur, out)) case False{}: (cur, out) = st (SCon{c, cur}, out) def words.go(s: String, st: String & List<&2, String>) -> List<&2, String>: match s: case SNil{}: (cur, out) = st List.reverse(&2, String, words.flush(cur, out)) case SCon{+c, t}: words.go(t, words.step(Char.is_space(c), c, st)) # Runs of non-space chars. def words(s: String) -> List<&2, String>: words.go(s, (SNil{}, Nil{})) def fits(+line: String, +width: U32) -> Bool: U32.is_le(Tty.width(line), width) def single.of(gs: List<&2, String>) -> Bool: match gs: case Con{_, Nil{}}: True{} case _: False{} # One grapheme cluster: the only kind of line that may be wider than the width. def single(+s: String) -> Bool: single.of(Unicode.graphemes(s)) def ok.pick(f: Bool, +s: String) -> Bool: match f: case True{}: True{} case False{}: single(s) # What wrap promises for each line: it fits, or it is one grapheme cluster. def ok(+s: String, +width: U32) -> Bool: ok.pick(fits(s, width), s) # The finished lines, newest first, and the line being built. type Wr is Data: Wr{out: List<&2, String>, cur: Maybe<&2, String>} def step0.pick(f: Bool, out: List<&2, String>, s: String, +c: Char) -> Wr: match f: case True{}: Wr{out, Some{s ++ SCon{c, SNil{}}}} case False{}: Wr{s <> out, Some{SCon{c, SNil{}}}} def step0(st: Wr, +c: Char, +width: U32) -> Wr: match st: case Wr{out, None{}}: Wr{out, Some{SCon{c, SNil{}}}} case Wr{out, Some{+s}}: step0.pick(fits(s ++ SCon{c, SNil{}}, width), out, s, c) # Code points, for a piece that neither fits nor segments as one cluster. One code point is one cluster. def run0(s: String, +width: U32, st: Wr) -> Wr: match s: case SNil{}: st case SCon{c, t}: run0(t, width, step0(st, c, width)) def start1(ok: Bool, out: List<&2, String>, +g: String, +width: U32) -> Wr: match ok: case True{}: Wr{out, Some{g}} case False{}: run0(g, width, Wr{out, None{}}) def step1.pick(f: Bool, out: List<&2, String>, s: String, +g: String, +width: U32) -> Wr: match f: case True{}: Wr{out, Some{s ++ g}} case False{}: start1(ok(g, width), s <> out, g, width) def step1(st: Wr, +g: String, +width: U32) -> Wr: match st: case Wr{out, None{}}: start1(ok(g, width), out, g, width) case Wr{out, Some{+s}}: step1.pick(fits(s ++ g, width), out, s, g, width) # Grapheme clusters, for a word wider than the line. def run1(gs: List<&2, String>, +width: U32, st: Wr) -> Wr: match gs: case Nil{}: st case Con{g, t}: run1(t, width, step1(st, g, width)) def start2(ok: Bool, out: List<&2, String>, +w: String, +width: U32) -> Wr: match ok: case True{}: Wr{out, Some{w}} case False{}: run1(Unicode.graphemes(w), width, Wr{out, None{}}) def step2.pick(f: Bool, out: List<&2, String>, s: String, +w: String, +width: U32) -> Wr: match f: case True{}: Wr{out, Some{s ++ " " ++ w}} case False{}: start2(ok(w, width), s <> out, w, width) def step2(st: Wr, +w: String, +width: U32) -> Wr: match st: case Wr{out, None{}}: start2(ok(w, width), out, w, width) case Wr{out, Some{+s}}: step2.pick(fits(s ++ " " ++ w, width), out, s, w, width) def run2(ws: List<&2, String>, +width: U32, st: Wr) -> Wr: match ws: case Nil{}: st case Con{w, t}: run2(t, width, step2(st, w, width)) def wrap.lines(st: Wr) -> List<&2, String>: match st: case Wr{out, None{}}: List.reverse(&2, String, out) case Wr{out, Some{s}}: List.reverse(&2, String, s <> out) # Greedy word wrap to width display columns. Whitespace runs separate words; lines join words with one space. # Each candidate line is measured whole, so a cluster that spans a join counts right. A word wider than width # breaks between grapheme clusters; a cluster wider than width stays whole on its own line. def wrap(text: String, +width: U32) -> List<&2, String>: wrap.lines(run2(words(text), width, Wr{Nil{}, None{}}))