Thread (20 messages) 20 messages, 3 authors, 2016-06-15

[PATCH v10 04/13] utf8: add function to align a string into given strbuf

flat view
STALE3770d SUPERSEDED

From: Karthik Nayak <hidden>
Date: 2016-06-15 23:06:07
Subsystem: the rest · Maintainer: Linus Torvalds

Revision v10 of 6 in this series.

Revisions (6)
  1. v3 [diff vs current]
  2. v4 [diff vs current]
  3. v10 current
  4. v13 [diff vs current]
  5. v16 [diff vs current]
  6. v17 [diff vs current]
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 [off-list ref]
Mentored-by: Christian Couder [off-list ref]
Mentored-by: Matthieu Moy [off-list ref]
Signed-off-by: Karthik Nayak <redacted>
---
 utf8.c | 22 ++++++++++++++++++++++
 utf8.h | 13 +++++++++++++
 2 files changed, 35 insertions(+)
diff --git a/utf8.c b/utf8.c
index 28e6d76..65e55cc 100644
--- a/utf8.c
+++ b/utf8.c
@@ -644,3 +644,25 @@ int skip_utf8_bom(char **text, size_t len)
 	*text += strlen(utf8_bom);
 	return 1;
 }
+
+void strbuf_utf8_align(struct strbuf *buf, align_type position, unsigned int width,
+		       const char *s)
+{
+	int display_len = utf8_strnwidth(s, strlen(s), 0);
+	int utf8_compenstation = strlen(s) - display_len;
+
+	if (!strlen(s))
+		return;
+	if (display_len >= width) {
+		strbuf_addstr(buf, s);
+		return;
+	}
+
+	if (position == ALIGN_LEFT)
+		strbuf_addf(buf, "%-*s", width + utf8_compenstation, s);
+	else if (position == ALIGN_MIDDLE) {
+		int left = (width - display_len)/2;
+		strbuf_addf(buf, "%*s%-*s", left, "", width - left + utf8_compenstation, s);
+	} else if (position == ALIGN_RIGHT)
+		strbuf_addf(buf, "%*s", width + utf8_compenstation, s);
+}
diff --git a/utf8.h b/utf8.h
index 5a9e94b..db8ca63 100644
--- a/utf8.h
+++ b/utf8.h
@@ -55,4 +55,17 @@ int mbs_chrlen(const char **text, size_t *remainder_p, const char *encoding);
  */
 int is_hfs_dotgit(const char *path);
 
+typedef enum {
+	ALIGN_LEFT,
+	ALIGN_MIDDLE,
+	ALIGN_RIGHT
+} align_type;
+
+/*
+ * Align the string given and store it into a strbuf as per the type
+ * and width.
+ */
+void strbuf_utf8_align(struct strbuf *buf, align_type position, unsigned int width,
+		       const char *s);
+
 #endif
-- 
2.5.0
Keyboard shortcuts
hback out one level
jnext message in thread
kprevious message in thread
ldrill in
Escclose help / fold thread tree
?toggle this help