main
1package lipgloss
2
3import (
4 "strings"
5
6 "github.com/charmbracelet/x/ansi"
7)
8
9// Width returns the cell width of characters in the string. ANSI sequences are
10// ignored and characters wider than one cell (such as Chinese characters and
11// emojis) are appropriately measured.
12//
13// You should use this instead of len(string) len([]rune(string) as neither
14// will give you accurate results.
15func Width(str string) (width int) {
16 for _, l := range strings.Split(str, "\n") {
17 w := ansi.StringWidth(l)
18 if w > width {
19 width = w
20 }
21 }
22
23 return width
24}
25
26// Height returns height of a string in cells. This is done simply by
27// counting \n characters. If your strings use \r\n for newlines you should
28// convert them to \n first, or simply write a separate function for measuring
29// height.
30func Height(str string) int {
31 return strings.Count(str, "\n") + 1
32}
33
34// Size returns the width and height of the string in cells. ANSI sequences are
35// ignored and characters wider than one cell (such as Chinese characters and
36// emojis) are appropriately measured.
37func Size(str string) (width, height int) {
38 width = Width(str)
39 height = Height(str)
40 return width, height
41}