From c34f9aba29b965bf1da7e16da91ebf94ae123e89 Mon Sep 17 00:00:00 2001 From: Lukas Fleischer Date: Thu, 25 Feb 2016 21:48:39 +0100 Subject: Refactor UTF-8 chopping Add a function that makes sure a string does not exceed a given display size. If the string is too long, dots ("...") are appended. Signed-off-by: Lukas Fleischer --- src/utf8.c | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) (limited to 'src/utf8.c') diff --git a/src/utf8.c b/src/utf8.c index b42ba16..c735ab5 100644 --- a/src/utf8.c +++ b/src/utf8.c @@ -336,3 +336,26 @@ int utf8_strwidth(char *s) return width; } + +/* Trim a UTF-8 string if it is too long, possibly adding dots for padding. */ +int utf8_chop(char *s, int width) +{ + int i, n = 0; + + for (i = 0; s[i] && width > 0; i++) { + if (!UTF8_ISCONT(s[i])) + width -= utf8_width(&s[i]); + if (width >= 3) + n = i + 1; + } + + if (s[i] == '\0') + return 0; + + if (s[n] != '\0' && s[n + 1] != '\0' && s[n + 2] != '\0') { + s[n] = s[n + 1] = s[n + 2] = '.'; + s[n + 3] = '\0'; + } + + return 1; +} -- cgit v1.2.3-54-g00ecf