Skip to contentSkip to conversation

client: handle wide chars for table rows

PATCH Applied Pinghao Wu 2 participants 2 messages Oct 12, 2022

lore
Share & tools
lore

Pinghao Wu

author
#0 lore raw

PATCH v4 1/1 client: handle wide chars for table rows

Find out printing width of wide chars via wcwidth().

---
 client/display.c | 35 ++++++++++++++++++++++++++---------
 client/main.c    |  3 +++
 2 files changed, 29 insertions(+), 9 deletions(-)
client/display.c +26 -9
index b729ad4c..ddd9551c 100644
@@ -30,6 +30,7 @@
 #include <sys/stat.h>
 #include <sys/ioctl.h>
 #include <unistd.h>
+#include <wchar.h>
 
 #include <readline/history.h>
 #include <readline/readline.h>
@@ -398,21 +399,37 @@ static unsigned int color_end(char *s)
  */
 static char* next_line(char *s, unsigned int *max, char **color_out)
 {
-	unsigned int i;
+	unsigned int i = 0;
 	int last_space = -1;
 	int last_color = -1;
+	unsigned int s_len = strlen(s);
 
 	/* Find the last space before 'max', as well as any color */
-	for (i = 0; i <= *max && s[i] != '\0'; i++) {
-		if (s[i] == ' ')
-			last_space = i;
-		else if (s[i] == 0x1b) {
+	while (i <= *max && i != s_len) {
+		int sequence_len;
+		int sequence_columns;
+		wchar_t w;
+
+		if (s[i] == 0x1b) {
+			sequence_len = color_end(s + i);
 			/* color escape won't count for column width */
-			*max += color_end(s + i);
+			sequence_columns = 0;
 			last_color = i;
-		/* Add width for non-codepoint UTF-8 bytes */
-		} else if (((uint8_t)s[i] >> 6) == 2)
-			*max += 1;
+		} else {
+			if (s[i] == ' ')
+				last_space = i;
+			sequence_len = l_utf8_get_codepoint(&s[i], s_len - i,
+									&w);
+			if (sequence_len < 0) {
+				sequence_len = 1;
+				sequence_columns = 1;
+			} else
+				sequence_columns = wcwidth(w);
+		}
+
+		/* Compensate max bytes */
+		*max += sequence_len - sequence_columns;
+		i += sequence_len;
 	}
 
 	/* Reached the end of the string within the column bounds */
client/main.c +3 -0
index df5c0a61..7e8dead4 100644
@@ -25,6 +25,7 @@
 #endif
 
 #include <errno.h>
+#include <locale.h>
 #include <signal.h>
 #include <ell/ell.h>
 
@@ -50,6 +51,8 @@ int main(int argc, char *argv[])
 {
 	bool all_done;
 
+	setlocale(LC_CTYPE, "");
+
 	if (!l_main_init())
 		return EXIT_FAILURE;
 
Signature · 1 line
2.38.0
#1 lore raw

Hi Pinghao,

Quoted 6 lines · Pinghao Wu

Find out printing width of wide chars via wcwidth().

---
  client/display.c | 35 ++++++++++++++++++++++++++---------
  client/main.c    |  3 +++
  2 files changed, 29 insertions(+), 9 deletions(-)

Applied, thanks.

Regards,
-Denis