]> gitweb.factorcode.org Git - factor.git/blob - basis/wrap/wrap.factor
wrap: use infimum-by instead of min-by.
[factor.git] / basis / wrap / wrap.factor
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 ;
5 IN: wrap
6
7 ! black is the text length, white is the whitespace length
8 TUPLE: element contents black white ;
9 C: <element> element
10
11 <PRIVATE
12
13 : element-length ( element -- n )
14     [ black>> ] [ white>> ] bi + ; inline
15
16 TUPLE: paragraph line-max line-ideal lines head-width tail-cost ;
17 C: <paragraph> paragraph
18
19 TYPED: top-fits? ( paragraph: paragraph -- ? )
20     [ head-width>> ]
21     [ dup lines>> 1list? [ line-ideal>> ] [ line-max>> ] if ] bi <= ; inline
22
23 TYPED: fits? ( paragraph: paragraph -- ? )
24     ! Make this not count spaces at end
25     { [ lines>> car 1list? ] [ top-fits? ] } 1|| ; inline
26
27 TYPED: paragraph-cost ( paragraph: paragraph -- cost )
28     dup lines>> 1list? [ drop 0 ] [
29         [ [ head-width>> ] [ line-ideal>> ] bi - sq ]
30         [ tail-cost>> ] bi +
31     ] if ; inline
32
33 : min-cost ( paragraphs -- paragraph )
34     [ paragraph-cost ] infimum-by ; inline
35
36 TYPED: new-line ( paragraph: paragraph element: element -- paragraph )
37     {
38         [ drop [ line-max>> ] [ line-ideal>> ] bi ]
39         [ [ lines>> ] [ 1list ] bi* swons ]
40         [ nip black>> ]
41         [ drop paragraph-cost ]
42     } 2cleave <paragraph> ; inline
43
44 TYPED: add-element ( paragraph: paragraph element: element -- )
45     [ element-length [ + ] curry change-head-width ]
46     [ [ [ unswons ] dip swons swons ] curry change-lines ]
47     bi drop ; inline
48
49 TYPED: wrap-step ( paragraphs: array element: element -- paragraphs )
50     [ [ min-cost ] dip new-line ]
51     [ dupd '[ _ add-element ] each ]
52     2bi swap prefix { array } declare
53     [ fits? ] filter ;
54
55 : 1paragraph ( line-max line-ideal element -- paragraph )
56     [ 1list 1list ] [ black>> ] bi 0 <paragraph> ;
57
58 : post-process ( paragraph -- array )
59     lines>> [ [ contents>> ] lmap>array ] lmap>array ;
60
61 : initialize ( line-max line-ideal elements -- elements paragraph )
62     reverse unclip [ -rot ] dip 1paragraph 1array ;
63
64 PRIVATE>
65
66 : wrap ( elements line-max line-ideal -- array )
67     rot [ 2drop { } ] [
68         initialize
69         [ wrap-step ] reduce
70         min-cost
71         post-process
72     ] if-empty ;