buffer.go 708 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package ansi
  2. import (
  3. "bytes"
  4. "github.com/mattn/go-runewidth"
  5. )
  6. // Buffer is a buffer aware of ANSI escape sequences.
  7. type Buffer struct {
  8. bytes.Buffer
  9. }
  10. // PrintableRuneWidth returns the cell width of all printable runes in the
  11. // buffer.
  12. func (w Buffer) PrintableRuneWidth() int {
  13. return PrintableRuneWidth(w.String())
  14. }
  15. // PrintableRuneWidth returns the cell width of the given string.
  16. func PrintableRuneWidth(s string) int {
  17. var n int
  18. var ansi bool
  19. for _, c := range s {
  20. if c == Marker {
  21. // ANSI escape sequence
  22. ansi = true
  23. } else if ansi {
  24. if IsTerminator(c) {
  25. // ANSI sequence terminated
  26. ansi = false
  27. }
  28. } else {
  29. n += runewidth.RuneWidth(c)
  30. }
  31. }
  32. return n
  33. }