MCPcopy Create free account
hub / github.com/antirez/ds4 / utf8StrWidth

Function utf8StrWidth

linenoise.c:441–478  ·  view source on GitHub ↗

Calculate the display width of a UTF-8 string of 'len' bytes. * This is used for cursor positioning in the terminal. * Handles grapheme clusters: characters joined by ZWJ contribute 0 width * after the first character in the sequence. * ANSI CSI escape sequences (e.g. color codes in the prompt) are treated * as zero-width. */

Source from the content-addressed store, hash-verified

439 (cp >= 0xFFE0 && cp <= 0xFFE6) || /* Fullwidth Signs */
440 (cp >= 0x1F1E6 && cp <= 0x1F1FF) || /* Regional Indicators (flags) */
441 (cp >= 0x1F300 && cp <= 0x1F64F) || /* Misc Symbols and Emoticons */
442 (cp >= 0x1F680 && cp <= 0x1F6FF) || /* Transport and Map Symbols */
443 (cp >= 0x1F900 && cp <= 0x1F9FF) || /* Supplemental Symbols */
444 (cp >= 0x1FA00 && cp <= 0x1FAFF) || /* Chess, Extended-A */
445 (cp >= 0x20000 && cp <= 0x2FFFF))) /* CJK Extension B and beyond */
446 return 2;
447
448 return 1; /* Default: single width */
449}
450
451int linenoiseCharacterWidth(uint32_t cp) {
452 return utf8CharWidth(cp);
453}
454
455size_t linenoiseNextGrapheme(const char *s, size_t len, int *width) {
456 uint32_t cp;
457 size_t used = linenoiseUtf8Decode(s, len, &cp);
458 if (!used) { if (width) *width = 0; return 0; }
459 int w = utf8CharWidth(cp), regional = isRegionalIndicator(cp), joined = 0;
460 while (used < len) {
461 size_t n = linenoiseUtf8Decode(s + used, len - used, &cp);
462 if (!n) break;
463 if (joined) {
464 if (utf8CharWidth(cp) > w) w = utf8CharWidth(cp);
465 joined = 0;
466 } else if (isZWJ(cp)) {
467 joined = 1;
468 } else if (isGraphemeExtend(cp)) {
469 if (cp == 0xfe0f && w) w = 2;
470 } else if (regional && isRegionalIndicator(cp)) {
471 regional = 0;
472 } else break;
473 used += n;
474 }
475 if (width) *width = w;
476 return used;
477}
478
479/* If s[] points at an ANSI CSI escape sequence (e.g. a color change like
480 * ESC [ 1 ; 32 m), return its length in bytes. Otherwise return 0.
481 *

Callers 4

refreshShowHintsFunction · 0.85
refreshSingleLineFunction · 0.85
refreshMultiLineFunction · 0.85
linenoiseEditInsertFunction · 0.85

Calls 4

utf8DecodeCharFunction · 0.85
ansiEscapeLenFunction · 0.85
utf8CharWidthFunction · 0.85
isZWJFunction · 0.85

Tested by

no test coverage detected