...

Source file src/github.com/c-bata/go-prompt/filter.go

Documentation: github.com/c-bata/go-prompt

     1  package prompt
     2  
     3  import "strings"
     4  
     5  // Filter is the type to filter the prompt.Suggestion array.
     6  type Filter func([]Suggest, string, bool) []Suggest
     7  
     8  // FilterHasPrefix checks whether the string completions.Text begins with sub.
     9  func FilterHasPrefix(completions []Suggest, sub string, ignoreCase bool) []Suggest {
    10  	return filterSuggestions(completions, sub, ignoreCase, strings.HasPrefix)
    11  }
    12  
    13  // FilterHasSuffix checks whether the completion.Text ends with sub.
    14  func FilterHasSuffix(completions []Suggest, sub string, ignoreCase bool) []Suggest {
    15  	return filterSuggestions(completions, sub, ignoreCase, strings.HasSuffix)
    16  }
    17  
    18  // FilterContains checks whether the completion.Text contains sub.
    19  func FilterContains(completions []Suggest, sub string, ignoreCase bool) []Suggest {
    20  	return filterSuggestions(completions, sub, ignoreCase, strings.Contains)
    21  }
    22  
    23  // FilterFuzzy checks whether the completion.Text fuzzy matches sub.
    24  // Fuzzy searching for "dog" is equivalent to "*d*o*g*". This search term
    25  // would match, for example, "Good food is gone"
    26  //                               ^  ^      ^
    27  func FilterFuzzy(completions []Suggest, sub string, ignoreCase bool) []Suggest {
    28  	return filterSuggestions(completions, sub, ignoreCase, fuzzyMatch)
    29  }
    30  
    31  func fuzzyMatch(s, sub string) bool {
    32  	sChars := []rune(s)
    33  	sIdx := 0
    34  
    35  	// https://staticcheck.io/docs/checks#S1029
    36  	for _, c := range sub {
    37  		found := false
    38  		for ; sIdx < len(sChars); sIdx++ {
    39  			if sChars[sIdx] == c {
    40  				found = true
    41  				sIdx++
    42  				break
    43  			}
    44  		}
    45  		if !found {
    46  			return false
    47  		}
    48  	}
    49  	return true
    50  }
    51  
    52  func filterSuggestions(suggestions []Suggest, sub string, ignoreCase bool, function func(string, string) bool) []Suggest {
    53  	if sub == "" {
    54  		return suggestions
    55  	}
    56  	if ignoreCase {
    57  		sub = strings.ToUpper(sub)
    58  	}
    59  
    60  	ret := make([]Suggest, 0, len(suggestions))
    61  	for i := range suggestions {
    62  		c := suggestions[i].Text
    63  		if ignoreCase {
    64  			c = strings.ToUpper(c)
    65  		}
    66  		if function(c, sub) {
    67  			ret = append(ret, suggestions[i])
    68  		}
    69  	}
    70  	return ret
    71  }
    72  

View as plain text