utf8: add function to align a string into given strbuf

Add strbuf_utf8_align() which will align a given string into a strbuf as per given align_type and width. If the width is greater than the string length then no alignment is performed. Helped-by: Eric Sunshine <sunshine@sunshineco.com> Mentored-by: Christian Couder <christian.couder@gmail.com> Mentored-by: Matthieu Moy <matthieu.moy@grenoble-inp.fr> Signed-off-by: Karthik Nayak <karthik.188@gmail.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Karthik Nayak committed Sep 10, 2015 at 21:18 UTC 110dcda50d5ddaf3557666eea3b012a6ccc74dce
2 files changed +36
utf8.c
+21
@@ -644,3 +644,24 @@ int skip_utf8_bom(char **text, size_t len)
644 *text += strlen(utf8_bom);
645 return 1;
646 }
647 +
648 +void strbuf_utf8_align(struct strbuf *buf, align_type position, unsigned int width,
649 + const char *s)
650 +{
651 + int slen = strlen(s);
652 + int display_len = utf8_strnwidth(s, slen, 0);
653 + int utf8_compensation = slen - display_len;
654 +
655 + if (display_len >= width) {
656 + strbuf_addstr(buf, s);
657 + return;
658 + }
659 +
660 + if (position == ALIGN_LEFT)
661 + strbuf_addf(buf, "%-*s", width + utf8_compensation, s);
662 + else if (position == ALIGN_MIDDLE) {
663 + int left = (width - display_len) / 2;
664 + strbuf_addf(buf, "%*s%-*s", left, "", width - left + utf8_compensation, s);
665 + } else if (position == ALIGN_RIGHT)
666 + strbuf_addf(buf, "%*s", width + utf8_compensation, s);
667 +}
utf8.h
+15
@@ -55,4 +55,19 @@ int mbs_chrlen(const char **text, size_t *remainder_p, const char *encoding);
55 */
56 int is_hfs_dotgit(const char *path);
57
58 +typedef enum {
59 + ALIGN_LEFT,
60 + ALIGN_MIDDLE,
61 + ALIGN_RIGHT
62 +} align_type;
63 +
64 +/*
65 + * Align the string given and store it into a strbuf as per the
66 + * 'position' and 'width'. If the given string length is larger than
67 + * 'width' than then the input string is not truncated and no
68 + * alignment is done.
69 + */
70 +void strbuf_utf8_align(struct strbuf *buf, align_type position, unsigned int width,
71 + const char *s);
72 +
73 #endif