]> git.ipfire.org Git - thirdparty/git.git/blame - utf8.c
use xstrdup instead of xmalloc + strcpy
[thirdparty/git.git] / utf8.c
CommitLineData
9e832665 1#include "git-compat-util.h"
a94410c8 2#include "strbuf.h"
9e832665
JS
3#include "utf8.h"
4
5/* This code is originally from http://www.cl.cam.ac.uk/~mgk25/ucs/ */
6
7struct interval {
a68a67de
JK
8 ucs_char_t first;
9 ucs_char_t last;
9e832665
JS
10};
11
1640632b 12size_t display_mode_esc_sequence_len(const char *s)
4247fe79
NTND
13{
14 const char *p = s;
15 if (*p++ != '\033')
16 return 0;
17 if (*p++ != '[')
18 return 0;
19 while (isdigit(*p) || *p == ';')
20 p++;
21 if (*p++ != 'm')
22 return 0;
23 return p - s;
24}
25
9e832665 26/* auxiliary function for binary search in interval table */
f3fa1838
JH
27static int bisearch(ucs_char_t ucs, const struct interval *table, int max)
28{
9e832665
JS
29 int min = 0;
30 int mid;
31
32 if (ucs < table[0].first || ucs > table[max].last)
33 return 0;
34 while (max >= min) {
35 mid = (min + max) / 2;
36 if (ucs > table[mid].last)
37 min = mid + 1;
38 else if (ucs < table[mid].first)
39 max = mid - 1;
40 else
41 return 1;
42 }
43
44 return 0;
45}
46
47/* The following two functions define the column width of an ISO 10646
48 * character as follows:
49 *
50 * - The null character (U+0000) has a column width of 0.
51 *
52 * - Other C0/C1 control characters and DEL will lead to a return
53 * value of -1.
54 *
55 * - Non-spacing and enclosing combining characters (general
56 * category code Mn or Me in the Unicode database) have a
57 * column width of 0.
58 *
59 * - SOFT HYPHEN (U+00AD) has a column width of 1.
60 *
61 * - Other format characters (general category code Cf in the Unicode
62 * database) and ZERO WIDTH SPACE (U+200B) have a column width of 0.
63 *
64 * - Hangul Jamo medial vowels and final consonants (U+1160-U+11FF)
65 * have a column width of 0.
66 *
67 * - Spacing characters in the East Asian Wide (W) or East Asian
68 * Full-width (F) category as defined in Unicode Technical
69 * Report #11 have a column width of 2.
70 *
71 * - All remaining characters (including all printable
72 * ISO 8859-1 and WGL4 characters, Unicode control characters,
73 * etc.) have a column width of 1.
74 *
28321145 75 * This implementation assumes that ucs_char_t characters are encoded
9e832665
JS
76 * in ISO 10646.
77 */
78
b51be13c 79static int git_wcwidth(ucs_char_t ch)
9e832665
JS
80{
81 /*
82 * Sorted list of non-overlapping intervals of non-spacing characters,
9e832665 83 */
9c94389c 84#include "unicode_width.h"
9e832665
JS
85
86 /* test for 8-bit control characters */
87 if (ch == 0)
88 return 0;
89 if (ch < 32 || (ch >= 0x7f && ch < 0xa0))
90 return -1;
91
92 /* binary search in table of non-spacing characters */
9c94389c 93 if (bisearch(ch, zero_width, sizeof(zero_width)
9e832665
JS
94 / sizeof(struct interval) - 1))
95 return 0;
96
08460345
TB
97 /* binary search in table of double width characters */
98 if (bisearch(ch, double_width, sizeof(double_width)
99 / sizeof(struct interval) - 1))
100 return 2;
9e832665 101
08460345 102 return 1;
9e832665
JS
103}
104
105/*
396ccf1f
JH
106 * Pick one ucs character starting from the location *start points at,
107 * and return it, while updating the *start pointer to point at the
44b25b87
JH
108 * end of that character. When remainder_p is not NULL, the location
109 * holds the number of bytes remaining in the string that we are allowed
110 * to pick from. Otherwise we are allowed to pick up to the NUL that
111 * would eventually appear in the string. *remainder_p is also reduced
112 * by the number of bytes we have consumed.
396ccf1f
JH
113 *
114 * If the string was not a valid UTF-8, *start pointer is set to NULL
115 * and the return value is undefined.
9e832665 116 */
5e133b8c 117static ucs_char_t pick_one_utf8_char(const char **start, size_t *remainder_p)
9e832665
JS
118{
119 unsigned char *s = (unsigned char *)*start;
28321145 120 ucs_char_t ch;
44b25b87 121 size_t remainder, incr;
9e832665 122
44b25b87
JH
123 /*
124 * A caller that assumes NUL terminated text can choose
125 * not to bother with the remainder length. We will
126 * stop at the first NUL.
127 */
128 remainder = (remainder_p ? *remainder_p : 999);
129
130 if (remainder < 1) {
131 goto invalid;
132 } else if (*s < 0x80) {
9e832665
JS
133 /* 0xxxxxxx */
134 ch = *s;
44b25b87 135 incr = 1;
9e832665
JS
136 } else if ((s[0] & 0xe0) == 0xc0) {
137 /* 110XXXXx 10xxxxxx */
44b25b87
JH
138 if (remainder < 2 ||
139 (s[1] & 0xc0) != 0x80 ||
140 (s[0] & 0xfe) == 0xc0)
9e832665
JS
141 goto invalid;
142 ch = ((s[0] & 0x1f) << 6) | (s[1] & 0x3f);
44b25b87 143 incr = 2;
9e832665
JS
144 } else if ((s[0] & 0xf0) == 0xe0) {
145 /* 1110XXXX 10Xxxxxx 10xxxxxx */
44b25b87
JH
146 if (remainder < 3 ||
147 (s[1] & 0xc0) != 0x80 ||
148 (s[2] & 0xc0) != 0x80 ||
149 /* overlong? */
150 (s[0] == 0xe0 && (s[1] & 0xe0) == 0x80) ||
151 /* surrogate? */
152 (s[0] == 0xed && (s[1] & 0xe0) == 0xa0) ||
153 /* U+FFFE or U+FFFF? */
154 (s[0] == 0xef && s[1] == 0xbf &&
155 (s[2] & 0xfe) == 0xbe))
9e832665
JS
156 goto invalid;
157 ch = ((s[0] & 0x0f) << 12) |
158 ((s[1] & 0x3f) << 6) | (s[2] & 0x3f);
44b25b87 159 incr = 3;
9e832665
JS
160 } else if ((s[0] & 0xf8) == 0xf0) {
161 /* 11110XXX 10XXxxxx 10xxxxxx 10xxxxxx */
44b25b87
JH
162 if (remainder < 4 ||
163 (s[1] & 0xc0) != 0x80 ||
164 (s[2] & 0xc0) != 0x80 ||
165 (s[3] & 0xc0) != 0x80 ||
166 /* overlong? */
167 (s[0] == 0xf0 && (s[1] & 0xf0) == 0x80) ||
168 /* > U+10FFFF? */
169 (s[0] == 0xf4 && s[1] > 0x8f) || s[0] > 0xf4)
9e832665
JS
170 goto invalid;
171 ch = ((s[0] & 0x07) << 18) | ((s[1] & 0x3f) << 12) |
172 ((s[2] & 0x3f) << 6) | (s[3] & 0x3f);
44b25b87 173 incr = 4;
9e832665
JS
174 } else {
175invalid:
176 *start = NULL;
177 return 0;
178 }
179
44b25b87
JH
180 *start += incr;
181 if (remainder_p)
182 *remainder_p = remainder - incr;
396ccf1f
JH
183 return ch;
184}
185
186/*
187 * This function returns the number of columns occupied by the character
188 * pointed to by the variable start. The pointer is updated to point at
44b25b87
JH
189 * the next character. When remainder_p is not NULL, it points at the
190 * location that stores the number of remaining bytes we can use to pick
191 * a character (see pick_one_utf8_char() above).
396ccf1f 192 */
44b25b87 193int utf8_width(const char **start, size_t *remainder_p)
396ccf1f 194{
44b25b87 195 ucs_char_t ch = pick_one_utf8_char(start, remainder_p);
396ccf1f
JH
196 if (!*start)
197 return 0;
b51be13c 198 return git_wcwidth(ch);
9e832665
JS
199}
200
8a9391e9
GT
201/*
202 * Returns the total number of columns required by a null-terminated
203 * string, assuming that the string is utf8. Returns strlen() instead
204 * if the string does not look like a valid utf8 string.
205 */
2bc1e7ec 206int utf8_strnwidth(const char *string, int len, int skip_ansi)
8a9391e9
GT
207{
208 int width = 0;
209 const char *orig = string;
210
2bc1e7ec
NTND
211 if (len == -1)
212 len = strlen(string);
213 while (string && string < orig + len) {
214 int skip;
215 while (skip_ansi &&
216 (skip = display_mode_esc_sequence_len(string)) != 0)
217 string += skip;
8a9391e9
GT
218 width += utf8_width(&string, NULL);
219 }
2bc1e7ec
NTND
220 return string ? width : len;
221}
222
223int utf8_strwidth(const char *string)
224{
225 return utf8_strnwidth(string, -1, 0);
8a9391e9
GT
226}
227
9e832665
JS
228int is_utf8(const char *text)
229{
230 while (*text) {
231 if (*text == '\n' || *text == '\t' || *text == '\r') {
232 text++;
233 continue;
234 }
44b25b87 235 utf8_width(&text, NULL);
9e832665
JS
236 if (!text)
237 return 0;
238 }
239 return 1;
240}
241
3c0ff44a 242static void strbuf_addchars(struct strbuf *sb, int c, size_t n)
a94410c8 243{
3c0ff44a
RS
244 strbuf_grow(sb, n);
245 memset(sb->buf + sb->len, c, n);
246 strbuf_setlen(sb, sb->len + n);
9e832665
JS
247}
248
37bb5d74
RS
249static void strbuf_add_indented_text(struct strbuf *buf, const char *text,
250 int indent, int indent2)
251{
252 if (indent < 0)
253 indent = 0;
254 while (*text) {
255 const char *eol = strchrnul(text, '\n');
256 if (*eol == '\n')
257 eol++;
3c0ff44a 258 strbuf_addchars(buf, ' ', indent);
68ad5e1e 259 strbuf_add(buf, text, eol - text);
37bb5d74
RS
260 text = eol;
261 indent = indent2;
262 }
263}
264
9e832665
JS
265/*
266 * Wrap the text, if necessary. The variable indent is the indent for the
267 * first line, indent2 is the indent for all other lines.
094e03b0
JS
268 * If indent is negative, assume that already -indent columns have been
269 * consumed (and no extra indent is necessary for the first line).
9e832665 270 */
e0db1765 271void strbuf_add_wrapped_text(struct strbuf *buf,
462749b7 272 const char *text, int indent1, int indent2, int width)
9e832665 273{
462749b7
RS
274 int indent, w, assume_utf8 = 1;
275 const char *bol, *space, *start = text;
276 size_t orig_len = buf->len;
9e832665 277
00d39473 278 if (width <= 0) {
462749b7 279 strbuf_add_indented_text(buf, text, indent1, indent2);
e0db1765 280 return;
00d39473
JH
281 }
282
462749b7
RS
283retry:
284 bol = text;
285 w = indent = indent1;
286 space = NULL;
094e03b0
JS
287 if (indent < 0) {
288 w = -indent;
289 space = text;
290 }
291
9e832665 292 for (;;) {
8a3c63e0
RS
293 char c;
294 size_t skip;
295
296 while ((skip = display_mode_esc_sequence_len(text)))
297 text += skip;
298
299 c = *text;
9e832665 300 if (!c || isspace(c)) {
14e1a4e1 301 if (w <= width || !space) {
9e832665 302 const char *start = bol;
ae0b2702 303 if (!c && text == start)
e0db1765 304 return;
9e832665
JS
305 if (space)
306 start = space;
307 else
3c0ff44a 308 strbuf_addchars(buf, ' ', indent);
68ad5e1e 309 strbuf_add(buf, start, text - start);
094e03b0 310 if (!c)
e0db1765 311 return;
9e832665 312 space = text;
ae0b2702
JS
313 if (c == '\t')
314 w |= 0x07;
315 else if (c == '\n') {
316 space++;
317 if (*space == '\n') {
68ad5e1e 318 strbuf_addch(buf, '\n');
ae0b2702
JS
319 goto new_line;
320 }
321 else if (!isalnum(*space))
322 goto new_line;
323 else
68ad5e1e 324 strbuf_addch(buf, ' ');
ae0b2702 325 }
9e832665
JS
326 w++;
327 text++;
328 }
329 else {
ae0b2702 330new_line:
68ad5e1e 331 strbuf_addch(buf, '\n');
62273826 332 text = bol = space + isspace(*space);
9e832665
JS
333 space = NULL;
334 w = indent = indent2;
335 }
336 continue;
337 }
462749b7 338 if (assume_utf8) {
44b25b87 339 w += utf8_width(&text, NULL);
462749b7
RS
340 if (!text) {
341 assume_utf8 = 0;
342 text = start;
343 strbuf_setlen(buf, orig_len);
344 goto retry;
345 }
346 } else {
9e832665
JS
347 w++;
348 text++;
349 }
350 }
351}
b45974a6 352
e0db1765 353void strbuf_add_wrapped_bytes(struct strbuf *buf, const char *data, int len,
98acc837
JK
354 int indent, int indent2, int width)
355{
356 char *tmp = xstrndup(data, len);
e0db1765 357 strbuf_add_wrapped_text(buf, tmp, indent, indent2, width);
98acc837 358 free(tmp);
98acc837
JK
359}
360
a7f01c6b
NTND
361void strbuf_utf8_replace(struct strbuf *sb_src, int pos, int width,
362 const char *subst)
363{
364 struct strbuf sb_dst = STRBUF_INIT;
365 char *src = sb_src->buf;
366 char *end = src + sb_src->len;
367 char *dst;
368 int w = 0, subst_len = 0;
369
370 if (subst)
371 subst_len = strlen(subst);
372 strbuf_grow(&sb_dst, sb_src->len + subst_len);
373 dst = sb_dst.buf;
374
375 while (src < end) {
376 char *old;
377 size_t n;
378
379 while ((n = display_mode_esc_sequence_len(src))) {
380 memcpy(dst, src, n);
381 src += n;
382 dst += n;
383 }
384
385 old = src;
386 n = utf8_width((const char**)&src, NULL);
387 if (!src) /* broken utf-8, do nothing */
388 return;
389 if (n && w >= pos && w < pos + width) {
390 if (subst) {
391 memcpy(dst, subst, subst_len);
392 dst += subst_len;
393 subst = NULL;
394 }
395 w += n;
396 continue;
397 }
398 memcpy(dst, old, src - old);
399 dst += src - old;
400 w += n;
401 }
402 strbuf_setlen(&sb_dst, dst - sb_dst.buf);
980419b9
RJ
403 strbuf_swap(sb_src, &sb_dst);
404 strbuf_release(&sb_dst);
a7f01c6b
NTND
405}
406
677cfed5
JH
407int is_encoding_utf8(const char *name)
408{
409 if (!name)
410 return 1;
411 if (!strcasecmp(name, "utf-8") || !strcasecmp(name, "utf8"))
412 return 1;
413 return 0;
414}
415
0e18bcd5
JH
416int same_encoding(const char *src, const char *dst)
417{
418 if (is_encoding_utf8(src) && is_encoding_utf8(dst))
419 return 1;
420 return !strcasecmp(src, dst);
421}
422
c0821965
JX
423/*
424 * Wrapper for fprintf and returns the total number of columns required
425 * for the printed string, assuming that the string is utf8.
426 */
427int utf8_fprintf(FILE *stream, const char *format, ...)
428{
429 struct strbuf buf = STRBUF_INIT;
430 va_list arg;
431 int columns;
432
433 va_start(arg, format);
434 strbuf_vaddf(&buf, format, arg);
435 va_end(arg);
436
437 columns = fputs(buf.buf, stream);
438 if (0 <= columns) /* keep the error from the I/O */
439 columns = utf8_strwidth(buf.buf);
440 strbuf_release(&buf);
441 return columns;
442}
443
b45974a6
JH
444/*
445 * Given a buffer and its encoding, return it re-encoded
446 * with iconv. If the conversion fails, returns NULL.
447 */
448#ifndef NO_ICONV
309dbc82 449#if defined(OLD_ICONV) || (defined(__sun__) && !defined(_XPG6))
fd547a97
RJ
450 typedef const char * iconv_ibp;
451#else
452 typedef char * iconv_ibp;
453#endif
b782bbab 454char *reencode_string_iconv(const char *in, size_t insz, iconv_t conv, int *outsz_p)
b45974a6 455{
76759c7d 456 size_t outsz, outalloc;
fd547a97
RJ
457 char *out, *outpos;
458 iconv_ibp cp;
b45974a6 459
b45974a6
JH
460 outsz = insz;
461 outalloc = outsz + 1; /* for terminating NUL */
462 out = xmalloc(outalloc);
463 outpos = out;
fd547a97 464 cp = (iconv_ibp)in;
b45974a6
JH
465
466 while (1) {
467 size_t cnt = iconv(conv, &cp, &insz, &outpos, &outsz);
468
df5213b7 469 if (cnt == (size_t) -1) {
b45974a6
JH
470 size_t sofar;
471 if (errno != E2BIG) {
472 free(out);
b45974a6
JH
473 return NULL;
474 }
475 /* insz has remaining number of bytes.
476 * since we started outsz the same as insz,
477 * it is likely that insz is not enough for
478 * converting the rest.
479 */
480 sofar = outpos - out;
481 outalloc = sofar + insz * 2 + 32;
482 out = xrealloc(out, outalloc);
483 outpos = out + sofar;
484 outsz = outalloc - sofar - 1;
485 }
486 else {
487 *outpos = '\0';
b782bbab
NTND
488 if (outsz_p)
489 *outsz_p = outpos - out;
b45974a6
JH
490 break;
491 }
492 }
76759c7d
TB
493 return out;
494}
495
b782bbab
NTND
496char *reencode_string_len(const char *in, int insz,
497 const char *out_encoding, const char *in_encoding,
498 int *outsz)
76759c7d
TB
499{
500 iconv_t conv;
501 char *out;
502
503 if (!in_encoding)
504 return NULL;
5c680be1 505
76759c7d 506 conv = iconv_open(out_encoding, in_encoding);
5c680be1
JK
507 if (conv == (iconv_t) -1) {
508 /*
509 * Some platforms do not have the variously spelled variants of
510 * UTF-8, so let's fall back to trying the most official
511 * spelling. We do so only as a fallback in case the platform
512 * does understand the user's spelling, but not our official
513 * one.
514 */
515 if (is_encoding_utf8(in_encoding))
516 in_encoding = "UTF-8";
517 if (is_encoding_utf8(out_encoding))
518 out_encoding = "UTF-8";
519 conv = iconv_open(out_encoding, in_encoding);
520 if (conv == (iconv_t) -1)
521 return NULL;
522 }
523
b782bbab 524 out = reencode_string_iconv(in, insz, conv, outsz);
b45974a6
JH
525 iconv_close(conv);
526 return out;
527}
528#endif
6cd3c053
KS
529
530/*
531 * Returns first character length in bytes for multi-byte `text` according to
532 * `encoding`.
533 *
534 * - The `text` pointer is updated to point at the next character.
535 * - When `remainder_p` is not NULL, on entry `*remainder_p` is how much bytes
536 * we can consume from text, and on exit `*remainder_p` is reduced by returned
537 * character length. Otherwise `text` is treated as limited by NUL.
538 */
539int mbs_chrlen(const char **text, size_t *remainder_p, const char *encoding)
540{
541 int chrlen;
542 const char *p = *text;
543 size_t r = (remainder_p ? *remainder_p : SIZE_MAX);
544
545 if (r < 1)
546 return 0;
547
548 if (is_encoding_utf8(encoding)) {
549 pick_one_utf8_char(&p, &r);
550
551 chrlen = p ? (p - *text)
552 : 1 /* not valid UTF-8 -> raw byte sequence */;
553 }
554 else {
555 /*
556 * TODO use iconv to decode one char and obtain its chrlen
557 * for now, let's treat encodings != UTF-8 as one-byte
558 */
559 chrlen = 1;
560 }
561
562 *text += chrlen;
563 if (remainder_p)
564 *remainder_p -= chrlen;
565
566 return chrlen;
567}