mirror of
https://github.com/charmbracelet/lipgloss.git
synced 2024-08-17 18:00:46 +03:00
* feat: switch to term/ansi for text manipulation Use ANSI aware, wide characters support, uniseg backed term/ansi package to calculate string widths, truncate, and wrap strings. Related: https://github.com/muesli/reflow/pull/71 Fixes: https://github.com/charmbracelet/lipgloss/issues/258 Fixes: https://github.com/charmbracelet/lipgloss/issues/220 * Update get.go
42 lines
1.1 KiB
Go
42 lines
1.1 KiB
Go
package lipgloss
|
|
|
|
import (
|
|
"strings"
|
|
|
|
"github.com/charmbracelet/x/exp/term/ansi"
|
|
)
|
|
|
|
// Width returns the cell width of characters in the string. ANSI sequences are
|
|
// ignored and characters wider than one cell (such as Chinese characters and
|
|
// emojis) are appropriately measured.
|
|
//
|
|
// You should use this instead of len(string) len([]rune(string) as neither
|
|
// will give you accurate results.
|
|
func Width(str string) (width int) {
|
|
for _, l := range strings.Split(str, "\n") {
|
|
w := ansi.StringWidth(l)
|
|
if w > width {
|
|
width = w
|
|
}
|
|
}
|
|
|
|
return width
|
|
}
|
|
|
|
// Height returns height of a string in cells. This is done simply by
|
|
// counting \n characters. If your strings use \r\n for newlines you should
|
|
// convert them to \n first, or simply write a separate function for measuring
|
|
// height.
|
|
func Height(str string) int {
|
|
return strings.Count(str, "\n") + 1
|
|
}
|
|
|
|
// Size returns the width and height of the string in cells. ANSI sequences are
|
|
// ignored and characters wider than one cell (such as Chinese characters and
|
|
// emojis) are appropriately measured.
|
|
func Size(str string) (width, height int) {
|
|
width = Width(str)
|
|
height = Height(str)
|
|
return width, height
|
|
}
|