From a9cba9b6e60ff4aec081d48b0d86ec175c3e8e99 Mon Sep 17 00:00:00 2001 From: Robin Jarry Date: Wed, 21 Dec 2022 12:50:01 +0100 Subject: format: add utf-8 aware truncate head function The runewidth module only allows truncating at the end of strings. Add a function to truncate at the beginning. It will be used for the table widget in the next commit. Signed-off-by: Robin Jarry Acked-by: Tim Culverhouse --- lib/format/format.go | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) (limited to 'lib') diff --git a/lib/format/format.go b/lib/format/format.go index 3f00fe18..ad0b778c 100644 --- a/lib/format/format.go +++ b/lib/format/format.go @@ -11,6 +11,7 @@ import ( "git.sr.ht/~rjarry/aerc/models" "github.com/emersion/go-message/mail" "github.com/mattn/go-runewidth" + "github.com/rivo/uniseg" ) // AddressForHumans formats the address. If the address's name @@ -67,6 +68,31 @@ func CompactPath(name string, sep rune) (compact string) { return } +func TruncateHead(s string, w int, head string) string { + width := runewidth.StringWidth(s) + if width <= w { + return s + } + w -= runewidth.StringWidth(head) + pos := 0 + g := uniseg.NewGraphemes(s) + for g.Next() { + var chWidth int + for _, r := range g.Runes() { + chWidth = runewidth.RuneWidth(r) + if chWidth > 0 { + break + } + } + if width-chWidth <= w { + pos, _ = g.Positions() + break + } + width -= chWidth + } + return head + s[pos:] +} + type Ctx struct { FromAddress string AccountName string -- cgit