blob: de4ce5c0e68adc5da1976806e45e73f42b6e1346 [file] [log] [blame]
Johannes Schindelin9e832662006-12-22 22:06:08 +01001#include "git-compat-util.h"
Johannes Schindelina94410c2008-11-10 18:47:00 +01002#include "strbuf.h"
Johannes Schindelin9e832662006-12-22 22:06:08 +01003#include "utf8.h"
4
5/* This code is originally from http://www.cl.cam.ac.uk/~mgk25/ucs/ */
6
Torsten Bögershausenaab2a1a2019-01-30 16:01:52 +01007static const char utf16_be_bom[] = {'\xFE', '\xFF'};
8static const char utf16_le_bom[] = {'\xFF', '\xFE'};
9static const char utf32_be_bom[] = {'\0', '\0', '\xFE', '\xFF'};
10static const char utf32_le_bom[] = {'\xFF', '\xFE', '\0', '\0'};
11
Johannes Schindelin9e832662006-12-22 22:06:08 +010012struct interval {
John Keepinga68a67d2014-02-16 16:06:04 +000013 ucs_char_t first;
14 ucs_char_t last;
Johannes Schindelin9e832662006-12-22 22:06:08 +010015};
16
Nguyễn Thái Ngọc Duy16406322013-04-19 09:08:52 +100017size_t display_mode_esc_sequence_len(const char *s)
Nguyễn Thái Ngọc Duy4247fe72013-04-19 09:08:44 +100018{
19 const char *p = s;
20 if (*p++ != '\033')
21 return 0;
22 if (*p++ != '[')
23 return 0;
24 while (isdigit(*p) || *p == ';')
25 p++;
26 if (*p++ != 'm')
27 return 0;
28 return p - s;
29}
30
Johannes Schindelin9e832662006-12-22 22:06:08 +010031/* auxiliary function for binary search in interval table */
Junio C Hamanof3fa1832007-11-08 15:35:32 -080032static int bisearch(ucs_char_t ucs, const struct interval *table, int max)
33{
Johannes Schindelin9e832662006-12-22 22:06:08 +010034 int min = 0;
35 int mid;
36
37 if (ucs < table[0].first || ucs > table[max].last)
38 return 0;
39 while (max >= min) {
Derrick Stolee19716b22017-10-08 14:29:37 -040040 mid = min + (max - min) / 2;
Johannes Schindelin9e832662006-12-22 22:06:08 +010041 if (ucs > table[mid].last)
42 min = mid + 1;
43 else if (ucs < table[mid].first)
44 max = mid - 1;
45 else
46 return 1;
47 }
48
49 return 0;
50}
51
52/* The following two functions define the column width of an ISO 10646
53 * character as follows:
54 *
55 * - The null character (U+0000) has a column width of 0.
56 *
57 * - Other C0/C1 control characters and DEL will lead to a return
58 * value of -1.
59 *
60 * - Non-spacing and enclosing combining characters (general
61 * category code Mn or Me in the Unicode database) have a
62 * column width of 0.
63 *
64 * - SOFT HYPHEN (U+00AD) has a column width of 1.
65 *
66 * - Other format characters (general category code Cf in the Unicode
67 * database) and ZERO WIDTH SPACE (U+200B) have a column width of 0.
68 *
69 * - Hangul Jamo medial vowels and final consonants (U+1160-U+11FF)
70 * have a column width of 0.
71 *
72 * - Spacing characters in the East Asian Wide (W) or East Asian
73 * Full-width (F) category as defined in Unicode Technical
74 * Report #11 have a column width of 2.
75 *
76 * - All remaining characters (including all printable
77 * ISO 8859-1 and WGL4 characters, Unicode control characters,
78 * etc.) have a column width of 1.
79 *
Ramsay Jones28321142007-03-03 18:28:57 +000080 * This implementation assumes that ucs_char_t characters are encoded
Johannes Schindelin9e832662006-12-22 22:06:08 +010081 * in ISO 10646.
82 */
83
Amos Waterlandb51be132007-05-08 00:46:08 -040084static int git_wcwidth(ucs_char_t ch)
Johannes Schindelin9e832662006-12-22 22:06:08 +010085{
86 /*
87 * Sorted list of non-overlapping intervals of non-spacing characters,
Johannes Schindelin9e832662006-12-22 22:06:08 +010088 */
Stefan Bellere233bef2018-04-10 14:26:17 -070089#include "unicode-width.h"
Johannes Schindelin9e832662006-12-22 22:06:08 +010090
91 /* test for 8-bit control characters */
92 if (ch == 0)
93 return 0;
94 if (ch < 32 || (ch >= 0x7f && ch < 0xa0))
95 return -1;
96
97 /* binary search in table of non-spacing characters */
Beat Bollifa364ad2019-10-11 20:41:23 +020098 if (bisearch(ch, zero_width, ARRAY_SIZE(zero_width) - 1))
Johannes Schindelin9e832662006-12-22 22:06:08 +010099 return 0;
100
Torsten Bögershausen08460342014-05-09 23:51:38 +0200101 /* binary search in table of double width characters */
Beat Bollifa364ad2019-10-11 20:41:23 +0200102 if (bisearch(ch, double_width, ARRAY_SIZE(double_width) - 1))
Torsten Bögershausen08460342014-05-09 23:51:38 +0200103 return 2;
Johannes Schindelin9e832662006-12-22 22:06:08 +0100104
Torsten Bögershausen08460342014-05-09 23:51:38 +0200105 return 1;
Johannes Schindelin9e832662006-12-22 22:06:08 +0100106}
107
108/*
Junio C Hamano396ccf12008-01-06 19:02:22 -0800109 * Pick one ucs character starting from the location *start points at,
110 * and return it, while updating the *start pointer to point at the
Junio C Hamano44b25b82008-01-02 01:49:58 -0800111 * end of that character. When remainder_p is not NULL, the location
112 * holds the number of bytes remaining in the string that we are allowed
113 * to pick from. Otherwise we are allowed to pick up to the NUL that
114 * would eventually appear in the string. *remainder_p is also reduced
115 * by the number of bytes we have consumed.
Junio C Hamano396ccf12008-01-06 19:02:22 -0800116 *
117 * If the string was not a valid UTF-8, *start pointer is set to NULL
118 * and the return value is undefined.
Johannes Schindelin9e832662006-12-22 22:06:08 +0100119 */
Junio C Hamano5e133b82010-01-11 22:32:29 -0800120static ucs_char_t pick_one_utf8_char(const char **start, size_t *remainder_p)
Johannes Schindelin9e832662006-12-22 22:06:08 +0100121{
122 unsigned char *s = (unsigned char *)*start;
Ramsay Jones28321142007-03-03 18:28:57 +0000123 ucs_char_t ch;
Junio C Hamano44b25b82008-01-02 01:49:58 -0800124 size_t remainder, incr;
Johannes Schindelin9e832662006-12-22 22:06:08 +0100125
Junio C Hamano44b25b82008-01-02 01:49:58 -0800126 /*
127 * A caller that assumes NUL terminated text can choose
128 * not to bother with the remainder length. We will
129 * stop at the first NUL.
130 */
131 remainder = (remainder_p ? *remainder_p : 999);
132
133 if (remainder < 1) {
134 goto invalid;
135 } else if (*s < 0x80) {
Johannes Schindelin9e832662006-12-22 22:06:08 +0100136 /* 0xxxxxxx */
137 ch = *s;
Junio C Hamano44b25b82008-01-02 01:49:58 -0800138 incr = 1;
Johannes Schindelin9e832662006-12-22 22:06:08 +0100139 } else if ((s[0] & 0xe0) == 0xc0) {
140 /* 110XXXXx 10xxxxxx */
Junio C Hamano44b25b82008-01-02 01:49:58 -0800141 if (remainder < 2 ||
142 (s[1] & 0xc0) != 0x80 ||
143 (s[0] & 0xfe) == 0xc0)
Johannes Schindelin9e832662006-12-22 22:06:08 +0100144 goto invalid;
145 ch = ((s[0] & 0x1f) << 6) | (s[1] & 0x3f);
Junio C Hamano44b25b82008-01-02 01:49:58 -0800146 incr = 2;
Johannes Schindelin9e832662006-12-22 22:06:08 +0100147 } else if ((s[0] & 0xf0) == 0xe0) {
148 /* 1110XXXX 10Xxxxxx 10xxxxxx */
Junio C Hamano44b25b82008-01-02 01:49:58 -0800149 if (remainder < 3 ||
150 (s[1] & 0xc0) != 0x80 ||
151 (s[2] & 0xc0) != 0x80 ||
152 /* overlong? */
153 (s[0] == 0xe0 && (s[1] & 0xe0) == 0x80) ||
154 /* surrogate? */
155 (s[0] == 0xed && (s[1] & 0xe0) == 0xa0) ||
156 /* U+FFFE or U+FFFF? */
157 (s[0] == 0xef && s[1] == 0xbf &&
158 (s[2] & 0xfe) == 0xbe))
Johannes Schindelin9e832662006-12-22 22:06:08 +0100159 goto invalid;
160 ch = ((s[0] & 0x0f) << 12) |
161 ((s[1] & 0x3f) << 6) | (s[2] & 0x3f);
Junio C Hamano44b25b82008-01-02 01:49:58 -0800162 incr = 3;
Johannes Schindelin9e832662006-12-22 22:06:08 +0100163 } else if ((s[0] & 0xf8) == 0xf0) {
164 /* 11110XXX 10XXxxxx 10xxxxxx 10xxxxxx */
Junio C Hamano44b25b82008-01-02 01:49:58 -0800165 if (remainder < 4 ||
166 (s[1] & 0xc0) != 0x80 ||
167 (s[2] & 0xc0) != 0x80 ||
168 (s[3] & 0xc0) != 0x80 ||
169 /* overlong? */
170 (s[0] == 0xf0 && (s[1] & 0xf0) == 0x80) ||
171 /* > U+10FFFF? */
172 (s[0] == 0xf4 && s[1] > 0x8f) || s[0] > 0xf4)
Johannes Schindelin9e832662006-12-22 22:06:08 +0100173 goto invalid;
174 ch = ((s[0] & 0x07) << 18) | ((s[1] & 0x3f) << 12) |
175 ((s[2] & 0x3f) << 6) | (s[3] & 0x3f);
Junio C Hamano44b25b82008-01-02 01:49:58 -0800176 incr = 4;
Johannes Schindelin9e832662006-12-22 22:06:08 +0100177 } else {
178invalid:
179 *start = NULL;
180 return 0;
181 }
182
Junio C Hamano44b25b82008-01-02 01:49:58 -0800183 *start += incr;
184 if (remainder_p)
185 *remainder_p = remainder - incr;
Junio C Hamano396ccf12008-01-06 19:02:22 -0800186 return ch;
187}
188
189/*
190 * This function returns the number of columns occupied by the character
191 * pointed to by the variable start. The pointer is updated to point at
Junio C Hamano44b25b82008-01-02 01:49:58 -0800192 * the next character. When remainder_p is not NULL, it points at the
193 * location that stores the number of remaining bytes we can use to pick
194 * a character (see pick_one_utf8_char() above).
Junio C Hamano396ccf12008-01-06 19:02:22 -0800195 */
Junio C Hamano44b25b82008-01-02 01:49:58 -0800196int utf8_width(const char **start, size_t *remainder_p)
Junio C Hamano396ccf12008-01-06 19:02:22 -0800197{
Junio C Hamano44b25b82008-01-02 01:49:58 -0800198 ucs_char_t ch = pick_one_utf8_char(start, remainder_p);
Junio C Hamano396ccf12008-01-06 19:02:22 -0800199 if (!*start)
200 return 0;
Amos Waterlandb51be132007-05-08 00:46:08 -0400201 return git_wcwidth(ch);
Johannes Schindelin9e832662006-12-22 22:06:08 +0100202}
203
Geoffrey Thomas8a9391e2009-01-30 04:41:28 -0500204/*
205 * Returns the total number of columns required by a null-terminated
206 * string, assuming that the string is utf8. Returns strlen() instead
207 * if the string does not look like a valid utf8 string.
208 */
Nguyễn Thái Ngọc Duy2bc1e7e2013-04-19 09:08:45 +1000209int utf8_strnwidth(const char *string, int len, int skip_ansi)
Geoffrey Thomas8a9391e2009-01-30 04:41:28 -0500210{
211 int width = 0;
212 const char *orig = string;
213
Nguyễn Thái Ngọc Duy2bc1e7e2013-04-19 09:08:45 +1000214 if (len == -1)
215 len = strlen(string);
216 while (string && string < orig + len) {
217 int skip;
218 while (skip_ansi &&
219 (skip = display_mode_esc_sequence_len(string)) != 0)
220 string += skip;
Geoffrey Thomas8a9391e2009-01-30 04:41:28 -0500221 width += utf8_width(&string, NULL);
222 }
Nguyễn Thái Ngọc Duy2bc1e7e2013-04-19 09:08:45 +1000223 return string ? width : len;
224}
225
226int utf8_strwidth(const char *string)
227{
228 return utf8_strnwidth(string, -1, 0);
Geoffrey Thomas8a9391e2009-01-30 04:41:28 -0500229}
230
Johannes Schindelin9e832662006-12-22 22:06:08 +0100231int is_utf8(const char *text)
232{
233 while (*text) {
234 if (*text == '\n' || *text == '\t' || *text == '\r') {
235 text++;
236 continue;
237 }
Junio C Hamano44b25b82008-01-02 01:49:58 -0800238 utf8_width(&text, NULL);
Johannes Schindelin9e832662006-12-22 22:06:08 +0100239 if (!text)
240 return 0;
241 }
242 return 1;
243}
244
René Scharfe37bb5d72009-11-22 17:15:29 +0100245static void strbuf_add_indented_text(struct strbuf *buf, const char *text,
246 int indent, int indent2)
247{
248 if (indent < 0)
249 indent = 0;
250 while (*text) {
251 const char *eol = strchrnul(text, '\n');
252 if (*eol == '\n')
253 eol++;
René Scharfe3c0ff442010-02-19 23:15:55 +0100254 strbuf_addchars(buf, ' ', indent);
René Scharfe68ad5e12010-02-19 23:16:45 +0100255 strbuf_add(buf, text, eol - text);
René Scharfe37bb5d72009-11-22 17:15:29 +0100256 text = eol;
257 indent = indent2;
258 }
259}
260
Johannes Schindelin9e832662006-12-22 22:06:08 +0100261/*
262 * Wrap the text, if necessary. The variable indent is the indent for the
263 * first line, indent2 is the indent for all other lines.
Johannes Schindelin094e03b2007-02-27 16:20:31 +0100264 * If indent is negative, assume that already -indent columns have been
265 * consumed (and no extra indent is necessary for the first line).
Johannes Schindelin9e832662006-12-22 22:06:08 +0100266 */
Steffen Prohaskae0db1762012-12-11 06:59:22 +0100267void strbuf_add_wrapped_text(struct strbuf *buf,
René Scharfe462749b2010-02-19 23:20:44 +0100268 const char *text, int indent1, int indent2, int width)
Johannes Schindelin9e832662006-12-22 22:06:08 +0100269{
René Scharfe462749b2010-02-19 23:20:44 +0100270 int indent, w, assume_utf8 = 1;
271 const char *bol, *space, *start = text;
272 size_t orig_len = buf->len;
Johannes Schindelin9e832662006-12-22 22:06:08 +0100273
Junio C Hamano00d39472009-10-18 23:40:35 -0700274 if (width <= 0) {
René Scharfe462749b2010-02-19 23:20:44 +0100275 strbuf_add_indented_text(buf, text, indent1, indent2);
Steffen Prohaskae0db1762012-12-11 06:59:22 +0100276 return;
Junio C Hamano00d39472009-10-18 23:40:35 -0700277 }
278
René Scharfe462749b2010-02-19 23:20:44 +0100279retry:
280 bol = text;
281 w = indent = indent1;
282 space = NULL;
Johannes Schindelin094e03b2007-02-27 16:20:31 +0100283 if (indent < 0) {
284 w = -indent;
285 space = text;
286 }
287
Johannes Schindelin9e832662006-12-22 22:06:08 +0100288 for (;;) {
René Scharfe8a3c63e2009-11-23 23:40:03 +0100289 char c;
290 size_t skip;
291
292 while ((skip = display_mode_esc_sequence_len(text)))
293 text += skip;
294
295 c = *text;
Johannes Schindelin9e832662006-12-22 22:06:08 +0100296 if (!c || isspace(c)) {
Jan H. Schönherr14e1a4e2012-10-18 16:43:28 +0200297 if (w <= width || !space) {
Johannes Schindelin9e832662006-12-22 22:06:08 +0100298 const char *start = bol;
Johannes Schindelinae0b2702007-11-11 14:14:15 +0000299 if (!c && text == start)
Steffen Prohaskae0db1762012-12-11 06:59:22 +0100300 return;
Johannes Schindelin9e832662006-12-22 22:06:08 +0100301 if (space)
302 start = space;
303 else
René Scharfe3c0ff442010-02-19 23:15:55 +0100304 strbuf_addchars(buf, ' ', indent);
René Scharfe68ad5e12010-02-19 23:16:45 +0100305 strbuf_add(buf, start, text - start);
Johannes Schindelin094e03b2007-02-27 16:20:31 +0100306 if (!c)
Steffen Prohaskae0db1762012-12-11 06:59:22 +0100307 return;
Johannes Schindelin9e832662006-12-22 22:06:08 +0100308 space = text;
Johannes Schindelinae0b2702007-11-11 14:14:15 +0000309 if (c == '\t')
310 w |= 0x07;
311 else if (c == '\n') {
312 space++;
313 if (*space == '\n') {
René Scharfe68ad5e12010-02-19 23:16:45 +0100314 strbuf_addch(buf, '\n');
Johannes Schindelinae0b2702007-11-11 14:14:15 +0000315 goto new_line;
316 }
317 else if (!isalnum(*space))
318 goto new_line;
319 else
René Scharfe68ad5e12010-02-19 23:16:45 +0100320 strbuf_addch(buf, ' ');
Johannes Schindelinae0b2702007-11-11 14:14:15 +0000321 }
Johannes Schindelin9e832662006-12-22 22:06:08 +0100322 w++;
323 text++;
324 }
325 else {
Johannes Schindelinae0b2702007-11-11 14:14:15 +0000326new_line:
René Scharfe68ad5e12010-02-19 23:16:45 +0100327 strbuf_addch(buf, '\n');
Johannes Schindelin62273822007-03-02 15:28:00 +0100328 text = bol = space + isspace(*space);
Johannes Schindelin9e832662006-12-22 22:06:08 +0100329 space = NULL;
330 w = indent = indent2;
331 }
332 continue;
333 }
René Scharfe462749b2010-02-19 23:20:44 +0100334 if (assume_utf8) {
Junio C Hamano44b25b82008-01-02 01:49:58 -0800335 w += utf8_width(&text, NULL);
René Scharfe462749b2010-02-19 23:20:44 +0100336 if (!text) {
337 assume_utf8 = 0;
338 text = start;
339 strbuf_setlen(buf, orig_len);
340 goto retry;
341 }
342 } else {
Johannes Schindelin9e832662006-12-22 22:06:08 +0100343 w++;
344 text++;
345 }
346 }
347}
Junio C Hamanob45974a2006-12-23 23:36:55 -0800348
Steffen Prohaskae0db1762012-12-11 06:59:22 +0100349void strbuf_add_wrapped_bytes(struct strbuf *buf, const char *data, int len,
Jeff King98acc832011-02-23 04:50:19 -0500350 int indent, int indent2, int width)
351{
352 char *tmp = xstrndup(data, len);
Steffen Prohaskae0db1762012-12-11 06:59:22 +0100353 strbuf_add_wrapped_text(buf, tmp, indent, indent2, width);
Jeff King98acc832011-02-23 04:50:19 -0500354 free(tmp);
Jeff King98acc832011-02-23 04:50:19 -0500355}
356
Nguyễn Thái Ngọc Duya7f01c62013-04-19 09:08:51 +1000357void strbuf_utf8_replace(struct strbuf *sb_src, int pos, int width,
358 const char *subst)
359{
360 struct strbuf sb_dst = STRBUF_INIT;
361 char *src = sb_src->buf;
362 char *end = src + sb_src->len;
363 char *dst;
364 int w = 0, subst_len = 0;
365
366 if (subst)
367 subst_len = strlen(subst);
368 strbuf_grow(&sb_dst, sb_src->len + subst_len);
369 dst = sb_dst.buf;
370
371 while (src < end) {
372 char *old;
373 size_t n;
374
375 while ((n = display_mode_esc_sequence_len(src))) {
376 memcpy(dst, src, n);
377 src += n;
378 dst += n;
379 }
380
Nguyễn Thái Ngọc Duy43087592014-08-10 14:05:21 +0700381 if (src >= end)
382 break;
383
Nguyễn Thái Ngọc Duya7f01c62013-04-19 09:08:51 +1000384 old = src;
385 n = utf8_width((const char**)&src, NULL);
386 if (!src) /* broken utf-8, do nothing */
Rene Scharfe9a012bf2017-08-30 20:20:16 +0200387 goto out;
Nguyễn Thái Ngọc Duya7f01c62013-04-19 09:08:51 +1000388 if (n && w >= pos && w < pos + width) {
389 if (subst) {
390 memcpy(dst, subst, subst_len);
391 dst += subst_len;
392 subst = NULL;
393 }
394 w += n;
395 continue;
396 }
397 memcpy(dst, old, src - old);
398 dst += src - old;
399 w += n;
400 }
401 strbuf_setlen(&sb_dst, dst - sb_dst.buf);
Ramsay Jones980419b2013-04-27 20:43:36 +0100402 strbuf_swap(sb_src, &sb_dst);
Rene Scharfe9a012bf2017-08-30 20:20:16 +0200403out:
Ramsay Jones980419b2013-04-27 20:43:36 +0100404 strbuf_release(&sb_dst);
Nguyễn Thái Ngọc Duya7f01c62013-04-19 09:08:51 +1000405}
406
Lars Schneider2f0c4a32018-04-15 20:16:04 +0200407/*
408 * Returns true (1) if the src encoding name matches the dst encoding
409 * name directly or one of its alternative names. E.g. UTF-16BE is the
410 * same as UTF16BE.
411 */
412static int same_utf_encoding(const char *src, const char *dst)
413{
René Scharfe89f8cab2019-11-08 21:25:21 +0100414 if (skip_iprefix(src, "utf", &src) && skip_iprefix(dst, "utf", &dst)) {
415 skip_prefix(src, "-", &src);
416 skip_prefix(dst, "-", &dst);
417 return !strcasecmp(src, dst);
Lars Schneider2f0c4a32018-04-15 20:16:04 +0200418 }
419 return 0;
420}
421
Junio C Hamano677cfed2006-12-30 12:20:43 -0800422int is_encoding_utf8(const char *name)
423{
424 if (!name)
425 return 1;
Lars Schneider2f0c4a32018-04-15 20:16:04 +0200426 if (same_utf_encoding("utf-8", name))
Junio C Hamano677cfed2006-12-30 12:20:43 -0800427 return 1;
428 return 0;
429}
430
Junio C Hamano0e18bcd2012-10-18 22:41:56 -0700431int same_encoding(const char *src, const char *dst)
432{
Lars Schneider2f0c4a32018-04-15 20:16:04 +0200433 static const char utf8[] = "UTF-8";
434
435 if (!src)
436 src = utf8;
437 if (!dst)
438 dst = utf8;
439 if (same_utf_encoding(src, dst))
Junio C Hamano0e18bcd2012-10-18 22:41:56 -0700440 return 1;
441 return !strcasecmp(src, dst);
442}
443
Junio C Hamanob45974a2006-12-23 23:36:55 -0800444/*
Jiang Xinc0821962013-02-09 14:31:09 +0800445 * Wrapper for fprintf and returns the total number of columns required
446 * for the printed string, assuming that the string is utf8.
447 */
448int utf8_fprintf(FILE *stream, const char *format, ...)
449{
450 struct strbuf buf = STRBUF_INIT;
451 va_list arg;
452 int columns;
453
454 va_start(arg, format);
455 strbuf_vaddf(&buf, format, arg);
456 va_end(arg);
457
458 columns = fputs(buf.buf, stream);
459 if (0 <= columns) /* keep the error from the I/O */
460 columns = utf8_strwidth(buf.buf);
461 strbuf_release(&buf);
462 return columns;
463}
464
465/*
Junio C Hamanob45974a2006-12-23 23:36:55 -0800466 * Given a buffer and its encoding, return it re-encoded
467 * with iconv. If the conversion fails, returns NULL.
468 */
469#ifndef NO_ICONV
Brandon Casey309dbc82009-06-05 18:36:12 -0500470#if defined(OLD_ICONV) || (defined(__sun__) && !defined(_XPG6))
Ramsay Jonesfd547a92007-03-03 18:29:03 +0000471 typedef const char * iconv_ibp;
472#else
473 typedef char * iconv_ibp;
474#endif
Torsten Bögershausenaab2a1a2019-01-30 16:01:52 +0100475char *reencode_string_iconv(const char *in, size_t insz, iconv_t conv,
476 size_t bom_len, size_t *outsz_p)
Junio C Hamanob45974a2006-12-23 23:36:55 -0800477{
Torsten Bögershausen76759c72012-07-08 15:50:25 +0200478 size_t outsz, outalloc;
Ramsay Jonesfd547a92007-03-03 18:29:03 +0000479 char *out, *outpos;
480 iconv_ibp cp;
Junio C Hamanob45974a2006-12-23 23:36:55 -0800481
Junio C Hamanob45974a2006-12-23 23:36:55 -0800482 outsz = insz;
Torsten Bögershausenaab2a1a2019-01-30 16:01:52 +0100483 outalloc = st_add(outsz, 1 + bom_len); /* for terminating NUL */
Junio C Hamanob45974a2006-12-23 23:36:55 -0800484 out = xmalloc(outalloc);
Torsten Bögershausenaab2a1a2019-01-30 16:01:52 +0100485 outpos = out + bom_len;
Ramsay Jonesfd547a92007-03-03 18:29:03 +0000486 cp = (iconv_ibp)in;
Junio C Hamanob45974a2006-12-23 23:36:55 -0800487
488 while (1) {
489 size_t cnt = iconv(conv, &cp, &insz, &outpos, &outsz);
490
John Keepingdf5213b2014-02-16 16:06:03 +0000491 if (cnt == (size_t) -1) {
Junio C Hamanob45974a2006-12-23 23:36:55 -0800492 size_t sofar;
493 if (errno != E2BIG) {
494 free(out);
Junio C Hamanob45974a2006-12-23 23:36:55 -0800495 return NULL;
496 }
497 /* insz has remaining number of bytes.
498 * since we started outsz the same as insz,
499 * it is likely that insz is not enough for
500 * converting the rest.
501 */
502 sofar = outpos - out;
Jeff King77aa03d2018-07-24 06:50:10 -0400503 outalloc = st_add3(sofar, st_mult(insz, 2), 32);
Junio C Hamanob45974a2006-12-23 23:36:55 -0800504 out = xrealloc(out, outalloc);
505 outpos = out + sofar;
506 outsz = outalloc - sofar - 1;
507 }
508 else {
509 *outpos = '\0';
Nguyễn Thái Ngọc Duyb782bba2013-04-19 09:08:46 +1000510 if (outsz_p)
511 *outsz_p = outpos - out;
Junio C Hamanob45974a2006-12-23 23:36:55 -0800512 break;
513 }
514 }
Torsten Bögershausen76759c72012-07-08 15:50:25 +0200515 return out;
516}
517
Junio C Hamano32707412016-09-26 18:09:48 -0700518static const char *fallback_encoding(const char *name)
519{
520 /*
521 * Some platforms do not have the variously spelled variants of
522 * UTF-8, so let's fall back to trying the most official
523 * spelling. We do so only as a fallback in case the platform
524 * does understand the user's spelling, but not our official
525 * one.
526 */
527 if (is_encoding_utf8(name))
528 return "UTF-8";
529
Junio C Hamanodf375582016-09-26 18:09:48 -0700530 /*
531 * Even though latin-1 is still seen in e-mail
532 * headers, some platforms only install ISO-8859-1.
533 */
534 if (!strcasecmp(name, "latin-1"))
535 return "ISO-8859-1";
536
Junio C Hamano32707412016-09-26 18:09:48 -0700537 return name;
538}
539
Jeff Kingc7d017d2018-07-24 06:50:33 -0400540char *reencode_string_len(const char *in, size_t insz,
Nguyễn Thái Ngọc Duyb782bba2013-04-19 09:08:46 +1000541 const char *out_encoding, const char *in_encoding,
Jeff Kingc7d017d2018-07-24 06:50:33 -0400542 size_t *outsz)
Torsten Bögershausen76759c72012-07-08 15:50:25 +0200543{
544 iconv_t conv;
545 char *out;
Torsten Bögershausenaab2a1a2019-01-30 16:01:52 +0100546 const char *bom_str = NULL;
547 size_t bom_len = 0;
Torsten Bögershausen76759c72012-07-08 15:50:25 +0200548
549 if (!in_encoding)
550 return NULL;
Jeff King5c680be2013-02-25 15:31:00 -0500551
Torsten Bögershausenaab2a1a2019-01-30 16:01:52 +0100552 /* UTF-16LE-BOM is the same as UTF-16 for reading */
553 if (same_utf_encoding("UTF-16LE-BOM", in_encoding))
554 in_encoding = "UTF-16";
555
556 /*
557 * For writing, UTF-16 iconv typically creates "UTF-16BE-BOM"
558 * Some users under Windows want the little endian version
brian m. carlson79444c92019-02-12 00:52:06 +0000559 *
560 * We handle UTF-16 and UTF-32 ourselves only if the platform does not
561 * provide a BOM (which we require), since we want to match the behavior
562 * of the system tools and libc as much as possible.
Torsten Bögershausenaab2a1a2019-01-30 16:01:52 +0100563 */
564 if (same_utf_encoding("UTF-16LE-BOM", out_encoding)) {
565 bom_str = utf16_le_bom;
566 bom_len = sizeof(utf16_le_bom);
567 out_encoding = "UTF-16LE";
568 } else if (same_utf_encoding("UTF-16BE-BOM", out_encoding)) {
569 bom_str = utf16_be_bom;
570 bom_len = sizeof(utf16_be_bom);
571 out_encoding = "UTF-16BE";
brian m. carlson79444c92019-02-12 00:52:06 +0000572#ifdef ICONV_OMITS_BOM
573 } else if (same_utf_encoding("UTF-16", out_encoding)) {
574 bom_str = utf16_be_bom;
575 bom_len = sizeof(utf16_be_bom);
576 out_encoding = "UTF-16BE";
577 } else if (same_utf_encoding("UTF-32", out_encoding)) {
578 bom_str = utf32_be_bom;
579 bom_len = sizeof(utf32_be_bom);
580 out_encoding = "UTF-32BE";
581#endif
Torsten Bögershausenaab2a1a2019-01-30 16:01:52 +0100582 }
583
Torsten Bögershausen76759c72012-07-08 15:50:25 +0200584 conv = iconv_open(out_encoding, in_encoding);
Jeff King5c680be2013-02-25 15:31:00 -0500585 if (conv == (iconv_t) -1) {
Junio C Hamano32707412016-09-26 18:09:48 -0700586 in_encoding = fallback_encoding(in_encoding);
587 out_encoding = fallback_encoding(out_encoding);
588
Jeff King5c680be2013-02-25 15:31:00 -0500589 conv = iconv_open(out_encoding, in_encoding);
590 if (conv == (iconv_t) -1)
591 return NULL;
592 }
Torsten Bögershausenaab2a1a2019-01-30 16:01:52 +0100593 out = reencode_string_iconv(in, insz, conv, bom_len, outsz);
Junio C Hamanob45974a2006-12-23 23:36:55 -0800594 iconv_close(conv);
Torsten Bögershausenaab2a1a2019-01-30 16:01:52 +0100595 if (out && bom_str && bom_len)
596 memcpy(out, bom_str, bom_len);
Junio C Hamanob45974a2006-12-23 23:36:55 -0800597 return out;
598}
599#endif
Kirill Smelkov6cd3c052013-03-07 14:55:07 +0400600
Lars Schneider10ecb822018-04-15 20:16:05 +0200601static int has_bom_prefix(const char *data, size_t len,
602 const char *bom, size_t bom_len)
603{
604 return data && bom && (len >= bom_len) && !memcmp(data, bom, bom_len);
605}
606
Lars Schneider10ecb822018-04-15 20:16:05 +0200607int has_prohibited_utf_bom(const char *enc, const char *data, size_t len)
608{
609 return (
610 (same_utf_encoding("UTF-16BE", enc) ||
611 same_utf_encoding("UTF-16LE", enc)) &&
612 (has_bom_prefix(data, len, utf16_be_bom, sizeof(utf16_be_bom)) ||
613 has_bom_prefix(data, len, utf16_le_bom, sizeof(utf16_le_bom)))
614 ) || (
615 (same_utf_encoding("UTF-32BE", enc) ||
616 same_utf_encoding("UTF-32LE", enc)) &&
617 (has_bom_prefix(data, len, utf32_be_bom, sizeof(utf32_be_bom)) ||
618 has_bom_prefix(data, len, utf32_le_bom, sizeof(utf32_le_bom)))
619 );
620}
621
Lars Schneiderc6e48652018-04-15 20:16:06 +0200622int is_missing_required_utf_bom(const char *enc, const char *data, size_t len)
623{
624 return (
625 (same_utf_encoding(enc, "UTF-16")) &&
626 !(has_bom_prefix(data, len, utf16_be_bom, sizeof(utf16_be_bom)) ||
627 has_bom_prefix(data, len, utf16_le_bom, sizeof(utf16_le_bom)))
628 ) || (
629 (same_utf_encoding(enc, "UTF-32")) &&
630 !(has_bom_prefix(data, len, utf32_be_bom, sizeof(utf32_be_bom)) ||
631 has_bom_prefix(data, len, utf32_le_bom, sizeof(utf32_le_bom)))
632 );
633}
634
Kirill Smelkov6cd3c052013-03-07 14:55:07 +0400635/*
636 * Returns first character length in bytes for multi-byte `text` according to
637 * `encoding`.
638 *
639 * - The `text` pointer is updated to point at the next character.
640 * - When `remainder_p` is not NULL, on entry `*remainder_p` is how much bytes
641 * we can consume from text, and on exit `*remainder_p` is reduced by returned
642 * character length. Otherwise `text` is treated as limited by NUL.
643 */
644int mbs_chrlen(const char **text, size_t *remainder_p, const char *encoding)
645{
646 int chrlen;
647 const char *p = *text;
648 size_t r = (remainder_p ? *remainder_p : SIZE_MAX);
649
650 if (r < 1)
651 return 0;
652
653 if (is_encoding_utf8(encoding)) {
654 pick_one_utf8_char(&p, &r);
655
656 chrlen = p ? (p - *text)
657 : 1 /* not valid UTF-8 -> raw byte sequence */;
658 }
659 else {
660 /*
661 * TODO use iconv to decode one char and obtain its chrlen
662 * for now, let's treat encodings != UTF-8 as one-byte
663 */
664 chrlen = 1;
665 }
666
667 *text += chrlen;
668 if (remainder_p)
669 *remainder_p -= chrlen;
670
671 return chrlen;
672}
Jeff King6162a1d2014-12-15 17:56:59 -0500673
674/*
Jeff King6aaf9562014-12-23 03:45:36 -0500675 * Pick the next char from the stream, ignoring codepoints an HFS+ would.
676 * Note that this is _not_ complete by any means. It's just enough
Jeff King6162a1d2014-12-15 17:56:59 -0500677 * to make is_hfs_dotgit() work, and should not be used otherwise.
678 */
679static ucs_char_t next_hfs_char(const char **in)
680{
681 while (1) {
682 ucs_char_t out = pick_one_utf8_char(in, NULL);
683 /*
684 * check for malformed utf8. Technically this
685 * gets converted to a percent-sequence, but
686 * returning 0 is good enough for is_hfs_dotgit
687 * to realize it cannot be .git
688 */
689 if (!*in)
690 return 0;
691
692 /* these code points are ignored completely */
693 switch (out) {
694 case 0x200c: /* ZERO WIDTH NON-JOINER */
695 case 0x200d: /* ZERO WIDTH JOINER */
696 case 0x200e: /* LEFT-TO-RIGHT MARK */
697 case 0x200f: /* RIGHT-TO-LEFT MARK */
698 case 0x202a: /* LEFT-TO-RIGHT EMBEDDING */
699 case 0x202b: /* RIGHT-TO-LEFT EMBEDDING */
700 case 0x202c: /* POP DIRECTIONAL FORMATTING */
701 case 0x202d: /* LEFT-TO-RIGHT OVERRIDE */
702 case 0x202e: /* RIGHT-TO-LEFT OVERRIDE */
703 case 0x206a: /* INHIBIT SYMMETRIC SWAPPING */
704 case 0x206b: /* ACTIVATE SYMMETRIC SWAPPING */
705 case 0x206c: /* INHIBIT ARABIC FORM SHAPING */
706 case 0x206d: /* ACTIVATE ARABIC FORM SHAPING */
707 case 0x206e: /* NATIONAL DIGIT SHAPES */
708 case 0x206f: /* NOMINAL DIGIT SHAPES */
709 case 0xfeff: /* ZERO WIDTH NO-BREAK SPACE */
710 continue;
711 }
712
Jeff King6aaf9562014-12-23 03:45:36 -0500713 return out;
Jeff King6162a1d2014-12-15 17:56:59 -0500714 }
715}
716
Jeff King0fc333b2018-05-02 15:23:45 -0400717static int is_hfs_dot_generic(const char *path,
718 const char *needle, size_t needle_len)
Jeff King6162a1d2014-12-15 17:56:59 -0500719{
720 ucs_char_t c;
721
Jeff King6aaf9562014-12-23 03:45:36 -0500722 c = next_hfs_char(&path);
723 if (c != '.')
724 return 0;
Jeff King6aaf9562014-12-23 03:45:36 -0500725
726 /*
727 * there's a great deal of other case-folding that occurs
Jeff King0fc333b2018-05-02 15:23:45 -0400728 * in HFS+, but this is enough to catch our fairly vanilla
729 * hard-coded needles.
Jeff King6aaf9562014-12-23 03:45:36 -0500730 */
Jeff King0fc333b2018-05-02 15:23:45 -0400731 for (; needle_len > 0; needle++, needle_len--) {
732 c = next_hfs_char(&path);
733
734 /*
735 * We know our needles contain only ASCII, so we clamp here to
736 * make the results of tolower() sane.
737 */
738 if (c > 127)
739 return 0;
740 if (tolower(c) != *needle)
741 return 0;
742 }
743
Jeff King6162a1d2014-12-15 17:56:59 -0500744 c = next_hfs_char(&path);
745 if (c && !is_dir_sep(c))
746 return 0;
747
748 return 1;
749}
Junio C Hamanodde843e2015-04-16 10:45:29 -0700750
Jeff King0fc333b2018-05-02 15:23:45 -0400751/*
752 * Inline wrapper to make sure the compiler resolves strlen() on literals at
753 * compile time.
754 */
755static inline int is_hfs_dot_str(const char *path, const char *needle)
756{
757 return is_hfs_dot_generic(path, needle, strlen(needle));
758}
759
760int is_hfs_dotgit(const char *path)
761{
762 return is_hfs_dot_str(path, "git");
763}
764
765int is_hfs_dotgitmodules(const char *path)
766{
767 return is_hfs_dot_str(path, "gitmodules");
768}
769
770int is_hfs_dotgitignore(const char *path)
771{
772 return is_hfs_dot_str(path, "gitignore");
773}
774
775int is_hfs_dotgitattributes(const char *path)
776{
777 return is_hfs_dot_str(path, "gitattributes");
778}
779
Jeff King801ed012021-05-03 16:43:22 -0400780int is_hfs_dotmailmap(const char *path)
781{
782 return is_hfs_dot_str(path, "mailmap");
783}
784
Junio C Hamanodde843e2015-04-16 10:45:29 -0700785const char utf8_bom[] = "\357\273\277";
786
787int skip_utf8_bom(char **text, size_t len)
788{
789 if (len < strlen(utf8_bom) ||
790 memcmp(*text, utf8_bom, strlen(utf8_bom)))
791 return 0;
792 *text += strlen(utf8_bom);
793 return 1;
794}
Karthik Nayak110dcda2015-09-10 21:18:19 +0530795
796void strbuf_utf8_align(struct strbuf *buf, align_type position, unsigned int width,
797 const char *s)
798{
799 int slen = strlen(s);
800 int display_len = utf8_strnwidth(s, slen, 0);
801 int utf8_compensation = slen - display_len;
802
803 if (display_len >= width) {
804 strbuf_addstr(buf, s);
805 return;
806 }
807
808 if (position == ALIGN_LEFT)
809 strbuf_addf(buf, "%-*s", width + utf8_compensation, s);
810 else if (position == ALIGN_MIDDLE) {
811 int left = (width - display_len) / 2;
812 strbuf_addf(buf, "%*s%-*s", left, "", width - left + utf8_compensation, s);
813 } else if (position == ALIGN_RIGHT)
814 strbuf_addf(buf, "%*s", width + utf8_compensation, s);
815}