]> gitweb.factorcode.org Git - factor.git/blob - basis/wrap/wrap.factor
Merge branch 'master' of git://factorcode.org/git/factor
[factor.git] / basis / wrap / wrap.factor
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 make combinators.short-circuit namespaces
5 grouping splitting.monotonic ;
6 IN: wrap
7
8 ! black is the text length, white is the whitespace length
9 TUPLE: element contents black white ;
10 C: <element> element
11
12 : element-length ( element -- n )
13     [ black>> ] [ white>> ] bi + ;
14
15 TUPLE: paragraph lines head-width tail-cost ;
16 C: <paragraph> paragraph
17
18 SYMBOL: line-max
19 SYMBOL: line-ideal
20
21 : deviation ( length -- n )
22     line-ideal get - sq ;
23
24 : top-fits? ( paragraph -- ? )
25     [ head-width>> ]
26     [ lines>> 1list? line-ideal line-max ? get ] bi <= ;
27
28 : fits? ( paragraph -- ? )
29     ! Make this not count spaces at end
30     { [ lines>> car 1list? ] [ top-fits? ] } 1|| ;
31
32 :: min-by ( seq quot -- elt )
33     f 1/0. seq [| key value new |
34         new quot call :> newvalue
35         newvalue value < [ new newvalue ] [ key value ] if
36     ] each drop ; inline
37
38 : paragraph-cost ( paragraph -- cost )
39     dup lines>> 1list? [ drop 0 ] [
40         [ head-width>> deviation ]
41         [ tail-cost>> ] bi +
42     ] if ;
43
44 : min-cost ( paragraphs -- paragraph )
45     [ paragraph-cost ] min-by ;
46
47 : new-line ( paragraph element -- paragraph )
48     [ [ lines>> ] [ 1list ] bi* swons ]
49     [ nip black>> ]
50     [ drop paragraph-cost ] 2tri
51     <paragraph> ;
52
53 : glue ( paragraph element -- paragraph )
54     [ [ lines>> unswons ] dip swons swons ]
55     [ [ head-width>> ] [ element-length ] bi* + ]
56     [ drop tail-cost>> ] 2tri
57     <paragraph> ;
58
59 : wrap-step ( paragraphs element -- paragraphs )
60     [ '[ _ glue ] map ]
61     [ [ min-cost ] dip new-line ]
62     2bi prefix
63     [ fits? ] filter ;
64
65 : 1paragraph ( element -- paragraph )
66     [ 1list 1list ]
67     [ black>> ] bi
68     0 <paragraph> ;
69
70 : post-process ( paragraph -- array )
71     lines>> [ [ contents>> ] lmap>array ] lmap>array ;
72
73 : initialize ( elements -- elements paragraph )
74     <reversed> unclip-slice 1paragraph 1array ;
75
76 : wrap ( elements line-max line-ideal -- paragraph )
77     [
78         line-ideal set
79         line-max set
80         [ { } ] [
81             initialize
82             [ wrap-step ] reduce
83             min-cost
84             post-process
85         ] if-empty
86     ] with-scope ;