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 c49cc09
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 4 deletions.
17 changes: 13 additions & 4 deletions cliphist.go
Original file line number Diff line number Diff line change
Expand Up @@ -396,10 +396,19 @@ 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 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 {

Check failure on line 414 in cliphist.go

View workflow job for this annotation

GitHub Actions / Lint and test

func `min` is unused (unused)
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 c49cc09

Please sign in to comment.