1 ! Copyright (C) 2009 Daniel Ehrenberg
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: kernel sequences math arrays locals fry accessors
4 lists splitting call make combinators.short-circuit namespaces
5 grouping splitting.monotonic ;
8 ! black is the text length, white is the whitespace length
9 TUPLE: element contents black white ;
12 : element-length ( element -- n )
13 [ black>> ] [ white>> ] bi + ;
15 TUPLE: paragraph lines head-width tail-cost ;
16 C: <paragraph> paragraph
21 : deviation ( length -- n )
24 : top-fits? ( paragraph -- ? )
26 [ lines>> 1list? line-ideal line-max ? get ] bi <= ;
28 : fits? ( paragraph -- ? )
29 ! Make this not count spaces at end
30 { [ lines>> car 1list? ] [ top-fits? ] } 1|| ;
32 :: min-by ( seq quot -- elt )
33 f 1.0/0.0 seq [| key value new |
34 new quot call :> newvalue
35 newvalue value < [ new newvalue ] [ key value ] if
38 : paragraph-cost ( paragraph -- cost )
39 dup lines>> 1list? [ drop 0 ] [
40 [ head-width>> deviation ]
44 : min-cost ( paragraphs -- paragraph )
45 [ paragraph-cost ] min-by ;
47 : new-line ( paragraph element -- paragraph )
48 [ [ lines>> ] [ 1list ] bi* swons ]
50 [ drop paragraph-cost ] 2tri
53 : glue ( paragraph element -- paragraph )
54 [ [ lines>> unswons ] dip swons swons ]
55 [ [ head-width>> ] [ element-length ] bi* + ]
56 [ drop tail-cost>> ] 2tri
59 : wrap-step ( paragraphs element -- paragraphs )
61 [ [ min-cost ] dip new-line ]
65 : 1paragraph ( element -- paragraph )
70 : post-process ( paragraph -- array )
71 lines>> deep-list>array
72 [ [ contents>> ] map ] map ;
74 : initialize ( elements -- elements paragraph )
75 <reversed> unclip-slice 1paragraph 1array ;
77 : wrap ( elements line-max line-ideal -- paragraph )