size.go 1.1 KB

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