stagit-gopher-index: sync utf8pad from stagit-gopher.c - stagit-gopher - A git gopher frontend. (mirror)
 (HTM) git clone git://bitreich.org/stagit-gopher/ git://enlrupgkhuxnvlhsf6lc3fziv5h2hhfrinws65d7roiv6bfj7d652fid.onion/stagit-gopher/
 (DIR) Log
 (DIR) Files
 (DIR) Refs
 (DIR) Tags
 (DIR) README
 (DIR) LICENSE
       ---
 (DIR) commit 8091f757ce641307bcdc69c9e5348ef54ab82e5c
 (DIR) parent 70e0e50a6c4d83f7b809be4338bcf2868c13b49b
 (HTM) Author: Hiltjo Posthuma <hiltjo@codemadness.org>
       Date:   Fri,  8 Jan 2021 14:30:44 +0100
       
       stagit-gopher-index: sync utf8pad from stagit-gopher.c
       
       Syncs a fix from commit e32410fe:
       "fix truncation and padding for lines containing multiwidth glyphs"
       
       Diffstat:
         M stagit-gopher-index.c               |      22 +++++++++++++---------
       
       1 file changed, 13 insertions(+), 9 deletions(-)
       ---
 (DIR) diff --git a/stagit-gopher-index.c b/stagit-gopher-index.c
       @@ -22,29 +22,33 @@ static char *name = "";
        int
        utf8pad(char *buf, size_t bufsiz, const char *s, size_t len, int pad)
        {
       -        wchar_t w;
       +        wchar_t wc;
                size_t col = 0, i, slen, siz = 0;
       -        int rl, wc;
       +        int rl, w;
        
                if (!len)
                        return -1;
        
                slen = strlen(s);
       -        for (i = 0; i < slen && col < len + 1; i += rl) {
       -                if ((rl = mbtowc(&w, &s[i], slen - i < 4 ? slen - i : 4)) <= 0)
       +        for (i = 0; i < slen; i += rl) {
       +                if ((rl = mbtowc(&wc, &s[i], slen - i < 4 ? slen - i : 4)) <= 0)
                                break;
       -                if ((wc = wcwidth(w)) == -1)
       -                        wc = 1;
       -                col += wc;
       -                if (col >= len && s[i + rl]) {
       +                if ((w = wcwidth(wc)) == -1)
       +                        continue;
       +                if (col + w > len || (col + w == len && s[i + rl])) {
                                if (siz + 4 >= bufsiz)
                                        return -1;
       -                        memcpy(&buf[siz], "\xe2\x80\xa6", 4);
       +                        memcpy(&buf[siz], "\xe2\x80\xa6", 3);
       +                        siz += 3;
       +                        if (col + w == len && w > 1)
       +                                buf[siz++] = pad;
       +                        buf[siz] = '\0';
                                return 0;
                        }
                        if (siz + rl + 1 >= bufsiz)
                                return -1;
                        memcpy(&buf[siz], &s[i], rl);
       +                col += w;
                        siz += rl;
                        buf[siz] = '\0';
                }