unexpand: fix "a b"\n" input case
[oweals/busybox.git] / coreutils / expand.c
index 649b4c175a0a5ec28f68a92dd06c2c910bf63ded..cfb1e25d9216eebbd72593d18433233aa53afe00 100644 (file)
@@ -49,7 +49,11 @@ static void expand(FILE *file, unsigned tab_size, unsigned opt)
                                unsigned len;
                                *ptr = '\0';
 # if ENABLE_FEATURE_ASSUME_UNICODE
-                               len = bb_mbstrlen(ptr_strbeg);
+                               {
+                                       uni_stat_t uni_stat;
+                                       printable_string(&uni_stat, ptr_strbeg);
+                                       len = uni_stat.unicode_width;
+                               }
 # else
                                len = ptr - ptr_strbeg;
 # endif
@@ -77,12 +81,13 @@ static void unexpand(FILE *file, unsigned tab_size, unsigned opt)
 
                while (*ptr) {
                        unsigned n;
-                       unsigned len;
+                       unsigned len = 0;
 
                        while (*ptr == ' ') {
-                               column++;
                                ptr++;
+                               len++;
                        }
+                       column += len;
                        if (*ptr == '\t') {
                                column += tab_size - (column % tab_size);
                                ptr++;
@@ -90,22 +95,26 @@ static void unexpand(FILE *file, unsigned tab_size, unsigned opt)
                        }
 
                        n = column / tab_size;
-                       column = column % tab_size;
-                       while (n--)
-                               putchar('\t');
+                       if (n) {
+                               len = column = column % tab_size;
+                               while (n--)
+                                       putchar('\t');
+                       }
 
                        if ((opt & OPT_INITIAL) && ptr != line) {
-                               printf("%*s%s", column, "", ptr);
+                               printf("%*s%s", len, "", ptr);
                                break;
                        }
                        n = strcspn(ptr, "\t ");
-                       printf("%*s%.*s", column, "", n, ptr);
+                       printf("%*s%.*s", len, "", n, ptr);
 # if ENABLE_FEATURE_ASSUME_UNICODE
                        {
                                char c;
+                               uni_stat_t uni_stat;
                                c = ptr[n];
                                ptr[n] = '\0';
-                               len = bb_mbstrlen(ptr);
+                               printable_string(&uni_stat, ptr);
+                               len = uni_stat.unicode_width;
                                ptr[n] = c;
                        }
 # else