Skip to content

Commit

Permalink
Add utility function to calculate display width of a string
Browse files Browse the repository at this point in the history
This is based on the implementation of text_line_width_get
from text-motions.c. There might be an opportunity for code
sharing.
  • Loading branch information
martanne committed May 24, 2016
1 parent 9bcfd3f commit 3cea78b
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
38 changes: 38 additions & 0 deletions text-util.c
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
#include "util.h"
#include <wchar.h>
#include <errno.h>
#include <stdlib.h>

bool text_range_valid(const Filerange *r) {
return r->start != EPOS && r->end != EPOS && r->start <= r->end;
Expand Down Expand Up @@ -75,3 +76,40 @@ int text_char_count(const char *data, size_t len) {
}
return count;
}

int text_string_width(const char *data, size_t len) {

int width = 0;
mbstate_t ps = { 0 };
const char *s = data;

while (len > 0) {
char buf[MB_CUR_MAX];
wchar_t wc;
size_t wclen = mbrtowc(&wc, s, len, &ps);
if (wclen == (size_t)-1 && errno == EILSEQ) {
/* assume a replacement symbol will be displayed */
width++;
wclen = 1;
} else if (wclen == (size_t)-2) {
/* do nothing, advance to next character */
wclen = 1;
} else if (wclen == 0) {
/* assume NUL byte will be displayed as ^@ */
width += 2;
wclen = 1;
} else if (buf[0] == '\t') {
width++;
wclen = 1;
} else {
int w = wcwidth(wc);
if (w == -1)
w = 2; /* assume non-printable will be displayed as ^{char} */
width += w;
}
len -= wclen;
s += wclen;
}

return width;
}
2 changes: 2 additions & 0 deletions text-util.h
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,7 @@ bool text_range_overlap(const Filerange*, const Filerange*);
bool text_range_contains(const Filerange*, size_t pos);
/* count the number of graphemes in data */
int text_char_count(const char *data, size_t len);
/* get the approximate display width of data */
int text_string_width(const char *data, size_t len);

#endif

0 comments on commit 3cea78b

Please sign in to comment.