2009-02-03 01:27:34 -05:00
|
|
|
USING: sequences kernel namespaces make splitting
|
|
|
|
math math.order fry assocs accessors ;
|
2008-01-31 12:51:38 -05:00
|
|
|
IN: wrap
|
|
|
|
|
2009-02-03 01:27:34 -05:00
|
|
|
! Word wrapping/line breaking -- not Unicode-aware
|
|
|
|
|
|
|
|
TUPLE: word key width break? ;
|
|
|
|
|
|
|
|
C: <word> word
|
|
|
|
|
|
|
|
<PRIVATE
|
2008-01-31 12:51:38 -05:00
|
|
|
|
|
|
|
SYMBOL: width
|
|
|
|
|
2009-02-03 01:27:34 -05:00
|
|
|
: break-here? ( column word -- ? )
|
|
|
|
break?>> not [ width get > ] [ drop f ] if ;
|
|
|
|
|
|
|
|
: find-optimal-break ( words -- n )
|
|
|
|
[ 0 ] dip [ [ width>> + dup ] keep break-here? ] find drop nip ;
|
2008-01-31 12:51:38 -05:00
|
|
|
|
2009-02-03 01:27:34 -05:00
|
|
|
: (wrap) ( words -- )
|
|
|
|
dup find-optimal-break
|
|
|
|
[ 1 max cut-slice [ , ] [ (wrap) ] bi* ] [ , ] if* ;
|
2008-01-31 12:51:38 -05:00
|
|
|
|
2009-02-03 01:27:34 -05:00
|
|
|
: intersperse ( seq elt -- seq' )
|
|
|
|
[ '[ _ , ] [ , ] interleave ] { } make ;
|
2008-01-31 12:51:38 -05:00
|
|
|
|
2009-02-03 01:27:34 -05:00
|
|
|
: split-lines ( string -- words-lines )
|
|
|
|
string-lines [
|
|
|
|
" \t" split harvest
|
|
|
|
[ dup length f <word> ] map
|
|
|
|
" " 1 t <word> intersperse
|
|
|
|
] map ;
|
2008-02-01 17:43:12 -05:00
|
|
|
|
2009-02-03 01:27:34 -05:00
|
|
|
: join-words ( wrapped-lines -- lines )
|
|
|
|
[
|
|
|
|
[ break?>> ]
|
|
|
|
[ trim-head-slice ]
|
|
|
|
[ trim-tail-slice ] bi
|
|
|
|
[ key>> ] map concat
|
|
|
|
] map ;
|
|
|
|
|
|
|
|
: join-lines ( strings -- string )
|
|
|
|
"\n" join ;
|
|
|
|
|
|
|
|
PRIVATE>
|
|
|
|
|
|
|
|
: wrap ( words width -- lines )
|
2008-01-31 12:51:38 -05:00
|
|
|
width [
|
2009-02-03 01:27:34 -05:00
|
|
|
[ (wrap) ] { } make
|
2008-01-31 12:51:38 -05:00
|
|
|
] with-variable ;
|
|
|
|
|
2009-02-03 01:27:34 -05:00
|
|
|
: wrap-lines ( lines width -- newlines )
|
|
|
|
[ split-lines ] dip '[ _ wrap join-words ] map concat ;
|
|
|
|
|
|
|
|
: wrap-string ( string width -- newstring )
|
|
|
|
wrap-lines join-lines ;
|
2008-01-31 12:51:38 -05:00
|
|
|
|
2009-02-03 01:27:34 -05:00
|
|
|
: wrap-indented-string ( string width indent -- newstring )
|
|
|
|
[ length - wrap-lines ] keep '[ _ prepend ] map join-lines ;
|