doc: specify complete file names
[vis.git] / text-util.c
blobf3ba0a06ab4da6212f56129551e9dcc514ca999a
1 #include "text-util.h"
2 #include "util.h"
3 #include <wchar.h>
4 #include <errno.h>
5 #include <stdlib.h>
7 bool text_range_valid(const Filerange *r) {
8 return r->start != EPOS && r->end != EPOS && r->start <= r->end;
11 size_t text_range_size(const Filerange *r) {
12 return text_range_valid(r) ? r->end - r->start : 0;
15 Filerange text_range_empty(void) {
16 return (Filerange){ .start = EPOS, .end = EPOS };
19 Filerange text_range_union(const Filerange *r1, const Filerange *r2) {
20 if (!text_range_valid(r1))
21 return *r2;
22 if (!text_range_valid(r2))
23 return *r1;
24 return (Filerange) {
25 .start = MIN(r1->start, r2->start),
26 .end = MAX(r1->end, r2->end),
30 Filerange text_range_new(size_t a, size_t b) {
31 return (Filerange) {
32 .start = MIN(a, b),
33 .end = MAX(a, b),
37 bool text_range_equal(const Filerange *r1, const Filerange *r2) {
38 if (!text_range_valid(r1) && !text_range_valid(r2))
39 return true;
40 return r1->start == r2->start && r1->end == r2->end;
43 bool text_range_overlap(const Filerange *r1, const Filerange *r2) {
44 if (!text_range_valid(r1) || !text_range_valid(r2))
45 return false;
46 return r1->start <= r2->end && r2->start <= r1->end;
49 bool text_range_contains(const Filerange *r, size_t pos) {
50 return text_range_valid(r) && r->start <= pos && pos <= r->end;
53 int text_char_count(const char *data, size_t len) {
54 int count = 0;
55 mbstate_t ps = { 0 };
56 while (len > 0) {
57 wchar_t wc;
58 size_t wclen = mbrtowc(&wc, data, len, &ps);
59 if (wclen == (size_t)-1 && errno == EILSEQ) {
60 count++;
61 while (!ISUTF8(*data))
62 data++, len--;
63 } else if (wclen == (size_t)-2) {
64 break;
65 } else if (wclen == 0) {
66 count++;
67 data++;
68 len--;
69 } else {
70 int width = wcwidth(wc);
71 if (width != 0)
72 count++;
73 data += wclen;
74 len -= wclen;
77 return count;
80 int text_string_width(const char *data, size_t len) {
82 int width = 0;
83 mbstate_t ps = { 0 };
84 const char *s = data;
86 while (len > 0) {
87 wchar_t wc;
88 size_t wclen = mbrtowc(&wc, s, len, &ps);
89 if (wclen == (size_t)-1 && errno == EILSEQ) {
90 /* assume a replacement symbol will be displayed */
91 width++;
92 wclen = 1;
93 } else if (wclen == (size_t)-2) {
94 /* do nothing, advance to next character */
95 wclen = 1;
96 } else if (wclen == 0) {
97 /* assume NUL byte will be displayed as ^@ */
98 width += 2;
99 wclen = 1;
100 } else if (wc == L'\t') {
101 width++;
102 wclen = 1;
103 } else {
104 int w = wcwidth(wc);
105 if (w == -1)
106 w = 2; /* assume non-printable will be displayed as ^{char} */
107 width += w;
109 len -= wclen;
110 s += wclen;
113 return width;