From d082410b3d56614aa5492372fb40699558062748 Mon Sep 17 00:00:00 2001 From: Joe Lim <50560759+joelim-work@users.noreply.github.com> Date: Wed, 4 Mar 2026 19:32:46 +1100 Subject: [PATCH] chore: remove go-runewidth as dependency (#2411) * Add truncate functions * Replace code for printing command line * Replace code in truncateFilename function * Remove restriction for truncatechar to be width 1 * Replace code in printdir function * Replace code in listmatches * Remove go-runewidth * Revert truncatechar limitation change --- eval.go | 4 +- go.mod | 2 - go.sum | 4 -- misc.go | 118 ++++++++++++++++++++-------------------- misc_test.go | 149 +++++++++++++++++++-------------------------------- ui.go | 47 ++++++++-------- 6 files changed, 136 insertions(+), 188 deletions(-) diff --git a/eval.go b/eval.go index 5228dbe5..a9cba372 100644 --- a/eval.go +++ b/eval.go @@ -15,6 +15,7 @@ import ( "unicode/utf8" "github.com/gdamore/tcell/v3" + "github.com/rivo/uniseg" ) func applyBoolOpt(opt *bool, e *setExpr) error { @@ -416,11 +417,10 @@ func (e *setExpr) eval(app *app, _ []string) { case "timefmt": gOpts.timefmt = e.val case "truncatechar": - if runeSliceWidth([]rune(e.val)) != 1 { + if uniseg.StringWidth(e.val) != 1 { app.ui.echoerr("truncatechar: value should be a single character") return } - gOpts.truncatechar = e.val case "truncatepct": n, err := strconv.Atoi(e.val) diff --git a/go.mod b/go.mod index 1ec38be9..e88f7015 100644 --- a/go.mod +++ b/go.mod @@ -6,14 +6,12 @@ require ( github.com/djherbis/times v1.6.0 github.com/fsnotify/fsnotify v1.9.0 github.com/gdamore/tcell/v3 v3.1.2 - github.com/mattn/go-runewidth v0.0.20 github.com/rivo/uniseg v0.4.7 golang.org/x/sys v0.41.0 golang.org/x/term v0.40.0 ) require ( - github.com/clipperhouse/uax29/v2 v2.7.0 // indirect github.com/gdamore/encoding v1.0.1 // indirect github.com/lucasb-eyer/go-colorful v1.3.0 // indirect golang.org/x/text v0.34.0 // indirect diff --git a/go.sum b/go.sum index d65c17b4..161dfd67 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,3 @@ -github.com/clipperhouse/uax29/v2 v2.7.0 h1:+gs4oBZ2gPfVrKPthwbMzWZDaAFPGYK72F0NJv2v7Vk= -github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM= github.com/djherbis/times v1.6.0 h1:w2ctJ92J8fBvWPxugmXIv7Nz7Q3iDMKNx9v5ocVH20c= github.com/djherbis/times v1.6.0/go.mod h1:gOHeRAz2h+VJNZ5Gmc/o7iD9k4wW7NMVqieYCY99oc0= github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= @@ -10,8 +8,6 @@ github.com/gdamore/tcell/v3 v3.1.2 h1:qEaXnDaYZpCIMDfa3XFHkxrwFBINUuDiePwj39vErZ github.com/gdamore/tcell/v3 v3.1.2/go.mod h1:MikpZpivMtggrw1kL999dI2VuXw6Wya4724VAh3DzIg= github.com/lucasb-eyer/go-colorful v1.3.0 h1:2/yBRLdWBZKrf7gB40FoiKfAWYQ0lqNcbuQwVHXptag= github.com/lucasb-eyer/go-colorful v1.3.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= -github.com/mattn/go-runewidth v0.0.20 h1:WcT52H91ZUAwy8+HUkdM3THM6gXqXuLJi9O3rjcQQaQ= -github.com/mattn/go-runewidth v0.0.20/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs= github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= diff --git a/misc.go b/misc.go index fbbf284a..818488a4 100644 --- a/misc.go +++ b/misc.go @@ -11,11 +11,11 @@ import ( "os" "path/filepath" "regexp" + "slices" "strconv" "strings" "unicode" - "github.com/mattn/go-runewidth" "github.com/rivo/uniseg" ) @@ -39,51 +39,6 @@ func replaceTilde(s string) string { return s } -func runeSliceWidth(rs []rune) int { - w := 0 - for _, r := range rs { - w += runewidth.RuneWidth(r) - } - return w -} - -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) - if curr >= beg && !foundb { - b = i - foundb = true - } - if curr == end || curr+w > end { - return rs[b:i] - } - curr += w - } - - return rs[b:] -} - -// runeSliceWidthLastRange returns the last runes of `rs` that take up -// at most `maxWidth` space. -func runeSliceWidthLastRange(rs []rune, maxWidth int) []rune { - lastWidth := 0 - for i := len(rs) - 1; i >= 0; i-- { - w := runewidth.RuneWidth(rs[i]) - if lastWidth+w > maxWidth { - return rs[i+1:] - } - lastWidth += w - } - return rs -} - // firstGraphemeCluster returns the runes forming the first grapheme cluster of // the input. func firstGraphemeCluster(rs []rune) []rune { @@ -103,6 +58,54 @@ func lastGraphemeCluster(rs []rune) []rune { return last } +// truncateRight truncates a string from the right based on Unicode widths, +// taking into account grapheme clusters. +func truncateRight(s string, maxWidth int) string { + buf := make([]byte, 0, len(s)) + width := 0 + + gr := uniseg.NewGraphemes(s) + for gr.Next() { + width += gr.Width() + if width > maxWidth { + break + } + + buf = append(buf, gr.Bytes()...) + } + + return string(buf) +} + +// truncateLeft truncates a string from the left based on Unicode widths, +// taking into account grapheme clusters. +func truncateLeft(s string, maxWidth int) string { + type cluster struct { + bytes []byte + width int + } + + var clusters []cluster + totalWidth := 0 + gr := uniseg.NewGraphemes(s) + for gr.Next() { + clusters = append(clusters, cluster{slices.Clone(gr.Bytes()), gr.Width()}) + totalWidth += gr.Width() + } + + buf := make([]byte, 0, len(s)) + width := 0 + for _, cluster := range clusters { + if totalWidth-width <= maxWidth { + buf = append(buf, cluster.bytes...) + } + + width += cluster.width + } + + return string(buf) +} + // cmdEscape is used to escape whitespace and special characters with // backslashes in a given string. func cmdEscape(s string) string { @@ -427,29 +430,22 @@ func getFileExtension(file fs.FileInfo) string { // character will appear (0 means left, 50 means middle, 100 means right). // The file extension is not affected by truncation, however it will be clipped // if it exceeds the allowed width. -func truncateFilename(file fs.FileInfo, maxWidth, truncatePct int, truncateChar rune) string { +func truncateFilename(file fs.FileInfo, maxWidth, truncatePct int, truncateChar string) string { filename := file.Name() - if runeSliceWidth([]rune(filename)) <= maxWidth { + if uniseg.StringWidth(filename) <= maxWidth { return filename } ext := getFileExtension(file) - avail := maxWidth - runewidth.RuneWidth(truncateChar) - runeSliceWidth([]rune(ext)) + avail := maxWidth - uniseg.StringWidth(truncateChar) - uniseg.StringWidth(ext) if avail < 0 { - result := append([]rune{truncateChar}, []rune(ext)...) - return string(runeSliceWidthRange(result, 0, maxWidth)) + return truncateRight(truncateChar+ext, maxWidth) } - basename := []rune(strings.TrimSuffix(filename, ext)) - left := runeSliceWidthRange(basename, 0, avail*truncatePct/100) - right := runeSliceWidthLastRange(basename, avail-runeSliceWidth(left)) - - var result []rune - result = append(result, left...) - result = append(result, truncateChar) - result = append(result, right...) - result = append(result, []rune(ext)...) - return string(result) + basename := strings.TrimSuffix(filename, ext) + left := truncateRight(basename, avail*truncatePct/100) + right := truncateLeft(basename, avail-uniseg.StringWidth(left)) + return left + truncateChar + right + ext } // deletePathRecursive deletes entries from a map if the key is either the given diff --git a/misc_test.go b/misc_test.go index ea52ac51..96bb3f37 100644 --- a/misc_test.go +++ b/misc_test.go @@ -32,100 +32,6 @@ func TestIsRoot(t *testing.T) { } } -func TestRuneSliceWidth(t *testing.T) { - tests := []struct { - rs []rune - exp int - }{ - {[]rune{'a', 'b'}, 2}, - {[]rune{'ı', 'ş'}, 2}, - {[]rune{'世', '界'}, 4}, - {[]rune{'世', 'a', '界', 'ı'}, 6}, - } - - for _, test := range tests { - if got := runeSliceWidth(test.rs); got != test.exp { - t.Errorf("at input '%v' expected '%d' but got '%d'", test.rs, test.exp, got) - } - } -} - -func TestRuneSliceWidthRange(t *testing.T) { - tests := []struct { - rs []rune - beg int - 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 { - if got := runeSliceWidthRange(test.rs, test.beg, test.end); !reflect.DeepEqual(got, test.exp) { - t.Errorf("at input '%v' expected '%v' but got '%v'", test.rs, test.exp, got) - } - } -} - -func TestRuneSliceWidthLastRange(t *testing.T) { - tests := []struct { - rs []rune - maxWidth int - exp []rune - }{ - {[]rune{}, 0, []rune{}}, - {[]rune{}, 1, []rune{}}, - {[]rune{'a', 'ı', 'b', ' '}, 0, []rune{}}, - {[]rune{'a', 'ı', 'b', ' '}, 1, []rune{' '}}, - {[]rune{'a', 'ı', 'b', ' '}, 2, []rune{'b', ' '}}, - {[]rune{'a', 'ı', 'b', ' '}, 3, []rune{'ı', 'b', ' '}}, - {[]rune{'a', 'ı', 'b', ' '}, 4, []rune{'a', 'ı', 'b', ' '}}, - {[]rune{'a', 'ı', 'b', ' '}, 5, []rune{'a', 'ı', 'b', ' '}}, - {[]rune{'世', '界', '世', '界'}, 0, []rune{}}, - {[]rune{'世', '界', '世', '界'}, 1, []rune{}}, - {[]rune{'世', '界', '世', '界'}, 2, []rune{'界'}}, - {[]rune{'世', '界', '世', '界'}, 3, []rune{'界'}}, - {[]rune{'世', '界', '世', '界'}, 4, []rune{'世', '界'}}, - {[]rune{'世', '界', '世', '界'}, 5, []rune{'世', '界'}}, - {[]rune{'世', '界', '世', '界'}, 6, []rune{'界', '世', '界'}}, - {[]rune{'世', '界', '世', '界'}, 7, []rune{'界', '世', '界'}}, - {[]rune{'世', '界', '世', '界'}, 8, []rune{'世', '界', '世', '界'}}, - {[]rune{'世', '界', '世', '界'}, 9, []rune{'世', '界', '世', '界'}}, - {[]rune{'世', 'a', '界', 'ı'}, 0, []rune{}}, - {[]rune{'世', 'a', '界', 'ı'}, 1, []rune{'ı'}}, - {[]rune{'世', 'a', '界', 'ı'}, 2, []rune{'ı'}}, - {[]rune{'世', 'a', '界', 'ı'}, 3, []rune{'界', 'ı'}}, - {[]rune{'世', 'a', '界', 'ı'}, 4, []rune{'a', '界', 'ı'}}, - {[]rune{'世', 'a', '界', 'ı'}, 5, []rune{'a', '界', 'ı'}}, - {[]rune{'世', 'a', '界', 'ı'}, 6, []rune{'世', 'a', '界', 'ı'}}, - {[]rune{'世', 'a', '界', 'ı'}, 7, []rune{'世', 'a', '界', 'ı'}}, - } - - for _, test := range tests { - if got := runeSliceWidthLastRange(test.rs, test.maxWidth); !reflect.DeepEqual(got, test.exp) { - t.Errorf("at input '%v' expected '%v' but got '%v'", test.rs, test.exp, got) - } - } -} - func TestFirstGraphemeCluster(t *testing.T) { tests := []struct { rs []rune @@ -162,6 +68,59 @@ func TestLastGraphemeCluster(t *testing.T) { } } +func TestTruncateRight(t *testing.T) { + tests := []struct { + s string + maxWidth int + exp string + }{ + {"", 0, ""}, + {"", 1, ""}, + {"a", 0, ""}, + {"a", 1, "a"}, + {"ab", 1, "a"}, + {"世", 0, ""}, + {"世", 1, ""}, + {"世界", 2, "世"}, + {"世界", 3, "世"}, + {"a🏳️b", 2, "a"}, + {"a🏳️b", 3, "a🏳️"}, + {"a🏳️b", 4, "a🏳️b"}, + } + + for _, test := range tests { + if got := truncateRight(test.s, test.maxWidth); got != test.exp { + t.Errorf("at input ('%v', %v) expected '%v' but got '%v'", test.s, test.maxWidth, test.exp, got) + } + } +} +func TestTruncateLeft(t *testing.T) { + tests := []struct { + s string + maxWidth int + exp string + }{ + {"", 0, ""}, + {"", 1, ""}, + {"a", 0, ""}, + {"a", 1, "a"}, + {"ab", 1, "b"}, + {"世", 0, ""}, + {"世", 1, ""}, + {"世界", 2, "界"}, + {"世界", 3, "界"}, + {"a🏳️b", 2, "b"}, + {"a🏳️b", 3, "🏳️b"}, + {"a🏳️b", 4, "a🏳️b"}, + } + + for _, test := range tests { + if got := truncateLeft(test.s, test.maxWidth); got != test.exp { + t.Errorf("at input ('%v', %v) expected '%v' but got '%v'", test.s, test.maxWidth, test.exp, got) + } + } +} + func TestCmdEscape(t *testing.T) { tests := []struct { s string @@ -538,7 +497,7 @@ func TestTruncateFilename(t *testing.T) { } for _, test := range tests { - if got := truncateFilename(test.file, test.maxWidth, test.truncatePct, '~'); got != test.exp { + if got := truncateFilename(test.file, test.maxWidth, test.truncatePct, "~"); got != test.exp { t.Errorf("at input (%v, %v, %v) expected '%s' but got '%s'", test.file, test.maxWidth, test.truncatePct, test.exp, got) } } diff --git a/ui.go b/ui.go index 94ebdc68..848e6aae 100644 --- a/ui.go +++ b/ui.go @@ -366,15 +366,15 @@ func (win *win) printDir(ui *ui, dir *dir, context *dirContext, dirStyle *dirSty // make space for select marker, and leave another space at the end maxWidth := win.w - lnwidth - 2 - var icon []rune + var icon string var iconDef iconDef if gOpts.icons { iconDef = dirStyle.icons.get(f) - icon = slices.Concat([]rune(iconDef.icon), []rune{' '}) + icon = iconDef.icon + " " } // subtract space for icon - maxFilenameWidth := maxWidth - runeSliceWidth(icon) + maxFilenameWidth := maxWidth - uniseg.StringWidth(icon) // subtract space for tag if not merged with selection marker if !gOpts.mergeindicators { maxFilenameWidth-- @@ -387,14 +387,15 @@ func (win *win) printDir(ui *ui, dir *dir, context *dirContext, dirStyle *dirSty maxFilenameWidth -= infolen } - filename := []rune(truncateFilename(f, maxFilenameWidth, gOpts.truncatepct, []rune(gOpts.truncatechar)[0])) - for j := uniseg.StringWidth(string(filename)); j < maxFilenameWidth; j++ { - filename = append(filename, ' ') + filename := truncateFilename(f, maxFilenameWidth, gOpts.truncatepct, gOpts.truncatechar) + spacing := maxFilenameWidth - uniseg.StringWidth(filename) + if spacing > 0 { + filename += strings.Repeat(" ", spacing) } if showInfo { - filename = append(filename, []rune(info)...) - customOff += nameOff + runeSliceWidth(icon) + maxFilenameWidth + filename += info + customOff += nameOff + uniseg.StringWidth(icon) + maxFilenameWidth } if i == dir.pos { @@ -413,8 +414,7 @@ func (win *win) printDir(ui *ui, dir *dir, context *dirContext, dirStyle *dirSty win.print(ui.screen, tagOff, i, st, fmt.Sprintf(cursorFmt, tag)) } - line := slices.Concat(icon, filename, []rune{' '}) - win.print(ui.screen, nameOff, i, st, fmt.Sprintf(cursorFmt, string(line))) + win.print(ui.screen, nameOff, i, st, fmt.Sprintf(cursorFmt, icon+filename+" ")) // print over the empty space we reserved for the custom info if showInfo && custom != "" { @@ -435,11 +435,10 @@ func (win *win) printDir(ui *ui, dir *dir, context *dirContext, dirStyle *dirSty if iconDef.hasStyle { iconStyle = iconDef.style } - win.print(ui.screen, nameOff, i, iconStyle, string(icon)) + win.print(ui.screen, nameOff, i, iconStyle, icon) } - line := slices.Concat(filename, []rune{' '}) - win.print(ui.screen, nameOff+runeSliceWidth(icon), i, st, string(line)) + win.print(ui.screen, nameOff+uniseg.StringWidth(icon), i, st, filename+" ") // print over the empty space we reserved for the custom info if showInfo && custom != "" { @@ -1135,17 +1134,17 @@ func (ui *ui) draw(nav *nav) { ui.screen.HideCursor() case ">": maxWidth := ui.msgWin.w - 1 // leave space for cursor at the end - prefix := runeSliceWidthRange([]rune(ui.cmdPrefix), 0, maxWidth) - left := runeSliceWidthLastRange(ui.cmdAccLeft, maxWidth-runeSliceWidth(prefix)-printLength(ui.msg)) - ui.msgWin.printLine(ui.screen, 0, 0, st, string(prefix)+ui.msg) - ui.msgWin.print(ui.screen, runeSliceWidth(prefix)+printLength(ui.msg), 0, st, string(left)+string(ui.cmdAccRight)) - ui.screen.ShowCursor(ui.msgWin.x+runeSliceWidth(prefix)+printLength(ui.msg)+runeSliceWidth(left), ui.msgWin.y) + prefix := truncateRight(ui.cmdPrefix, maxWidth) + left := truncateLeft(string(ui.cmdAccLeft), maxWidth-uniseg.StringWidth(prefix)-printLength(ui.msg)) + ui.msgWin.printLine(ui.screen, 0, 0, st, prefix+ui.msg) + ui.msgWin.print(ui.screen, uniseg.StringWidth(prefix)+printLength(ui.msg), 0, st, left+string(ui.cmdAccRight)) + ui.screen.ShowCursor(ui.msgWin.x+uniseg.StringWidth(prefix)+printLength(ui.msg)+uniseg.StringWidth(left), ui.msgWin.y) default: maxWidth := ui.msgWin.w - 1 // leave space for cursor at the end - prefix := runeSliceWidthRange([]rune(ui.cmdPrefix), 0, maxWidth) - left := runeSliceWidthLastRange(ui.cmdAccLeft, maxWidth-runeSliceWidth(prefix)) - ui.msgWin.printLine(ui.screen, 0, 0, st, string(prefix)+string(left)+string(ui.cmdAccRight)) - ui.screen.ShowCursor(ui.msgWin.x+runeSliceWidth(prefix)+uniseg.StringWidth(string(left)), ui.msgWin.y) + prefix := truncateRight(ui.cmdPrefix, maxWidth) + left := truncateLeft(string(ui.cmdAccLeft), maxWidth-uniseg.StringWidth(prefix)) + ui.msgWin.printLine(ui.screen, 0, 0, st, prefix+left+string(ui.cmdAccRight)) + ui.screen.ShowCursor(ui.msgWin.x+uniseg.StringWidth(prefix)+uniseg.StringWidth(left), ui.msgWin.y) } ui.drawPreview(nav, &context) @@ -1605,7 +1604,7 @@ func listMatches(screen tcell.Screen, matches []compMatch, selectedInd int) (str wtot, _ := screen.Size() wcol := 0 for _, m := range matches { - wcol = max(wcol, runeSliceWidth([]rune(m.name))) + wcol = max(wcol, uniseg.StringWidth(m.name)) } wcol += gOpts.tabstop - wcol%gOpts.tabstop ncol := max(wtot/wcol, 1) @@ -1617,7 +1616,7 @@ func listMatches(screen tcell.Screen, matches []compMatch, selectedInd int) (str if i%ncol == 0 { b.WriteByte('\n') } - w := runeSliceWidth([]rune(match.name)) + w := uniseg.StringWidth(match.name) fmt.Fprintf(&b, "%s%*s", match.name, wcol-w, "") }