From f7be510d2669646c60845b091087362d51ae29ea Mon Sep 17 00:00:00 2001 From: Přemysl Eric Janouch Date: Sat, 27 Aug 2022 08:55:44 +0200 Subject: xC: make fancy-prompt.lua alignment more reliable And generally clean up that script. --- xC.c | 33 ++++++++++++++++++++++++++++++--- 1 file changed, 30 insertions(+), 3 deletions(-) (limited to 'xC.c') diff --git a/xC.c b/xC.c index 9cb97c8..7b61fb9 100644 --- a/xC.c +++ b/xC.c @@ -3776,7 +3776,7 @@ explode_text (struct exploder *self, const char *text) if (!strchr ("\a\b\x0e\x0f\x1b" /* BEL BS SO SI ESC */, *p)) str_append_c (&filtered, *p); - size_t term_len = 0; + size_t term_len = 0, processed = 0, len; char *term = iconv_xstrdup (self->ctx->term_from_utf8, filtered.str, filtered.len + 1, &term_len); str_free (&filtered); @@ -3785,11 +3785,10 @@ explode_text (struct exploder *self, const char *text) memset (&ps, 0, sizeof ps); wchar_t wch; - size_t len, processed = 0; while ((len = mbrtowc (&wch, term + processed, term_len - processed, &ps))) { hard_assert (len != (size_t) -2 && len != (size_t) -1); - processed += len; + hard_assert ((processed += len) <= term_len); struct line_char *c = line_char_new (wch); c->attrs = self->attrs; @@ -10527,6 +10526,33 @@ lua_plugin_get_screen_size (lua_State *L) return 2; } +static int +lua_plugin_measure (lua_State *L) +{ + struct lua_plugin *plugin = lua_touserdata (L, lua_upvalueindex (1)); + const char *line = lua_plugin_check_utf8 (L, 1); + + size_t term_len = 0, processed = 0, width = 0, len; + char *term = iconv_xstrdup (plugin->ctx->term_from_utf8, + (char *) line, strlen (line) + 1, &term_len); + + mbstate_t ps; + memset (&ps, 0, sizeof ps); + + wchar_t wch; + while ((len = mbrtowc (&wch, term + processed, term_len - processed, &ps))) + { + hard_assert (len != (size_t) -2 && len != (size_t) -1); + hard_assert ((processed += len) <= term_len); + + int wch_width = wcwidth (wch); + width += MAX (0, wch_width); + } + free (term); + lua_pushinteger (L, width); + return 1; +} + static int lua_ctx_gc (lua_State *L) { @@ -10547,6 +10573,7 @@ static luaL_Reg lua_plugin_library[] = // And these are methods: { "get_screen_size", lua_plugin_get_screen_size }, + { "measure", lua_plugin_measure }, { "__gc", lua_ctx_gc }, { NULL, NULL }, }; -- cgit v1.2.3-54-g00ecf