+ /*
+ * See the relevant comments in cpstripped() to explain what's
+ * going on here; we want to handle the case where we get
+ * characters that mbtowc() cannot handle
+ */
+
+ if (char_len < 0) {
+ altstr = "?";
+ char_len = mbtowc(&wide_char, altstr, 1);
+ }
+
+ if (char_len <= 0) {
+ break;
+ }
+
+ w = wcwidth(wide_char);
+
+ /* If w > remaining, w must be positive. */
+ if (w > remaining) {
+ break;
+ }
+
+ end -= char_len;
+
+ if (iswcntrl(wide_char) || iswspace(wide_char)) {
+ sp += char_len;
+#else
+ int c;
+ end--;
+ /* isnctrl(), etc., take an int argument. Cygwin's ctype.h
+ intentionally warns if they are passed a char. */
+ c = (unsigned char) *sp;
+ if (iscntrl(c) || isspace(c)) {
+ sp++;
+#endif
+ if (!prevCtrl) {
+ charstring_push_back (trimmed, ' ');
+ remaining--;
+ }
+
+ prevCtrl = 1;
+ continue;
+ }
+ prevCtrl = 0;
+
+#ifdef MULTIBYTE_SUPPORT
+ if (w >= 0 && remaining >= w) {
+ charstring_push_back_chars (trimmed, altstr ? altstr : sp,
+ char_len, w);
+ remaining -= w;
+ altstr = NULL;
+ }
+ sp += char_len;
+#else
+ charstring_push_back (trimmed, *sp++);
+ remaining--;
+#endif
+ }
+ }
+
+ while (remaining-- > 0) {
+ charstring_push_back(dest, fill);
+ }
+
+ if (rjust) {
+ charstring_append(dest, trimmed);
+ charstring_free(trimmed);
+ }
+}
+
+#ifdef MULTIBYTE_SUPPORT
+static void
+cpstripped (charstring_t dest, size_t max, char *str)
+{
+ static bool deja_vu;
+ static char *oddchar;
+ static size_t oddlen;
+ static char *spacechar;
+ static size_t spacelen;
+ char *end;
+ bool squash;
+ char *src;
+ int srclen;
+ wchar_t rune;
+ int w;
+
+ if (!deja_vu) {
+ size_t two;
+
+ deja_vu = true;
+
+ two = MB_CUR_MAX * 2; /* Varies at run-time. */
+
+ oddchar = mh_xmalloc(two);
+ oddlen = wcstombs(oddchar, L"?", two);
+ assert(oddlen > 0);
+
+ assert(wcwidth(L' ') == 1); /* Need to pad in ones. */
+ spacechar = mh_xmalloc(two);
+ spacelen = wcstombs(spacechar, L" ", two);
+ assert(spacelen > 0);
+ }
+
+ if (!str)
+ return; /* It's unclear why no padding in this case. */
+ end = str + strlen(str);
+
+ if (mbtowc(NULL, NULL, 0))
+ {} /* Reset shift state. */
+
+ squash = true; /* Trim `space' or `cntrl' from the start. */
+ while (max) {
+ if (!*str)
+ return; /* It's unclear why no padding in this case. */
+
+ srclen = mbtowc(&rune, str, end - str);
+ if (srclen == -1) {
+ /* Invalid rune, or not enough bytes to finish it. */
+ rune = L'?';
+ src = oddchar;
+ srclen = oddlen;
+ str++; /* Skip one byte. */
+ } else {
+ src = str;
+ str += srclen;