Subject: [PATCH] strbuf_add_wrapped_text(): skip over colour codes

From: René Scharfe <[email-masked]>
Date: Mon, 23 Nov 2009 23:40:03 +0100

Ignore display mode escape sequences (colour codes) for the purpose of
text wrapping because they don't have a visible width.

Signed-off-by: Rene Scharfe <[email-masked]>
---
Renamed function to document its purpose and limitation, and remove
the note that is obsoleted by this patch.

 Documentation/pretty-formats.txt |    4 +---
 utf8.c                           |   22 +++++++++++++++++++++-
 2 files changed, 22 insertions(+), 4 deletions(-)

diff --git a/Documentation/pretty-formats.txt b/Documentation/pretty-formats.txt
index 7ff6a6c..0683fb3 100644
--- a/Documentation/pretty-formats.txt
+++ b/Documentation/pretty-formats.txt
@@ -136,9 +136,7 @@ The placeholders are:
 - '%n': newline
 - '%x00': print a byte from a hex code
 - '%w([<w>[,<i1>[,<i2>]]])': switch line wrapping, like the -w option of
-  linkgit:git-shortlog[1].  NOTE: Color placeholders (`%C*`) are not
-  recognized as having no width, so they should not be put into wrapped
-  sections.
+  linkgit:git-shortlog[1].
 
 NOTE: Some placeholders may depend on other options given to the
 revision traversal engine. For example, the `%g*` reflog options will
diff --git a/utf8.c b/utf8.c
index 01d1869..7ddff23 100644
--- a/utf8.c
+++ b/utf8.c
@@ -314,6 +314,20 @@ static void strbuf_add_indented_text(struct strbuf *buf, const char *text,
 	}
 }
 
+static size_t display_mode_esc_sequence_len(const char *s)
+{
+	const char *p = s;
+	if (*p++ != '\033')
+		return 0;
+	if (*p++ != '[')
+		return 0;
+	while (isdigit(*p) || *p == ';')
+		p++;
+	if (*p++ != 'm')
+		return 0;
+	return p - s;
+}
+
 /*
  * Wrap the text, if necessary. The variable indent is the indent for the
  * first line, indent2 is the indent for all other lines.
@@ -337,7 +351,13 @@ int strbuf_add_wrapped_text(struct strbuf *buf,
 	}
 
 	for (;;) {
-		char c = *text;
+		char c;
+		size_t skip;
+
+		while ((skip = display_mode_esc_sequence_len(text)))
+			text += skip;
+
+		c = *text;
 		if (!c || isspace(c)) {
 			if (w < width || !space) {
 				const char *start = bol;
-- 
1.6.5