diff --git a/misc.go b/misc.go index ea33664b..b0303eaf 100644 --- a/misc.go +++ b/misc.go @@ -31,23 +31,26 @@ func runeSliceWidth(rs []rune) int { } func runeSliceWidthRange(rs []rune, beg, end int) []rune { + if beg == end { + return []rune{} + } + curr := 0 b := 0 + foundb := false for i, r := range rs { w := runewidth.RuneWidth(r) - switch { - case curr == beg: + if curr >= beg && !foundb { b = i - case curr < beg && curr+w > beg: - b = i + 1 - case curr == end: + foundb = true + } + if curr == end || curr+w > end { return rs[b:i] - case curr > end: - return rs[b : i-1] } curr += w } - return nil + + return rs[b:] } // This function is used to escape whitespaces and special characters with diff --git a/misc_test.go b/misc_test.go index ae351ed8..aa6f6df5 100644 --- a/misc_test.go +++ b/misc_test.go @@ -55,16 +55,25 @@ func TestRuneSliceWidthRange(t *testing.T) { end int exp []rune }{ + {[]rune{}, 0, 0, []rune{}}, {[]rune{'a', 'b', 'c', 'd'}, 1, 3, []rune{'b', 'c'}}, {[]rune{'a', 'ı', 'b', 'ş'}, 1, 3, []rune{'ı', 'b'}}, {[]rune{'世', '界', '世', '界'}, 2, 6, []rune{'界', '世'}}, {[]rune{'世', '界', '世', '界'}, 3, 6, []rune{'世'}}, {[]rune{'世', '界', '世', '界'}, 2, 5, []rune{'界'}}, {[]rune{'世', '界', '世', '界'}, 3, 5, []rune{}}, + {[]rune{'世', '界', '世', '界'}, 4, 4, []rune{}}, + {[]rune{'世', '界', '世', '界'}, 5, 5, []rune{}}, + {[]rune{'世', '界', '世', '界'}, 4, 7, []rune{'世'}}, + {[]rune{'世', '界', '世', '界'}, 4, 8, []rune{'世', '界'}}, {[]rune{'世', 'a', '界', 'ı'}, 2, 5, []rune{'a', '界'}}, {[]rune{'世', 'a', '界', 'ı'}, 2, 4, []rune{'a'}}, {[]rune{'世', 'a', '界', 'ı'}, 3, 5, []rune{'界'}}, {[]rune{'世', 'a', '界', 'ı'}, 3, 4, []rune{}}, + {[]rune{'世', 'a', '界', 'ı'}, 3, 3, []rune{}}, + {[]rune{'世', 'a', '界', 'ı'}, 4, 4, []rune{}}, + {[]rune{'世', 'a', '界', 'ı'}, 4, 6, []rune{'ı'}}, + {[]rune{'世', 'a', '界', 'ı'}, 5, 6, []rune{'ı'}}, } for _, test := range tests {