From ef67a45702c01ff93e0ea99a51594c8160f66cc1 Mon Sep 17 00:00:00 2001 From: Junegunn Choi Date: Tue, 29 Mar 2022 21:35:36 +0900 Subject: Add --ellipsis=.. option Close #2432 Also see - #1769 - https://github.com/junegunn/fzf/pull/1844#issuecomment-586663660 --- src/util/util.go | 17 +++++++++++++++++ src/util/util_test.go | 10 ++++++++++ 2 files changed, 27 insertions(+) (limited to 'src/util') diff --git a/src/util/util.go b/src/util/util.go index c3995bfd..a1c37f7a 100644 --- a/src/util/util.go +++ b/src/util/util.go @@ -34,6 +34,23 @@ func RunesWidth(runes []rune, prefixWidth int, tabstop int, limit int) (int, int return width, -1 } +// Truncate returns the truncated runes and its width +func Truncate(input string, limit int) ([]rune, int) { + runes := []rune{} + width := 0 + gr := uniseg.NewGraphemes(input) + for gr.Next() { + rs := gr.Runes() + w := runewidth.StringWidth(string(rs)) + if width+w > limit { + return runes, width + } + width += w + runes = append(runes, rs...) + } + return runes, width +} + // Max returns the largest integer func Max(first int, second int) int { if first >= second { diff --git a/src/util/util_test.go b/src/util/util_test.go index 45a5a2d0..20bdb92a 100644 --- a/src/util/util_test.go +++ b/src/util/util_test.go @@ -54,3 +54,13 @@ func TestRunesWidth(t *testing.T) { } } } + +func TestTruncate(t *testing.T) { + truncated, width := Truncate("가나다라마", 7) + if string(truncated) != "가나다" { + t.Errorf("Expected: 가나다, actual: %s", string(truncated)) + } + if width != 6 { + t.Errorf("Expected: 6, actual: %d", width) + } +} -- cgit v1.2.3