2020-09-20 00:00:50 +08: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-08-30 23:18:50 +08:00
|
|
|
// PrintableRuneWidth returns the cell width of all printable runes in the
|
|
|
|
// buffer.
|
2021-03-12 20:28:46 +08:00
|
|
|
func (w Buffer) PrintableRuneWidth() int {
|
|
|
|
return PrintableRuneWidth(w.String())
|
|
|
|
}
|
|
|
|
|
2021-08-30 23:18:50 +08:00
|
|
|
// PrintableRuneWidth returns the cell width of the given string.
|
2021-03-12 20:28:46 +08:00
|
|
|
func PrintableRuneWidth(s string) int {
|
2020-09-20 00:00:50 +08:00
|
|
|
var n int
|
|
|
|
var ansi bool
|
2021-03-12 20:28:46 +08:00
|
|
|
|
|
|
|
for _, c := range s {
|
2021-08-30 23:18:50 +08:00
|
|
|
if c == Marker {
|
2020-09-20 00:00:50 +08:00
|
|
|
// ANSI escape sequence
|
|
|
|
ansi = true
|
|
|
|
} else if ansi {
|
2021-08-30 23:18:50 +08:00
|
|
|
if IsTerminator(c) {
|
2020-09-20 00:00:50 +08:00
|
|
|
// ANSI sequence terminated
|
|
|
|
ansi = false
|
|
|
|
}
|
|
|
|
} else {
|
2021-08-30 23:18:50 +08:00
|
|
|
n += runewidth.RuneWidth(c)
|
2020-09-20 00:00:50 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return n
|
|
|
|
}
|