]> gitweb.factorcode.org Git - factor.git/blob - basis/wrap/wrap.factor
Merge branch 'master' into fortran
[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 call 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 : swons ( cdr car -- cons )
16     swap cons ;
17
18 : unswons ( cons -- cdr car )
19     [ cdr ] [ car ] bi ;
20
21 : 1list? ( list -- ? )
22     { [ ] [ cdr +nil+ = ] } 1&& ;
23
24 : lists>arrays ( lists -- arrays )
25     [ list>seq ] lmap>array ;
26
27 TUPLE: paragraph lines head-width tail-cost ;
28 C: <paragraph> paragraph
29
30 SYMBOL: line-max
31 SYMBOL: line-ideal
32
33 : deviation ( length -- n )
34     line-ideal get - sq ;
35
36 : top-fits? ( paragraph -- ? )
37     [ head-width>> ]
38     [ lines>> 1list? line-ideal line-max ? get ] bi <= ;
39
40 : fits? ( paragraph -- ? )
41     ! Make this not count spaces at end
42     { [ lines>> car 1list? ] [ top-fits? ] } 1|| ;
43
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
48     ] each drop ; inline
49
50 : paragraph-cost ( paragraph -- cost )
51     [ head-width>> deviation ]
52     [ tail-cost>> ] bi + ;
53
54 : min-cost ( paragraphs -- paragraph )
55     [ paragraph-cost ] min-by ;
56
57 : new-line ( paragraph element -- paragraph )
58     [ [ lines>> ] [ 1list ] bi* swons ]
59     [ nip black>> ]
60     [ drop paragraph-cost ] 2tri
61     <paragraph> ;
62
63 : glue ( paragraph element -- paragraph )
64     [ [ lines>> unswons ] dip swons swons ]
65     [ [ head-width>> ] [ element-length ] bi* + ]
66     [ drop tail-cost>> ] 2tri
67     <paragraph> ;
68
69 : wrap-step ( paragraphs element -- paragraphs )
70     [ '[ _ glue ] map ]
71     [ [ min-cost ] dip new-line ]
72     2bi prefix
73     [ fits? ] filter ;
74
75 : 1paragraph ( element -- paragraph )
76     [ 1list 1list ]
77     [ black>> ] bi
78     0 <paragraph> ;
79
80 : post-process ( paragraph -- array )
81     lines>> lists>arrays
82     [ [ contents>> ] map ] map ;
83
84 : initialize ( elements -- elements paragraph )
85     <reversed> unclip-slice 1paragraph 1array ;
86
87 : wrap ( elements line-max line-ideal -- paragraph )
88     [
89         line-ideal set
90         line-max set
91         initialize
92         [ wrap-step ] reduce
93         min-cost
94         post-process
95     ] with-scope ;