Skip to content

Commit

Permalink
fix: correctly truncate utf-8 string
Browse files Browse the repository at this point in the history
closes #82

Co-authored-by: 1024th <[email protected]>
  • Loading branch information
sentriz and 1024th committed Feb 12, 2024
1 parent 34dadcd commit ef339c2
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 5 deletions.
19 changes: 14 additions & 5 deletions cliphist.go
Original file line number Diff line number Diff line change
Expand Up @@ -396,13 +396,22 @@ func preview(index uint64, data []byte) string {
return fmt.Sprintf("%d%s[[ binary data %s %s %dx%d ]]",
index, fieldSep, sizeStr(len(data)), format, config.Width, config.Height)
}
data = data[:min(len(data), 100)]
data = bytes.TrimSpace(data)
data = bytes.Join(bytes.Fields(data), []byte(" "))
return fmt.Sprintf("%d%s%s", index, fieldSep, data)
prev := string(data)
prev = strings.TrimSpace(prev)
prev = trunc(prev, 100, "…")
prev = strings.Join(strings.Fields(prev), " ")
return fmt.Sprintf("%d%s%s", index, fieldSep, prev)
}

func min(a, b int) int {
func trunc(in string, max int, ellip string) string {
runes := []rune(in)
if len(runes) > max {
return string(runes[:max]) + ellip
}
return in
}

func min(a, b int) int { //nolint:unused // we still support go1.19
if a < b {
return a
}
Expand Down
27 changes: 27 additions & 0 deletions testdata/truncate.txtar
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
stdin in
exec cliphist store

exec cliphist list
stdout '^1 one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen sev…$'

-- in --
one
two
three
four
five
six
seven
eight
nine
ten
eleven
twelve
thirteen
fourteen
fifteen
sixteen
seventeen
eighteen
nineteen
twenty

0 comments on commit ef339c2

Please sign in to comment.