text: fix escape sequence disapearing at the end of a line

Michael Muré created

Change summary

util/text/text.go      | 7 ++++++-
util/text/text_test.go | 6 ++++++
2 files changed, 12 insertions(+), 1 deletion(-)

Detailed changes

util/text/text.go 🔗

@@ -60,7 +60,7 @@ func WrapLeftPadded(text string, lineWidth int, leftPad int) (string, int) {
 // WRAPPING ALGORITHM: The line is broken into non-breakable chunks, then line
 // breaks ("\n") are inserted between these groups so that the total length
 // between breaks does not exceed the required width. Words that are longer than
-// the textWidth are broen into pieces no longer than textWidth.
+// the textWidth are broken into pieces no longer than textWidth.
 //
 func softwrapLine(line string, textWidth int) string {
 	// NOTE: terminal escapes are stripped out of the line so the algorithm is
@@ -187,6 +187,11 @@ func applyTermEscapes(line string, escapes []escapeItem) string {
 		}
 	}
 
+	// Don't forget the trailing escape, if any.
+	if currItem == len(escapes)-1 && currPos == escapes[currItem].pos {
+		out += escapes[currItem].item
+	}
+
 	return out
 }
 

util/text/text_test.go 🔗

@@ -307,6 +307,12 @@ func TestExtractApplyTermEscapes(t *testing.T) {
 			"This is an example.",
 			[]escapeItem{{"\x1b[31m", 5}, {"\x1b[0m", 10}},
 		},
+		// Escape at the end
+		{
+			"This \x1b[31mis an example.\x1b[0m",
+			"This is an example.",
+			[]escapeItem{{"\x1b[31m", 5}, {"\x1b[0m", 19}},
+		},
 		// A plain wide line with escapes.
 		{
 			"一只敏捷\x1b[31m的狐狸\x1b[0m跳过了一只懒狗。",