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