! Copyright (C) 2008 Daniel Ehrenberg. ! See http://factorcode.org/license.txt for BSD license. USING: accessors alien.syntax arrays assocs combinators combinators.short-circuit compiler.units fry interval-maps io io.encodings.ascii io.files kernel literals locals make math math.parser math.ranges memoize namespaces sequences sets simple-flat-file splitting unicode.categories unicode.categories.syntax unicode.data unicode.normalize unicode.normalize.private words ; FROM: sequences => change-nth ; IN: unicode.breaks ] curry replicate ; SYMBOL: table : finish-table ( -- table ) table get [ [ 1 = ] map ] map ; : eval-seq ( seq -- seq ) [ ?execute ] map ; : (set-table) ( class1 class2 val -- ) [ table get nth ] dip '[ _ or ] change-nth ; : set-table ( classes1 classes2 val -- ) [ [ eval-seq ] bi@ ] dip [ [ (set-table) ] curry with each ] 2curry each ; : connect ( class1 class2 -- ) 1 set-table ; : disconnect ( class1 class2 -- ) 0 set-table ; : make-grapheme-table ( -- ) { CR } { LF } connect { Control CR LF } graphemes iota disconnect graphemes iota { Control CR LF } disconnect { L } { L V LV LVT } connect { LV V } { V T } connect { LVT T } { T } connect graphemes iota { Extend } connect graphemes iota { SpacingMark } connect { Prepend } graphemes iota connect ; SYMBOL: grapheme-table : grapheme-break? ( class1 class2 -- ? ) grapheme-table get-global nth nth not ; PRIVATE> : first-grapheme ( str -- i ) unclip-slice grapheme-class over [ grapheme-class [ nip ] [ grapheme-break? ] 2bi ] find drop nip swap length or 1 + ; : first-grapheme-from ( start str -- i ) over tail-slice first-grapheme + ; : last-grapheme ( str -- i ) unclip-last-slice grapheme-class swap [ grapheme-class dup rot grapheme-break? ] find-last drop ?1+ nip ; : last-grapheme-from ( end str -- i ) swap head-slice last-grapheme ; pieces ( str quot: ( str -- i ) -- graphemes ) [ dup empty? not ] swap '[ dup @ cut-slice swap ] produce nip ; inline PRIVATE> : >graphemes ( str -- graphemes ) [ first-grapheme ] >pieces ; : string-reverse ( str -- rts ) >graphemes reverse! concat ; new-class new-class (format/extended?) [ old-class dup ${ wCR wLF wNewline } member? ] [ new-class old-class over word-table-nth [ str i 1 - ] dip word-break? ] if ; PRIVATE> : first-word ( str -- i ) [ [ length ] [ first word-break-prop ] bi ] keep 1 swap dup '[ _ word-break-next ] find-index-from drop nip swap or ; : first-word2 ( str -- i ) [ unclip-slice word-break-prop over ] keep '[ _ word-break-next ] find-index drop nip swap length or 1 + ; : >words ( str -- words ) [ first-word ] >pieces ; : word-break-at? ( i str -- ? ) { [ drop zero? ] [ length = ] [ [ nth-next [ word-break-prop ] dip ] 2keep word-break-next nip ] } 2|| ; : first-word-from ( start str -- i ) over tail-slice first-word + ; : last-word ( str -- i ) [ length iota ] keep '[ _ word-break-at? ] find-last drop 0 or ; : last-word-from ( end str -- i ) swap head-slice last-word ;