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 : swons ( cdr car -- cons )
18 : unswons ( cons -- cdr car )
21 : 1list? ( list -- ? )
22 { [ ] [ cdr +nil+ = ] } 1&& ;
24 : lists>arrays ( lists -- arrays )
25 [ list>seq ] lmap>array ;
27 TUPLE: paragraph lines head-width tail-cost ;
28 C: <paragraph> paragraph
33 : deviation ( length -- n )
36 : top-fits? ( paragraph -- ? )
38 [ lines>> 1list? line-ideal line-max ? get ] bi <= ;
40 : fits? ( paragraph -- ? )
41 ! Make this not count spaces at end
42 { [ lines>> car 1list? ] [ top-fits? ] } 1|| ;
44 :: min-by ( seq quot -- elt )
45 f 1.0/0.0 seq [| key value new |
46 new quot call :> newvalue
47 newvalue value < [ new newvalue ] [ key value ] if
50 : paragraph-cost ( paragraph -- cost )
51 [ head-width>> deviation ]
52 [ tail-cost>> ] bi + ;
54 : min-cost ( paragraphs -- paragraph )
55 [ paragraph-cost ] min-by ;
57 : new-line ( paragraph element -- paragraph )
58 [ [ lines>> ] [ 1list ] bi* swons ]
60 [ drop paragraph-cost ] 2tri
63 : glue ( paragraph element -- paragraph )
64 [ [ lines>> unswons ] dip swons swons ]
65 [ [ head-width>> ] [ element-length ] bi* + ]
66 [ drop tail-cost>> ] 2tri
69 : wrap-step ( paragraphs element -- paragraphs )
71 [ [ min-cost ] dip new-line ]
75 : 1paragraph ( element -- paragraph )
80 : post-process ( paragraph -- array )
82 [ [ contents>> ] map ] map ;
84 : initialize ( elements -- elements paragraph )
85 <reversed> unclip-slice 1paragraph 1array ;
87 : wrap ( elements line-max line-ideal -- paragraph )