mirror of
https://github.com/rwinkhart/glamour-temp-MUTN.git
synced 2026-08-30 13:46:44 -04:00
Add PaddingWriter, an io.Writer proxy, that keeps lines at (least at) equal width
This commit is contained in:
+53
@@ -0,0 +1,53 @@
|
||||
package gold
|
||||
|
||||
import (
|
||||
"io"
|
||||
)
|
||||
|
||||
type PaddingFunc = func(w io.Writer)
|
||||
|
||||
type PaddingWriter struct {
|
||||
Forward *AnsiWriter
|
||||
Padding uint
|
||||
PadFunc PaddingFunc
|
||||
|
||||
lineLen int
|
||||
ansi bool
|
||||
}
|
||||
|
||||
// Write is used to write content to the padding buffer.
|
||||
func (w *PaddingWriter) Write(b []byte) (int, error) {
|
||||
for _, c := range string(b) {
|
||||
if c == '\x1B' {
|
||||
// ANSI escape sequence
|
||||
w.ansi = true
|
||||
} else if w.ansi {
|
||||
if (c >= 0x40 && c <= 0x5a) || (c >= 0x61 && c <= 0x7a) {
|
||||
// ANSI sequence terminated
|
||||
w.ansi = false
|
||||
w.lineLen--
|
||||
}
|
||||
} else {
|
||||
if c == '\n' {
|
||||
// end of current line
|
||||
if w.Padding > 0 && uint(w.lineLen) < w.Padding {
|
||||
for i := 0; i < int(w.Padding)-w.lineLen; i++ {
|
||||
w.PadFunc(w.Forward)
|
||||
}
|
||||
}
|
||||
w.Forward.ResetAnsi()
|
||||
w.lineLen = -1
|
||||
}
|
||||
}
|
||||
|
||||
if !w.ansi {
|
||||
w.lineLen++
|
||||
}
|
||||
_, err := w.Forward.Write([]byte(string(c)))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
|
||||
return len(b), nil
|
||||
}
|
||||
Reference in New Issue
Block a user