factor/basis/tools/completion/completion.factor

75 lines
1.9 KiB
Factor
Raw Normal View History

2008-02-01 00:48:51 -05:00
! Copyright (C) 2005, 2008 Slava Pestov.
2007-09-20 18:09:08 -04:00
! See http://factorcode.org/license.txt for BSD license.
2008-12-11 17:47:38 -05:00
USING: kernel arrays sequences math namespaces strings io fry
2008-02-01 00:48:51 -05:00
vectors words assocs combinators sorting unicode.case
unicode.categories math.order ;
IN: tools.completion
2007-09-20 18:09:08 -04:00
: (fuzzy) ( accum ch i full -- accum i ? )
2008-12-11 17:47:38 -05:00
index-from
2007-09-20 18:09:08 -04:00
[
[ swap push ] 2keep 1+ t
] [
drop f -1 f
] if* ;
: fuzzy ( full short -- indices )
dup length <vector> -rot 0 -rot
[ -rot [ (fuzzy) ] keep swap ] all? 3drop ;
: (runs) ( runs n seq -- runs n )
[
[
2dup number=
[ drop ] [ nip V{ } clone pick push ] if
1+
] keep pick peek push
] each ;
: runs ( seq -- newseq )
V{ V{ } } [ clone ] map over first rot (runs) drop ;
: score-1 ( i full -- n )
{
{ [ over zero? ] [ 2drop 10 ] }
{ [ 2dup length 1- number= ] [ 2drop 4 ] }
2008-12-03 09:46:16 -05:00
{ [ 2dup [ 1- ] dip nth Letter? not ] [ 2drop 10 ] }
{ [ 2dup [ 1+ ] dip nth Letter? not ] [ 2drop 4 ] }
2008-04-11 13:57:43 -04:00
[ 2drop 1 ]
2007-09-20 18:09:08 -04:00
} cond ;
: score ( full fuzzy -- n )
dup [
2008-03-29 21:36:58 -04:00
[ [ length ] bi@ - 15 swap [-] 3 /f ] 2keep
2007-09-20 18:09:08 -04:00
runs [
[ 0 [ pick score-1 max ] reduce nip ] keep
length * +
2008-01-09 17:36:30 -05:00
] with each
2007-09-20 18:09:08 -04:00
] [
2drop 0
] if ;
: rank-completions ( results -- newresults )
sort-keys <reversed>
[ 0 [ first max ] reduce 3 /f ] keep
[ first < ] with filter
2007-09-20 18:09:08 -04:00
[ second ] map ;
: complete ( full short -- score )
[ dupd fuzzy score ] 2keep
2008-03-29 21:36:58 -04:00
[ <reversed> ] bi@
2007-09-20 18:09:08 -04:00
dupd fuzzy score max ;
: completion ( short candidate -- result )
2008-12-11 17:47:38 -05:00
[ second >lower swap complete ] keep 2array ;
2007-09-20 18:09:08 -04:00
: completions ( short candidates -- seq )
2008-12-11 17:47:38 -05:00
[ '[ _ ] ]
[ '[ >lower _ [ completion ] with map rank-completions ] ] bi
if-empty ;
2007-09-20 18:09:08 -04:00
: limited-completions ( short candidates -- seq )
[ completions ] [ drop ] 2bi
2dup [ length 50 > ] [ empty? ] bi* and
[ 2drop f ] [ drop 50 short head ] if ;