Skip to content

Commit

Permalink
Merge pull request #40 from koki-develop/multibyte-string
Browse files Browse the repository at this point in the history
  • Loading branch information
koki-develop committed Apr 8, 2023
2 parents fb3c42b + 4d58e4a commit 3830500
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 5 deletions.
2 changes: 1 addition & 1 deletion model.go
Expand Up @@ -239,7 +239,7 @@ func (m *model) itemView(match Match, cursorLine bool) string {
}

// write item
for ci, c := range match.Str {
for ci, c := range []rune(match.Str) {
// matches
if intContains(match.MatchedIndexes, ci) {
if cursorLine {
Expand Down
10 changes: 6 additions & 4 deletions search.go
Expand Up @@ -4,6 +4,7 @@ import (
"sort"
"strings"
"sync"
"unicode/utf8"
)

var (
Expand Down Expand Up @@ -143,19 +144,20 @@ func fuzzySearch(str, search string, option searchOption) (Match, bool) {
}

// Create a slice to store the matched indexes.
matchedIndexes := make([]int, 0, len(search))
matchedIndexes := make([]int, 0, utf8.RuneCountInString(search))
j := 0

// Check for matching between the item's characters and the search string.
for i, r := range item {
if j < len(search) && r == rune(search[j]) {
searchRunes := []rune(search)
for i, r := range []rune(item) {
if j < len(searchRunes) && r == searchRunes[j] {
matchedIndexes = append(matchedIndexes, i)
j++
}
}

// Returns Match if all characters in the search string match.
if j == len(search) {
if j == len(searchRunes) {
return Match{Str: str, MatchedIndexes: matchedIndexes}, true
} else {
return Match{}, false
Expand Down
12 changes: 12 additions & 0 deletions search_test.go
Expand Up @@ -42,6 +42,18 @@ func Test_fuzzySearch(t *testing.T) {
{str: "abc", search: "d"},
{str: "abc", search: "abcd"},

{str: "こんにけは", search: "", matchedIndexes: []int{}},
{str: "こんにけは", search: "こ", matchedIndexes: []int{0}},
{str: "こんにけは", search: "こん", matchedIndexes: []int{0, 1}},
{str: "こんにけは", search: "こんに", matchedIndexes: []int{0, 1, 2}},
{str: "こんにけは", search: "こんにけ", matchedIndexes: []int{0, 1, 2, 3}},
{str: "こんにけは", search: "こんにけは", matchedIndexes: []int{0, 1, 2, 3, 4}},
{str: "こんにけは", search: "γ‚“", matchedIndexes: []int{1}},
{str: "こんにけは", search: "んに", matchedIndexes: []int{1, 2}},
{str: "こんにけは", search: "んにけ", matchedIndexes: []int{1, 2, 3}},
{str: "こんにけは", search: "んにけは", matchedIndexes: []int{1, 2, 3, 4}},
{str: "こんにけは", search: "こには", matchedIndexes: []int{0, 2, 4}},

{str: "xaxbxc", search: "a", matchedIndexes: []int{1}},
{str: "xaxbxc", search: "ab", matchedIndexes: []int{1, 3}},
{str: "xaxbxc", search: "ac", matchedIndexes: []int{1, 5}},
Expand Down

0 comments on commit 3830500

Please sign in to comment.