2020-09-19 18:00:50 +02:00
|
|
|
package ansi
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
|
|
|
|
"github.com/mattn/go-runewidth"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Buffer is a buffer aware of ANSI escape sequences.
|
|
|
|
type Buffer struct {
|
|
|
|
bytes.Buffer
|
|
|
|
}
|
|
|
|
|
2021-03-05 11:06:25 +01:00
|
|
|
// PrintableRuneCount returns the amount of printable runes in the buffer.
|
|
|
|
func (w Buffer) PrintableRuneCount() int {
|
2020-09-19 18:00:50 +02:00
|
|
|
var n int
|
|
|
|
var ansi bool
|
2021-03-05 11:06:25 +01:00
|
|
|
for _, c := range w.String() {
|
2020-09-19 18:00:50 +02:00
|
|
|
if c == '\x1B' {
|
|
|
|
// ANSI escape sequence
|
|
|
|
ansi = true
|
|
|
|
} else if ansi {
|
|
|
|
if (c >= 0x40 && c <= 0x5a) || (c >= 0x61 && c <= 0x7a) {
|
|
|
|
// ANSI sequence terminated
|
|
|
|
ansi = false
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
n += runewidth.StringWidth(string(c))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return n
|
|
|
|
}
|