Skip to content
Myr

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

2 files+26 added−26 removed

modified:main.c+15 added-17 removed
2 unmodified lines
3#include <string.h>4#include <stdbool.h>5#include <unistd.h>67#include <locale.h>8#include <threads.h>9#include <poll.h>1011#include <sys/types.h>
200 unmodified lines
212213static size_t214prompt_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;217218 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 }221221 do {222 c++;223 } while (c < end && ((unsigned char)*c >> 6) == 2);224225 return c - prompt->text;222 return prompt->cursor + clen;223}224225static size_t226prompt_prev_char(const struct prompt *prompt)227{228 if (prompt->cursor == 0)229 return 0;230234 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 }237236 do {237 c--;238 } while (c > prompt->text && !((unsigned char)*c >> 7 == 0 ||239 (unsigned char)*c >> 6 == 3));240241 assert(c >= prompt->text);242 return c - prompt->text;238 return cursor;239}240241static size_t242prompt_prev_word(const struct prompt *prompt)
556 unmodified lines
799main(int argc, const char *const *argv)800{801 int ret = EXIT_FAILURE;802803 setlocale(LC_ALL, "");804805 struct context c = {806 .keep_running = true,807 .wl = {0},808 .prompt = {
198 unmodified lines
modified:render.c+11 added-9 removed
51 unmodified lines
52 clusters, num_clusters, cluster_flags);5354 /* 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;5859 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 }6566 cursor += clen;67 cursor_at_glyph++;68 }6970 int cursor_x;
103 unmodified lines