summaryrefslogtreecommitdiff
path: root/src/utf8.c
diff options
context:
space:
mode:
authorLukas Fleischer <lfleischer@calcurse.org>2016-02-25 21:48:39 +0100
committerLukas Fleischer <lfleischer@calcurse.org>2016-02-26 09:14:40 +0100
commitc34f9aba29b965bf1da7e16da91ebf94ae123e89 (patch)
tree84fbe45575d63ca93df3f3631af55deb867b5350 /src/utf8.c
parent85772d746f7b1123b94ce9556273b4a9df77eeaf (diff)
downloadcalcurse-c34f9aba29b965bf1da7e16da91ebf94ae123e89.zip
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 <lfleischer@calcurse.org>
Diffstat (limited to 'src/utf8.c')
-rw-r--r--src/utf8.c23
1 files changed, 23 insertions, 0 deletions
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;
+}