From 550c0bdbd51441c63bff17732aa667485715e92f Mon Sep 17 00:00:00 2001 From: Christian Muehlhaeuser Date: Wed, 4 Dec 2019 08:56:15 +0100 Subject: [PATCH] Don't indent line if all we're outputting is ANSI sequences --- ansiwriter.go | 2 +- indent.go | 44 ++++++++++++++++++++++++++++---------------- padding.go | 2 +- 3 files changed, 30 insertions(+), 18 deletions(-) diff --git a/ansiwriter.go b/ansiwriter.go index ffe5eb9..badad5f 100644 --- a/ansiwriter.go +++ b/ansiwriter.go @@ -24,7 +24,7 @@ func (w *AnsiWriter) Write(b []byte) (int, error) { w.ansiseq += string(c) } else if w.ansi { w.ansiseq += string(c) - if (c >= 0x40 && c <= 0x5a) || (c >= 0x61 && c <= 0x7a) { + if (c >= 0x41 && c <= 0x5a) || (c >= 0x61 && c <= 0x7a) { // ANSI sequence terminated w.ansi = false diff --git a/indent.go b/indent.go index 9fbc483..9f5f3d0 100644 --- a/indent.go +++ b/indent.go @@ -13,32 +13,44 @@ type IndentWriter struct { IndentFunc IndentFunc skipIndent bool + ansi bool } // Write is used to write content to the indent buffer. func (w *IndentWriter) Write(b []byte) (int, error) { for _, c := range string(b) { - if !w.skipIndent { - if w.IndentFunc != nil { - for i := 0; i < int(w.Indent); i++ { - w.IndentFunc(w.Forward) - } - } else { - _, err := w.Forward.Write([]byte(strings.Repeat(" ", int(w.Indent)))) - if err != nil { - return 0, err + if c == '\x1B' { + // ANSI escape sequence + w.ansi = true + } else if w.ansi { + if (c >= 0x41 && c <= 0x5a) || (c >= 0x61 && c <= 0x7a) { + // ANSI sequence terminated + w.ansi = false + } + } else { + if !w.skipIndent { + w.Forward.ResetAnsi() + if w.IndentFunc != nil { + for i := 0; i < int(w.Indent); i++ { + w.IndentFunc(w.Forward) + } + } else { + _, err := w.Forward.Write([]byte(strings.Repeat(" ", int(w.Indent)))) + if err != nil { + return 0, err + } } + + w.skipIndent = true + w.Forward.RestoreAnsi() } - w.Forward.RestoreAnsi() - w.skipIndent = true + if c == '\n' { + // end of current line + w.skipIndent = false + } } - if c == '\n' { - // end of current line - w.skipIndent = false - w.Forward.ResetAnsi() - } _, err := w.Forward.Write([]byte(string(c))) if err != nil { return 0, err diff --git a/padding.go b/padding.go index 75c7935..bfce1cf 100644 --- a/padding.go +++ b/padding.go @@ -22,7 +22,7 @@ func (w *PaddingWriter) Write(b []byte) (int, error) { // ANSI escape sequence w.ansi = true } else if w.ansi { - if (c >= 0x40 && c <= 0x5a) || (c >= 0x61 && c <= 0x7a) { + if (c >= 0x41 && c <= 0x5a) || (c >= 0x61 && c <= 0x7a) { // ANSI sequence terminated w.ansi = false w.lineLen--