robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
95.3 KiB3169 linesraw
1/// mbyte.c: Code specifically for handling multi-byte characters.
2/// Multibyte extensions partly by Sung-Hoon Baek
3///
4/// Strings internal to Nvim are always encoded as UTF-8 (thus the legacy
5/// 'encoding' option is always "utf-8").
6///
7/// The cell width on the display needs to be determined from the character
8/// value. Recognizing UTF-8 bytes is easy: 0xxx.xxxx is a single-byte char,
9/// 10xx.xxxx is a trailing byte, 11xx.xxxx is a leading byte of a multi-byte
10/// character. To make things complicated, up to six composing characters
11/// are allowed. These are drawn on top of the first char. For most editing
12/// the sequence of bytes with composing characters included is considered to
13/// be one character.
14///
15/// UTF-8 is used everywhere in the core. This is in registers, text
16/// manipulation, buffers, etc. Nvim core communicates with external plugins
17/// and GUIs in this encoding.
18///
19/// The encoding of a file is specified with 'fileencoding'.  Conversion
20/// is to be done when it's different from "utf-8".
21///
22/// Vim scripts may contain an ":scriptencoding" command. This has an effect
23/// for some commands, like ":menutrans".
24
25#include <assert.h>
26#include <ctype.h>
27#include <errno.h>
28#include <iconv.h>
29#include <limits.h>
30#include <locale.h>
31#include <stdbool.h>
32#include <stddef.h>
33#include <stdio.h>
34#include <stdlib.h>
35#include <string.h>
36#include <utf8proc.h>
37#include <uv.h>
38#include <wctype.h>
39
40#include "auto/config.h"
41#include "nvim/arabic.h"
42#include "nvim/ascii_defs.h"
43#include "nvim/buffer_defs.h"
44#include "nvim/charset.h"
45#include "nvim/cmdexpand_defs.h"
46#include "nvim/cursor.h"
47#include "nvim/drawscreen.h"
48#include "nvim/errors.h"
49#include "nvim/eval/typval.h"
50#include "nvim/eval/typval_defs.h"
51#include "nvim/gettext_defs.h"
52#include "nvim/globals.h"
53#include "nvim/grid.h"
54#include "nvim/iconv_defs.h"
55#include "nvim/input.h"
56#include "nvim/keycodes.h"
57#include "nvim/macros_defs.h"
58#include "nvim/mark.h"
59#include "nvim/mbyte.h"
60#include "nvim/mbyte_defs.h"
61#include "nvim/memline.h"
62#include "nvim/memory.h"
63#include "nvim/message.h"
64#include "nvim/move.h"
65#include "nvim/option_vars.h"
66#include "nvim/optionstr.h"
67#include "nvim/os/os.h"
68#include "nvim/pos_defs.h"
69#include "nvim/strings.h"
70#include "nvim/types_defs.h"
71#include "nvim/vim_defs.h"
72
73struct interval {
74  int first;
75  int last;
76};
77
78// uncrustify:off
79#include "mbyte.c.generated.h"
80// uncrustify:on
81
82static const char e_list_item_nr_is_not_list[]
83  = N_("E1109: List item %d is not a List");
84static const char e_list_item_nr_does_not_contain_3_numbers[]
85  = N_("E1110: List item %d does not contain 3 numbers");
86static const char e_list_item_nr_range_invalid[]
87  = N_("E1111: List item %d range invalid");
88static const char e_list_item_nr_cell_width_invalid[]
89  = N_("E1112: List item %d cell width invalid");
90static const char e_overlapping_ranges_for_nr[]
91  = N_("E1113: Overlapping ranges for 0x%lx");
92static const char e_only_values_of_0x80_and_higher_supported[]
93  = N_("E1114: Only values of 0x80 and higher supported");
94
95// To speed up BYTELEN(); keep a lookup table to quickly get the length in
96// bytes of a UTF-8 character from the first byte of a UTF-8 string.  Bytes
97// which are illegal when used as the first byte have a 1.  The NUL byte has
98// length 1.
99const uint8_t utf8len_tab[] = {
100  // ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9 ?A ?B ?C ?D ?E ?F
101  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  // 0?
102  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  // 1?
103  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  // 2?
104  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  // 3?
105  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  // 4?
106  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  // 5?
107  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  // 6?
108  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  // 7?
109  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  // 8?
110  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  // 9?
111  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  // A?
112  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  // B?
113  2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,  // C?
114  2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,  // D?
115  3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,  // E?
116  4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 1, 1,  // F?
117};
118
119// Like utf8len_tab above, but using a zero for illegal lead bytes.
120const uint8_t utf8len_tab_zero[] = {
121  // ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9 ?A ?B ?C ?D ?E ?F
122  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  // 0?
123  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  // 1?
124  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  // 2?
125  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  // 3?
126  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  // 4?
127  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  // 5?
128  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  // 6?
129  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  // 7?
130  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  // 8?
131  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  // 9?
132  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  // A?
133  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  // B?
134  2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,  // C?
135  2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,  // D?
136  3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,  // E?
137  4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 0, 0,  // F?
138};
139
140// Canonical encoding names and their properties.
141// "iso-8859-n" is handled by enc_canonize() directly.
142static struct
143{   const char *name;   int prop;              int codepage; }
144enc_canon_table[] = {
145#define IDX_LATIN_1     0
146  { "latin1",          ENC_8BIT + ENC_LATIN1,  1252 },
147#define IDX_ISO_2       1
148  { "iso-8859-2",      ENC_8BIT,               0 },
149#define IDX_ISO_3       2
150  { "iso-8859-3",      ENC_8BIT,               0 },
151#define IDX_ISO_4       3
152  { "iso-8859-4",      ENC_8BIT,               0 },
153#define IDX_ISO_5       4
154  { "iso-8859-5",      ENC_8BIT,               0 },
155#define IDX_ISO_6       5
156  { "iso-8859-6",      ENC_8BIT,               0 },
157#define IDX_ISO_7       6
158  { "iso-8859-7",      ENC_8BIT,               0 },
159#define IDX_ISO_8       7
160  { "iso-8859-8",      ENC_8BIT,               0 },
161#define IDX_ISO_9       8
162  { "iso-8859-9",      ENC_8BIT,               0 },
163#define IDX_ISO_10      9
164  { "iso-8859-10",     ENC_8BIT,               0 },
165#define IDX_ISO_11      10
166  { "iso-8859-11",     ENC_8BIT,               0 },
167#define IDX_ISO_13      11
168  { "iso-8859-13",     ENC_8BIT,               0 },
169#define IDX_ISO_14      12
170  { "iso-8859-14",     ENC_8BIT,               0 },
171#define IDX_ISO_15      13
172  { "iso-8859-15",     ENC_8BIT + ENC_LATIN9,  0 },
173#define IDX_KOI8_R      14
174  { "koi8-r",          ENC_8BIT,               0 },
175#define IDX_KOI8_U      15
176  { "koi8-u",          ENC_8BIT,               0 },
177#define IDX_UTF8        16
178  { "utf-8",           ENC_UNICODE,            0 },
179#define IDX_UCS2        17
180  { "ucs-2",           ENC_UNICODE + ENC_ENDIAN_B + ENC_2BYTE, 0 },
181#define IDX_UCS2LE      18
182  { "ucs-2le",         ENC_UNICODE + ENC_ENDIAN_L + ENC_2BYTE, 0 },
183#define IDX_UTF16       19
184  { "utf-16",          ENC_UNICODE + ENC_ENDIAN_B + ENC_2WORD, 0 },
185#define IDX_UTF16BE     20
186  { "utf-16be",        ENC_UNICODE + ENC_ENDIAN_B + ENC_2WORD, 0 },
187#define IDX_UTF16LE     21
188  { "utf-16le",        ENC_UNICODE + ENC_ENDIAN_L + ENC_2WORD, 0 },
189#define IDX_UCS4        22
190  { "ucs-4",           ENC_UNICODE + ENC_ENDIAN_B + ENC_4BYTE, 0 },
191#define IDX_UCS4LE      23
192  { "ucs-4le",         ENC_UNICODE + ENC_ENDIAN_L + ENC_4BYTE, 0 },
193
194  // For debugging DBCS encoding on Unix.
195#define IDX_DEBUG       24
196  { "debug",           ENC_DBCS,               DBCS_DEBUG },
197#define IDX_EUC_JP      25
198  { "euc-jp",          ENC_DBCS,               DBCS_JPNU },
199#define IDX_SJIS        26
200  { "sjis",            ENC_DBCS,               DBCS_JPN },
201#define IDX_EUC_KR      27
202  { "euc-kr",          ENC_DBCS,               DBCS_KORU },
203#define IDX_EUC_CN      28
204  { "euc-cn",          ENC_DBCS,               DBCS_CHSU },
205#define IDX_EUC_TW      29
206  { "euc-tw",          ENC_DBCS,               DBCS_CHTU },
207#define IDX_BIG5        30
208  { "big5",            ENC_DBCS,               DBCS_CHT },
209
210  // MS-DOS and MS-Windows codepages are included here, so that they can be
211  // used on Unix too.  Most of them are similar to ISO-8859 encodings, but
212  // not exactly the same.
213#define IDX_CP437       31
214  { "cp437",           ENC_8BIT,               437 },   // like iso-8859-1
215#define IDX_CP737       32
216  { "cp737",           ENC_8BIT,               737 },   // like iso-8859-7
217#define IDX_CP775       33
218  { "cp775",           ENC_8BIT,               775 },   // Baltic
219#define IDX_CP850       34
220  { "cp850",           ENC_8BIT,               850 },   // like iso-8859-4
221#define IDX_CP852       35
222  { "cp852",           ENC_8BIT,               852 },   // like iso-8859-1
223#define IDX_CP855       36
224  { "cp855",           ENC_8BIT,               855 },   // like iso-8859-2
225#define IDX_CP857       37
226  { "cp857",           ENC_8BIT,               857 },   // like iso-8859-5
227#define IDX_CP860       38
228  { "cp860",           ENC_8BIT,               860 },   // like iso-8859-9
229#define IDX_CP861       39
230  { "cp861",           ENC_8BIT,               861 },   // like iso-8859-1
231#define IDX_CP862       40
232  { "cp862",           ENC_8BIT,               862 },   // like iso-8859-1
233#define IDX_CP863       41
234  { "cp863",           ENC_8BIT,               863 },   // like iso-8859-8
235#define IDX_CP865       42
236  { "cp865",           ENC_8BIT,               865 },   // like iso-8859-1
237#define IDX_CP866       43
238  { "cp866",           ENC_8BIT,               866 },   // like iso-8859-5
239#define IDX_CP869       44
240  { "cp869",           ENC_8BIT,               869 },   // like iso-8859-7
241#define IDX_CP874       45
242  { "cp874",           ENC_8BIT,               874 },   // Thai
243#define IDX_CP932       46
244  { "cp932",           ENC_DBCS,               DBCS_JPN },
245#define IDX_CP936       47
246  { "cp936",           ENC_DBCS,               DBCS_CHS },
247#define IDX_CP949       48
248  { "cp949",           ENC_DBCS,               DBCS_KOR },
249#define IDX_CP950       49
250  { "cp950",           ENC_DBCS,               DBCS_CHT },
251#define IDX_CP1250      50
252  { "cp1250",          ENC_8BIT,               1250 },   // Czech, Polish, etc.
253#define IDX_CP1251      51
254  { "cp1251",          ENC_8BIT,               1251 },   // Cyrillic
255  // cp1252 is considered to be equal to latin1
256#define IDX_CP1253      52
257  { "cp1253",          ENC_8BIT,               1253 },   // Greek
258#define IDX_CP1254      53
259  { "cp1254",          ENC_8BIT,               1254 },   // Turkish
260#define IDX_CP1255      54
261  { "cp1255",          ENC_8BIT,               1255 },   // Hebrew
262#define IDX_CP1256      55
263  { "cp1256",          ENC_8BIT,               1256 },   // Arabic
264#define IDX_CP1257      56
265  { "cp1257",          ENC_8BIT,               1257 },   // Baltic
266#define IDX_CP1258      57
267  { "cp1258",          ENC_8BIT,               1258 },   // Vietnamese
268
269#define IDX_MACROMAN    58
270  { "macroman",        ENC_8BIT + ENC_MACROMAN, 0 },      // Mac OS
271#define IDX_HPROMAN8    59
272  { "hp-roman8",       ENC_8BIT,               0 },       // HP Roman8
273#define IDX_COUNT       60
274};
275
276// Aliases for encoding names.
277static struct
278{   const char *name; int canon; }
279enc_alias_table[] = {
280  { "ansi",            IDX_LATIN_1 },
281  { "iso-8859-1",      IDX_LATIN_1 },
282  { "iso-8859",        IDX_LATIN_1 },
283  { "latin2",          IDX_ISO_2 },
284  { "latin3",          IDX_ISO_3 },
285  { "latin4",          IDX_ISO_4 },
286  { "cyrillic",        IDX_ISO_5 },
287  { "arabic",          IDX_ISO_6 },
288  { "greek",           IDX_ISO_7 },
289  { "hebrew",          IDX_ISO_8 },
290  { "latin5",          IDX_ISO_9 },
291  { "turkish",         IDX_ISO_9 },   // ?
292  { "latin6",          IDX_ISO_10 },
293  { "nordic",          IDX_ISO_10 },  // ?
294  { "thai",            IDX_ISO_11 },  // ?
295  { "latin7",          IDX_ISO_13 },
296  { "latin8",          IDX_ISO_14 },
297  { "latin9",          IDX_ISO_15 },
298  { "utf8",            IDX_UTF8 },
299  { "unicode",         IDX_UCS2 },
300  { "ucs2",            IDX_UCS2 },
301  { "ucs2be",          IDX_UCS2 },
302  { "ucs-2be",         IDX_UCS2 },
303  { "ucs2le",          IDX_UCS2LE },
304  { "utf16",           IDX_UTF16 },
305  { "utf16be",         IDX_UTF16BE },
306  { "utf-16be",        IDX_UTF16BE },
307  { "utf16le",         IDX_UTF16LE },
308  { "ucs4",            IDX_UCS4 },
309  { "ucs4be",          IDX_UCS4 },
310  { "ucs-4be",         IDX_UCS4 },
311  { "ucs4le",          IDX_UCS4LE },
312  { "utf32",           IDX_UCS4 },
313  { "utf-32",          IDX_UCS4 },
314  { "utf32be",         IDX_UCS4 },
315  { "utf-32be",        IDX_UCS4 },
316  { "utf32le",         IDX_UCS4LE },
317  { "utf-32le",        IDX_UCS4LE },
318  { "932",             IDX_CP932 },
319  { "949",             IDX_CP949 },
320  { "936",             IDX_CP936 },
321  { "gbk",             IDX_CP936 },
322  { "950",             IDX_CP950 },
323  { "eucjp",           IDX_EUC_JP },
324  { "unix-jis",        IDX_EUC_JP },
325  { "ujis",            IDX_EUC_JP },
326  { "shift-jis",       IDX_SJIS },
327  { "pck",             IDX_SJIS },        // Sun: PCK
328  { "euckr",           IDX_EUC_KR },
329  { "5601",            IDX_EUC_KR },      // Sun: KS C 5601
330  { "euccn",           IDX_EUC_CN },
331  { "gb2312",          IDX_EUC_CN },
332  { "euctw",           IDX_EUC_TW },
333  { "japan",           IDX_EUC_JP },
334  { "korea",           IDX_EUC_KR },
335  { "prc",             IDX_EUC_CN },
336  { "zh-cn",           IDX_EUC_CN },
337  { "chinese",         IDX_EUC_CN },
338  { "zh-tw",           IDX_EUC_TW },
339  { "taiwan",          IDX_EUC_TW },
340  { "cp950",           IDX_BIG5 },
341  { "950",             IDX_BIG5 },
342  { "mac",             IDX_MACROMAN },
343  { "mac-roman",       IDX_MACROMAN },
344  { NULL,              0 }
345};
346
347/// Find encoding "name" in the list of canonical encoding names.
348/// Returns -1 if not found.
349static int enc_canon_search(const char *name)
350  FUNC_ATTR_PURE
351{
352  for (int i = 0; i < IDX_COUNT; i++) {
353    if (strcmp(name, enc_canon_table[i].name) == 0) {
354      return i;
355    }
356  }
357  return -1;
358}
359
360// Find canonical encoding "name" in the list and return its properties.
361// Returns 0 if not found.
362int enc_canon_props(const char *name)
363  FUNC_ATTR_PURE
364{
365  int i = enc_canon_search(name);
366  if (i >= 0) {
367    return enc_canon_table[i].prop;
368  } else if (strncmp(name, "2byte-", 6) == 0) {
369    return ENC_DBCS;
370  } else if (strncmp(name, "8bit-", 5) == 0 || strncmp(name, "iso-8859-", 9) == 0) {
371    return ENC_8BIT;
372  }
373  return 0;
374}
375
376// Return the size of the BOM for the current buffer:
377// 0 - no BOM
378// 2 - UCS-2 or UTF-16 BOM
379// 4 - UCS-4 BOM
380// 3 - UTF-8 BOM
381int bomb_size(void)
382  FUNC_ATTR_PURE
383{
384  int n = 0;
385
386  if (curbuf->b_p_bomb && !curbuf->b_p_bin) {
387    if (*curbuf->b_p_fenc == NUL
388        || strcmp(curbuf->b_p_fenc, "utf-8") == 0) {
389      n = 3;
390    } else if (strncmp(curbuf->b_p_fenc, "ucs-2", 5) == 0
391               || strncmp(curbuf->b_p_fenc, "utf-16", 6) == 0) {
392      n = 2;
393    } else if (strncmp(curbuf->b_p_fenc, "ucs-4", 5) == 0) {
394      n = 4;
395    }
396  }
397  return n;
398}
399
400// Remove all BOM from "s" by moving remaining text.
401void remove_bom(char *s)
402  FUNC_ATTR_NONNULL_ALL
403{
404  char *p = s;
405
406  while ((p = strchr(p, 0xef)) != NULL) {
407    if ((uint8_t)p[1] == 0xbb && (uint8_t)p[2] == 0xbf) {
408      STRMOVE(p, p + 3);
409    } else {
410      p++;
411    }
412  }
413}
414
415/// Get class of pointer:
416/// 0 for blank or NUL
417/// 1 for punctuation
418/// 2 for an alphanumeric word character
419/// >2 for other word characters, including CJK and emoji
420int mb_get_class(const char *p)
421  FUNC_ATTR_PURE
422{
423  return mb_get_class_tab(p, curbuf->b_chartab);
424}
425
426int mb_get_class_tab(const char *p, const uint64_t *const chartab)
427  FUNC_ATTR_PURE
428{
429  if (MB_BYTE2LEN((uint8_t)p[0]) == 1) {
430    if (p[0] == NUL || ascii_iswhite(p[0])) {
431      return 0;
432    }
433    if (vim_iswordc_tab((uint8_t)p[0], chartab)) {
434      return 2;
435    }
436    return 1;
437  }
438  return utf_class_tab(utf_ptr2char(p), chartab);
439}
440
441static bool prop_is_emojilike(const utf8proc_property_t *prop)
442  FUNC_ATTR_PURE FUNC_ATTR_NONNULL_ALL
443{
444  return prop->boundclass == UTF8PROC_BOUNDCLASS_EXTENDED_PICTOGRAPHIC
445         || prop->boundclass == UTF8PROC_BOUNDCLASS_REGIONAL_INDICATOR;
446}
447
448/// For UTF-8 character "c" return 2 for a double-width character, 1 for others.
449/// Returns 4 or 6 for an unprintable character.
450/// Is only correct for characters >= 0x80.
451/// When p_ambw is "double", return 2 for a character with East Asian Width
452/// class 'A'(mbiguous).
453int utf_char2cells(int c)
454  FUNC_ATTR_PURE
455{
456  if (c < 0x80) {
457    return 1;
458  }
459
460  if (!vim_isprintc(c)) {
461    assert(c <= 0xFFFF);
462    // unprintable is displayed either as <xx> or <xxxx>
463    return c > 0xFF ? 6 : 4;
464  }
465
466  int n = cw_value(c);
467  if (n != 0) {
468    return n;
469  }
470
471  const utf8proc_property_t *prop = utf8proc_get_property(c);
472
473  if (prop->charwidth == 2) {
474    return 2;
475  }
476  if (*p_ambw == 'd' && prop->ambiguous_width) {
477    return 2;
478  }
479
480  // Characters below 1F000 may be considered single width traditionally,
481  // making them double width causes problems.
482  if (p_emoji && c >= 0x1f000 && !prop->ambiguous_width && prop_is_emojilike(prop)) {
483    return 2;
484  }
485
486  return 1;
487}
488
489/// Number of extra display cells needed by the SpacingMarks in the grapheme
490/// cluster starting at "p", whose first codepoint is "firstlen" bytes. "size"
491/// bounds the read, or -1 when "p" is NUL-terminated.
492///
493/// A SpacingMark does not break the cluster (UAX#29 GB9a) but has positive
494/// advance width (Unicode core spec D55), so it needs a cell of its own.
495static int utf_cluster_spacing_cells(const char *p, int firstlen, int size)
496  FUNC_ATTR_NONNULL_ALL
497{
498  GraphemeState state = GRAPHEME_STATE_INIT;
499  const char *prev = p;
500  const char *cur = p + firstlen;
501  int extra = 0;
502
503  while (*cur != NUL) {
504    int remaining = (size < 0) ? -1 : size - (int)(cur - p);
505    if (remaining == 0) {
506      break;
507    }
508
509    int len = (remaining < 0) ? utf_ptr2len(cur) : utf_ptr2len_len(cur, remaining);
510    if (len <= 0 || (remaining > 0 && len > remaining)) {
511      break;  // truncated sequence
512    }
513
514    if (!utf_composinglike(prev, cur, &state)) {
515      break;  // end of the cluster
516    }
517
518    int c = utf_ptr2char(cur);
519    if (utf8proc_get_property(c)->boundclass == UTF8PROC_BOUNDCLASS_SPACINGMARK
520        || (c & ~1) == 0xFF9E) {  // halfwidth katakana voiced sound marks
521      extra += utf_char2cells(c);
522    }
523
524    prev = cur;
525    cur += len;
526  }
527
528  return extra;
529}
530
531/// Return number of display cells occupied by character at "*p".
532/// A TAB is counted as two cells: "^I" or four: "<09>".
533///
534/// Consider using utf_ClusterInfo() instead to calculate both
535/// byte length and cell width of a printable cluster at once
536///
537/// @param p
538///
539/// @return number of display cells.
540int ptr2cells(const char *p_in)
541{
542  return utf_ClusterInfo(utf_ptr2StrCharInfo((char *)p_in)).cells;
543}
544
545/// Return the number of display cells character at "*p" occupies.
546///
547/// This considers all ASCII bytes to have width "1". Use ptr2cells()
548/// for 'display' style printing of unprintable ASCII.
549int utf_ptr2cells(const char *p_in)
550  FUNC_ATTR_PURE FUNC_ATTR_NONNULL_ALL
551{
552  const uint8_t *p = (const uint8_t *)p_in;
553  if (*p < 0x80) {
554    return 1;
555  }
556
557  return ptr2cells(p_in);
558}
559
560/// Convert a UTF-8 byte sequence to a character number.
561/// Doesn't handle ascii! only multibyte and illegal sequences. ASCII (including NUL)
562/// are treated like illegal sequences.
563///
564/// @param[in]  p      String to convert.
565/// @param[in]  len    Length of the character in bytes, 0 or 1 if illegal.
566///
567/// @return Unicode codepoint. A negative value when the sequence is illegal (or
568///         ASCII, including NUL).
569int32_t utf_ptr2CharInfo_impl(uint8_t const *p, uintptr_t const len)
570  FUNC_ATTR_PURE FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
571{
572// uint8_t is a reminder for clang to use smaller cmp
573#define CHECK \
574  do { \
575    if (EXPECT((uint8_t)(cur & 0xC0U) != 0x80U, false)) { \
576      return -1; \
577    } \
578  } while (0)
579
580  static uint32_t const corrections[] = {
581    (1U << 31),  // invalid - set invalid bits (safe to add as first 2 bytes
582    (1U << 31),  // won't affect highest bit in normal ret)
583    -(0x80U + (0xC0U << 6)),  // multibyte - subtract added UTF8 bits (1..10xxx and 10xxx)
584    -(0x80U + (0x80U << 6) + (0xE0U << 12)),
585    -(0x80U + (0x80U << 6) + (0x80U << 12) + (0xF0U << 18)),
586    -(0x80U + (0x80U << 6) + (0x80U << 12) + (0x80U << 18) + (0xF8U << 24)),
587    -(0x80U + (0x80U << 6) + (0x80U << 12) + (0x80U << 18) + (0x80U << 24)),  // + (0xFCU << 30)
588  };
589
590  // len is 0-6, but declared uintptr_t to avoid zeroing out upper bits
591  uint32_t const corr = corrections[len];
592  uint8_t cur;
593
594  // reading second byte unconditionally, safe for invalid
595  // as it cannot be the last byte, not safe for ascii
596  uint32_t code_point = ((uint32_t)p[0] << 6) + (cur = p[1]);
597  CHECK;
598  if ((uint32_t)len < 3) {
599    goto ret;  // len == 0, 1, 2
600  }
601
602  code_point = (code_point << 6) + (cur = p[2]);
603  CHECK;
604  if ((uint32_t)len == 3) {
605    goto ret;
606  }
607
608  code_point = (code_point << 6) + (cur = p[3]);
609  CHECK;
610  if ((uint32_t)len == 4) {
611    goto ret;
612  }
613
614  code_point = (code_point << 6) + (cur = p[4]);
615  CHECK;
616  if ((uint32_t)len == 5) {
617    goto ret;
618  }
619
620  code_point = (code_point << 6) + (cur = p[5]);
621  CHECK;
622  // len == 6
623
624ret:
625  return (int32_t)(code_point + corr);
626
627#undef CHECK
628}
629
630/// Like utf_ptr2cells(), but limit string length to "size".
631/// For an empty string or truncated character returns 1.
632int utf_ptr2cells_len(const char *p, int size)
633  FUNC_ATTR_PURE
634{
635  // Need to convert to a wide character.
636  if (size > 0 && (uint8_t)(*p) >= 0x80) {
637    int len = utf_ptr2len_len(p, size);
638    if (len < utf8len_tab[(uint8_t)(*p)]) {
639      return 1;        // truncated
640    }
641    int c = utf_ptr2char(p);
642    // An illegal byte is displayed as <xx>.
643    if (utf_ptr2len(p) == 1 || c == NUL) {
644      return 4;
645    }
646    // If the char is ASCII it must be an overlong sequence.
647    if (c < 0x80) {
648      return char2cells(c);
649    }
650    int cells = utf_char2cells(c);
651    if (cells == 1 && p_emoji && size > len
652        && prop_is_emojilike(utf8proc_get_property(c))
653        && utf_ptr2len_len(p + len, size - len) == utf8len_tab[(uint8_t)p[len]]) {
654      int c2 = utf_ptr2char(p + len);
655      if (c2 == 0xFE0F) {
656        return 2;  // emoji presentation
657      }
658    }
659    if (cells >= 2) {
660      return cells;  // unprintable or already known to be doublewidth
661    }
662    // currently, the grid allows maximum two cells per cluster
663    int extra = utf_cluster_spacing_cells(p, len, size);
664    return MIN(cells + extra, 2);
665  }
666  return 1;
667}
668
669/// Calculate the number of cells occupied by string `str`.
670///
671/// @param str The source string, may not be NULL, must be a NUL-terminated
672///            string.
673/// @return The number of cells occupied by string `str`
674size_t mb_string2cells(const char *str)
675  FUNC_ATTR_PURE FUNC_ATTR_NONNULL_ALL
676{
677  size_t clen = 0;
678
679  StrCharInfo ci = utf_ptr2StrCharInfo((char *)str);
680  while (*ci.ptr != NUL) {
681    ClusterInfo cli = utf_ClusterInfo(ci);
682    // TODO(bfredl): moar unification, allowing dy_escape_width should be fine
683    clen += ci.chr.value < 0x80 ? 1 : (size_t)cli.cells;
684    ci = cli.next;
685  }
686
687  return clen;
688}
689
690/// Get the number of cells occupied by string `str` with maximum length `size`
691///
692/// @param str The source string, may not be NULL, must be a NUL-terminated
693///            string.
694/// @param size maximum length of string. It will terminate on earlier NUL.
695/// @return The number of cells occupied by string `str`
696size_t mb_string2cells_len(const char *str, size_t size)
697  FUNC_ATTR_PURE FUNC_ATTR_NONNULL_ARG(1)
698{
699  size_t clen = 0;
700
701  for (const char *p = str; *p != NUL && p < str + size;
702       p += utfc_ptr2len_len(p, (int)size - (int)(p - str))) {
703    clen += (size_t)utf_ptr2cells_len(p, (int)size - (int)(p - str));
704  }
705
706  return clen;
707}
708
709/// Convert a UTF-8 byte sequence to a character number.
710///
711/// If the sequence is illegal or truncated by a NUL then the first byte is
712/// returned.
713/// For an overlong sequence this may return zero.
714/// Does not include composing characters for obvious reasons.
715///
716/// @param[in]  p_in  String to convert.
717///
718/// @return Unicode codepoint or byte value.
719int utf_ptr2char(const char *const p_in)
720  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
721{
722  uint8_t *p = (uint8_t *)p_in;
723
724  uint32_t const v0 = p[0];
725  if (EXPECT(v0 < 0x80U, true)) {  // Be quick for ASCII.
726    return (int)v0;
727  }
728
729  const uint8_t len = utf8len_tab[v0];
730  if (EXPECT(len < 2, false)) {
731    return (int)v0;
732  }
733
734#define CHECK(v) \
735  do { \
736    if (EXPECT((uint8_t)((v) & 0xC0U) != 0x80U, false)) { \
737      return (int)v0; \
738    } \
739  } while (0)
740#define LEN_RETURN(len_v, result) \
741  do { \
742    if (len == (len_v)) { \
743      return (int)(result); \
744    } \
745  } while (0)
746#define S(s) ((uint32_t)0x80U << (s))
747
748  uint32_t const v1 = p[1];
749  CHECK(v1);
750  LEN_RETURN(2, (v0 << 6) + v1 - ((0xC0U << 6) + S(0)));
751
752  uint32_t const v2 = p[2];
753  CHECK(v2);
754  LEN_RETURN(3, (v0 << 12) + (v1 << 6) + v2 - ((0xE0U << 12) + S(6) + S(0)));
755
756  uint32_t const v3 = p[3];
757  CHECK(v3);
758  LEN_RETURN(4, (v0 << 18) + (v1 << 12) + (v2 << 6) + v3
759             - ((0xF0U << 18) + S(12) + S(6) + S(0)));
760
761  uint32_t const v4 = p[4];
762  CHECK(v4);
763  LEN_RETURN(5, (v0 << 24) + (v1 << 18) + (v2 << 12) + (v3 << 6) + v4
764             - ((0xF8U << 24) + S(18) + S(12) + S(6) + S(0)));
765
766  uint32_t const v5 = p[5];
767  CHECK(v5);
768  // len == 6
769  return (int)((v0 << 30) + (v1 << 24) + (v2 << 18) + (v3 << 12) + (v4 << 6) + v5
770               // - (0xFCU << 30)
771               - (S(24) + S(18) + S(12) + S(6) + S(0)));
772
773#undef S
774#undef CHECK
775#undef LEN_RETURN
776}
777
778// Convert a UTF-8 byte sequence to a wide character.
779// String is assumed to be terminated by NUL or after "n" bytes, whichever
780// comes first.
781// The function is safe in the sense that it never accesses memory beyond the
782// first "n" bytes of "s".
783//
784// On success, returns decoded codepoint, advances "s" to the beginning of
785// next character and decreases "n" accordingly.
786//
787// If end of string was reached, returns 0 and, if "n" > 0, advances "s" past
788// NUL byte.
789//
790// If byte sequence is illegal or incomplete, returns -1 and does not advance
791// "s".
792static int utf_safe_read_char_adv(const char **s, size_t *n)
793  FUNC_ATTR_NONNULL_ARG(2)
794{
795  if (*n == 0) {  // end of buffer
796    return 0;
797  }
798
799  uint8_t k = utf8len_tab_zero[(uint8_t)(**s)];
800
801  if (k == 1) {
802    // ASCII character or NUL
803    (*n)--;
804    return (uint8_t)(*(*s)++);
805  }
806
807  if (k <= *n) {
808    // We have a multibyte sequence and it isn't truncated by buffer
809    // limits so utf_ptr2char() is safe to use. Or the first byte is
810    // illegal (k=0), and it's also safe to use utf_ptr2char().
811    int c = utf_ptr2char(*s);
812
813    // On failure, utf_ptr2char() returns the first byte, so here we
814    // check equality with the first byte. The only non-ASCII character
815    // which equals the first byte of its own UTF-8 representation is
816    // U+00C3 (UTF-8: 0xC3 0x83), so need to check that special case too.
817    // It's safe even if n=1, else we would have k=2 > n.
818    if (c != (int)((uint8_t)(**s)) || (c == 0xC3 && (uint8_t)(*s)[1] == 0x83)) {
819      // byte sequence was successfully decoded
820      *s += k;
821      *n -= k;
822      return c;
823    }
824  }
825
826  // byte sequence is incomplete or illegal
827  return -1;
828}
829
830// Get character at **pp and advance *pp to the next character.
831// Note: composing characters are skipped!
832int mb_ptr2char_adv(const char **const pp)
833  FUNC_ATTR_NONNULL_ALL
834{
835  int c = utf_ptr2char(*pp);
836  *pp += utfc_ptr2len(*pp);
837  return c;
838}
839
840// Get character at **pp and advance *pp to the next character.
841// Note: composing characters are returned as separate characters.
842int mb_cptr2char_adv(const char **pp)
843  FUNC_ATTR_NONNULL_ALL
844{
845  int c = utf_ptr2char(*pp);
846  *pp += utf_ptr2len(*pp);
847  return c;
848}
849
850/// When "c" is the first char of a string, determine if it needs to be prefixed
851/// by a space byte to be drawn correctly, and not merge with the space left of
852/// the string.
853bool utf_iscomposing_first(int c)
854  FUNC_ATTR_PURE
855{
856  return c >= 128 && !utf8proc_grapheme_break(' ', c);
857}
858
859/// Check if the character pointed to by "p2" is a composing character when it
860/// comes after "p1".
861///
862/// We use the definition in UAX#29 as implemented by utf8proc with the following
863/// exceptions:
864///
865/// - ASCII chars always begin a new cluster. This is a long assumed invariant
866///   in the code base and very useful for performance (we can exit early for ASCII
867///   all over the place, branch predictor go brrr in ASCII-only text).
868///   As of Unicode 15.1 this will only break BOUNDCLASS_UREPEND followed by ASCII,
869///   which should be exceedingly rare (these PREPEND chars are expected to be
870///   followed by multibyte chars within the same script family)
871///
872/// - When 'arabicshape' is active, some pairs of arabic letters "ab" is replaced with
873///   "c" taking one single cell, which behaves like a cluster.
874///
875/// @param "state" should be set to GRAPHEME_STATE_INIT before first call
876///        it is allowed to be null, but will then not handle some longer
877///        sequences, like ZWJ based emoji
878bool utf_composinglike(const char *p1, const char *p2, GraphemeState *state)
879  FUNC_ATTR_NONNULL_ARG(1, 2)
880{
881  if ((uint8_t)(*p2) < 128) {
882    return false;
883  }
884
885  int first = utf_ptr2char(p1);
886  int second = utf_ptr2char(p2);
887
888  if (!utf8proc_grapheme_break_stateful(first, second, state)) {
889    return true;
890  }
891
892  return arabic_combine(first, second);
893}
894
895/// same as utf_composinglike but operating on UCS-4 values
896bool utf_iscomposing(int c1, int c2, GraphemeState *state)
897{
898  return (!utf8proc_grapheme_break_stateful(c1, c2, state)
899          || arabic_combine(c1, c2));
900}
901
902/// Get the screen char at the beginning of a string
903///
904/// Caller is expected to check for things like unprintable chars etc
905/// If first char in string is a composing char, prepend a space to display it correctly.
906///
907/// If "p" starts with an invalid sequence, zero is returned.
908///
909/// @param[out] firstc (required) The first codepoint of the screen char,
910///                    or the first byte of an invalid sequence
911///
912/// @return the char
913schar_T utfc_ptr2schar(const char *p, int *firstc)
914  FUNC_ATTR_NONNULL_ALL
915{
916  int c = utf_ptr2char(p);
917  *firstc = c;  // NOT optional, you are gonna need it
918  bool first_compose = utf_iscomposing_first(c);
919  size_t maxlen = MAX_SCHAR_SIZE - 1 - first_compose;
920  size_t len = (size_t)utfc_ptr2len_len(p, (int)maxlen);
921
922  if (len == 1 && (uint8_t)(*p) >= 0x80) {
923    return 0;  // invalid sequence
924  }
925
926  return schar_from_buf_first(p, len, first_compose);
927}
928
929/// Get the screen char from a char with a known length
930///
931/// Like utfc_ptr2schar but use no more than p[maxlen].
932schar_T utfc_ptrlen2schar(const char *p, int len, int *firstc)
933  FUNC_ATTR_NONNULL_ALL
934{
935  if ((len == 1 && (uint8_t)(*p) >= 0x80) || len == 0) {
936    // invalid or truncated sequence
937    *firstc = (uint8_t)(*p);
938    return 0;
939  }
940
941  int c = utf_ptr2char(p);
942  *firstc = c;
943  bool first_compose = utf_iscomposing_first(c);
944  int maxlen = MAX_SCHAR_SIZE - 1 - first_compose;
945  if (len > maxlen) {
946    len = utfc_ptr2len_len(p, maxlen);
947  }
948
949  return schar_from_buf_first(p, (size_t)len, first_compose);
950}
951
952/// Caller must ensure there is space for `first_compose`
953static schar_T schar_from_buf_first(const char *buf, size_t len, bool first_compose)
954  FUNC_ATTR_NONNULL_ALL
955{
956  if (first_compose) {
957    char cbuf[MAX_SCHAR_SIZE];
958    cbuf[0] = ' ';
959    memcpy(cbuf + 1, buf, len);
960    return schar_from_buf(cbuf, len + 1);
961  } else {
962    return schar_from_buf(buf, len);
963  }
964}
965
966/// Get the length of a UTF-8 byte sequence representing a single codepoint
967///
968/// @param[in]  p  UTF-8 string.
969///
970/// @return Sequence length, 0 for empty string and 1 for non-UTF-8 byte
971///         sequence.
972int utf_ptr2len(const char *const p_in)
973  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
974{
975  uint8_t *p = (uint8_t *)p_in;
976  if (*p == NUL) {
977    return 0;
978  }
979  const int len = utf8len_tab[*p];
980  for (int i = 1; i < len; i++) {
981    if ((p[i] & 0xc0) != 0x80) {
982      return 1;
983    }
984  }
985  return len;
986}
987
988// Return length of UTF-8 character, obtained from the first byte.
989// "b" must be between 0 and 255!
990// Returns 1 for an invalid first byte value.
991int utf_byte2len(int b)
992  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
993{
994  return utf8len_tab[b];
995}
996
997// Get the length of UTF-8 byte sequence "p[size]".  Does not include any
998// following composing characters.
999// Returns 1 for "".
1000// Returns 1 for an illegal byte sequence (also in incomplete byte seq.).
1001// Returns number > "size" for an incomplete byte sequence.
1002// Never returns zero.
1003int utf_ptr2len_len(const char *p, int size)
1004  FUNC_ATTR_PURE FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
1005{
1006  int m;
1007
1008  int len = utf8len_tab[(uint8_t)(*p)];
1009  if (len == 1) {
1010    return 1;           // NUL, ascii or illegal lead byte
1011  }
1012  if (len > size) {
1013    m = size;           // incomplete byte sequence.
1014  } else {
1015    m = len;
1016  }
1017  for (int i = 1; i < m; i++) {
1018    if ((p[i] & 0xc0) != 0x80) {
1019      return 1;
1020    }
1021  }
1022  return len;
1023}
1024
1025/// Return the number of bytes occupied by a UTF-8 character in a string.
1026/// This includes following composing characters.
1027/// Returns zero for NUL.
1028int utfc_ptr2len(const char *const p)
1029  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
1030{
1031  uint8_t b0 = (uint8_t)(*p);
1032
1033  if (b0 == NUL) {
1034    return 0;
1035  }
1036  if (b0 < 0x80 && (uint8_t)p[1] < 0x80) {  // be quick for ASCII
1037    return 1;
1038  }
1039
1040  // Skip over first UTF-8 char, stopping at a NUL byte.
1041  int len = utf_ptr2len(p);
1042
1043  // Check for illegal byte.
1044  if (len == 1 && b0 >= 0x80) {
1045    return 1;
1046  }
1047
1048  // Check for composing characters.
1049  int prevlen = 0;
1050  GraphemeState state = GRAPHEME_STATE_INIT;
1051  while (true) {
1052    if ((uint8_t)p[len] < 0x80 || !utf_composinglike(p + prevlen, p + len, &state)) {
1053      return len;
1054    }
1055
1056    // Skip over composing char.
1057    prevlen = len;
1058    len += utf_ptr2len(p + len);
1059  }
1060}
1061
1062/// Return the number of bytes the UTF-8 encoding of the character at "p[size]"
1063/// takes.  This includes following composing characters.
1064/// Returns 0 for an empty string.
1065/// Returns 1 for an illegal char or an incomplete byte sequence.
1066int utfc_ptr2len_len(const char *p, int size)
1067  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
1068{
1069  if (size < 1 || *p == NUL) {
1070    return 0;
1071  }
1072  if ((uint8_t)p[0] < 0x80 && (size == 1 || (uint8_t)p[1] < 0x80)) {  // be quick for ASCII
1073    return 1;
1074  }
1075
1076  // Skip over first UTF-8 char, stopping at a NUL byte.
1077  int len = utf_ptr2len_len(p, size);
1078
1079  // Check for illegal byte and incomplete byte sequence.
1080  if ((len == 1 && (uint8_t)p[0] >= 0x80) || len > size) {
1081    return 1;
1082  }
1083
1084  // Check for composing characters.  We can only display a limited amount, but
1085  // skip all of them (otherwise the cursor would get stuck).
1086  int prevlen = 0;
1087  GraphemeState state = GRAPHEME_STATE_INIT;
1088  while (len < size) {
1089    if ((uint8_t)p[len] < 0x80) {
1090      break;
1091    }
1092
1093    // Next character length should not go beyond size to ensure that
1094    // utf_composinglike(...) does not read beyond size.
1095    int len_next_char = utf_ptr2len_len(p + len, size - len);
1096    if (len_next_char > size - len) {
1097      break;
1098    }
1099
1100    if (!utf_composinglike(p + prevlen, p + len, &state)) {
1101      break;
1102    }
1103
1104    // Skip over composing char
1105    prevlen = len;
1106    len += len_next_char;
1107  }
1108  return len;
1109}
1110
1111/// Determine how many bytes certain unicode codepoint will occupy
1112int utf_char2len(const int c)
1113  FUNC_ATTR_CONST FUNC_ATTR_WARN_UNUSED_RESULT
1114{
1115  if (c < 0x80) {
1116    return 1;
1117  } else if (c < 0x800) {
1118    return 2;
1119  } else if (c < 0x10000) {
1120    return 3;
1121  } else if (c < 0x200000) {
1122    return 4;
1123  } else if (c < 0x4000000) {
1124    return 5;
1125  } else {
1126    return 6;
1127  }
1128}
1129
1130/// Convert Unicode character to UTF-8 string
1131///
1132/// @param c         character to convert to UTF-8 string in \p buf
1133/// @param[out] buf  UTF-8 string generated from \p c, does not add \0
1134///                  must have room for at least 6 bytes
1135/// @return Number of bytes (1-6).
1136int utf_char2bytes(const int c, char *const buf)
1137  FUNC_ATTR_NONNULL_ALL
1138{
1139  if (c < 0x80) {  // 7 bits
1140    buf[0] = (char)c;
1141    return 1;
1142  } else if (c < 0x800) {  // 11 bits
1143    buf[0] = (char)(0xc0 + ((unsigned)c >> 6));
1144    buf[1] = (char)(0x80 + ((unsigned)c & 0x3f));
1145    return 2;
1146  } else if (c < 0x10000) {  // 16 bits
1147    buf[0] = (char)(0xe0 + ((unsigned)c >> 12));
1148    buf[1] = (char)(0x80 + (((unsigned)c >> 6) & 0x3f));
1149    buf[2] = (char)(0x80 + ((unsigned)c & 0x3f));
1150    return 3;
1151  } else if (c < 0x200000) {  // 21 bits
1152    buf[0] = (char)(0xf0 + ((unsigned)c >> 18));
1153    buf[1] = (char)(0x80 + (((unsigned)c >> 12) & 0x3f));
1154    buf[2] = (char)(0x80 + (((unsigned)c >> 6) & 0x3f));
1155    buf[3] = (char)(0x80 + ((unsigned)c & 0x3f));
1156    return 4;
1157  } else if (c < 0x4000000) {  // 26 bits
1158    buf[0] = (char)(0xf8 + ((unsigned)c >> 24));
1159    buf[1] = (char)(0x80 + (((unsigned)c >> 18) & 0x3f));
1160    buf[2] = (char)(0x80 + (((unsigned)c >> 12) & 0x3f));
1161    buf[3] = (char)(0x80 + (((unsigned)c >> 6) & 0x3f));
1162    buf[4] = (char)(0x80 + ((unsigned)c & 0x3f));
1163    return 5;
1164  } else {  // 31 bits
1165    buf[0] = (char)(0xfc + ((unsigned)c >> 30));
1166    buf[1] = (char)(0x80 + (((unsigned)c >> 24) & 0x3f));
1167    buf[2] = (char)(0x80 + (((unsigned)c >> 18) & 0x3f));
1168    buf[3] = (char)(0x80 + (((unsigned)c >> 12) & 0x3f));
1169    buf[4] = (char)(0x80 + (((unsigned)c >> 6) & 0x3f));
1170    buf[5] = (char)(0x80 + ((unsigned)c & 0x3f));
1171    return 6;
1172  }
1173}
1174
1175/// Return true if "c" is a legacy composing UTF-8 character.
1176///
1177/// This is deprecated in favour of utf_composinglike() which uses the modern
1178/// stateful algorithm to determine grapheme clusters. Still available
1179/// to support some legacy code which hasn't been refactored yet.
1180///
1181/// To check if a char would combine with a preceding space, use
1182/// utf_iscomposing_first() instead.
1183///
1184/// Based on code from Markus Kuhn.
1185/// Returns false for negative values.
1186bool utf_iscomposing_legacy(int c)
1187  FUNC_ATTR_PURE
1188{
1189  const utf8proc_property_t *prop = utf8proc_get_property(c);
1190  return prop->category == UTF8PROC_CATEGORY_MN || prop->category == UTF8PROC_CATEGORY_ME;
1191}
1192
1193#ifdef __SSE2__
1194
1195# include <emmintrin.h>
1196
1197// Return true for characters that can be displayed in a normal way.
1198// Only for characters of 0x100 and above!
1199bool utf_printable(int c)
1200  FUNC_ATTR_CONST
1201{
1202  if (c < 0x180B || c > 0xFFFF) {
1203    return c != 0x70F;
1204  }
1205
1206# define L(v) ((int16_t)((v) - 1))  // lower bound (exclusive)
1207# define H(v) ((int16_t)(v))  // upper bound (inclusive)
1208
1209  // Boundaries of unprintable characters.
1210  // Some values are negative when converted to int16_t.
1211  // Ranges must not wrap around when converted to int16_t.
1212  __m128i const lo = _mm_setr_epi16(L(0x180b), L(0x200b), L(0x202a), L(0x2060),
1213                                    L(0xd800), L(0xfeff), L(0xfff9), L(0xfffe));
1214
1215  __m128i const hi = _mm_setr_epi16(H(0x180e), H(0x200f), H(0x202e), H(0x206f),
1216                                    H(0xdfff), H(0xfeff), H(0xfffb), H(0xffff));
1217
1218# undef L
1219# undef H
1220
1221  __m128i value = _mm_set1_epi16((int16_t)c);
1222
1223  // Using _mm_cmplt_epi16() is less optimal, since it would require
1224  // swapping operands (sse2 only has cmpgt instruction),
1225  // and only the second operand can be a memory location.
1226
1227  // Character is printable when it is above/below both bounds of each range
1228  // (corresponding bits in both masks are equal).
1229  return _mm_movemask_epi8(_mm_cmpgt_epi16(value, lo))
1230         == _mm_movemask_epi8(_mm_cmpgt_epi16(value, hi));
1231}
1232
1233#else
1234
1235// Return true if "c" is in "table".
1236static bool intable(const struct interval *table, size_t n_items, int c)
1237  FUNC_ATTR_CONST
1238{
1239  assert(n_items > 0);
1240  // first quick check for Latin1 etc. characters
1241  if (c < table[0].first) {
1242    return false;
1243  }
1244
1245  assert(n_items <= SIZE_MAX / 2);
1246  // binary search in table
1247  size_t bot = 0;
1248  size_t top = n_items;
1249  do {
1250    size_t mid = (bot + top) >> 1;
1251    if (table[mid].last < c) {
1252      bot = mid + 1;
1253    } else if (table[mid].first > c) {
1254      top = mid;
1255    } else {
1256      return true;
1257    }
1258  } while (top > bot);
1259  return false;
1260}
1261
1262// Return true for characters that can be displayed in a normal way.
1263// Only for characters of 0x100 and above!
1264bool utf_printable(int c)
1265  FUNC_ATTR_CONST
1266{
1267  // Sorted list of non-overlapping intervals.
1268  // 0xd800-0xdfff is reserved for UTF-16, actually illegal.
1269  static const struct interval nonprint[] = {
1270    { 0x070f, 0x070f }, { 0x180b, 0x180e }, { 0x200b, 0x200f }, { 0x202a, 0x202e },
1271    { 0x2060, 0x206f }, { 0xd800, 0xdfff }, { 0xfeff, 0xfeff }, { 0xfff9, 0xfffb },
1272    { 0xfffe, 0xffff }
1273  };
1274
1275  return !intable(nonprint, ARRAY_SIZE(nonprint), c);
1276}
1277
1278#endif
1279
1280// Get class of a Unicode character.
1281// 0: white space
1282// 1: punctuation
1283// 2 or bigger: some class of word character.
1284int utf_class(const int c)
1285  FUNC_ATTR_PURE
1286{
1287  return utf_class_tab(c, curbuf->b_chartab);
1288}
1289
1290int utf_class_tab(const int c, const uint64_t *const chartab)
1291  FUNC_ATTR_PURE
1292{
1293  // sorted list of non-overlapping intervals
1294  static struct clinterval {
1295    unsigned first;
1296    unsigned last;
1297    unsigned cls;
1298  } classes[] = {
1299    { 0x037e, 0x037e, 1 },              // Greek question mark
1300    { 0x0387, 0x0387, 1 },              // Greek ano teleia
1301    { 0x055a, 0x055f, 1 },              // Armenian punctuation
1302    { 0x0589, 0x0589, 1 },              // Armenian full stop
1303    { 0x05be, 0x05be, 1 },
1304    { 0x05c0, 0x05c0, 1 },
1305    { 0x05c3, 0x05c3, 1 },
1306    { 0x05f3, 0x05f4, 1 },
1307    { 0x060c, 0x060c, 1 },
1308    { 0x061b, 0x061b, 1 },
1309    { 0x061f, 0x061f, 1 },
1310    { 0x066a, 0x066d, 1 },
1311    { 0x06d4, 0x06d4, 1 },
1312    { 0x0700, 0x070d, 1 },              // Syriac punctuation
1313    { 0x0964, 0x0965, 1 },
1314    { 0x0970, 0x0970, 1 },
1315    { 0x0df4, 0x0df4, 1 },
1316    { 0x0e4f, 0x0e4f, 1 },
1317    { 0x0e5a, 0x0e5b, 1 },
1318    { 0x0f04, 0x0f12, 1 },
1319    { 0x0f3a, 0x0f3d, 1 },
1320    { 0x0f85, 0x0f85, 1 },
1321    { 0x104a, 0x104f, 1 },              // Myanmar punctuation
1322    { 0x10fb, 0x10fb, 1 },              // Georgian punctuation
1323    { 0x1361, 0x1368, 1 },              // Ethiopic punctuation
1324    { 0x166d, 0x166e, 1 },              // Canadian Syl. punctuation
1325    { 0x1680, 0x1680, 0 },
1326    { 0x169b, 0x169c, 1 },
1327    { 0x16eb, 0x16ed, 1 },
1328    { 0x1735, 0x1736, 1 },
1329    { 0x17d4, 0x17dc, 1 },              // Khmer punctuation
1330    { 0x1800, 0x180a, 1 },              // Mongolian punctuation
1331    { 0x2000, 0x200b, 0 },              // spaces
1332    { 0x200c, 0x2027, 1 },              // punctuation and symbols
1333    { 0x2028, 0x2029, 0 },
1334    { 0x202a, 0x202e, 1 },              // punctuation and symbols
1335    { 0x202f, 0x202f, 0 },
1336    { 0x2030, 0x205e, 1 },              // punctuation and symbols
1337    { 0x205f, 0x205f, 0 },
1338    { 0x2060, 0x206f, 1 },              // punctuation and symbols
1339    { 0x2070, 0x207f, 0x2070 },         // superscript
1340    { 0x2080, 0x2094, 0x2080 },         // subscript
1341    { 0x20a0, 0x27ff, 1 },              // all kinds of symbols
1342    { 0x2800, 0x28ff, 0x2800 },         // braille
1343    { 0x2900, 0x2998, 1 },              // arrows, brackets, etc.
1344    { 0x29d8, 0x29db, 1 },
1345    { 0x29fc, 0x29fd, 1 },
1346    { 0x2e00, 0x2e7f, 1 },              // supplemental punctuation
1347    { 0x3000, 0x3000, 0 },              // ideographic space
1348    { 0x3001, 0x3020, 1 },              // ideographic punctuation
1349    { 0x3030, 0x3030, 1 },
1350    { 0x303d, 0x303d, 1 },
1351    { 0x3040, 0x309f, 0x3040 },         // Hiragana
1352    { 0x30a0, 0x30ff, 0x30a0 },         // Katakana
1353    { 0x3300, 0x9fff, 0x4e00 },         // CJK Ideographs
1354    { 0xac00, 0xd7a3, 0xac00 },         // Hangul Syllables
1355    { 0xf900, 0xfaff, 0x4e00 },         // CJK Ideographs
1356    { 0xfd3e, 0xfd3f, 1 },
1357    { 0xfe30, 0xfe6b, 1 },              // punctuation forms
1358    { 0xff00, 0xff0f, 1 },              // half/fullwidth ASCII
1359    { 0xff1a, 0xff20, 1 },              // half/fullwidth ASCII
1360    { 0xff3b, 0xff40, 1 },              // half/fullwidth ASCII
1361    { 0xff5b, 0xff65, 1 },              // half/fullwidth ASCII
1362    { 0x1d000, 0x1d24f, 1 },            // Musical notation
1363    { 0x1d400, 0x1d7ff, 1 },            // Mathematical Alphanumeric Symbols
1364    { 0x1f000, 0x1f2ff, 1 },            // Game pieces; enclosed characters
1365    { 0x1f300, 0x1f9ff, 1 },            // Many symbol blocks
1366    { 0x20000, 0x2a6df, 0x4e00 },       // CJK Ideographs
1367    { 0x2a700, 0x2b73f, 0x4e00 },       // CJK Ideographs
1368    { 0x2b740, 0x2b81f, 0x4e00 },       // CJK Ideographs
1369    { 0x2f800, 0x2fa1f, 0x4e00 },       // CJK Ideographs
1370  };
1371  int bot = 0;
1372  int top = ARRAY_SIZE(classes) - 1;
1373
1374  // First quick check for Latin1 characters, use 'iskeyword'.
1375  if (c < 0x100) {
1376    if (c == ' ' || c == '\t' || c == NUL || c == 0xa0) {
1377      return 0;             // blank
1378    }
1379    if (vim_iswordc_tab(c, chartab)) {
1380      return 2;             // word character
1381    }
1382    return 1;               // punctuation
1383  }
1384
1385  const utf8proc_property_t *prop = utf8proc_get_property(c);
1386  // emoji
1387  if (prop_is_emojilike(prop)) {
1388    return 3;
1389  }
1390
1391  // binary search in table
1392  while (top >= bot) {
1393    int mid = (bot + top) / 2;
1394    if (classes[mid].last < (unsigned)c) {
1395      bot = mid + 1;
1396    } else if (classes[mid].first > (unsigned)c) {
1397      top = mid - 1;
1398    } else {
1399      return (int)classes[mid].cls;
1400    }
1401  }
1402
1403  // most other characters are "word" characters
1404  return 2;
1405}
1406
1407bool utf_ambiguous_width(const char *p)
1408  FUNC_ATTR_PURE FUNC_ATTR_NONNULL_ALL
1409{
1410  // be quick if there is nothing to print or ASCII-only
1411  if (p[0] == NUL || p[1] == NUL) {
1412    return false;
1413  }
1414
1415  CharInfo info = utf_ptr2CharInfo(p);
1416  if (info.value >= 0x80) {
1417    const utf8proc_property_t *prop = utf8proc_get_property(info.value);
1418    if (prop->ambiguous_width || prop_is_emojilike(prop)) {
1419      return true;
1420    }
1421  }
1422
1423  // check if second sequence is 0xFE0F VS-16 which can turn things into emoji,
1424  // safe with NUL (no second sequence)
1425  return memcmp(p + info.len, "\xef\xb8\x8f", 3) == 0;
1426}
1427
1428// Return the folded-case equivalent of "a", which is a UCS-4 character.  Uses
1429// full case folding.
1430int utf_fold(int a)
1431  FUNC_ATTR_PURE
1432{
1433  if (a < 0x80) {
1434    // be fast for ASCII
1435    return a >= 0x41 && a <= 0x5a ? a + 32 : a;
1436  }
1437
1438  // TODO(dundargoc): utf8proc only does full case folding, which breaks some tests. This is a
1439  // temporary workaround to circumvent failing tests.
1440  //
1441  // (0xdf) ß == ss in full casefolding. Using this however breaks the vim spell tests and the error
1442  // E763 is thrown. This is due to the test spells relying on the vim spell files.
1443  //
1444  // (0x130) İ == i̇ in full casefolding.
1445  if (a == 0xdf || a == 0x130) {
1446    return a;
1447  }
1448
1449  utf8proc_int32_t result[1];
1450
1451  utf8proc_ssize_t res = utf8proc_decompose_char(a, result, 1, UTF8PROC_CASEFOLD, NULL);
1452
1453  return (res == 1) ? result[0] : a;
1454}
1455
1456// Vim's own character class functions.  These exist because many library
1457// islower()/toupper() etc. do not work properly: they crash when used with
1458// invalid values or can't handle latin1 when the locale is C.
1459// Speed is most important here.
1460
1461/// Return the upper-case equivalent of "a", which is a UCS-4 character.  Use
1462/// simple case folding.
1463int mb_toupper(int a)
1464{
1465  // If 'casemap' contains "keepascii" use ASCII style toupper().
1466  if (a < 128 && (cmp_flags & kOptCmpFlagKeepascii)) {
1467    return TOUPPER_ASC(a);
1468  }
1469
1470  if (!(cmp_flags & kOptCmpFlagInternal)) {
1471    return (int)towupper((wint_t)a);
1472  }
1473
1474  // For characters below 128 use locale sensitive toupper().
1475  if (a < 128) {
1476    return TOUPPER_LOC(a);
1477  }
1478
1479  return utf8proc_toupper(a);
1480}
1481
1482bool mb_islower(int a)
1483{
1484  return mb_toupper(a) != a;
1485}
1486
1487/// Return the lower-case equivalent of "a", which is a UCS-4 character.  Use
1488/// simple case folding.
1489int mb_tolower(int a)
1490{
1491  // If 'casemap' contains "keepascii" use ASCII style tolower().
1492  if (a < 128 && (cmp_flags & kOptCmpFlagKeepascii)) {
1493    return TOLOWER_ASC(a);
1494  }
1495
1496  if (!(cmp_flags & kOptCmpFlagInternal)) {
1497    return (int)towlower((wint_t)a);
1498  }
1499
1500  // For characters below 128 use locale sensitive tolower().
1501  if (a < 128) {
1502    return TOLOWER_LOC(a);
1503  }
1504
1505  return utf8proc_tolower(a);
1506}
1507
1508bool mb_isupper(int a)
1509{
1510  return mb_tolower(a) != a;
1511}
1512
1513bool mb_isalpha(int a)
1514  FUNC_ATTR_WARN_UNUSED_RESULT
1515{
1516  return mb_islower(a) || mb_isupper(a);
1517}
1518
1519int utf_strnicmp(const char *s1, const char *s2, size_t n1, size_t n2)
1520  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
1521{
1522  int c1, c2;
1523  char buffer[6];
1524
1525  while (true) {
1526    c1 = utf_safe_read_char_adv(&s1, &n1);
1527    c2 = utf_safe_read_char_adv(&s2, &n2);
1528
1529    if (c1 <= 0 || c2 <= 0) {
1530      break;
1531    }
1532
1533    if (c1 == c2) {
1534      continue;
1535    }
1536
1537    int cdiff = utf_fold(c1) - utf_fold(c2);
1538    if (cdiff != 0) {
1539      return cdiff;
1540    }
1541  }
1542
1543  // some string ended or has an incomplete/illegal character sequence
1544
1545  if (c1 == 0 || c2 == 0) {
1546    // some string ended. shorter string is smaller
1547    if (c1 == 0 && c2 == 0) {
1548      return 0;
1549    }
1550    return c1 == 0 ? -1 : 1;
1551  }
1552
1553  // Continue with bytewise comparison to produce some result that
1554  // would make comparison operations involving this function transitive.
1555  //
1556  // If only one string had an error, comparison should be made with
1557  // folded version of the other string. In this case it is enough
1558  // to fold just one character to determine the result of comparison.
1559
1560  if (c1 != -1 && c2 == -1) {
1561    n1 = (size_t)utf_char2bytes(utf_fold(c1), buffer);
1562    s1 = buffer;
1563  } else if (c2 != -1 && c1 == -1) {
1564    n2 = (size_t)utf_char2bytes(utf_fold(c2), buffer);
1565    s2 = buffer;
1566  }
1567
1568  while (n1 > 0 && n2 > 0 && *s1 != NUL && *s2 != NUL) {
1569    int cdiff = (int)((uint8_t)(*s1)) - (int)((uint8_t)(*s2));
1570    if (cdiff != 0) {
1571      return cdiff;
1572    }
1573
1574    s1++;
1575    s2++;
1576    n1--;
1577    n2--;
1578  }
1579
1580  if (n1 > 0 && *s1 == NUL) {
1581    n1 = 0;
1582  }
1583  if (n2 > 0 && *s2 == NUL) {
1584    n2 = 0;
1585  }
1586
1587  if (n1 == 0 && n2 == 0) {
1588    return 0;
1589  }
1590  return n1 == 0 ? -1 : 1;
1591}
1592
1593#ifdef MSWIN
1594# ifndef CP_UTF8
1595#  define CP_UTF8 65001  // magic number from winnls.h
1596# endif
1597
1598/// Converts string from UTF-8 to UTF-16.
1599///
1600/// @param utf8  UTF-8 string.
1601/// @param utf8len  Length of `utf8`. May be -1 if `utf8` is NUL-terminated.
1602/// @param utf16[out,allocated]  NUL-terminated UTF-16 string, or NULL on error
1603/// @return 0 on success, or libuv error code
1604int utf8_to_utf16(const char *utf8, int utf8len, wchar_t **utf16)
1605  FUNC_ATTR_NONNULL_ALL
1606{
1607  // Compute the length needed for the converted UTF-16 string.
1608  int bufsize = MultiByteToWideChar(CP_UTF8,
1609                                    0,     // dwFlags: must be 0 for UTF-8
1610                                    utf8,  // -1: process up to NUL
1611                                    utf8len,
1612                                    NULL,
1613                                    0);    // 0: get length, don't convert
1614  if (bufsize == 0) {
1615    *utf16 = NULL;
1616    return uv_translate_sys_error(GetLastError());
1617  }
1618
1619  // Allocate the destination buffer adding an extra byte for the terminating
1620  // NULL. If `utf8len` is not -1 MultiByteToWideChar will not add it, so
1621  // we do it ourselves always, just in case.
1622  *utf16 = xmalloc(sizeof(wchar_t) * (bufsize + 1));
1623
1624  // Convert to UTF-16.
1625  bufsize = MultiByteToWideChar(CP_UTF8, 0, utf8, utf8len, *utf16, bufsize);
1626  if (bufsize == 0) {
1627    XFREE_CLEAR(*utf16);
1628    return uv_translate_sys_error(GetLastError());
1629  }
1630
1631  (*utf16)[bufsize] = L'\0';
1632  return 0;
1633}
1634
1635/// Converts string from UTF-16 to UTF-8.
1636///
1637/// @param utf16  UTF-16 string.
1638/// @param utf16len  Length of `utf16`. May be -1 if `utf16` is NUL-terminated.
1639/// @param utf8[out,allocated]  NUL-terminated UTF-8 string, or NULL on error
1640/// @return 0 on success, or libuv error code
1641int utf16_to_utf8(const wchar_t *utf16, int utf16len, char **utf8)
1642  FUNC_ATTR_NONNULL_ALL
1643{
1644  // Compute the space needed for the converted UTF-8 string.
1645  DWORD bufsize = WideCharToMultiByte(CP_UTF8,
1646                                      0,
1647                                      utf16,
1648                                      utf16len,
1649                                      NULL,
1650                                      0,
1651                                      NULL,
1652                                      NULL);
1653  if (bufsize == 0) {
1654    *utf8 = NULL;
1655    return uv_translate_sys_error(GetLastError());
1656  }
1657
1658  // Allocate the destination buffer adding an extra byte for the terminating
1659  // NULL. If `utf16len` is not -1 WideCharToMultiByte will not add it, so
1660  // we do it ourselves always, just in case.
1661  *utf8 = xmalloc(bufsize + 1);
1662
1663  // Convert to UTF-8.
1664  bufsize = WideCharToMultiByte(CP_UTF8,
1665                                0,
1666                                utf16,
1667                                utf16len,
1668                                *utf8,
1669                                bufsize,
1670                                NULL,
1671                                NULL);
1672  if (bufsize == 0) {
1673    XFREE_CLEAR(*utf8);
1674    return uv_translate_sys_error(GetLastError());
1675  }
1676
1677  (*utf8)[bufsize] = NUL;
1678  return 0;
1679}
1680
1681#endif
1682
1683/// Measure the length of a string in corresponding UTF-32 and UTF-16 units.
1684///
1685/// Invalid UTF-8 bytes, or embedded surrogates, count as one code point/unit
1686/// each.
1687///
1688/// The out parameters are incremented. This is used to measure the size of
1689/// a buffer region consisting of multiple line segments.
1690///
1691/// @param s the string
1692/// @param len maximum length (an earlier NUL terminates)
1693/// @param[out] codepoints incremented with UTF-32 code point size
1694/// @param[out] codeunits incremented with UTF-16 code unit size
1695void mb_utflen(const char *s, size_t len, size_t *codepoints, size_t *codeunits)
1696  FUNC_ATTR_NONNULL_ALL
1697{
1698  size_t count = 0;
1699  size_t extra = 0;
1700  size_t clen;
1701  for (size_t i = 0; i < len; i += clen) {
1702    clen = (size_t)utf_ptr2len_len(s + i, (int)(len - i));
1703    // NB: gets the byte value of invalid sequence bytes.
1704    // we only care whether the char fits in the BMP or not
1705    int c = (clen > 1) ? utf_ptr2char(s + i) : (uint8_t)s[i];
1706    count++;
1707    if (c > 0xFFFF) {
1708      extra++;
1709    }
1710  }
1711  *codepoints += count;
1712  *codeunits += count + extra;
1713}
1714
1715ssize_t mb_utf_index_to_bytes(const char *s, size_t len, size_t index, bool use_utf16_units)
1716  FUNC_ATTR_PURE FUNC_ATTR_NONNULL_ALL
1717{
1718  size_t count = 0;
1719  size_t clen;
1720  if (index == 0) {
1721    return 0;
1722  }
1723  for (size_t i = 0; i < len; i += clen) {
1724    clen = (size_t)utf_ptr2len_len(s + i, (int)(len - i));
1725    // NB: gets the byte value of invalid sequence bytes.
1726    // we only care whether the char fits in the BMP or not
1727    int c = (clen > 1) ? utf_ptr2char(s + i) : (uint8_t)s[i];
1728    count++;
1729    if (use_utf16_units && c > 0xFFFF) {
1730      count++;
1731    }
1732    if (count >= index) {
1733      // "clen" can exceed the remaining bytes for an incomplete sequence at the
1734      // end of the string, so clamp to "len".
1735      return (ssize_t)MIN(i + clen, len);
1736    }
1737  }
1738  return -1;
1739}
1740
1741/// Version of strnicmp() that handles multi-byte characters.
1742/// Needed for Big5, Shift-JIS and UTF-8 encoding.  Other DBCS encodings can
1743/// probably use strnicmp(), because there are no ASCII characters in the
1744/// second byte.
1745///
1746/// @return  zero if s1 and s2 are equal (ignoring case), the difference between
1747///          two characters otherwise.
1748int mb_strnicmp(const char *s1, const char *s2, const size_t nn)
1749  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
1750{
1751  return utf_strnicmp(s1, s2, nn, nn);
1752}
1753
1754/// Compare strings case-insensitively
1755///
1756/// @note We need to call mb_stricmp() even when we aren't dealing with
1757///       a multi-byte encoding because mb_stricmp() takes care of all ASCII and
1758///       non-ascii encodings, including characters with umlauts in latin1,
1759///       etc., while STRICMP() only handles the system locale version, which
1760///       often does not handle non-ascii properly.
1761///
1762/// @param[in]  s1  First string to compare, not more then #MAXCOL characters.
1763/// @param[in]  s2  Second string to compare, not more then #MAXCOL characters.
1764///
1765/// @return 0 if strings are equal, <0 if s1 < s2, >0 if s1 > s2.
1766int mb_stricmp(const char *s1, const char *s2)
1767  FUNC_ATTR_PURE FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
1768{
1769  return mb_strnicmp(s1, s2, MAXCOL);
1770}
1771
1772// "g8": show bytes of the UTF-8 char under the cursor.  Doesn't matter what
1773// 'encoding' has been set to.
1774void show_utf8(void)
1775{
1776  // Get the byte length of the char under the cursor, including composing
1777  // characters.
1778  char *line = get_cursor_pos_ptr();
1779  int len = utfc_ptr2len(line);
1780  if (len == 0) {
1781    msg("NUL", 0);
1782    return;
1783  }
1784
1785  size_t rlen = 0;
1786  int clen = 0;
1787  for (int i = 0; i < len; i++) {
1788    if (clen == 0) {
1789      // start of (composing) character, get its length
1790      if (i > 0) {
1791        STRCPY(IObuff + rlen, "+ ");
1792        rlen += 2;
1793      }
1794      clen = utf_ptr2len(line + i);
1795    }
1796    assert(IOSIZE > rlen);
1797    snprintf(IObuff + rlen, IOSIZE - rlen, "%02x ",
1798             (line[i] == NL) ? NUL : (uint8_t)line[i]);  // NUL is stored as NL
1799    clen--;
1800    rlen += strlen(IObuff + rlen);
1801    if (rlen > IOSIZE - 20) {
1802      break;
1803    }
1804  }
1805
1806  msg(IObuff, 0);
1807}
1808
1809/// @return true if boundclass bc always starts a new cluster regardless of what's before
1810/// false negatives are allowed (perf cost, not correctness)
1811static bool always_break(int bc)
1812  FUNC_ATTR_CONST
1813{
1814  return (bc == UTF8PROC_BOUNDCLASS_CONTROL);
1815}
1816
1817/// @return true if bc2 always starts a cluster after bc1
1818/// false negatives are allowed (perf cost, not correctness)
1819static bool always_break_two(int bc1, int bc2)
1820  FUNC_ATTR_CONST
1821{
1822  // don't check for UTF8PROC_BOUNDCLASS_CONTROL for bc2 as it either has been checked by
1823  // "always_break" on first iteration or when it was bc1 in the previous iteration
1824  return ((bc1 != UTF8PROC_BOUNDCLASS_PREPEND && bc2 == UTF8PROC_BOUNDCLASS_OTHER)
1825          || (bc1 >= UTF8PROC_BOUNDCLASS_CR && bc1 <= UTF8PROC_BOUNDCLASS_CONTROL)
1826          || (bc2 == UTF8PROC_BOUNDCLASS_EXTENDED_PICTOGRAPHIC
1827              && (bc1 == UTF8PROC_BOUNDCLASS_OTHER
1828                  || bc1 == UTF8PROC_BOUNDCLASS_EXTENDED_PICTOGRAPHIC)));
1829}
1830
1831/// Return offset from "p" to the start of a character, including composing characters.
1832/// "base" must be the start of the string, which must be NUL terminated.
1833/// If "p" points to the NUL at the end of the string return 0.
1834/// Returns 0 when already at the first byte of a character.
1835int utf_head_off(const char *base_in, const char *p_in)
1836  FUNC_ATTR_PURE FUNC_ATTR_NONNULL_ARG(2)
1837{
1838  if ((uint8_t)(*p_in) < 0x80) {              // be quick for ASCII
1839    return 0;
1840  }
1841
1842  const uint8_t *base = (uint8_t *)base_in;
1843  const uint8_t *p = (uint8_t *)p_in;
1844
1845  const uint8_t *start = p;
1846
1847  // move start to the first byte of this codepoint
1848  // might stop on a continuation byte if overlong, handled by utf_ptr2CharInfo_impl
1849  while (start > base && (*start & 0xc0) == 0x80 && (p - start) < 6) {
1850    start--;
1851  }
1852
1853  const uint8_t last_len = utf8len_tab[*start];
1854  int32_t cur_code = utf_ptr2CharInfo_impl(start, (uintptr_t)last_len);
1855  if (cur_code < 0 || p - start >= last_len) {
1856    return 0;  // p must be part of an illegal sequence
1857  }
1858  const uint8_t * const safe_end = start + last_len;
1859
1860  int cur_bc = utf8proc_get_property(cur_code)->boundclass;
1861  if (always_break(cur_bc) || start == base) {
1862    return (int)(p - start);
1863  }
1864
1865  // backtrack to find the start of a cluster. we might go too far, checked in the next loop
1866  const uint8_t *cur_pos = start;
1867  const uint8_t *const p_start = start;
1868
1869  while (true) {
1870    if (start[-1] == NUL) {
1871      break;
1872    }
1873
1874    start--;
1875    if (*start < 0x80) {  // stop on ascii, we are done
1876      break;
1877    }
1878
1879    while (start > base && (*start & 0xc0) == 0x80 && (cur_pos - start) < 6) {
1880      start--;
1881    }
1882
1883    int prev_len = utf8len_tab[*start];
1884    int32_t prev_code = utf_ptr2CharInfo_impl(start, (uintptr_t)prev_len);
1885    if (prev_code < 0 || prev_len < cur_pos - start) {
1886      start = cur_pos;  // start at valid sequence after invalid bytes
1887      break;
1888    }
1889
1890    int prev_bc = utf8proc_get_property(prev_code)->boundclass;
1891    if (always_break_two(prev_bc, cur_bc) && !arabic_combine(prev_code, cur_code)) {
1892      start = cur_pos;  // prev_code cannot be a part of this cluster
1893      break;
1894    } else if (start == base) {
1895      break;
1896    }
1897    cur_pos = start;
1898    cur_bc = prev_bc;
1899    cur_code = prev_code;
1900  }
1901
1902  // hot path: we are already on the first codepoint of a sequence
1903  if (start == p_start && last_len > p - start) {
1904    return (int)(p - start);
1905  }
1906
1907  const uint8_t *q = start;
1908  while (q < p) {
1909    // don't need to find end of cluster. once we reached the codepoint of p, we are done
1910    int len = utfc_ptr2len_len((const char *)q, (int)(safe_end - q));
1911
1912    if (q + len > p) {
1913      return (int)(p - q);
1914    }
1915
1916    q += len;
1917  }
1918
1919  return 0;
1920}
1921
1922ClusterInfo utf_ClusterInfo_impl(StrCharInfo cur)
1923{
1924  int cells = basechar_cells_impl(cur.chr);
1925  int32_t prev_code = cur.chr.value;
1926  uint8_t *next = (uint8_t *)(cur.ptr + cur.chr.len);
1927  GraphemeState state = GRAPHEME_STATE_INIT;
1928  assert(*next >= 0x80);
1929
1930  bool check_emoji = cells == 1 && p_emoji
1931                     && prop_is_emojilike(utf8proc_get_property(cur.chr.value));
1932
1933  while (true) {
1934    uint8_t const next_len = utf8len_tab[*next];
1935    int32_t const next_code = utf_ptr2CharInfo_impl(next, (uintptr_t)next_len);
1936    if (!utf_iscomposing(prev_code, next_code, &state)) {
1937      return (ClusterInfo){
1938        .next = (StrCharInfo){
1939          .ptr = (char *)next,
1940          .chr = (CharInfo){ .value = next_code, .len = (next_code < 0 ? 1 : next_len) },
1941        },
1942        .cells = cells,
1943      };
1944    }
1945
1946    if (check_emoji) {
1947      if (next_code == 0xFE0F) {
1948        cells = 2;
1949      }
1950      check_emoji = false;
1951    }
1952
1953    if (cells == 1) {
1954      if (utf8proc_get_property(next_code)->boundclass == UTF8PROC_BOUNDCLASS_SPACINGMARK
1955          || (next_code & ~1) == 0xFF9E) {  // halfwidth katakana voiced sound marks
1956        cells = 2;
1957      }
1958    }
1959
1960    prev_code = next_code;
1961    next += next_len;
1962    if (EXPECT(*next < 0x80U, true)) {
1963      return (ClusterInfo){
1964        .next = (StrCharInfo){
1965          .ptr = (char *)next,
1966          .chr = (CharInfo){ .value = *next, .len = 1 },
1967        },
1968        .cells = cells,
1969      };
1970    }
1971  }
1972}
1973
1974// Whether space is NOT allowed before/after 'c'.
1975bool utf_eat_space(int cc)
1976  FUNC_ATTR_CONST FUNC_ATTR_WARN_UNUSED_RESULT
1977{
1978  return (cc >= 0x2000 && cc <= 0x206F)   // General punctuations
1979         || (cc >= 0x2e00 && cc <= 0x2e7f)   // Supplemental punctuations
1980         || (cc >= 0x3000 && cc <= 0x303f)   // CJK symbols and punctuations
1981         || (cc >= 0xff01 && cc <= 0xff0f)   // Full width ASCII punctuations
1982         || (cc >= 0xff1a && cc <= 0xff20)   // ..
1983         || (cc >= 0xff3b && cc <= 0xff40)   // ..
1984         || (cc >= 0xff5b && cc <= 0xff65);  // ..
1985}
1986
1987// Whether line break is allowed before "cc".
1988bool utf_allow_break_before(int cc)
1989  FUNC_ATTR_CONST FUNC_ATTR_WARN_UNUSED_RESULT
1990{
1991  static const int BOL_prohibition_punct[] = {
1992    '!',
1993    '%',
1994    ')',
1995    ',',
1996    ':',
1997    ';',
1998    '>',
1999    '?',
2000    ']',
2001    '}',
2002    0x2019,  // ’ right single quotation mark
2003    0x201d,  // ” right double quotation mark
2004    0x2020,  // † dagger
2005    0x2021,  // ‡ double dagger
2006    0x2026,  // … horizontal ellipsis
2007    0x2030,  // ‰ per mille sign
2008    0x2031,  // ‱ per the thousand sign
2009    0x203c,  // ‼ double exclamation mark
2010    0x2047,  // ⁇ double question mark
2011    0x2048,  // ⁈ question exclamation mark
2012    0x2049,  // ⁉ exclamation question mark
2013    0x2103,  // ℃ degree celsius
2014    0x2109,  // ℉ degree fahrenheit
2015    0x3001,  // 、 ideographic comma
2016    0x3002,  // 。 ideographic full stop
2017    0x3009,  // 〉 right angle bracket
2018    0x300b,  // 》 right double angle bracket
2019    0x300d,  // 」 right corner bracket
2020    0x300f,  // 』 right white corner bracket
2021    0x3011,  // 】 right black lenticular bracket
2022    0x3015,  // 〕 right tortoise shell bracket
2023    0x3017,  // 〗 right white lenticular bracket
2024    0x3019,  // 〙 right white tortoise shell bracket
2025    0x301b,  // 〛 right white square bracket
2026    0xff01,  // ! fullwidth exclamation mark
2027    0xff09,  // ) fullwidth right parenthesis
2028    0xff0c,  // , fullwidth comma
2029    0xff0e,  // . fullwidth full stop
2030    0xff1a,  // : fullwidth colon
2031    0xff1b,  // ; fullwidth semicolon
2032    0xff1f,  // ? fullwidth question mark
2033    0xff3d,  // ] fullwidth right square bracket
2034    0xff5d,  // } fullwidth right curly bracket
2035  };
2036
2037  int first = 0;
2038  int last = ARRAY_SIZE(BOL_prohibition_punct) - 1;
2039
2040  while (first < last) {
2041    const int mid = (first + last) / 2;
2042
2043    if (cc == BOL_prohibition_punct[mid]) {
2044      return false;
2045    } else if (cc > BOL_prohibition_punct[mid]) {
2046      first = mid + 1;
2047    } else {
2048      last = mid - 1;
2049    }
2050  }
2051
2052  return cc != BOL_prohibition_punct[first];
2053}
2054
2055// Whether line break is allowed after "cc".
2056bool utf_allow_break_after(int cc)
2057  FUNC_ATTR_CONST FUNC_ATTR_WARN_UNUSED_RESULT
2058{
2059  static const int EOL_prohibition_punct[] = {
2060    '(',
2061    '<',
2062    '[',
2063    '`',
2064    '{',
2065    // 0x2014,  // — em dash
2066    0x2018,     // ‘ left single quotation mark
2067    0x201c,     // “ left double quotation mark
2068    // 0x2053,  // ~ swung dash
2069    0x3008,     // 〈 left angle bracket
2070    0x300a,     // 《 left double angle bracket
2071    0x300c,     // 「 left corner bracket
2072    0x300e,     // 『 left white corner bracket
2073    0x3010,     // 【 left black lenticular bracket
2074    0x3014,     // 〔 left tortoise shell bracket
2075    0x3016,     // 〖 left white lenticular bracket
2076    0x3018,     // 〘 left white tortoise shell bracket
2077    0x301a,     // 〚 left white square bracket
2078    0xff08,     // ( fullwidth left parenthesis
2079    0xff3b,     // [ fullwidth left square bracket
2080    0xff5b,     // { fullwidth left curly bracket
2081  };
2082
2083  int first = 0;
2084  int last = ARRAY_SIZE(EOL_prohibition_punct) - 1;
2085
2086  while (first < last) {
2087    const int mid = (first + last)/2;
2088
2089    if (cc == EOL_prohibition_punct[mid]) {
2090      return false;
2091    } else if (cc > EOL_prohibition_punct[mid]) {
2092      first = mid + 1;
2093    } else {
2094      last = mid - 1;
2095    }
2096  }
2097
2098  return cc != EOL_prohibition_punct[first];
2099}
2100
2101// Whether line break is allowed between "cc" and "ncc".
2102bool utf_allow_break(int cc, int ncc)
2103  FUNC_ATTR_CONST FUNC_ATTR_WARN_UNUSED_RESULT
2104{
2105  // don't break between two-letter punctuations
2106  if (cc == ncc
2107      && (cc == 0x2014         // em dash
2108          || cc == 0x2026)) {  // horizontal ellipsis
2109    return false;
2110  }
2111  return utf_allow_break_after(cc) && utf_allow_break_before(ncc);
2112}
2113
2114/// Copy a character, advancing the pointers
2115///
2116/// @param[in,out]  fp  Source of the character to copy.
2117/// @param[in,out]  tp  Destination to copy to.
2118void mb_copy_char(const char **const fp, char **const tp)
2119  FUNC_ATTR_NONNULL_ALL
2120{
2121  const size_t l = (size_t)utfc_ptr2len(*fp);
2122
2123  memmove(*tp, *fp, l);
2124  *tp += l;
2125  *fp += l;
2126}
2127
2128/// Return the offset from "p" to the first byte of a character.  When "p" is
2129/// at the start of a character 0 is returned, otherwise the offset to the next
2130/// character.  Can start anywhere in a stream of bytes.
2131int mb_off_next(const char *base, const char *p)
2132  FUNC_ATTR_PURE FUNC_ATTR_NONNULL_ARG(2)
2133{
2134  int head_off = utf_head_off(base, p);
2135
2136  if (head_off == 0) {
2137    return 0;
2138  }
2139
2140  return utfc_ptr2len(p - head_off) - head_off;
2141}
2142
2143/// Returns the offset in bytes from "p_in" to the first and one-past-end bytes
2144/// of the codepoint it points to.
2145/// "p_in" can point anywhere in a stream of bytes.
2146/// "p_len" limits number of bytes after "p_in".
2147/// Note: Counts individual codepoints of composed characters separately.
2148CharBoundsOff utf_cp_bounds_len(char const *base, char const *p_in, int p_len)
2149  FUNC_ATTR_PURE FUNC_ATTR_NONNULL_ALL
2150{
2151  assert(base <= p_in && p_len > 0);
2152  uint8_t const *const b = (uint8_t *)base;
2153  uint8_t const *const p = (uint8_t *)p_in;
2154  if (*p < 0x80U) {  // be quick for ASCII
2155    return (CharBoundsOff){ 0, 1 };
2156  }
2157
2158  int const max_first_off = -MIN((int)(p - b), MB_MAXCHAR - 1);
2159  int first_off = 0;
2160  for (; utf_is_trail_byte(p[first_off]); first_off--) {
2161    if (first_off == max_first_off) {  // failed to find first byte
2162      return (CharBoundsOff){ 0, 1 };
2163    }
2164  }
2165
2166  int const max_end_off = utf8len_tab[p[first_off]] + first_off;
2167  if (max_end_off <= 0 || max_end_off > p_len) {  // illegal or incomplete sequence
2168    return (CharBoundsOff){ 0, 1 };
2169  }
2170
2171  for (int end_off = 1; end_off < max_end_off; end_off++) {
2172    if (!utf_is_trail_byte(p[end_off])) {  // not enough trail bytes
2173      return (CharBoundsOff){ 0, 1 };
2174    }
2175  }
2176
2177  return (CharBoundsOff){ .begin_off = (int8_t)-first_off, .end_off = (int8_t)max_end_off };
2178}
2179
2180/// Returns the offset in bytes from "p_in" to the first and one-past-end bytes
2181/// of the codepoint it points to.
2182/// "p_in" can point anywhere in a stream of bytes.
2183/// Stream must be NUL-terminated.
2184/// Note: Counts individual codepoints of composed characters separately.
2185CharBoundsOff utf_cp_bounds(char const *base, char const *p_in)
2186  FUNC_ATTR_PURE FUNC_ATTR_NONNULL_ALL
2187{
2188  return utf_cp_bounds_len(base, p_in, INT_MAX);
2189}
2190
2191// Find the next illegal byte sequence.
2192void utf_find_illegal(void)
2193{
2194  pos_T pos = curwin->w_cursor;
2195  vimconv_T vimconv;
2196  char *tofree = NULL;
2197
2198  vimconv.vc_type = CONV_NONE;
2199  if (enc_canon_props(curbuf->b_p_fenc) & ENC_8BIT) {
2200    // 'encoding' is "utf-8" but we are editing a 8-bit encoded file,
2201    // possibly a utf-8 file with illegal bytes.  Setup for conversion
2202    // from utf-8 to 'fileencoding'.
2203    convert_setup(&vimconv, p_enc, curbuf->b_p_fenc);
2204  }
2205
2206  curwin->w_cursor.coladd = 0;
2207  while (true) {
2208    char *p = get_cursor_pos_ptr();
2209    if (vimconv.vc_type != CONV_NONE) {
2210      xfree(tofree);
2211      tofree = string_convert(&vimconv, p, NULL);
2212      if (tofree == NULL) {
2213        break;
2214      }
2215      p = tofree;
2216    }
2217
2218    while (*p != NUL) {
2219      // Illegal means that there are not enough trail bytes (checked by
2220      // utf_ptr2len()) or too many of them (overlong sequence).
2221      int len = utf_ptr2len(p);
2222      if ((uint8_t)(*p) >= 0x80 && (len == 1 || utf_char2len(utf_ptr2char(p)) != len)) {
2223        if (vimconv.vc_type == CONV_NONE) {
2224          curwin->w_cursor.col += (colnr_T)(p - get_cursor_pos_ptr());
2225        } else {
2226          int l;
2227
2228          len = (int)(p - tofree);
2229          for (p = get_cursor_pos_ptr(); *p != NUL && len-- > 0; p += l) {
2230            l = utf_ptr2len(p);
2231            curwin->w_cursor.col += l;
2232          }
2233        }
2234        curwin->w_set_curswant = true;
2235        goto theend;
2236      }
2237      p += len;
2238    }
2239    if (curwin->w_cursor.lnum == curbuf->b_ml.ml_line_count) {
2240      break;
2241    }
2242    curwin->w_cursor.lnum++;
2243    curwin->w_cursor.col = 0;
2244  }
2245
2246  // didn't find it: don't move and beep
2247  curwin->w_cursor = pos;
2248  beep_flush();
2249
2250theend:
2251  xfree(tofree);
2252  convert_setup(&vimconv, NULL, NULL);
2253}
2254
2255/// @return  true if string "s" is a valid utf-8 string.
2256/// When "end" is NULL stop at the first NUL.  Otherwise stop at "end".
2257bool utf_valid_string(const char *s, const char *end)
2258  FUNC_ATTR_PURE FUNC_ATTR_NONNULL_ARG(1)
2259{
2260  const uint8_t *p = (uint8_t *)s;
2261
2262  while (end == NULL ? *p != NUL : p < (uint8_t *)end) {
2263    int l = utf8len_tab_zero[*p];
2264    if (l == 0) {
2265      return false;  // invalid lead byte
2266    }
2267    if (end != NULL && p + l > (uint8_t *)end) {
2268      return false;  // incomplete byte sequence
2269    }
2270    p++;
2271    while (--l > 0) {
2272      if ((*p++ & 0xc0) != 0x80) {
2273        return false;  // invalid trail byte
2274      }
2275    }
2276  }
2277  return true;
2278}
2279
2280// If the cursor moves on an trail byte, set the cursor on the lead byte.
2281// Thus it moves left if necessary.
2282void mb_adjust_cursor(void)
2283{
2284  mark_mb_adjustpos(curbuf, &curwin->w_cursor);
2285}
2286
2287/// Checks and adjusts cursor column. Not mode-dependent.
2288/// @see check_cursor_col
2289///
2290/// @param  win_  Places cursor on a valid column for this window.
2291void mb_check_adjust_col(void *win_)
2292{
2293  win_T *win = (win_T *)win_;
2294  colnr_T oldcol = win->w_cursor.col;
2295
2296  // Column 0 is always valid.
2297  if (oldcol != 0) {
2298    char *p = ml_get_buf(win->w_buffer, win->w_cursor.lnum);
2299    colnr_T len = (colnr_T)strlen(p);
2300
2301    // Empty line or invalid column?
2302    if (len == 0 || oldcol < 0) {
2303      win->w_cursor.col = 0;
2304    } else {
2305      // Cursor column too big for line?
2306      if (oldcol > len) {
2307        win->w_cursor.col = len - 1;
2308      }
2309      // Move the cursor to the head byte.
2310      win->w_cursor.col -= utf_head_off(p, p + win->w_cursor.col);
2311    }
2312
2313    // Reset `coladd` when the cursor would be on the right half of a
2314    // double-wide character.
2315    if (win->w_cursor.coladd == 1 && p[win->w_cursor.col] != TAB
2316        && vim_isprintc(utf_ptr2char(p + win->w_cursor.col))
2317        && ptr2cells(p + win->w_cursor.col) > 1) {
2318      win->w_cursor.coladd = 0;
2319    }
2320  }
2321}
2322
2323/// @param line  start of the string
2324///
2325/// @return      a pointer to the character before "*p", if there is one.
2326char *mb_prevptr(char *line, char *p)
2327  FUNC_ATTR_PURE
2328{
2329  if (p > line) {
2330    MB_PTR_BACK(line, p);
2331  }
2332  return p;
2333}
2334
2335/// Return the character length of "str".  Each multi-byte character (with
2336/// following composing characters) counts as one.
2337int mb_charlen(const char *str)
2338  FUNC_ATTR_PURE
2339{
2340  const char *p = str;
2341  int count;
2342
2343  if (p == NULL) {
2344    return 0;
2345  }
2346
2347  for (count = 0; *p != NUL; count++) {
2348    p += utfc_ptr2len(p);
2349  }
2350
2351  return count;
2352}
2353
2354/// Like mb_charlen() but for a string with specified length.
2355int mb_charlen_len(const char *str, int len)
2356  FUNC_ATTR_PURE FUNC_ATTR_NONNULL_ALL
2357{
2358  const char *p = str;
2359  int count;
2360
2361  for (count = 0; *p != NUL && p < str + len; count++) {
2362    p += utfc_ptr2len(p);
2363  }
2364
2365  return count;
2366}
2367
2368/// Try to unescape a multibyte character
2369///
2370/// Used for the rhs and lhs of the mappings.
2371///
2372/// @param[in,out]  pp  String to unescape. Is advanced to just after the bytes
2373///                     that form a multibyte character.
2374///
2375/// @return Unescaped string if it is a multibyte character, NULL if no
2376///         multibyte character was found. Returns a static buffer, always one
2377///         and the same.
2378const char *mb_unescape(const char **const pp)
2379  FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
2380{
2381  static char buf[6];
2382  size_t buf_idx = 0;
2383  uint8_t *str = (uint8_t *)(*pp);
2384
2385  // Must translate K_SPECIAL KS_SPECIAL KE_FILLER to K_SPECIAL.
2386  // Maximum length of a utf-8 character is 4 bytes.
2387  for (size_t str_idx = 0; str[str_idx] != NUL && buf_idx < 4; str_idx++) {
2388    if (str[str_idx] == K_SPECIAL
2389        && str[str_idx + 1] == KS_SPECIAL
2390        && str[str_idx + 2] == KE_FILLER) {
2391      buf[buf_idx++] = (char)K_SPECIAL;
2392      str_idx += 2;
2393    } else if (str[str_idx] == K_SPECIAL) {
2394      break;  // A special key can't be a multibyte char.
2395    } else {
2396      buf[buf_idx++] = (char)str[str_idx];
2397    }
2398    buf[buf_idx] = NUL;
2399
2400    // Return a multi-byte character if it's found.  An illegal sequence
2401    // will result in a 1 here.
2402    if (utf_ptr2len(buf) > 1) {
2403      *pp = (const char *)str + str_idx + 1;
2404      return buf;
2405    }
2406
2407    // Bail out quickly for ASCII.
2408    if ((uint8_t)buf[0] < 128) {
2409      break;
2410    }
2411  }
2412  return NULL;
2413}
2414
2415/// Skip the Vim specific head of a 'encoding' name.
2416char *enc_skip(char *p)
2417  FUNC_ATTR_PURE FUNC_ATTR_NONNULL_ALL
2418{
2419  if (strncmp(p, "2byte-", 6) == 0) {
2420    return p + 6;
2421  }
2422  if (strncmp(p, "8bit-", 5) == 0) {
2423    return p + 5;
2424  }
2425  return p;
2426}
2427
2428/// Find the canonical name for encoding "enc".
2429/// When the name isn't recognized, returns "enc" itself, but with all lower
2430/// case characters and '_' replaced with '-'.
2431///
2432/// @return  an allocated string.
2433char *enc_canonize(char *enc)
2434  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET
2435{
2436  if (strcmp(enc, "default") == 0) {
2437    // Use the default encoding as found by set_init_1().
2438    return xstrdup(fenc_default);
2439  }
2440
2441  // copy "enc" to allocated memory, with room for two '-'
2442  char *r = xmalloc(strlen(enc) + 3);
2443  // Make it all lower case and replace '_' with '-'.
2444  char *p = r;
2445  for (char *s = enc; *s != NUL; s++) {
2446    if (*s == '_') {
2447      *p++ = '-';
2448    } else {
2449      *p++ = (char)TOLOWER_ASC(*s);
2450    }
2451  }
2452  *p = NUL;
2453
2454  // Skip "2byte-" and "8bit-".
2455  p = enc_skip(r);
2456
2457  // Change "microsoft-cp" to "cp".  Used in some spell files.
2458  if (strncmp(p, "microsoft-cp", 12) == 0) {
2459    STRMOVE(p, p + 10);
2460  }
2461
2462  // "iso8859" -> "iso-8859"
2463  if (strncmp(p, "iso8859", 7) == 0) {
2464    STRMOVE(p + 4, p + 3);
2465    p[3] = '-';
2466  }
2467
2468  // "iso-8859n" -> "iso-8859-n"
2469  if (strncmp(p, "iso-8859", 8) == 0 && isdigit(p[8])) {
2470    STRMOVE(p + 9, p + 8);
2471    p[8] = '-';
2472  }
2473
2474  // "latin-N" -> "latinN"
2475  if (strncmp(p, "latin-", 6) == 0) {
2476    STRMOVE(p + 5, p + 6);
2477  }
2478
2479  int i;
2480  if (enc_canon_search(p) >= 0) {
2481    // canonical name can be used unmodified
2482    if (p != r) {
2483      STRMOVE(r, p);
2484    }
2485  } else if ((i = enc_alias_search(p)) >= 0) {
2486    // alias recognized, get canonical name
2487    xfree(r);
2488    r = xstrdup(enc_canon_table[i].name);
2489  }
2490  return r;
2491}
2492
2493/// Search for an encoding alias of "name".
2494/// Returns -1 when not found.
2495static int enc_alias_search(const char *name)
2496  FUNC_ATTR_PURE FUNC_ATTR_NONNULL_ALL
2497{
2498  for (int i = 0; enc_alias_table[i].name != NULL; i++) {
2499    if (strcmp(name, enc_alias_table[i].name) == 0) {
2500      return enc_alias_table[i].canon;
2501    }
2502  }
2503  return -1;
2504}
2505
2506#ifdef HAVE_LANGINFO_H
2507# include <langinfo.h>
2508#endif
2509
2510// Get the canonicalized encoding of the current locale.
2511// Returns an allocated string when successful, NULL when not.
2512char *enc_locale(void)
2513{
2514  int i;
2515  char buf[50];
2516
2517  const char *s;
2518
2519#ifdef HAVE_NL_LANGINFO_CODESET
2520  if (!(s = nl_langinfo(CODESET)) || *s == NUL)
2521#endif
2522  {
2523    if (!(s = setlocale(LC_CTYPE, NULL)) || *s == NUL) {
2524      if ((s = os_getenv_noalloc("LC_ALL"))) {
2525        if ((s = os_getenv_noalloc("LC_CTYPE"))) {
2526          s = os_getenv_noalloc("LANG");
2527        }
2528      }
2529    }
2530  }
2531
2532  if (!s) {
2533    return NULL;
2534  }
2535
2536  // The most generic locale format is:
2537  // language[_territory][.codeset][@modifier][+special][,[sponsor][_revision]]
2538  // If there is a '.' remove the part before it.
2539  // if there is something after the codeset, remove it.
2540  // Make the name lowercase and replace '_' with '-'.
2541  // Exception: "ja_JP.EUC" == "euc-jp", "zh_CN.EUC" = "euc-cn",
2542  // "ko_KR.EUC" == "euc-kr"
2543  const char *p = vim_strchr(s, '.');
2544  if (p != NULL) {
2545    if (p > s + 2 && !STRNICMP(p + 1, "EUC", 3)
2546        && !isalnum((uint8_t)p[4]) && p[4] != '-' && p[-3] == '_') {
2547      // Copy "XY.EUC" to "euc-XY" to buf[10].
2548      memmove(buf, "euc-", 4);
2549      buf[4] = (char)(ASCII_ISALNUM(p[-2]) ? TOLOWER_ASC(p[-2]) : 0);
2550      buf[5] = (char)(ASCII_ISALNUM(p[-1]) ? TOLOWER_ASC(p[-1]) : 0);
2551      buf[6] = NUL;
2552    } else {
2553      s = p + 1;
2554      goto enc_locale_copy_enc;
2555    }
2556  } else {
2557enc_locale_copy_enc:
2558    for (i = 0; i < (int)sizeof(buf) - 1 && s[i] != NUL; i++) {
2559      if (s[i] == '_' || s[i] == '-') {
2560        buf[i] = '-';
2561      } else if (ASCII_ISALNUM((uint8_t)s[i])) {
2562        buf[i] = (char)TOLOWER_ASC(s[i]);
2563      } else {
2564        break;
2565      }
2566    }
2567    buf[i] = NUL;
2568  }
2569
2570  return enc_canonize(buf);
2571}
2572
2573// Call iconv_open() with a check if iconv() works properly (there are broken
2574// versions).
2575// Returns (void *)-1 if failed.
2576// (should return iconv_t, but that causes problems with prototypes).
2577void *my_iconv_open(char *to, char *from)
2578{
2579#define ICONV_TESTLEN 400
2580  char tobuf[ICONV_TESTLEN];
2581  static WorkingStatus iconv_working = kUnknown;
2582
2583  if (iconv_working == kBroken) {
2584    return (void *)-1;          // detected a broken iconv() previously
2585  }
2586  iconv_t fd = iconv_open(enc_skip(to), enc_skip(from));
2587
2588  if (fd != (iconv_t)-1 && iconv_working == kUnknown) {
2589    // Do a dummy iconv() call to check if it actually works.  There is a
2590    // version of iconv() on Linux that is broken.  We can't ignore it,
2591    // because it's wide-spread.  The symptoms are that after outputting
2592    // the initial shift state the "to" pointer is NULL and conversion
2593    // stops for no apparent reason after about 8160 characters.
2594    char *p = tobuf;
2595    size_t tolen = ICONV_TESTLEN;
2596    iconv(fd, NULL, NULL, &p, &tolen);
2597    if (p == NULL) {
2598      iconv_working = kBroken;
2599      iconv_close(fd);
2600      fd = (iconv_t)-1;
2601    } else {
2602      iconv_working = kWorking;
2603    }
2604  }
2605
2606  return (void *)fd;
2607}
2608
2609// Convert the string "str[slen]" with iconv().
2610// If "unconvlenp" is not NULL handle the string ending in an incomplete
2611// sequence and set "*unconvlenp" to the length of it.
2612// Returns the converted string in allocated memory.  NULL for an error.
2613// If resultlenp is not NULL, sets it to the result length in bytes.
2614static char *iconv_string(const vimconv_T *const vcp, const char *str, size_t slen,
2615                          size_t *unconvlenp, size_t *resultlenp)
2616  FUNC_ATTR_NONNULL_ARG(1)
2617{
2618  char *to;
2619  size_t len = 0;
2620  size_t done = 0;
2621  char *result = NULL;
2622
2623  const char *from = str;
2624  size_t fromlen = slen;
2625  while (true) {
2626    if (len == 0 || ICONV_ERRNO == ICONV_E2BIG) {
2627      // Allocate enough room for most conversions.  When re-allocating
2628      // increase the buffer size.
2629      len = len + fromlen * 2 + 40;
2630      char *p = xmalloc(len);
2631      if (done > 0) {
2632        memmove(p, result, done);
2633      }
2634      xfree(result);
2635      result = p;
2636    }
2637
2638    to = result + done;
2639    size_t tolen = len - done - 2;
2640    // Avoid a warning for systems with a wrong iconv() prototype by
2641    // casting the second argument to void *.
2642    if (iconv(vcp->vc_fd, (void *)&from, &fromlen, &to, &tolen) != SIZE_MAX) {
2643      // Finished, append a NUL.
2644      *to = NUL;
2645      break;
2646    }
2647
2648    // Check both ICONV_EINVAL and EINVAL, because the dynamically loaded
2649    // iconv library may use one of them.
2650    if (!vcp->vc_fail && unconvlenp != NULL
2651        && (ICONV_ERRNO == ICONV_EINVAL || ICONV_ERRNO == EINVAL)) {
2652      // Handle an incomplete sequence at the end.
2653      *to = NUL;
2654      *unconvlenp = fromlen;
2655      break;
2656    } else if (!vcp->vc_fail
2657               && (ICONV_ERRNO == ICONV_EILSEQ || ICONV_ERRNO == EILSEQ
2658                   || ICONV_ERRNO == ICONV_EINVAL || ICONV_ERRNO == EINVAL)) {
2659      // Check both ICONV_EILSEQ and EILSEQ, because the dynamically loaded
2660      // iconv library may use one of them.
2661
2662      // Can't convert: insert a '?' and skip a character.  This assumes
2663      // conversion from 'encoding' to something else.  In other
2664      // situations we don't know what to skip anyway.
2665      *to++ = '?';
2666      if (utf_ptr2cells(from) > 1) {
2667        *to++ = '?';
2668      }
2669      int l = utfc_ptr2len_len(from, (int)fromlen);
2670      from += l;
2671      fromlen -= (size_t)l;
2672    } else if (ICONV_ERRNO != ICONV_E2BIG) {
2673      // conversion failed
2674      XFREE_CLEAR(result);
2675      break;
2676    }
2677    // Not enough room or skipping illegal sequence.
2678    done = (size_t)(to - result);
2679  }
2680
2681  if (resultlenp != NULL && result != NULL) {
2682    *resultlenp = (size_t)(to - result);
2683  }
2684  return result;
2685}
2686
2687/// iconv() function
2688void f_iconv(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
2689{
2690  vimconv_T vimconv;
2691
2692  rettv->v_type = VAR_STRING;
2693  rettv->vval.v_string = NULL;
2694
2695  const char *const str = tv_get_string(&argvars[0]);
2696  char buf1[NUMBUFLEN];
2697  char *const from = enc_canonize(enc_skip((char *)tv_get_string_buf(&argvars[1], buf1)));
2698  char buf2[NUMBUFLEN];
2699  char *const to = enc_canonize(enc_skip((char *)tv_get_string_buf(&argvars[2], buf2)));
2700  vimconv.vc_type = CONV_NONE;
2701  convert_setup(&vimconv, from, to);
2702
2703  // If the encodings are equal, no conversion needed.
2704  if (vimconv.vc_type == CONV_NONE) {
2705    rettv->vval.v_string = xstrdup(str);
2706  } else {
2707    rettv->vval.v_string = string_convert(&vimconv, (char *)str, NULL);
2708  }
2709
2710  convert_setup(&vimconv, NULL, NULL);
2711  xfree(from);
2712  xfree(to);
2713}
2714
2715/// Setup "vcp" for conversion from "from" to "to".
2716/// The names must have been made canonical with enc_canonize().
2717/// vcp->vc_type must have been initialized to CONV_NONE.
2718/// Note: cannot be used for conversion from/to ucs-2 and ucs-4 (will use utf-8
2719/// instead).
2720/// Afterwards invoke with "from" and "to" equal to NULL to cleanup.
2721///
2722/// @return  FAIL when conversion is not supported, OK otherwise.
2723int convert_setup(vimconv_T *vcp, char *from, char *to)
2724  FUNC_ATTR_NONNULL_ARG(1)
2725{
2726  return convert_setup_ext(vcp, from, true, to, true);
2727}
2728
2729/// As convert_setup(), but only when from_unicode_is_utf8 is true will all
2730/// "from" unicode charsets be considered utf-8.  Same for "to".
2731int convert_setup_ext(vimconv_T *vcp, char *from, bool from_unicode_is_utf8, char *to,
2732                      bool to_unicode_is_utf8)
2733  FUNC_ATTR_NONNULL_ARG(1)
2734{
2735  int from_is_utf8;
2736  int to_is_utf8;
2737
2738  // Reset to no conversion.
2739  if (vcp->vc_type == CONV_ICONV && vcp->vc_fd != (iconv_t)-1) {
2740    iconv_close(vcp->vc_fd);
2741  }
2742  *vcp = (vimconv_T)MBYTE_NONE_CONV;
2743
2744  // No conversion when one of the names is empty or they are equal.
2745  if (from == NULL || *from == NUL || to == NULL || *to == NUL
2746      || strcmp(from, to) == 0) {
2747    return OK;
2748  }
2749
2750  int from_prop = enc_canon_props(from);
2751  int to_prop = enc_canon_props(to);
2752  if (from_unicode_is_utf8) {
2753    from_is_utf8 = from_prop & ENC_UNICODE;
2754  } else {
2755    from_is_utf8 = from_prop == ENC_UNICODE;
2756  }
2757  if (to_unicode_is_utf8) {
2758    to_is_utf8 = to_prop & ENC_UNICODE;
2759  } else {
2760    to_is_utf8 = to_prop == ENC_UNICODE;
2761  }
2762
2763  if ((from_prop & ENC_LATIN1) && to_is_utf8) {
2764    // Internal latin1 -> utf-8 conversion.
2765    vcp->vc_type = CONV_TO_UTF8;
2766    vcp->vc_factor = 2;         // up to twice as long
2767  } else if ((from_prop & ENC_LATIN9) && to_is_utf8) {
2768    // Internal latin9 -> utf-8 conversion.
2769    vcp->vc_type = CONV_9_TO_UTF8;
2770    vcp->vc_factor = 3;         // up to three as long (euro sign)
2771  } else if (from_is_utf8 && (to_prop & ENC_LATIN1)) {
2772    // Internal utf-8 -> latin1 conversion.
2773    vcp->vc_type = CONV_TO_LATIN1;
2774  } else if (from_is_utf8 && (to_prop & ENC_LATIN9)) {
2775    // Internal utf-8 -> latin9 conversion.
2776    vcp->vc_type = CONV_TO_LATIN9;
2777  } else {
2778    // Use iconv() for conversion.
2779    vcp->vc_fd = (iconv_t)my_iconv_open(to_is_utf8 ? "utf-8" : to,
2780                                        from_is_utf8 ? "utf-8" : from);
2781    if (vcp->vc_fd != (iconv_t)-1) {
2782      vcp->vc_type = CONV_ICONV;
2783      vcp->vc_factor = 4;       // could be longer too...
2784    }
2785  }
2786  if (vcp->vc_type == CONV_NONE) {
2787    return FAIL;
2788  }
2789
2790  return OK;
2791}
2792
2793/// Convert text "ptr[*lenp]" according to "vcp".
2794/// Returns the result in allocated memory and sets "*lenp".
2795/// When "lenp" is NULL, use NUL terminated strings.
2796/// Illegal chars are often changed to "?", unless vcp->vc_fail is set.
2797/// When something goes wrong, NULL is returned and "*lenp" is unchanged.
2798char *string_convert(const vimconv_T *const vcp, char *ptr, size_t *lenp)
2799{
2800  return string_convert_ext(vcp, ptr, lenp, NULL);
2801}
2802
2803// Like string_convert(), but when "unconvlenp" is not NULL and there are is
2804// an incomplete sequence at the end it is not converted and "*unconvlenp" is
2805// set to the number of remaining bytes.
2806char *string_convert_ext(const vimconv_T *const vcp, char *ptr, size_t *lenp, size_t *unconvlenp)
2807{
2808  uint8_t *retval = NULL;
2809  uint8_t *d;
2810  int c;
2811
2812  size_t len;
2813  if (lenp == NULL) {
2814    len = strlen(ptr);
2815  } else {
2816    len = *lenp;
2817  }
2818  if (len == 0) {
2819    return xstrdup("");
2820  }
2821
2822  switch (vcp->vc_type) {
2823  case CONV_TO_UTF8:            // latin1 to utf-8 conversion
2824    retval = xmalloc(len * 2 + 1);
2825    d = retval;
2826    for (size_t i = 0; i < len; i++) {
2827      c = (uint8_t)ptr[i];
2828      if (c < 0x80) {
2829        *d++ = (uint8_t)c;
2830      } else {
2831        *d++ = (uint8_t)(0xc0 + (uint8_t)((unsigned)c >> 6));
2832        *d++ = (uint8_t)(0x80 + (c & 0x3f));
2833      }
2834    }
2835    *d = NUL;
2836    if (lenp != NULL) {
2837      *lenp = (size_t)(d - retval);
2838    }
2839    break;
2840
2841  case CONV_9_TO_UTF8:          // latin9 to utf-8 conversion
2842    retval = xmalloc(len * 3 + 1);
2843    d = retval;
2844    for (size_t i = 0; i < len; i++) {
2845      c = (uint8_t)ptr[i];
2846      switch (c) {
2847      case 0xa4:
2848        c = 0x20ac; break;                 // euro
2849      case 0xa6:
2850        c = 0x0160; break;                 // S hat
2851      case 0xa8:
2852        c = 0x0161; break;                 // S -hat
2853      case 0xb4:
2854        c = 0x017d; break;                 // Z hat
2855      case 0xb8:
2856        c = 0x017e; break;                 // Z -hat
2857      case 0xbc:
2858        c = 0x0152; break;                 // OE
2859      case 0xbd:
2860        c = 0x0153; break;                 // oe
2861      case 0xbe:
2862        c = 0x0178; break;                 // Y
2863      }
2864      d += utf_char2bytes(c, (char *)d);
2865    }
2866    *d = NUL;
2867    if (lenp != NULL) {
2868      *lenp = (size_t)(d - retval);
2869    }
2870    break;
2871
2872  case CONV_TO_LATIN1:          // utf-8 to latin1 conversion
2873  case CONV_TO_LATIN9:          // utf-8 to latin9 conversion
2874    retval = xmalloc(len + 1);
2875    d = retval;
2876    for (size_t i = 0; i < len; i++) {
2877      int l = utf_ptr2len_len(ptr + i, (int)(len - i));
2878      if (l == 0) {
2879        *d++ = NUL;
2880      } else if (l == 1) {
2881        uint8_t l_w = utf8len_tab_zero[(uint8_t)ptr[i]];
2882
2883        if (l_w == 0) {
2884          // Illegal utf-8 byte cannot be converted
2885          xfree(retval);
2886          return NULL;
2887        }
2888        if (unconvlenp != NULL && l_w > len - i) {
2889          // Incomplete sequence at the end.
2890          *unconvlenp = len - i;
2891          break;
2892        }
2893        *d++ = (uint8_t)ptr[i];
2894      } else {
2895        c = utf_ptr2char(ptr + i);
2896        if (vcp->vc_type == CONV_TO_LATIN9) {
2897          switch (c) {
2898          case 0x20ac:
2899            c = 0xa4; break;                     // euro
2900          case 0x0160:
2901            c = 0xa6; break;                     // S hat
2902          case 0x0161:
2903            c = 0xa8; break;                     // S -hat
2904          case 0x017d:
2905            c = 0xb4; break;                     // Z hat
2906          case 0x017e:
2907            c = 0xb8; break;                     // Z -hat
2908          case 0x0152:
2909            c = 0xbc; break;                     // OE
2910          case 0x0153:
2911            c = 0xbd; break;                     // oe
2912          case 0x0178:
2913            c = 0xbe; break;                     // Y
2914          case 0xa4:
2915          case 0xa6:
2916          case 0xa8:
2917          case 0xb4:
2918          case 0xb8:
2919          case 0xbc:
2920          case 0xbd:
2921          case 0xbe:
2922            c = 0x100; break;                   // not in latin9
2923          }
2924        }
2925        if (!utf_iscomposing_legacy(c)) {  // skip composing chars
2926          if (c < 0x100) {
2927            *d++ = (uint8_t)c;
2928          } else if (vcp->vc_fail) {
2929            xfree(retval);
2930            return NULL;
2931          } else {
2932            *d++ = 0xbf;
2933            if (utf_char2cells(c) > 1) {
2934              *d++ = '?';
2935            }
2936          }
2937        }
2938        i += (size_t)l - 1;
2939      }
2940    }
2941    *d = NUL;
2942    if (lenp != NULL) {
2943      *lenp = (size_t)(d - retval);
2944    }
2945    break;
2946
2947  case CONV_ICONV:  // conversion with vcp->vc_fd
2948    retval = (uint8_t *)iconv_string(vcp, ptr, len, unconvlenp, lenp);
2949    break;
2950  }
2951
2952  return (char *)retval;
2953}
2954
2955/// Table set by setcellwidths().
2956typedef struct {
2957  int64_t first;
2958  int64_t last;
2959  char width;
2960} cw_interval_T;
2961
2962static cw_interval_T *cw_table = NULL;
2963static size_t cw_table_size = 0;
2964
2965/// Return the value of the cellwidth table for the character `c`.
2966///
2967/// @param c The source character.
2968/// @return 1 or 2 when `c` is in the cellwidth table, 0 if not.
2969static int cw_value(int c)
2970  FUNC_ATTR_PURE
2971{
2972  if (cw_table == NULL) {
2973    return 0;
2974  }
2975
2976  // first quick check for Latin1 etc. characters
2977  if (c < cw_table[0].first) {
2978    return 0;
2979  }
2980
2981  // binary search in table
2982  int bot = 0;
2983  int top = (int)cw_table_size - 1;
2984  while (top >= bot) {
2985    int mid = (bot + top) / 2;
2986    if (cw_table[mid].last < c) {
2987      bot = mid + 1;
2988    } else if (cw_table[mid].first > c) {
2989      top = mid - 1;
2990    } else {
2991      return cw_table[mid].width;
2992    }
2993  }
2994  return 0;
2995}
2996
2997static int tv_nr_compare(const void *a1, const void *a2)
2998  FUNC_ATTR_PURE FUNC_ATTR_NONNULL_ALL
2999{
3000  const listitem_T *const li1 = tv_list_first(*(const list_T **)a1);
3001  const listitem_T *const li2 = tv_list_first(*(const list_T **)a2);
3002  const varnumber_T n1 = TV_LIST_ITEM_TV(li1)->vval.v_number;
3003  const varnumber_T n2 = TV_LIST_ITEM_TV(li2)->vval.v_number;
3004
3005  return n1 == n2 ? 0 : n1 > n2 ? 1 : -1;
3006}
3007
3008/// "setcellwidths()" function
3009void f_setcellwidths(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
3010{
3011  if (argvars[0].v_type != VAR_LIST || argvars[0].vval.v_list == NULL) {
3012    emsg(_(e_listreq));
3013    return;
3014  }
3015
3016  const list_T *const l = argvars[0].vval.v_list;
3017  cw_interval_T *table = NULL;
3018  const size_t table_size = (size_t)tv_list_len(l);
3019  if (table_size == 0) {
3020    // Clearing the table.
3021    goto update;
3022  }
3023
3024  // Note: use list_T instead of listitem_T so that TV_LIST_ITEM_NEXT can be used properly below.
3025  const list_T **ptrs = xmalloc(sizeof(const list_T *) * table_size);
3026
3027  // Check that all entries are a list with three numbers, the range is
3028  // valid and the cell width is valid.
3029  int item = 0;
3030  TV_LIST_ITER_CONST(l, li, {
3031    const typval_T *const li_tv = TV_LIST_ITEM_TV(li);
3032
3033    if (li_tv->v_type != VAR_LIST || li_tv->vval.v_list == NULL) {
3034      semsg(_(e_list_item_nr_is_not_list), item);
3035      xfree((void *)ptrs);
3036      return;
3037    }
3038
3039    const list_T *const li_l = li_tv->vval.v_list;
3040    ptrs[item] = li_l;
3041    const listitem_T *lili = tv_list_first(li_l);
3042    int i;
3043    varnumber_T n1;
3044    for (i = 0; lili != NULL; lili = TV_LIST_ITEM_NEXT(li_l, lili), i++) {
3045      const typval_T *const lili_tv = TV_LIST_ITEM_TV(lili);
3046      if (lili_tv->v_type != VAR_NUMBER) {
3047        break;
3048      }
3049      if (i == 0) {
3050        n1 = lili_tv->vval.v_number;
3051        if (n1 < 0x80) {
3052          emsg(_(e_only_values_of_0x80_and_higher_supported));
3053          xfree((void *)ptrs);
3054          return;
3055        }
3056      } else if (i == 1 && lili_tv->vval.v_number < n1) {
3057        semsg(_(e_list_item_nr_range_invalid), item);
3058        xfree((void *)ptrs);
3059        return;
3060      } else if (i == 2 && (lili_tv->vval.v_number < 1 || lili_tv->vval.v_number > 2)) {
3061        semsg(_(e_list_item_nr_cell_width_invalid), item);
3062        xfree((void *)ptrs);
3063        return;
3064      }
3065    }
3066
3067    if (i != 3) {
3068      semsg(_(e_list_item_nr_does_not_contain_3_numbers), item);
3069      xfree((void *)ptrs);
3070      return;
3071    }
3072
3073    item++;
3074  });
3075
3076  // Sort the list on the first number.
3077  qsort((void *)ptrs, table_size, sizeof(const list_T *), tv_nr_compare);
3078
3079  table = xmalloc(sizeof(cw_interval_T) * table_size);
3080
3081  // Store the items in the new table.
3082  for (item = 0; (size_t)item < table_size; item++) {
3083    const list_T *const li_l = ptrs[item];
3084    const listitem_T *lili = tv_list_first(li_l);
3085    const varnumber_T n1 = TV_LIST_ITEM_TV(lili)->vval.v_number;
3086    if (item > 0 && n1 <= table[item - 1].last) {
3087      semsg(_(e_overlapping_ranges_for_nr), (size_t)n1);
3088      xfree((void *)ptrs);
3089      xfree(table);
3090      return;
3091    }
3092    table[item].first = n1;
3093    lili = TV_LIST_ITEM_NEXT(li_l, lili);
3094    table[item].last = TV_LIST_ITEM_TV(lili)->vval.v_number;
3095    lili = TV_LIST_ITEM_NEXT(li_l, lili);
3096    table[item].width = (char)TV_LIST_ITEM_TV(lili)->vval.v_number;
3097  }
3098
3099  xfree((void *)ptrs);
3100
3101update:
3102  ;
3103  cw_interval_T *const cw_table_save = cw_table;
3104  const size_t cw_table_size_save = cw_table_size;
3105  cw_table = table;
3106  cw_table_size = table_size;
3107
3108  // Check that the new value does not conflict with 'listchars' or
3109  // 'fillchars'.
3110  const char *const error = check_chars_options();
3111  if (error != NULL) {
3112    emsg(_(error));
3113    cw_table = cw_table_save;
3114    cw_table_size = cw_table_size_save;
3115    xfree(table);
3116    return;
3117  }
3118
3119  xfree(cw_table_save);
3120  changed_window_setting_all();
3121  redraw_all_later(UPD_NOT_VALID);
3122}
3123
3124/// "getcellwidths()" function
3125void f_getcellwidths(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
3126{
3127  tv_list_alloc_ret(rettv, (ptrdiff_t)cw_table_size);
3128
3129  for (size_t i = 0; i < cw_table_size; i++) {
3130    list_T *entry = tv_list_alloc(3);
3131    tv_list_append_number(entry, (varnumber_T)cw_table[i].first);
3132    tv_list_append_number(entry, (varnumber_T)cw_table[i].last);
3133    tv_list_append_number(entry, (varnumber_T)cw_table[i].width);
3134
3135    tv_list_append_list(rettv->vval.v_list, entry);
3136  }
3137}
3138
3139void f_charclass(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
3140{
3141  if (tv_check_for_string_arg(argvars, 0) == FAIL
3142      || argvars[0].vval.v_string == NULL) {
3143    return;
3144  }
3145  rettv->vval.v_number = mb_get_class(argvars[0].vval.v_string);
3146}
3147
3148/// Function given to ExpandGeneric() to obtain the possible arguments of the
3149/// encoding options.
3150char *get_encoding_name(expand_T *xp FUNC_ATTR_UNUSED, int idx)
3151  FUNC_ATTR_PURE
3152{
3153  if (idx >= (int)ARRAY_SIZE(enc_canon_table)) {
3154    return NULL;
3155  }
3156
3157  return (char *)enc_canon_table[idx].name;
3158}
3159
3160/// Compare strings
3161///
3162/// @param[in]  ic  True if case is to be ignored.
3163///
3164/// @return 0 if s1 == s2, <0 if s1 < s2, >0 if s1 > s2.
3165int mb_strcmp_ic(bool ic, const char *s1, const char *s2)
3166  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
3167{
3168  return (ic ? mb_stricmp(s1, s2) : strcmp(s1, s2));
3169}