1 ! Copyright (C) 2008, 2009 Daniel Ehrenberg, Slava Pestov
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: sequences kernel namespaces make splitting
4 math math.order fry assocs accessors ;
7 ! Word wrapping/line breaking -- not Unicode-aware
9 TUPLE: word key width break? ;
17 : break-here? ( column word -- ? )
18 break?>> not [ width get > ] [ drop f ] if ;
20 : walk ( n words -- n )
21 ! If on a break, take the rest of the breaks
22 ! If not on a break, go back until you hit a break
25 [ [ break?>> not ] find-from drop ]
26 [ [ break?>> ] find-last-from drop 1+ ] if
29 : find-optimal-break ( words -- n )
31 [ [ width>> + dup ] keep break-here? ] find drop nip
32 [ 1 max swap walk ] [ drop f ] if* ;
36 dup find-optimal-break
37 [ cut-slice [ , ] [ (wrap) ] bi* ] [ , ] if*
40 : intersperse ( seq elt -- seq' )
41 [ '[ _ , ] [ , ] interleave ] { } make ;
43 : split-lines ( string -- words-lines )
46 [ dup length f <word> ] map
47 " " 1 t <word> intersperse
50 : join-words ( wrapped-lines -- lines )
52 [ break?>> ] trim-slice
56 : join-lines ( strings -- string )
61 : wrap ( words width -- lines )
66 : wrap-lines ( lines width -- newlines )
67 [ split-lines ] dip '[ _ wrap join-words ] map concat ;
69 : wrap-string ( string width -- newstring )
70 wrap-lines join-lines ;
72 : wrap-indented-string ( string width indent -- newstring )
73 [ length - wrap-lines ] keep '[ _ prepend ] map join-lines ;