]> gitweb.factorcode.org Git - factor.git/blob - basis/wrap/wrap.factor
wrap: remove use of namespace, speed up a little.
[factor.git] / basis / wrap / wrap.factor
1 ! Copyright (C) 2009 Daniel Ehrenberg
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: combinators 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 line-max line-ideal lines head-width tail-cost ;
16 C: <paragraph> paragraph
17
18 : top-fits? ( paragraph -- ? )
19     [ head-width>> ]
20     [ dup lines>> 1list? [ line-ideal>> ] [ line-max>> ] if ] bi <= ;
21
22 : fits? ( paragraph -- ? )
23     ! Make this not count spaces at end
24     { [ lines>> car 1list? ] [ top-fits? ] } 1|| ;
25
26 :: min-by ( seq quot -- elt )
27     f 1/0. seq [| key value new |
28         new quot call :> newvalue
29         newvalue value < [ new newvalue ] [ key value ] if
30     ] each drop ; inline
31
32 : paragraph-cost ( paragraph -- cost )
33     dup lines>> 1list? [ drop 0 ] [
34         [ [ head-width>> ] [ line-ideal>> ] bi - sq ]
35         [ tail-cost>> ] bi +
36     ] if ;
37
38 : min-cost ( paragraphs -- paragraph )
39     [ paragraph-cost ] min-by ;
40
41 : new-line ( paragraph element -- paragraph )
42     {
43         [ drop [ line-max>> ] [ line-ideal>> ] bi ]
44         [ [ lines>> ] [ 1list ] bi* swons ]
45         [ nip black>> ]
46         [ drop paragraph-cost ]
47     } 2cleave <paragraph> ;
48
49 : glue ( paragraph element -- paragraph )
50     {
51         [ drop [ line-max>> ] [ line-ideal>> ] bi ]
52         [ [ lines>> unswons ] dip swons swons ]
53         [ [ head-width>> ] [ element-length ] bi* + ]
54         [ drop tail-cost>> ]
55     } 2cleave <paragraph> ;
56
57 : wrap-step ( paragraphs element -- paragraphs )
58     [ '[ _ glue ] map ]
59     [ [ min-cost ] dip new-line ]
60     2bi prefix
61     [ fits? ] filter ;
62
63 : 1paragraph ( line-max line-ideal element -- paragraph )
64     [ 1list 1list ] [ black>> ] bi 0 <paragraph> ;
65
66 : post-process ( paragraph -- array )
67     lines>> [ [ contents>> ] lmap>array ] lmap>array ;
68
69 : initialize ( line-max line-ideal elements -- elements paragraph )
70     <reversed> unclip-slice [ -rot ] dip 1paragraph 1array ;
71
72 : wrap ( elements line-max line-ideal -- paragraph )
73     rot [ 2drop { } ] [
74         initialize
75         [ wrap-step ] reduce
76         min-cost
77         post-process
78     ] if-empty ;