1
0
mirror of https://github.com/jesseduffield/lazygit.git synced 2025-08-07 22:02:56 +03:00

Refactor: move wrapMessageToWidth to utils/lines.go

to make it more generally usable by clients other than ConfirmationHelper, which
we will do later in this branch. Rename it to WrapViewLinesToWidth while we're
at it.

Add tests; in particular, add a sanity check that we wrap lines the same way as
gocui does. The tests that are added here are the same ones as in gocui for its
lineWrap function, but we'll extend them a bit in later commits in this branch.
This commit is contained in:
Stefan Haller
2024-11-08 22:17:26 +01:00
parent 2b49865d0d
commit 1f2cb35cc9
3 changed files with 244 additions and 55 deletions

View File

@@ -3,6 +3,8 @@ package utils
import (
"bytes"
"strings"
"github.com/mattn/go-runewidth"
)
// SplitLines takes a multiline string and splits it on newlines
@@ -100,3 +102,56 @@ func ScanLinesAndTruncateWhenLongerThanBuffer(maxBufferSize int) func(data []byt
return 0, nil, nil
}
}
// Wrap lines to a given width.
// If wrap is false, the text is returned as is.
// This code needs to behave the same as `gocui.lineWrap` does.
func WrapViewLinesToWidth(wrap bool, text string, width int) []string {
lines := strings.Split(text, "\n")
if !wrap {
return lines
}
wrappedLines := make([]string, 0, len(lines))
for _, line := range lines {
n := 0
offset := 0
lastWhitespaceIndex := -1
for i, currChr := range line {
rw := runewidth.RuneWidth(currChr)
n += rw
if n > width {
if currChr == ' ' {
wrappedLines = append(wrappedLines, line[offset:i])
offset = i + 1
n = 0
} else if currChr == '-' {
wrappedLines = append(wrappedLines, line[offset:i])
offset = i
n = rw
} else if lastWhitespaceIndex != -1 {
if line[lastWhitespaceIndex] == '-' {
wrappedLines = append(wrappedLines, line[offset:lastWhitespaceIndex+1])
} else {
wrappedLines = append(wrappedLines, line[offset:lastWhitespaceIndex])
}
offset = lastWhitespaceIndex + 1
n = runewidth.StringWidth(line[offset : i+1])
} else {
wrappedLines = append(wrappedLines, line[offset:i])
offset = i
n = rw
}
lastWhitespaceIndex = -1
} else if currChr == ' ' || currChr == '-' {
lastWhitespaceIndex = i
}
}
wrappedLines = append(wrappedLines, line[offset:])
}
return wrappedLines
}