1 ! Copyright (C) 2009 Daniel Ehrenberg
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors arrays combinators combinators.short-circuit
4 fry kernel kernel.private lists locals math sequences typed ;
7 ! black is the text length, white is the whitespace length
8 TUPLE: element contents black white ;
13 : element-length ( element -- n )
14 [ black>> ] [ white>> ] bi + ; inline
16 TUPLE: paragraph line-max line-ideal lines head-width tail-cost ;
17 C: <paragraph> paragraph
19 TYPED: top-fits? ( paragraph: paragraph -- ? )
21 [ dup lines>> 1list? [ line-ideal>> ] [ line-max>> ] if ] bi <= ; inline
23 TYPED: fits? ( paragraph: paragraph -- ? )
24 ! Make this not count spaces at end
25 { [ lines>> car 1list? ] [ top-fits? ] } 1|| ; inline
27 :: min-by ( seq quot -- elt )
28 f 1/0. seq [| key value newkey |
29 newkey quot call :> newvalue
30 newvalue value < [ newkey newvalue ] [ key value ] if
33 TYPED: paragraph-cost ( paragraph: paragraph -- cost )
34 dup lines>> 1list? [ drop 0 ] [
35 [ [ head-width>> ] [ line-ideal>> ] bi - sq ]
39 : min-cost ( paragraphs -- paragraph )
40 [ paragraph-cost ] min-by ; inline
42 TYPED: new-line ( paragraph: paragraph element: element -- paragraph )
44 [ drop [ line-max>> ] [ line-ideal>> ] bi ]
45 [ [ lines>> ] [ 1list ] bi* swons ]
47 [ drop paragraph-cost ]
48 } 2cleave <paragraph> ; inline
50 TYPED: add-element ( paragraph: paragraph element: element -- )
51 [ element-length [ + ] curry change-head-width ]
52 [ [ [ unswons ] dip swons swons ] curry change-lines ]
55 TYPED: wrap-step ( paragraphs: array element: element -- paragraphs )
56 [ [ min-cost ] dip new-line ]
57 [ dupd '[ _ add-element ] each ]
58 2bi swap prefix { array } declare
61 : 1paragraph ( line-max line-ideal element -- paragraph )
62 [ 1list 1list ] [ black>> ] bi 0 <paragraph> ;
64 : post-process ( paragraph -- array )
65 lines>> [ [ contents>> ] lmap>array ] lmap>array ;
67 : initialize ( line-max line-ideal elements -- elements paragraph )
68 reverse unclip [ -rot ] dip 1paragraph 1array ;
72 : wrap ( elements line-max line-ideal -- array )