prompt: use mblen() to parse multi-byte characters
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Daniel Eklöf · committed by Daniel Eklöf · parent a099247 · Browse files · 2 files·+26 added−26 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+26 added−26 removed
- other:+26 added−26 removed
Provenance
- Commit
4043825- Tree
ae64ca5- Author
Daniel Eklöf <daniel@ekloef.se>- Committer
Daniel Eklöf <daniel@ekloef.se>- Parent
a099247
2 files changed+26 added−26 removed
modified:main.c+15 added-17 removed
2 unmodified lines3 #include <string.h>4 #include <stdbool.h>5 #include <unistd.h>6 7+#include <locale.h>8 #include <threads.h>9 #include <poll.h>10 11 #include <sys/types.h>200 unmodified lines212 213 static size_t214 prompt_next_char(const struct prompt *prompt)215 {215- const char *c = &prompt->text[prompt->cursor];216- const char *end = prompt->text + strlen(prompt->text) + 1;217-218- if (prompt->cursor >= strlen(prompt->text))216+ int clen = mblen(&prompt->text[prompt->cursor], MB_CUR_MAX);217+ if (clen < 0) {218+ LOG_ERRNO("prompt: %s", prompt->text);219 return prompt->cursor;220+ }221 221- do {222- c++;223- } while (c < end && ((unsigned char)*c >> 6) == 2);224-225- return c - prompt->text;222+ return prompt->cursor + clen;223 }224 225 static size_t226 prompt_prev_char(const struct prompt *prompt)227 {228 if (prompt->cursor == 0)229 return 0;230 234- const char *c = &prompt->text[prompt->cursor];231+ size_t cursor = prompt->cursor;232+ while (cursor > 0) {233+ int clen = mblen(&prompt->text[--cursor], MB_CUR_MAX);234+ if (clen >= 0)235+ break;236+ }237 236- do {237- c--;238- } while (c > prompt->text && !((unsigned char)*c >> 7 == 0 ||239- (unsigned char)*c >> 6 == 3));240-241- assert(c >= prompt->text);242- return c - prompt->text;238+ return cursor;239 }240 241 static size_t242 prompt_prev_word(const struct prompt *prompt)556 unmodified lines799 main(int argc, const char *const *argv)800 {801 int ret = EXIT_FAILURE;802 803+ setlocale(LC_ALL, "");804+805 struct context c = {806 .keep_running = true,807 .wl = {0},808 .prompt = {198 unmodified linesmodified:render.c+11 added-9 removed
51 unmodified lines52 clusters, num_clusters, cluster_flags);53 54 /* prompt->cursor is the *byte* position, but we need the55 * *character| position */56- int cursor_at_glyph = 0;57- size_t i = 0;58- while (i < prompt->cursor) {59- if ((unsigned char)prompt->text[i] >> 7) {60- i++;61- while (((unsigned char)prompt->text[i] & 0xc0) == 0x80)62- i++;63- } else64- i++;56+ size_t cursor = 0;57+ size_t cursor_at_glyph = 0;58+59+ while (cursor < prompt->cursor) {60+ int clen = mblen(&prompt->text[cursor], MB_CUR_MAX);61+ if (clen < 0) {62+ LOG_ERRNO("prompt: %s", prompt->text);63+ break;64+ }65+66+ cursor += clen;67 cursor_at_glyph++;68 }69 70 int cursor_x;103 unmodified lines