xref: /vim-8.2.3635/src/mbyte.c (revision b86f10ee)
1 /* vi:set ts=8 sts=4 sw=4:
2  *
3  * VIM - Vi IMproved	by Bram Moolenaar
4  * Multibyte extensions partly by Sung-Hoon Baek
5  *
6  * Do ":help uganda"  in Vim to read copying and usage conditions.
7  * Do ":help credits" in Vim to see a list of people who contributed.
8  * See README.txt for an overview of the Vim source code.
9  */
10 /*
11  * mbyte.c: Code specifically for handling multi-byte characters.
12  *
13  * The encoding used in the core is set with 'encoding'.  When 'encoding' is
14  * changed, the following four variables are set (for speed).
15  * Currently these types of character encodings are supported:
16  *
17  * "enc_dbcs"	    When non-zero it tells the type of double byte character
18  *		    encoding (Chinese, Korean, Japanese, etc.).
19  *		    The cell width on the display is equal to the number of
20  *		    bytes.  (exception: DBCS_JPNU with first byte 0x8e)
21  *		    Recognizing the first or second byte is difficult, it
22  *		    requires checking a byte sequence from the start.
23  * "enc_utf8"	    When TRUE use Unicode characters in UTF-8 encoding.
24  *		    The cell width on the display needs to be determined from
25  *		    the character value.
26  *		    Recognizing bytes is easy: 0xxx.xxxx is a single-byte
27  *		    char, 10xx.xxxx is a trailing byte, 11xx.xxxx is a leading
28  *		    byte of a multi-byte character.
29  *		    To make things complicated, up to six composing characters
30  *		    are allowed.  These are drawn on top of the first char.
31  *		    For most editing the sequence of bytes with composing
32  *		    characters included is considered to be one character.
33  * "enc_unicode"    When 2 use 16-bit Unicode characters (or UTF-16).
34  *		    When 4 use 32-but Unicode characters.
35  *		    Internally characters are stored in UTF-8 encoding to
36  *		    avoid NUL bytes.  Conversion happens when doing I/O.
37  *		    "enc_utf8" will also be TRUE.
38  *
39  * "has_mbyte" is set when "enc_dbcs" or "enc_utf8" is non-zero.
40  *
41  * If none of these is TRUE, 8-bit bytes are used for a character.  The
42  * encoding isn't currently specified (TODO).
43  *
44  * 'encoding' specifies the encoding used in the core.  This is in registers,
45  * text manipulation, buffers, etc.  Conversion has to be done when characters
46  * in another encoding are received or send:
47  *
48  *		       clipboard
49  *			   ^
50  *			   | (2)
51  *			   V
52  *		   +---------------+
53  *	      (1)  |		   | (3)
54  *  keyboard ----->|	 core	   |-----> display
55  *		   |		   |
56  *		   +---------------+
57  *			   ^
58  *			   | (4)
59  *			   V
60  *			 file
61  *
62  * (1) Typed characters arrive in the current locale.  Conversion is to be
63  *     done when 'encoding' is different from 'termencoding'.
64  * (2) Text will be made available with the encoding specified with
65  *     'encoding'.  If this is not sufficient, system-specific conversion
66  *     might be required.
67  * (3) For the GUI the correct font must be selected, no conversion done.
68  *     Otherwise, conversion is to be done when 'encoding' differs from
69  *     'termencoding'.  (Different in the GTK+ 2 port -- 'termencoding'
70  *     is always used for both input and output and must always be set to
71  *     "utf-8".  gui_mch_init() does this automatically.)
72  * (4) The encoding of the file is specified with 'fileencoding'.  Conversion
73  *     is to be done when it's different from 'encoding'.
74  *
75  * The viminfo file is a special case: Only text is converted, not file names.
76  * Vim scripts may contain an ":encoding" command.  This has an effect for
77  * some commands, like ":menutrans"
78  */
79 
80 #include "vim.h"
81 
82 #ifdef WIN32UNIX
83 # ifndef WIN32_LEAN_AND_MEAN
84 #  define WIN32_LEAN_AND_MEAN
85 # endif
86 # if defined(FEAT_GUI) || defined(FEAT_XCLIPBOARD)
87 #  include <X11/Xwindows.h>
88 #  define WINBYTE wBYTE
89 # else
90 #  include <windows.h>
91 #  define WINBYTE BYTE
92 # endif
93 # ifdef WIN32
94 #  undef WIN32	    /* Some windows.h define WIN32, we don't want that here. */
95 # endif
96 #else
97 # define WINBYTE BYTE
98 #endif
99 
100 #if (defined(WIN3264) || defined(WIN32UNIX)) && !defined(__MINGW32__)
101 # include <winnls.h>
102 #endif
103 
104 #ifdef FEAT_GUI_X11
105 # include <X11/Intrinsic.h>
106 #endif
107 #ifdef X_LOCALE
108 #include <X11/Xlocale.h>
109 #endif
110 
111 #if defined(FEAT_GUI_GTK) && defined(FEAT_XIM)
112 # if GTK_CHECK_VERSION(3,0,0)
113 #  include <gdk/gdkkeysyms-compat.h>
114 # else
115 #  include <gdk/gdkkeysyms.h>
116 # endif
117 # ifdef WIN3264
118 #  include <gdk/gdkwin32.h>
119 # else
120 #  include <gdk/gdkx.h>
121 # endif
122 #endif
123 
124 #ifdef HAVE_WCHAR_H
125 # include <wchar.h>
126 #endif
127 
128 #if 0
129 /* This has been disabled, because several people reported problems with the
130  * wcwidth() and iswprint() library functions, esp. for Hebrew. */
131 # ifdef __STDC_ISO_10646__
132 #  define USE_WCHAR_FUNCTIONS
133 # endif
134 #endif
135 
136 #if defined(FEAT_MBYTE) || defined(PROTO)
137 
138 static int enc_canon_search(char_u *name);
139 static int dbcs_char2len(int c);
140 static int dbcs_char2bytes(int c, char_u *buf);
141 static int dbcs_ptr2len(char_u *p);
142 static int dbcs_ptr2len_len(char_u *p, int size);
143 static int utf_ptr2cells_len(char_u *p, int size);
144 static int dbcs_char2cells(int c);
145 static int dbcs_ptr2cells_len(char_u *p, int size);
146 static int dbcs_ptr2char(char_u *p);
147 static int utf_safe_read_char_adv(char_u **s, size_t *n);
148 
149 /*
150  * Lookup table to quickly get the length in bytes of a UTF-8 character from
151  * the first byte of a UTF-8 string.
152  * Bytes which are illegal when used as the first byte have a 1.
153  * The NUL byte has length 1.
154  */
155 static char utf8len_tab[256] =
156 {
157     1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
158     1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
159     1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
160     1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
161     1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
162     1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
163     2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
164     3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,6,6,1,1,
165 };
166 
167 /*
168  * Like utf8len_tab above, but using a zero for illegal lead bytes.
169  */
170 static char utf8len_tab_zero[256] =
171 {
172     1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
173     1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
174     1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
175     1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
176     0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
177     0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
178     2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
179     3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,6,6,0,0,
180 };
181 
182 /*
183  * XIM often causes trouble.  Define XIM_DEBUG to get a log of XIM callbacks
184  * in the "xim.log" file.
185  */
186 /* #define XIM_DEBUG */
187 #ifdef XIM_DEBUG
188     static void
189 xim_log(char *s, ...)
190 {
191     va_list arglist;
192     static FILE *fd = NULL;
193 
194     if (fd == (FILE *)-1)
195 	return;
196     if (fd == NULL)
197     {
198 	fd = mch_fopen("xim.log", "w");
199 	if (fd == NULL)
200 	{
201 	    EMSG("Cannot open xim.log");
202 	    fd = (FILE *)-1;
203 	    return;
204 	}
205     }
206 
207     va_start(arglist, s);
208     vfprintf(fd, s, arglist);
209     va_end(arglist);
210 }
211 #endif
212 
213 #endif
214 
215 #if defined(FEAT_MBYTE) || defined(FEAT_POSTSCRIPT) || defined(PROTO)
216 /*
217  * Canonical encoding names and their properties.
218  * "iso-8859-n" is handled by enc_canonize() directly.
219  */
220 static struct
221 {   char *name;		int prop;		int codepage;}
222 enc_canon_table[] =
223 {
224 #define IDX_LATIN_1	0
225     {"latin1",		ENC_8BIT + ENC_LATIN1,	1252},
226 #define IDX_ISO_2	1
227     {"iso-8859-2",	ENC_8BIT,		0},
228 #define IDX_ISO_3	2
229     {"iso-8859-3",	ENC_8BIT,		0},
230 #define IDX_ISO_4	3
231     {"iso-8859-4",	ENC_8BIT,		0},
232 #define IDX_ISO_5	4
233     {"iso-8859-5",	ENC_8BIT,		0},
234 #define IDX_ISO_6	5
235     {"iso-8859-6",	ENC_8BIT,		0},
236 #define IDX_ISO_7	6
237     {"iso-8859-7",	ENC_8BIT,		0},
238 #define IDX_ISO_8	7
239     {"iso-8859-8",	ENC_8BIT,		0},
240 #define IDX_ISO_9	8
241     {"iso-8859-9",	ENC_8BIT,		0},
242 #define IDX_ISO_10	9
243     {"iso-8859-10",	ENC_8BIT,		0},
244 #define IDX_ISO_11	10
245     {"iso-8859-11",	ENC_8BIT,		0},
246 #define IDX_ISO_13	11
247     {"iso-8859-13",	ENC_8BIT,		0},
248 #define IDX_ISO_14	12
249     {"iso-8859-14",	ENC_8BIT,		0},
250 #define IDX_ISO_15	13
251     {"iso-8859-15",	ENC_8BIT + ENC_LATIN9,	0},
252 #define IDX_KOI8_R	14
253     {"koi8-r",		ENC_8BIT,		0},
254 #define IDX_KOI8_U	15
255     {"koi8-u",		ENC_8BIT,		0},
256 #define IDX_UTF8	16
257     {"utf-8",		ENC_UNICODE,		0},
258 #define IDX_UCS2	17
259     {"ucs-2",		ENC_UNICODE + ENC_ENDIAN_B + ENC_2BYTE, 0},
260 #define IDX_UCS2LE	18
261     {"ucs-2le",		ENC_UNICODE + ENC_ENDIAN_L + ENC_2BYTE, 0},
262 #define IDX_UTF16	19
263     {"utf-16",		ENC_UNICODE + ENC_ENDIAN_B + ENC_2WORD, 0},
264 #define IDX_UTF16LE	20
265     {"utf-16le",	ENC_UNICODE + ENC_ENDIAN_L + ENC_2WORD, 0},
266 #define IDX_UCS4	21
267     {"ucs-4",		ENC_UNICODE + ENC_ENDIAN_B + ENC_4BYTE, 0},
268 #define IDX_UCS4LE	22
269     {"ucs-4le",		ENC_UNICODE + ENC_ENDIAN_L + ENC_4BYTE, 0},
270 
271     /* For debugging DBCS encoding on Unix. */
272 #define IDX_DEBUG	23
273     {"debug",		ENC_DBCS,		DBCS_DEBUG},
274 #define IDX_EUC_JP	24
275     {"euc-jp",		ENC_DBCS,		DBCS_JPNU},
276 #define IDX_SJIS	25
277     {"sjis",		ENC_DBCS,		DBCS_JPN},
278 #define IDX_EUC_KR	26
279     {"euc-kr",		ENC_DBCS,		DBCS_KORU},
280 #define IDX_EUC_CN	27
281     {"euc-cn",		ENC_DBCS,		DBCS_CHSU},
282 #define IDX_EUC_TW	28
283     {"euc-tw",		ENC_DBCS,		DBCS_CHTU},
284 #define IDX_BIG5	29
285     {"big5",		ENC_DBCS,		DBCS_CHT},
286 
287     /* MS-DOS and MS-Windows codepages are included here, so that they can be
288      * used on Unix too.  Most of them are similar to ISO-8859 encodings, but
289      * not exactly the same. */
290 #define IDX_CP437	30
291     {"cp437",		ENC_8BIT,		437}, /* like iso-8859-1 */
292 #define IDX_CP737	31
293     {"cp737",		ENC_8BIT,		737}, /* like iso-8859-7 */
294 #define IDX_CP775	32
295     {"cp775",		ENC_8BIT,		775}, /* Baltic */
296 #define IDX_CP850	33
297     {"cp850",		ENC_8BIT,		850}, /* like iso-8859-4 */
298 #define IDX_CP852	34
299     {"cp852",		ENC_8BIT,		852}, /* like iso-8859-1 */
300 #define IDX_CP855	35
301     {"cp855",		ENC_8BIT,		855}, /* like iso-8859-2 */
302 #define IDX_CP857	36
303     {"cp857",		ENC_8BIT,		857}, /* like iso-8859-5 */
304 #define IDX_CP860	37
305     {"cp860",		ENC_8BIT,		860}, /* like iso-8859-9 */
306 #define IDX_CP861	38
307     {"cp861",		ENC_8BIT,		861}, /* like iso-8859-1 */
308 #define IDX_CP862	39
309     {"cp862",		ENC_8BIT,		862}, /* like iso-8859-1 */
310 #define IDX_CP863	40
311     {"cp863",		ENC_8BIT,		863}, /* like iso-8859-8 */
312 #define IDX_CP865	41
313     {"cp865",		ENC_8BIT,		865}, /* like iso-8859-1 */
314 #define IDX_CP866	42
315     {"cp866",		ENC_8BIT,		866}, /* like iso-8859-5 */
316 #define IDX_CP869	43
317     {"cp869",		ENC_8BIT,		869}, /* like iso-8859-7 */
318 #define IDX_CP874	44
319     {"cp874",		ENC_8BIT,		874}, /* Thai */
320 #define IDX_CP932	45
321     {"cp932",		ENC_DBCS,		DBCS_JPN},
322 #define IDX_CP936	46
323     {"cp936",		ENC_DBCS,		DBCS_CHS},
324 #define IDX_CP949	47
325     {"cp949",		ENC_DBCS,		DBCS_KOR},
326 #define IDX_CP950	48
327     {"cp950",		ENC_DBCS,		DBCS_CHT},
328 #define IDX_CP1250	49
329     {"cp1250",		ENC_8BIT,		1250}, /* Czech, Polish, etc. */
330 #define IDX_CP1251	50
331     {"cp1251",		ENC_8BIT,		1251}, /* Cyrillic */
332     /* cp1252 is considered to be equal to latin1 */
333 #define IDX_CP1253	51
334     {"cp1253",		ENC_8BIT,		1253}, /* Greek */
335 #define IDX_CP1254	52
336     {"cp1254",		ENC_8BIT,		1254}, /* Turkish */
337 #define IDX_CP1255	53
338     {"cp1255",		ENC_8BIT,		1255}, /* Hebrew */
339 #define IDX_CP1256	54
340     {"cp1256",		ENC_8BIT,		1256}, /* Arabic */
341 #define IDX_CP1257	55
342     {"cp1257",		ENC_8BIT,		1257}, /* Baltic */
343 #define IDX_CP1258	56
344     {"cp1258",		ENC_8BIT,		1258}, /* Vietnamese */
345 
346 #define IDX_MACROMAN	57
347     {"macroman",	ENC_8BIT + ENC_MACROMAN, 0},	/* Mac OS */
348 #define IDX_DECMCS	58
349     {"dec-mcs",		ENC_8BIT,		0},	/* DEC MCS */
350 #define IDX_HPROMAN8	59
351     {"hp-roman8",	ENC_8BIT,		0},	/* HP Roman8 */
352 #define IDX_COUNT	60
353 };
354 
355 /*
356  * Aliases for encoding names.
357  */
358 static struct
359 {   char *name;		int canon;}
360 enc_alias_table[] =
361 {
362     {"ansi",		IDX_LATIN_1},
363     {"iso-8859-1",	IDX_LATIN_1},
364     {"latin2",		IDX_ISO_2},
365     {"latin3",		IDX_ISO_3},
366     {"latin4",		IDX_ISO_4},
367     {"cyrillic",	IDX_ISO_5},
368     {"arabic",		IDX_ISO_6},
369     {"greek",		IDX_ISO_7},
370 #ifdef WIN3264
371     {"hebrew",		IDX_CP1255},
372 #else
373     {"hebrew",		IDX_ISO_8},
374 #endif
375     {"latin5",		IDX_ISO_9},
376     {"turkish",		IDX_ISO_9}, /* ? */
377     {"latin6",		IDX_ISO_10},
378     {"nordic",		IDX_ISO_10}, /* ? */
379     {"thai",		IDX_ISO_11}, /* ? */
380     {"latin7",		IDX_ISO_13},
381     {"latin8",		IDX_ISO_14},
382     {"latin9",		IDX_ISO_15},
383     {"utf8",		IDX_UTF8},
384     {"unicode",		IDX_UCS2},
385     {"ucs2",		IDX_UCS2},
386     {"ucs2be",		IDX_UCS2},
387     {"ucs-2be",		IDX_UCS2},
388     {"ucs2le",		IDX_UCS2LE},
389     {"utf16",		IDX_UTF16},
390     {"utf16be",		IDX_UTF16},
391     {"utf-16be",	IDX_UTF16},
392     {"utf16le",		IDX_UTF16LE},
393     {"ucs4",		IDX_UCS4},
394     {"ucs4be",		IDX_UCS4},
395     {"ucs-4be",		IDX_UCS4},
396     {"ucs4le",		IDX_UCS4LE},
397     {"utf32",		IDX_UCS4},
398     {"utf-32",		IDX_UCS4},
399     {"utf32be",		IDX_UCS4},
400     {"utf-32be",	IDX_UCS4},
401     {"utf32le",		IDX_UCS4LE},
402     {"utf-32le",	IDX_UCS4LE},
403     {"932",		IDX_CP932},
404     {"949",		IDX_CP949},
405     {"936",		IDX_CP936},
406     {"gbk",		IDX_CP936},
407     {"950",		IDX_CP950},
408     {"eucjp",		IDX_EUC_JP},
409     {"unix-jis",	IDX_EUC_JP},
410     {"ujis",		IDX_EUC_JP},
411     {"shift-jis",	IDX_SJIS},
412     {"pck",		IDX_SJIS},	/* Sun: PCK */
413     {"euckr",		IDX_EUC_KR},
414     {"5601",		IDX_EUC_KR},	/* Sun: KS C 5601 */
415     {"euccn",		IDX_EUC_CN},
416     {"gb2312",		IDX_EUC_CN},
417     {"euctw",		IDX_EUC_TW},
418 #if defined(WIN3264) || defined(WIN32UNIX) || defined(MACOS)
419     {"japan",		IDX_CP932},
420     {"korea",		IDX_CP949},
421     {"prc",		IDX_CP936},
422     {"chinese",		IDX_CP936},
423     {"taiwan",		IDX_CP950},
424     {"big5",		IDX_CP950},
425 #else
426     {"japan",		IDX_EUC_JP},
427     {"korea",		IDX_EUC_KR},
428     {"prc",		IDX_EUC_CN},
429     {"chinese",		IDX_EUC_CN},
430     {"taiwan",		IDX_EUC_TW},
431     {"cp950",		IDX_BIG5},
432     {"950",		IDX_BIG5},
433 #endif
434     {"mac",		IDX_MACROMAN},
435     {"mac-roman",	IDX_MACROMAN},
436     {NULL,		0}
437 };
438 
439 #ifndef CP_UTF8
440 # define CP_UTF8 65001	/* magic number from winnls.h */
441 #endif
442 
443 /*
444  * Find encoding "name" in the list of canonical encoding names.
445  * Returns -1 if not found.
446  */
447     static int
448 enc_canon_search(char_u *name)
449 {
450     int		i;
451 
452     for (i = 0; i < IDX_COUNT; ++i)
453 	if (STRCMP(name, enc_canon_table[i].name) == 0)
454 	    return i;
455     return -1;
456 }
457 
458 #endif
459 
460 #if defined(FEAT_MBYTE) || defined(PROTO)
461 
462 /*
463  * Find canonical encoding "name" in the list and return its properties.
464  * Returns 0 if not found.
465  */
466     int
467 enc_canon_props(char_u *name)
468 {
469     int		i;
470 
471     i = enc_canon_search(name);
472     if (i >= 0)
473 	return enc_canon_table[i].prop;
474 #ifdef WIN3264
475     if (name[0] == 'c' && name[1] == 'p' && VIM_ISDIGIT(name[2]))
476     {
477 	CPINFO	cpinfo;
478 
479 	/* Get info on this codepage to find out what it is. */
480 	if (GetCPInfo(atoi((char *)name + 2), &cpinfo) != 0)
481 	{
482 	    if (cpinfo.MaxCharSize == 1) /* some single-byte encoding */
483 		return ENC_8BIT;
484 	    if (cpinfo.MaxCharSize == 2
485 		    && (cpinfo.LeadByte[0] != 0 || cpinfo.LeadByte[1] != 0))
486 		/* must be a DBCS encoding */
487 		return ENC_DBCS;
488 	}
489 	return 0;
490     }
491 #endif
492     if (STRNCMP(name, "2byte-", 6) == 0)
493 	return ENC_DBCS;
494     if (STRNCMP(name, "8bit-", 5) == 0 || STRNCMP(name, "iso-8859-", 9) == 0)
495 	return ENC_8BIT;
496     return 0;
497 }
498 
499 /*
500  * Set up for using multi-byte characters.
501  * Called in three cases:
502  * - by main() to initialize (p_enc == NULL)
503  * - by set_init_1() after 'encoding' was set to its default.
504  * - by do_set() when 'encoding' has been set.
505  * p_enc must have been passed through enc_canonize() already.
506  * Sets the "enc_unicode", "enc_utf8", "enc_dbcs" and "has_mbyte" flags.
507  * Fills mb_bytelen_tab[] and returns NULL when there are no problems.
508  * When there is something wrong: Returns an error message and doesn't change
509  * anything.
510  */
511     char_u *
512 mb_init(void)
513 {
514     int		i;
515     int		idx;
516     int		n;
517     int		enc_dbcs_new = 0;
518 #if defined(USE_ICONV) && !defined(WIN3264) && !defined(WIN32UNIX) \
519 	&& !defined(MACOS)
520 # define LEN_FROM_CONV
521     vimconv_T	vimconv;
522     char_u	*p;
523 #endif
524 
525     if (p_enc == NULL)
526     {
527 	/* Just starting up: set the whole table to one's. */
528 	for (i = 0; i < 256; ++i)
529 	    mb_bytelen_tab[i] = 1;
530 	input_conv.vc_type = CONV_NONE;
531 	input_conv.vc_factor = 1;
532 	output_conv.vc_type = CONV_NONE;
533 	return NULL;
534     }
535 
536 #ifdef WIN3264
537     if (p_enc[0] == 'c' && p_enc[1] == 'p' && VIM_ISDIGIT(p_enc[2]))
538     {
539 	CPINFO	cpinfo;
540 
541 	/* Get info on this codepage to find out what it is. */
542 	if (GetCPInfo(atoi((char *)p_enc + 2), &cpinfo) != 0)
543 	{
544 	    if (cpinfo.MaxCharSize == 1)
545 	    {
546 		/* some single-byte encoding */
547 		enc_unicode = 0;
548 		enc_utf8 = FALSE;
549 	    }
550 	    else if (cpinfo.MaxCharSize == 2
551 		    && (cpinfo.LeadByte[0] != 0 || cpinfo.LeadByte[1] != 0))
552 	    {
553 		/* must be a DBCS encoding, check below */
554 		enc_dbcs_new = atoi((char *)p_enc + 2);
555 	    }
556 	    else
557 		goto codepage_invalid;
558 	}
559 	else if (GetLastError() == ERROR_INVALID_PARAMETER)
560 	{
561 codepage_invalid:
562 	    return (char_u *)N_("E543: Not a valid codepage");
563 	}
564     }
565 #endif
566     else if (STRNCMP(p_enc, "8bit-", 5) == 0
567 	    || STRNCMP(p_enc, "iso-8859-", 9) == 0)
568     {
569 	/* Accept any "8bit-" or "iso-8859-" name. */
570 	enc_unicode = 0;
571 	enc_utf8 = FALSE;
572     }
573     else if (STRNCMP(p_enc, "2byte-", 6) == 0)
574     {
575 #ifdef WIN3264
576 	/* Windows: accept only valid codepage numbers, check below. */
577 	if (p_enc[6] != 'c' || p_enc[7] != 'p'
578 			      || (enc_dbcs_new = atoi((char *)p_enc + 8)) == 0)
579 	    return e_invarg;
580 #else
581 	/* Unix: accept any "2byte-" name, assume current locale. */
582 	enc_dbcs_new = DBCS_2BYTE;
583 #endif
584     }
585     else if ((idx = enc_canon_search(p_enc)) >= 0)
586     {
587 	i = enc_canon_table[idx].prop;
588 	if (i & ENC_UNICODE)
589 	{
590 	    /* Unicode */
591 	    enc_utf8 = TRUE;
592 	    if (i & (ENC_2BYTE | ENC_2WORD))
593 		enc_unicode = 2;
594 	    else if (i & ENC_4BYTE)
595 		enc_unicode = 4;
596 	    else
597 		enc_unicode = 0;
598 	}
599 	else if (i & ENC_DBCS)
600 	{
601 	    /* 2byte, handle below */
602 	    enc_dbcs_new = enc_canon_table[idx].codepage;
603 	}
604 	else
605 	{
606 	    /* Must be 8-bit. */
607 	    enc_unicode = 0;
608 	    enc_utf8 = FALSE;
609 	}
610     }
611     else    /* Don't know what encoding this is, reject it. */
612 	return e_invarg;
613 
614     if (enc_dbcs_new != 0)
615     {
616 #ifdef WIN3264
617 	/* Check if the DBCS code page is OK. */
618 	if (!IsValidCodePage(enc_dbcs_new))
619 	    goto codepage_invalid;
620 #endif
621 	enc_unicode = 0;
622 	enc_utf8 = FALSE;
623     }
624     enc_dbcs = enc_dbcs_new;
625     has_mbyte = (enc_dbcs != 0 || enc_utf8);
626 
627 #if defined(WIN3264) || defined(FEAT_CYGWIN_WIN32_CLIPBOARD)
628     enc_codepage = encname2codepage(p_enc);
629     enc_latin9 = (STRCMP(p_enc, "iso-8859-15") == 0);
630 #endif
631 
632     /* Detect an encoding that uses latin1 characters. */
633     enc_latin1like = (enc_utf8 || STRCMP(p_enc, "latin1") == 0
634 					|| STRCMP(p_enc, "iso-8859-15") == 0);
635 
636     /*
637      * Set the function pointers.
638      */
639     if (enc_utf8)
640     {
641 	mb_ptr2len = utfc_ptr2len;
642 	mb_ptr2len_len = utfc_ptr2len_len;
643 	mb_char2len = utf_char2len;
644 	mb_char2bytes = utf_char2bytes;
645 	mb_ptr2cells = utf_ptr2cells;
646 	mb_ptr2cells_len = utf_ptr2cells_len;
647 	mb_char2cells = utf_char2cells;
648 	mb_off2cells = utf_off2cells;
649 	mb_ptr2char = utf_ptr2char;
650 	mb_head_off = utf_head_off;
651     }
652     else if (enc_dbcs != 0)
653     {
654 	mb_ptr2len = dbcs_ptr2len;
655 	mb_ptr2len_len = dbcs_ptr2len_len;
656 	mb_char2len = dbcs_char2len;
657 	mb_char2bytes = dbcs_char2bytes;
658 	mb_ptr2cells = dbcs_ptr2cells;
659 	mb_ptr2cells_len = dbcs_ptr2cells_len;
660 	mb_char2cells = dbcs_char2cells;
661 	mb_off2cells = dbcs_off2cells;
662 	mb_ptr2char = dbcs_ptr2char;
663 	mb_head_off = dbcs_head_off;
664     }
665     else
666     {
667 	mb_ptr2len = latin_ptr2len;
668 	mb_ptr2len_len = latin_ptr2len_len;
669 	mb_char2len = latin_char2len;
670 	mb_char2bytes = latin_char2bytes;
671 	mb_ptr2cells = latin_ptr2cells;
672 	mb_ptr2cells_len = latin_ptr2cells_len;
673 	mb_char2cells = latin_char2cells;
674 	mb_off2cells = latin_off2cells;
675 	mb_ptr2char = latin_ptr2char;
676 	mb_head_off = latin_head_off;
677     }
678 
679     /*
680      * Fill the mb_bytelen_tab[] for MB_BYTE2LEN().
681      */
682 #ifdef LEN_FROM_CONV
683     /* When 'encoding' is different from the current locale mblen() won't
684      * work.  Use conversion to "utf-8" instead. */
685     vimconv.vc_type = CONV_NONE;
686     if (enc_dbcs)
687     {
688 	p = enc_locale();
689 	if (p == NULL || STRCMP(p, p_enc) != 0)
690 	{
691 	    convert_setup(&vimconv, p_enc, (char_u *)"utf-8");
692 	    vimconv.vc_fail = TRUE;
693 	}
694 	vim_free(p);
695     }
696 #endif
697 
698     for (i = 0; i < 256; ++i)
699     {
700 	/* Our own function to reliably check the length of UTF-8 characters,
701 	 * independent of mblen(). */
702 	if (enc_utf8)
703 	    n = utf8len_tab[i];
704 	else if (enc_dbcs == 0)
705 	    n = 1;
706 	else
707 	{
708 #if defined(WIN3264) || defined(WIN32UNIX)
709 	    /* enc_dbcs is set by setting 'fileencoding'.  It becomes a Windows
710 	     * CodePage identifier, which we can pass directly in to Windows
711 	     * API */
712 	    n = IsDBCSLeadByteEx(enc_dbcs, (WINBYTE)i) ? 2 : 1;
713 #else
714 # if defined(MACOS) || defined(__amigaos4__) || defined(__ANDROID__)
715 	    /*
716 	     * if mblen() is not available, character which MSB is turned on
717 	     * are treated as leading byte character. (note : This assumption
718 	     * is not always true.)
719 	     */
720 	    n = (i & 0x80) ? 2 : 1;
721 # else
722 	    char buf[MB_MAXBYTES + 1];
723 # ifdef X_LOCALE
724 #  ifndef mblen
725 #   define mblen _Xmblen
726 #  endif
727 # endif
728 	    if (i == NUL)	/* just in case mblen() can't handle "" */
729 		n = 1;
730 	    else
731 	    {
732 		buf[0] = i;
733 		buf[1] = 0;
734 #ifdef LEN_FROM_CONV
735 		if (vimconv.vc_type != CONV_NONE)
736 		{
737 		    /*
738 		     * string_convert() should fail when converting the first
739 		     * byte of a double-byte character.
740 		     */
741 		    p = string_convert(&vimconv, (char_u *)buf, NULL);
742 		    if (p != NULL)
743 		    {
744 			vim_free(p);
745 			n = 1;
746 		    }
747 		    else
748 			n = 2;
749 		}
750 		else
751 #endif
752 		{
753 		    /*
754 		     * mblen() should return -1 for invalid (means the leading
755 		     * multibyte) character.  However there are some platforms
756 		     * where mblen() returns 0 for invalid character.
757 		     * Therefore, following condition includes 0.
758 		     */
759 		    ignored = mblen(NULL, 0);	/* First reset the state. */
760 		    if (mblen(buf, (size_t)1) <= 0)
761 			n = 2;
762 		    else
763 			n = 1;
764 		}
765 	    }
766 # endif
767 #endif
768 	}
769 
770 	mb_bytelen_tab[i] = n;
771     }
772 
773 #ifdef LEN_FROM_CONV
774     convert_setup(&vimconv, NULL, NULL);
775 #endif
776 
777     /* The cell width depends on the type of multi-byte characters. */
778     (void)init_chartab();
779 
780     /* When enc_utf8 is set or reset, (de)allocate ScreenLinesUC[] */
781     screenalloc(FALSE);
782 
783     /* When using Unicode, set default for 'fileencodings'. */
784     if (enc_utf8 && !option_was_set((char_u *)"fencs"))
785 	set_string_option_direct((char_u *)"fencs", -1,
786 		       (char_u *)"ucs-bom,utf-8,default,latin1", OPT_FREE, 0);
787 
788 #if defined(HAVE_BIND_TEXTDOMAIN_CODESET) && defined(FEAT_GETTEXT)
789     /* GNU gettext 0.10.37 supports this feature: set the codeset used for
790      * translated messages independently from the current locale. */
791     (void)bind_textdomain_codeset(VIMPACKAGE,
792 					  enc_utf8 ? "utf-8" : (char *)p_enc);
793 #endif
794 
795 #ifdef WIN32
796     /* When changing 'encoding' while starting up, then convert the command
797      * line arguments from the active codepage to 'encoding'. */
798     if (starting != 0)
799 	fix_arg_enc();
800 #endif
801 
802 #ifdef FEAT_AUTOCMD
803     /* Fire an autocommand to let people do custom font setup. This must be
804      * after Vim has been setup for the new encoding. */
805     apply_autocmds(EVENT_ENCODINGCHANGED, NULL, (char_u *)"", FALSE, curbuf);
806 #endif
807 
808 #ifdef FEAT_SPELL
809     /* Need to reload spell dictionaries */
810     spell_reload();
811 #endif
812 
813     return NULL;
814 }
815 
816 /*
817  * Return the size of the BOM for the current buffer:
818  * 0 - no BOM
819  * 2 - UCS-2 or UTF-16 BOM
820  * 4 - UCS-4 BOM
821  * 3 - UTF-8 BOM
822  */
823     int
824 bomb_size(void)
825 {
826     int n = 0;
827 
828     if (curbuf->b_p_bomb && !curbuf->b_p_bin)
829     {
830 	if (*curbuf->b_p_fenc == NUL)
831 	{
832 	    if (enc_utf8)
833 	    {
834 		if (enc_unicode != 0)
835 		    n = enc_unicode;
836 		else
837 		    n = 3;
838 	    }
839 	}
840 	else if (STRCMP(curbuf->b_p_fenc, "utf-8") == 0)
841 	    n = 3;
842 	else if (STRNCMP(curbuf->b_p_fenc, "ucs-2", 5) == 0
843 		|| STRNCMP(curbuf->b_p_fenc, "utf-16", 6) == 0)
844 	    n = 2;
845 	else if (STRNCMP(curbuf->b_p_fenc, "ucs-4", 5) == 0)
846 	    n = 4;
847     }
848     return n;
849 }
850 
851 /*
852  * Remove all BOM from "s" by moving remaining text.
853  */
854     void
855 remove_bom(char_u *s)
856 {
857     if (enc_utf8)
858     {
859 	char_u *p = s;
860 
861 	while ((p = vim_strbyte(p, 0xef)) != NULL)
862 	{
863 	    if (p[1] == 0xbb && p[2] == 0xbf)
864 		STRMOVE(p, p + 3);
865 	    else
866 		++p;
867 	}
868     }
869 }
870 
871 /*
872  * Get class of pointer:
873  * 0 for blank or NUL
874  * 1 for punctuation
875  * 2 for an (ASCII) word character
876  * >2 for other word characters
877  */
878     int
879 mb_get_class(char_u *p)
880 {
881     return mb_get_class_buf(p, curbuf);
882 }
883 
884     int
885 mb_get_class_buf(char_u *p, buf_T *buf)
886 {
887     if (MB_BYTE2LEN(p[0]) == 1)
888     {
889 	if (p[0] == NUL || vim_iswhite(p[0]))
890 	    return 0;
891 	if (vim_iswordc_buf(p[0], buf))
892 	    return 2;
893 	return 1;
894     }
895     if (enc_dbcs != 0 && p[0] != NUL && p[1] != NUL)
896 	return dbcs_class(p[0], p[1]);
897     if (enc_utf8)
898 	return utf_class(utf_ptr2char(p));
899     return 0;
900 }
901 
902 /*
903  * Get class of a double-byte character.  This always returns 3 or bigger.
904  * TODO: Should return 1 for punctuation.
905  */
906     int
907 dbcs_class(unsigned lead, unsigned trail)
908 {
909     switch (enc_dbcs)
910     {
911 	/* please add classify routine for your language in here */
912 
913 	case DBCS_JPNU:	/* ? */
914 	case DBCS_JPN:
915 	    {
916 		/* JIS code classification */
917 		unsigned char lb = lead;
918 		unsigned char tb = trail;
919 
920 		/* convert process code to JIS */
921 # if defined(WIN3264) || defined(WIN32UNIX) || defined(MACOS)
922 		/* process code is SJIS */
923 		if (lb <= 0x9f)
924 		    lb = (lb - 0x81) * 2 + 0x21;
925 		else
926 		    lb = (lb - 0xc1) * 2 + 0x21;
927 		if (tb <= 0x7e)
928 		    tb -= 0x1f;
929 		else if (tb <= 0x9e)
930 		    tb -= 0x20;
931 		else
932 		{
933 		    tb -= 0x7e;
934 		    lb += 1;
935 		}
936 # else
937 		/*
938 		 * XXX: Code page identification can not use with all
939 		 *	    system! So, some other encoding information
940 		 *	    will be needed.
941 		 *	    In japanese: SJIS,EUC,UNICODE,(JIS)
942 		 *	    Note that JIS-code system don't use as
943 		 *	    process code in most system because it uses
944 		 *	    escape sequences(JIS is context depend encoding).
945 		 */
946 		/* assume process code is JAPANESE-EUC */
947 		lb &= 0x7f;
948 		tb &= 0x7f;
949 # endif
950 		/* exceptions */
951 		switch (lb << 8 | tb)
952 		{
953 		    case 0x2121: /* ZENKAKU space */
954 			return 0;
955 		    case 0x2122: /* TOU-TEN (Japanese comma) */
956 		    case 0x2123: /* KU-TEN (Japanese period) */
957 		    case 0x2124: /* ZENKAKU comma */
958 		    case 0x2125: /* ZENKAKU period */
959 			return 1;
960 		    case 0x213c: /* prolongedsound handled as KATAKANA */
961 			return 13;
962 		}
963 		/* sieved by KU code */
964 		switch (lb)
965 		{
966 		    case 0x21:
967 		    case 0x22:
968 			/* special symbols */
969 			return 10;
970 		    case 0x23:
971 			/* alpha-numeric */
972 			return 11;
973 		    case 0x24:
974 			/* hiragana */
975 			return 12;
976 		    case 0x25:
977 			/* katakana */
978 			return 13;
979 		    case 0x26:
980 			/* greek */
981 			return 14;
982 		    case 0x27:
983 			/* russian */
984 			return 15;
985 		    case 0x28:
986 			/* lines */
987 			return 16;
988 		    default:
989 			/* kanji */
990 			return 17;
991 		}
992 	    }
993 
994 	case DBCS_KORU:	/* ? */
995 	case DBCS_KOR:
996 	    {
997 		/* KS code classification */
998 		unsigned char c1 = lead;
999 		unsigned char c2 = trail;
1000 
1001 		/*
1002 		 * 20 : Hangul
1003 		 * 21 : Hanja
1004 		 * 22 : Symbols
1005 		 * 23 : Alpha-numeric/Roman Letter (Full width)
1006 		 * 24 : Hangul Letter(Alphabet)
1007 		 * 25 : Roman Numeral/Greek Letter
1008 		 * 26 : Box Drawings
1009 		 * 27 : Unit Symbols
1010 		 * 28 : Circled/Parenthesized Letter
1011 		 * 29 : Hiragana/Katakana
1012 		 * 30 : Cyrillic Letter
1013 		 */
1014 
1015 		if (c1 >= 0xB0 && c1 <= 0xC8)
1016 		    /* Hangul */
1017 		    return 20;
1018 #if defined(WIN3264) || defined(WIN32UNIX)
1019 		else if (c1 <= 0xA0 || c2 <= 0xA0)
1020 		    /* Extended Hangul Region : MS UHC(Unified Hangul Code) */
1021 		    /* c1: 0x81-0xA0 with c2: 0x41-0x5A, 0x61-0x7A, 0x81-0xFE
1022 		     * c1: 0xA1-0xC6 with c2: 0x41-0x5A, 0x61-0x7A, 0x81-0xA0
1023 		     */
1024 		    return 20;
1025 #endif
1026 
1027 		else if (c1 >= 0xCA && c1 <= 0xFD)
1028 		    /* Hanja */
1029 		    return 21;
1030 		else switch (c1)
1031 		{
1032 		    case 0xA1:
1033 		    case 0xA2:
1034 			/* Symbols */
1035 			return 22;
1036 		    case 0xA3:
1037 			/* Alpha-numeric */
1038 			return 23;
1039 		    case 0xA4:
1040 			/* Hangul Letter(Alphabet) */
1041 			return 24;
1042 		    case 0xA5:
1043 			/* Roman Numeral/Greek Letter */
1044 			return 25;
1045 		    case 0xA6:
1046 			/* Box Drawings */
1047 			return 26;
1048 		    case 0xA7:
1049 			/* Unit Symbols */
1050 			return 27;
1051 		    case 0xA8:
1052 		    case 0xA9:
1053 			if (c2 <= 0xAF)
1054 			    return 25;  /* Roman Letter */
1055 			else if (c2 >= 0xF6)
1056 			    return 22;  /* Symbols */
1057 			else
1058 			    /* Circled/Parenthesized Letter */
1059 			    return 28;
1060 		    case 0xAA:
1061 		    case 0xAB:
1062 			/* Hiragana/Katakana */
1063 			return 29;
1064 		    case 0xAC:
1065 			/* Cyrillic Letter */
1066 			return 30;
1067 		}
1068 	    }
1069 	default:
1070 	    break;
1071     }
1072     return 3;
1073 }
1074 
1075 /*
1076  * mb_char2len() function pointer.
1077  * Return length in bytes of character "c".
1078  * Returns 1 for a single-byte character.
1079  */
1080     int
1081 latin_char2len(int c UNUSED)
1082 {
1083     return 1;
1084 }
1085 
1086     static int
1087 dbcs_char2len(
1088     int		c)
1089 {
1090     if (c >= 0x100)
1091 	return 2;
1092     return 1;
1093 }
1094 
1095 /*
1096  * mb_char2bytes() function pointer.
1097  * Convert a character to its bytes.
1098  * Returns the length in bytes.
1099  */
1100     int
1101 latin_char2bytes(int c, char_u *buf)
1102 {
1103     buf[0] = c;
1104     return 1;
1105 }
1106 
1107     static int
1108 dbcs_char2bytes(int c, char_u *buf)
1109 {
1110     if (c >= 0x100)
1111     {
1112 	buf[0] = (unsigned)c >> 8;
1113 	buf[1] = c;
1114 	/* Never use a NUL byte, it causes lots of trouble.  It's an invalid
1115 	 * character anyway. */
1116 	if (buf[1] == NUL)
1117 	    buf[1] = '\n';
1118 	return 2;
1119     }
1120     buf[0] = c;
1121     return 1;
1122 }
1123 
1124 /*
1125  * mb_ptr2len() function pointer.
1126  * Get byte length of character at "*p" but stop at a NUL.
1127  * For UTF-8 this includes following composing characters.
1128  * Returns 0 when *p is NUL.
1129  */
1130     int
1131 latin_ptr2len(char_u *p)
1132 {
1133  return MB_BYTE2LEN(*p);
1134 }
1135 
1136     static int
1137 dbcs_ptr2len(
1138     char_u	*p)
1139 {
1140     int		len;
1141 
1142     /* Check if second byte is not missing. */
1143     len = MB_BYTE2LEN(*p);
1144     if (len == 2 && p[1] == NUL)
1145 	len = 1;
1146     return len;
1147 }
1148 
1149 /*
1150  * mb_ptr2len_len() function pointer.
1151  * Like mb_ptr2len(), but limit to read "size" bytes.
1152  * Returns 0 for an empty string.
1153  * Returns 1 for an illegal char or an incomplete byte sequence.
1154  */
1155     int
1156 latin_ptr2len_len(char_u *p, int size)
1157 {
1158     if (size < 1 || *p == NUL)
1159 	return 0;
1160     return 1;
1161 }
1162 
1163     static int
1164 dbcs_ptr2len_len(char_u *p, int size)
1165 {
1166     int		len;
1167 
1168     if (size < 1 || *p == NUL)
1169 	return 0;
1170     if (size == 1)
1171 	return 1;
1172     /* Check that second byte is not missing. */
1173     len = MB_BYTE2LEN(*p);
1174     if (len == 2 && p[1] == NUL)
1175 	len = 1;
1176     return len;
1177 }
1178 
1179 struct interval
1180 {
1181     long first;
1182     long last;
1183 };
1184 
1185 /*
1186  * Return TRUE if "c" is in "table[size / sizeof(struct interval)]".
1187  */
1188     static int
1189 intable(struct interval *table, size_t size, int c)
1190 {
1191     int mid, bot, top;
1192 
1193     /* first quick check for Latin1 etc. characters */
1194     if (c < table[0].first)
1195 	return FALSE;
1196 
1197     /* binary search in table */
1198     bot = 0;
1199     top = (int)(size / sizeof(struct interval) - 1);
1200     while (top >= bot)
1201     {
1202 	mid = (bot + top) / 2;
1203 	if (table[mid].last < c)
1204 	    bot = mid + 1;
1205 	else if (table[mid].first > c)
1206 	    top = mid - 1;
1207 	else
1208 	    return TRUE;
1209     }
1210     return FALSE;
1211 }
1212 
1213 /*
1214  * For UTF-8 character "c" return 2 for a double-width character, 1 for others.
1215  * Returns 4 or 6 for an unprintable character.
1216  * Is only correct for characters >= 0x80.
1217  * When p_ambw is "double", return 2 for a character with East Asian Width
1218  * class 'A'(mbiguous).
1219  */
1220     int
1221 utf_char2cells(int c)
1222 {
1223     /* Sorted list of non-overlapping intervals of East Asian double width
1224      * characters, generated with ../runtime/tools/unicode.vim. */
1225     static struct interval doublewidth[] =
1226     {
1227 	{0x1100, 0x115f},
1228 	{0x2329, 0x232a},
1229 	{0x2e80, 0x2e99},
1230 	{0x2e9b, 0x2ef3},
1231 	{0x2f00, 0x2fd5},
1232 	{0x2ff0, 0x2ffb},
1233 	{0x3000, 0x303e},
1234 	{0x3041, 0x3096},
1235 	{0x3099, 0x30ff},
1236 	{0x3105, 0x312d},
1237 	{0x3131, 0x318e},
1238 	{0x3190, 0x31ba},
1239 	{0x31c0, 0x31e3},
1240 	{0x31f0, 0x321e},
1241 	{0x3220, 0x3247},
1242 	{0x3250, 0x32fe},
1243 	{0x3300, 0x4dbf},
1244 	{0x4e00, 0xa48c},
1245 	{0xa490, 0xa4c6},
1246 	{0xa960, 0xa97c},
1247 	{0xac00, 0xd7a3},
1248 	{0xf900, 0xfaff},
1249 	{0xfe10, 0xfe19},
1250 	{0xfe30, 0xfe52},
1251 	{0xfe54, 0xfe66},
1252 	{0xfe68, 0xfe6b},
1253 	{0xff01, 0xff60},
1254 	{0xffe0, 0xffe6},
1255 	{0x20000, 0x2fffd},
1256 	{0x30000, 0x3fffd}
1257     };
1258 
1259     /* Sorted list of non-overlapping intervals of East Asian Ambiguous
1260      * characters, generated with ../runtime/tools/unicode.vim. */
1261     static struct interval ambiguous[] =
1262     {
1263 	{0x00a1, 0x00a1},
1264 	{0x00a4, 0x00a4},
1265 	{0x00a7, 0x00a8},
1266 	{0x00aa, 0x00aa},
1267 	{0x00ad, 0x00ae},
1268 	{0x00b0, 0x00b4},
1269 	{0x00b6, 0x00ba},
1270 	{0x00bc, 0x00bf},
1271 	{0x00c6, 0x00c6},
1272 	{0x00d0, 0x00d0},
1273 	{0x00d7, 0x00d8},
1274 	{0x00de, 0x00e1},
1275 	{0x00e6, 0x00e6},
1276 	{0x00e8, 0x00ea},
1277 	{0x00ec, 0x00ed},
1278 	{0x00f0, 0x00f0},
1279 	{0x00f2, 0x00f3},
1280 	{0x00f7, 0x00fa},
1281 	{0x00fc, 0x00fc},
1282 	{0x00fe, 0x00fe},
1283 	{0x0101, 0x0101},
1284 	{0x0111, 0x0111},
1285 	{0x0113, 0x0113},
1286 	{0x011b, 0x011b},
1287 	{0x0126, 0x0127},
1288 	{0x012b, 0x012b},
1289 	{0x0131, 0x0133},
1290 	{0x0138, 0x0138},
1291 	{0x013f, 0x0142},
1292 	{0x0144, 0x0144},
1293 	{0x0148, 0x014b},
1294 	{0x014d, 0x014d},
1295 	{0x0152, 0x0153},
1296 	{0x0166, 0x0167},
1297 	{0x016b, 0x016b},
1298 	{0x01ce, 0x01ce},
1299 	{0x01d0, 0x01d0},
1300 	{0x01d2, 0x01d2},
1301 	{0x01d4, 0x01d4},
1302 	{0x01d6, 0x01d6},
1303 	{0x01d8, 0x01d8},
1304 	{0x01da, 0x01da},
1305 	{0x01dc, 0x01dc},
1306 	{0x0251, 0x0251},
1307 	{0x0261, 0x0261},
1308 	{0x02c4, 0x02c4},
1309 	{0x02c7, 0x02c7},
1310 	{0x02c9, 0x02cb},
1311 	{0x02cd, 0x02cd},
1312 	{0x02d0, 0x02d0},
1313 	{0x02d8, 0x02db},
1314 	{0x02dd, 0x02dd},
1315 	{0x02df, 0x02df},
1316 	{0x0300, 0x036f},
1317 	{0x0391, 0x03a1},
1318 	{0x03a3, 0x03a9},
1319 	{0x03b1, 0x03c1},
1320 	{0x03c3, 0x03c9},
1321 	{0x0401, 0x0401},
1322 	{0x0410, 0x044f},
1323 	{0x0451, 0x0451},
1324 	{0x2010, 0x2010},
1325 	{0x2013, 0x2016},
1326 	{0x2018, 0x2019},
1327 	{0x201c, 0x201d},
1328 	{0x2020, 0x2022},
1329 	{0x2024, 0x2027},
1330 	{0x2030, 0x2030},
1331 	{0x2032, 0x2033},
1332 	{0x2035, 0x2035},
1333 	{0x203b, 0x203b},
1334 	{0x203e, 0x203e},
1335 	{0x2074, 0x2074},
1336 	{0x207f, 0x207f},
1337 	{0x2081, 0x2084},
1338 	{0x20ac, 0x20ac},
1339 	{0x2103, 0x2103},
1340 	{0x2105, 0x2105},
1341 	{0x2109, 0x2109},
1342 	{0x2113, 0x2113},
1343 	{0x2116, 0x2116},
1344 	{0x2121, 0x2122},
1345 	{0x2126, 0x2126},
1346 	{0x212b, 0x212b},
1347 	{0x2153, 0x2154},
1348 	{0x215b, 0x215e},
1349 	{0x2160, 0x216b},
1350 	{0x2170, 0x2179},
1351 	{0x2189, 0x2189},
1352 	{0x2190, 0x2199},
1353 	{0x21b8, 0x21b9},
1354 	{0x21d2, 0x21d2},
1355 	{0x21d4, 0x21d4},
1356 	{0x21e7, 0x21e7},
1357 	{0x2200, 0x2200},
1358 	{0x2202, 0x2203},
1359 	{0x2207, 0x2208},
1360 	{0x220b, 0x220b},
1361 	{0x220f, 0x220f},
1362 	{0x2211, 0x2211},
1363 	{0x2215, 0x2215},
1364 	{0x221a, 0x221a},
1365 	{0x221d, 0x2220},
1366 	{0x2223, 0x2223},
1367 	{0x2225, 0x2225},
1368 	{0x2227, 0x222c},
1369 	{0x222e, 0x222e},
1370 	{0x2234, 0x2237},
1371 	{0x223c, 0x223d},
1372 	{0x2248, 0x2248},
1373 	{0x224c, 0x224c},
1374 	{0x2252, 0x2252},
1375 	{0x2260, 0x2261},
1376 	{0x2264, 0x2267},
1377 	{0x226a, 0x226b},
1378 	{0x226e, 0x226f},
1379 	{0x2282, 0x2283},
1380 	{0x2286, 0x2287},
1381 	{0x2295, 0x2295},
1382 	{0x2299, 0x2299},
1383 	{0x22a5, 0x22a5},
1384 	{0x22bf, 0x22bf},
1385 	{0x2312, 0x2312},
1386 	{0x2460, 0x24e9},
1387 	{0x24eb, 0x254b},
1388 	{0x2550, 0x2573},
1389 	{0x2580, 0x258f},
1390 	{0x2592, 0x2595},
1391 	{0x25a0, 0x25a1},
1392 	{0x25a3, 0x25a9},
1393 	{0x25b2, 0x25b3},
1394 	{0x25b6, 0x25b7},
1395 	{0x25bc, 0x25bd},
1396 	{0x25c0, 0x25c1},
1397 	{0x25c6, 0x25c8},
1398 	{0x25cb, 0x25cb},
1399 	{0x25ce, 0x25d1},
1400 	{0x25e2, 0x25e5},
1401 	{0x25ef, 0x25ef},
1402 	{0x2605, 0x2606},
1403 	{0x2609, 0x2609},
1404 	{0x260e, 0x260f},
1405 	{0x2614, 0x2615},
1406 	{0x261c, 0x261c},
1407 	{0x261e, 0x261e},
1408 	{0x2640, 0x2640},
1409 	{0x2642, 0x2642},
1410 	{0x2660, 0x2661},
1411 	{0x2663, 0x2665},
1412 	{0x2667, 0x266a},
1413 	{0x266c, 0x266d},
1414 	{0x266f, 0x266f},
1415 	{0x269e, 0x269f},
1416 	{0x26be, 0x26bf},
1417 	{0x26c4, 0x26cd},
1418 	{0x26cf, 0x26e1},
1419 	{0x26e3, 0x26e3},
1420 	{0x26e8, 0x26ff},
1421 	{0x273d, 0x273d},
1422 	{0x2757, 0x2757},
1423 	{0x2776, 0x277f},
1424 	{0x2b55, 0x2b59},
1425 	{0x3248, 0x324f},
1426 	{0xe000, 0xf8ff},
1427 	{0xfe00, 0xfe0f},
1428 	{0xfffd, 0xfffd},
1429 	{0x1f100, 0x1f10a},
1430 	{0x1f110, 0x1f12d},
1431 	{0x1f130, 0x1f169},
1432 	{0x1f170, 0x1f19a},
1433 	{0xe0100, 0xe01ef},
1434 	{0xf0000, 0xffffd},
1435 	{0x100000, 0x10fffd}
1436     };
1437 
1438     /* Sorted list of non-overlapping intervals of Emoji characters that don't
1439      * have ambiguous or double width,
1440      * based on http://unicode.org/emoji/charts/emoji-list.html */
1441     static struct interval emoji_width[] =
1442     {
1443 	{0x203c, 0x203c},
1444 	{0x2049, 0x2049},
1445 	{0x2139, 0x2139},
1446 	{0x21a9, 0x21aa},
1447 	{0x231a, 0x231b},
1448 	{0x2328, 0x2328},
1449 	{0x23cf, 0x23cf},
1450 	{0x23e9, 0x23f3},
1451 	{0x25aa, 0x25ab},
1452 	{0x25fb, 0x25fe},
1453 	{0x2600, 0x2604},
1454 	{0x2611, 0x2611},
1455 	{0x2618, 0x2618},
1456 	{0x261d, 0x261d},
1457 	{0x2620, 0x2620},
1458 	{0x2622, 0x2623},
1459 	{0x2626, 0x2626},
1460 	{0x262a, 0x262a},
1461 	{0x262e, 0x262f},
1462 	{0x2638, 0x263a},
1463 	{0x2648, 0x2653},
1464 	{0x2666, 0x2666},
1465 	{0x267b, 0x267b},
1466 	{0x267f, 0x267f},
1467 	{0x2692, 0x2694},
1468 	{0x2696, 0x2697},
1469 	{0x2699, 0x2699},
1470 	{0x269b, 0x269c},
1471 	{0x26a0, 0x26a1},
1472 	{0x26aa, 0x26ab},
1473 	{0x26b0, 0x26b1},
1474 	{0x26bd, 0x26bd},
1475 	{0x26ce, 0x26ce},
1476 	{0x2702, 0x2702},
1477 	{0x2705, 0x2705},
1478 	{0x2708, 0x270d},
1479 	{0x270f, 0x270f},
1480 	{0x2712, 0x2712},
1481 	{0x2714, 0x2714},
1482 	{0x2716, 0x2716},
1483 	{0x271d, 0x271d},
1484 	{0x2721, 0x2721},
1485 	{0x2728, 0x2728},
1486 	{0x2733, 0x2734},
1487 	{0x2744, 0x2744},
1488 	{0x2747, 0x2747},
1489 	{0x274c, 0x274c},
1490 	{0x274e, 0x274e},
1491 	{0x2753, 0x2755},
1492 	{0x2763, 0x2764},
1493 	{0x2795, 0x2797},
1494 	{0x27a1, 0x27a1},
1495 	{0x27b0, 0x27b0},
1496 	{0x27bf, 0x27bf},
1497 	{0x2934, 0x2935},
1498 	{0x2b05, 0x2b07},
1499 	{0x2b1b, 0x2b1c},
1500 	{0x2b50, 0x2b50},
1501 	{0x1f004, 0x1f004},
1502 	{0x1f0cf, 0x1f0cf},
1503 	{0x1f1e6, 0x1f1ff},
1504 	{0x1f300, 0x1f320},
1505 	{0x1f330, 0x1f335},
1506 	{0x1f337, 0x1f37c},
1507 	{0x1f380, 0x1f393},
1508 	{0x1f3a0, 0x1f3c4},
1509 	{0x1f3c6, 0x1f3ca},
1510 	{0x1f3e0, 0x1f3f0},
1511 	{0x1f400, 0x1f43e},
1512 	{0x1f440, 0x1f440},
1513 	{0x1f442, 0x1f4f7},
1514 	{0x1f4f9, 0x1f4fc},
1515 	{0x1f500, 0x1f53d},
1516 	{0x1f550, 0x1f567},
1517 	{0x1f5fb, 0x1f640},
1518 	{0x1f645, 0x1f64f},
1519 	{0x1f680, 0x1f6c5}
1520     };
1521 
1522     if (c >= 0x100)
1523     {
1524 #ifdef USE_WCHAR_FUNCTIONS
1525 	/*
1526 	 * Assume the library function wcwidth() works better than our own
1527 	 * stuff.  It should return 1 for ambiguous width chars!
1528 	 */
1529 	int	n = wcwidth(c);
1530 
1531 	if (n < 0)
1532 	    return 6;		/* unprintable, displays <xxxx> */
1533 	if (n > 1)
1534 	    return n;
1535 #else
1536 	if (!utf_printable(c))
1537 	    return 6;		/* unprintable, displays <xxxx> */
1538 	if (intable(doublewidth, sizeof(doublewidth), c))
1539 	    return 2;
1540 #endif
1541 	if (p_emoji && intable(emoji_width, sizeof(emoji_width), c))
1542 	    return 2;
1543     }
1544 
1545     /* Characters below 0x100 are influenced by 'isprint' option */
1546     else if (c >= 0x80 && !vim_isprintc(c))
1547 	return 4;		/* unprintable, displays <xx> */
1548 
1549     if (c >= 0x80 && *p_ambw == 'd' && intable(ambiguous, sizeof(ambiguous), c))
1550 	return 2;
1551 
1552     return 1;
1553 }
1554 
1555 /*
1556  * mb_ptr2cells() function pointer.
1557  * Return the number of display cells character at "*p" occupies.
1558  * This doesn't take care of unprintable characters, use ptr2cells() for that.
1559  */
1560     int
1561 latin_ptr2cells(char_u *p UNUSED)
1562 {
1563     return 1;
1564 }
1565 
1566     int
1567 utf_ptr2cells(
1568     char_u	*p)
1569 {
1570     int		c;
1571 
1572     /* Need to convert to a wide character. */
1573     if (*p >= 0x80)
1574     {
1575 	c = utf_ptr2char(p);
1576 	/* An illegal byte is displayed as <xx>. */
1577 	if (utf_ptr2len(p) == 1 || c == NUL)
1578 	    return 4;
1579 	/* If the char is ASCII it must be an overlong sequence. */
1580 	if (c < 0x80)
1581 	    return char2cells(c);
1582 	return utf_char2cells(c);
1583     }
1584     return 1;
1585 }
1586 
1587     int
1588 dbcs_ptr2cells(char_u *p)
1589 {
1590     /* Number of cells is equal to number of bytes, except for euc-jp when
1591      * the first byte is 0x8e. */
1592     if (enc_dbcs == DBCS_JPNU && *p == 0x8e)
1593 	return 1;
1594     return MB_BYTE2LEN(*p);
1595 }
1596 
1597 /*
1598  * mb_ptr2cells_len() function pointer.
1599  * Like mb_ptr2cells(), but limit string length to "size".
1600  * For an empty string or truncated character returns 1.
1601  */
1602     int
1603 latin_ptr2cells_len(char_u *p UNUSED, int size UNUSED)
1604 {
1605     return 1;
1606 }
1607 
1608     static int
1609 utf_ptr2cells_len(char_u *p, int size)
1610 {
1611     int		c;
1612 
1613     /* Need to convert to a wide character. */
1614     if (size > 0 && *p >= 0x80)
1615     {
1616 	if (utf_ptr2len_len(p, size) < utf8len_tab[*p])
1617 	    return 1;  /* truncated */
1618 	c = utf_ptr2char(p);
1619 	/* An illegal byte is displayed as <xx>. */
1620 	if (utf_ptr2len(p) == 1 || c == NUL)
1621 	    return 4;
1622 	/* If the char is ASCII it must be an overlong sequence. */
1623 	if (c < 0x80)
1624 	    return char2cells(c);
1625 	return utf_char2cells(c);
1626     }
1627     return 1;
1628 }
1629 
1630     static int
1631 dbcs_ptr2cells_len(char_u *p, int size)
1632 {
1633     /* Number of cells is equal to number of bytes, except for euc-jp when
1634      * the first byte is 0x8e. */
1635     if (size <= 1 || (enc_dbcs == DBCS_JPNU && *p == 0x8e))
1636 	return 1;
1637     return MB_BYTE2LEN(*p);
1638 }
1639 
1640 /*
1641  * mb_char2cells() function pointer.
1642  * Return the number of display cells character "c" occupies.
1643  * Only takes care of multi-byte chars, not "^C" and such.
1644  */
1645     int
1646 latin_char2cells(int c UNUSED)
1647 {
1648     return 1;
1649 }
1650 
1651     static int
1652 dbcs_char2cells(int c)
1653 {
1654     /* Number of cells is equal to number of bytes, except for euc-jp when
1655      * the first byte is 0x8e. */
1656     if (enc_dbcs == DBCS_JPNU && ((unsigned)c >> 8) == 0x8e)
1657 	return 1;
1658     /* use the first byte */
1659     return MB_BYTE2LEN((unsigned)c >> 8);
1660 }
1661 
1662 /*
1663  * Return the number of cells occupied by string "p".
1664  * Stop at a NUL character.  When "len" >= 0 stop at character "p[len]".
1665  */
1666     int
1667 mb_string2cells(char_u *p, int len)
1668 {
1669     int i;
1670     int clen = 0;
1671 
1672     for (i = 0; (len < 0 || i < len) && p[i] != NUL; i += (*mb_ptr2len)(p + i))
1673 	clen += (*mb_ptr2cells)(p + i);
1674     return clen;
1675 }
1676 
1677 /*
1678  * mb_off2cells() function pointer.
1679  * Return number of display cells for char at ScreenLines[off].
1680  * We make sure that the offset used is less than "max_off".
1681  */
1682     int
1683 latin_off2cells(unsigned off UNUSED, unsigned max_off UNUSED)
1684 {
1685     return 1;
1686 }
1687 
1688     int
1689 dbcs_off2cells(unsigned off, unsigned max_off)
1690 {
1691     /* never check beyond end of the line */
1692     if (off >= max_off)
1693 	return 1;
1694 
1695     /* Number of cells is equal to number of bytes, except for euc-jp when
1696      * the first byte is 0x8e. */
1697     if (enc_dbcs == DBCS_JPNU && ScreenLines[off] == 0x8e)
1698 	return 1;
1699     return MB_BYTE2LEN(ScreenLines[off]);
1700 }
1701 
1702     int
1703 utf_off2cells(unsigned off, unsigned max_off)
1704 {
1705     return (off + 1 < max_off && ScreenLines[off + 1] == 0) ? 2 : 1;
1706 }
1707 
1708 /*
1709  * mb_ptr2char() function pointer.
1710  * Convert a byte sequence into a character.
1711  */
1712     int
1713 latin_ptr2char(char_u *p)
1714 {
1715     return *p;
1716 }
1717 
1718     static int
1719 dbcs_ptr2char(char_u *p)
1720 {
1721     if (MB_BYTE2LEN(*p) > 1 && p[1] != NUL)
1722 	return (p[0] << 8) + p[1];
1723     return *p;
1724 }
1725 
1726 /*
1727  * Convert a UTF-8 byte sequence to a wide character.
1728  * If the sequence is illegal or truncated by a NUL the first byte is
1729  * returned.
1730  * Does not include composing characters, of course.
1731  */
1732     int
1733 utf_ptr2char(char_u *p)
1734 {
1735     int		len;
1736 
1737     if (p[0] < 0x80)	/* be quick for ASCII */
1738 	return p[0];
1739 
1740     len = utf8len_tab_zero[p[0]];
1741     if (len > 1 && (p[1] & 0xc0) == 0x80)
1742     {
1743 	if (len == 2)
1744 	    return ((p[0] & 0x1f) << 6) + (p[1] & 0x3f);
1745 	if ((p[2] & 0xc0) == 0x80)
1746 	{
1747 	    if (len == 3)
1748 		return ((p[0] & 0x0f) << 12) + ((p[1] & 0x3f) << 6)
1749 		    + (p[2] & 0x3f);
1750 	    if ((p[3] & 0xc0) == 0x80)
1751 	    {
1752 		if (len == 4)
1753 		    return ((p[0] & 0x07) << 18) + ((p[1] & 0x3f) << 12)
1754 			+ ((p[2] & 0x3f) << 6) + (p[3] & 0x3f);
1755 		if ((p[4] & 0xc0) == 0x80)
1756 		{
1757 		    if (len == 5)
1758 			return ((p[0] & 0x03) << 24) + ((p[1] & 0x3f) << 18)
1759 			    + ((p[2] & 0x3f) << 12) + ((p[3] & 0x3f) << 6)
1760 			    + (p[4] & 0x3f);
1761 		    if ((p[5] & 0xc0) == 0x80 && len == 6)
1762 			return ((p[0] & 0x01) << 30) + ((p[1] & 0x3f) << 24)
1763 			    + ((p[2] & 0x3f) << 18) + ((p[3] & 0x3f) << 12)
1764 			    + ((p[4] & 0x3f) << 6) + (p[5] & 0x3f);
1765 		}
1766 	    }
1767 	}
1768     }
1769     /* Illegal value, just return the first byte */
1770     return p[0];
1771 }
1772 
1773 /*
1774  * Convert a UTF-8 byte sequence to a wide character.
1775  * String is assumed to be terminated by NUL or after "n" bytes, whichever
1776  * comes first.
1777  * The function is safe in the sense that it never accesses memory beyond the
1778  * first "n" bytes of "s".
1779  *
1780  * On success, returns decoded codepoint, advances "s" to the beginning of
1781  * next character and decreases "n" accordingly.
1782  *
1783  * If end of string was reached, returns 0 and, if "n" > 0, advances "s" past
1784  * NUL byte.
1785  *
1786  * If byte sequence is illegal or incomplete, returns -1 and does not advance
1787  * "s".
1788  */
1789     static int
1790 utf_safe_read_char_adv(char_u **s, size_t *n)
1791 {
1792     int		c, k;
1793 
1794     if (*n == 0) /* end of buffer */
1795 	return 0;
1796 
1797     k = utf8len_tab_zero[**s];
1798 
1799     if (k == 1)
1800     {
1801 	/* ASCII character or NUL */
1802 	(*n)--;
1803 	return *(*s)++;
1804     }
1805 
1806     if ((size_t)k <= *n)
1807     {
1808 	/* We have a multibyte sequence and it isn't truncated by buffer
1809 	 * limits so utf_ptr2char() is safe to use. Or the first byte is
1810 	 * illegal (k=0), and it's also safe to use utf_ptr2char(). */
1811 	c = utf_ptr2char(*s);
1812 
1813 	/* On failure, utf_ptr2char() returns the first byte, so here we
1814 	 * check equality with the first byte. The only non-ASCII character
1815 	 * which equals the first byte of its own UTF-8 representation is
1816 	 * U+00C3 (UTF-8: 0xC3 0x83), so need to check that special case too.
1817 	 * It's safe even if n=1, else we would have k=2 > n. */
1818 	if (c != (int)(**s) || (c == 0xC3 && (*s)[1] == 0x83))
1819 	{
1820 	    /* byte sequence was successfully decoded */
1821 	    *s += k;
1822 	    *n -= k;
1823 	    return c;
1824 	}
1825     }
1826 
1827     /* byte sequence is incomplete or illegal */
1828     return -1;
1829 }
1830 
1831 /*
1832  * Get character at **pp and advance *pp to the next character.
1833  * Note: composing characters are skipped!
1834  */
1835     int
1836 mb_ptr2char_adv(char_u **pp)
1837 {
1838     int		c;
1839 
1840     c = (*mb_ptr2char)(*pp);
1841     *pp += (*mb_ptr2len)(*pp);
1842     return c;
1843 }
1844 
1845 /*
1846  * Get character at **pp and advance *pp to the next character.
1847  * Note: composing characters are returned as separate characters.
1848  */
1849     int
1850 mb_cptr2char_adv(char_u **pp)
1851 {
1852     int		c;
1853 
1854     c = (*mb_ptr2char)(*pp);
1855     if (enc_utf8)
1856 	*pp += utf_ptr2len(*pp);
1857     else
1858 	*pp += (*mb_ptr2len)(*pp);
1859     return c;
1860 }
1861 
1862 #if defined(FEAT_ARABIC) || defined(PROTO)
1863 /*
1864  * Check whether we are dealing with Arabic combining characters.
1865  * Note: these are NOT really composing characters!
1866  */
1867     int
1868 arabic_combine(
1869     int		one,	    /* first character */
1870     int		two)	    /* character just after "one" */
1871 {
1872     if (one == a_LAM)
1873 	return arabic_maycombine(two);
1874     return FALSE;
1875 }
1876 
1877 /*
1878  * Check whether we are dealing with a character that could be regarded as an
1879  * Arabic combining character, need to check the character before this.
1880  */
1881     int
1882 arabic_maycombine(int two)
1883 {
1884     if (p_arshape && !p_tbidi)
1885 	return (two == a_ALEF_MADDA
1886 		    || two == a_ALEF_HAMZA_ABOVE
1887 		    || two == a_ALEF_HAMZA_BELOW
1888 		    || two == a_ALEF);
1889     return FALSE;
1890 }
1891 
1892 /*
1893  * Check if the character pointed to by "p2" is a composing character when it
1894  * comes after "p1".  For Arabic sometimes "ab" is replaced with "c", which
1895  * behaves like a composing character.
1896  */
1897     int
1898 utf_composinglike(char_u *p1, char_u *p2)
1899 {
1900     int		c2;
1901 
1902     c2 = utf_ptr2char(p2);
1903     if (utf_iscomposing(c2))
1904 	return TRUE;
1905     if (!arabic_maycombine(c2))
1906 	return FALSE;
1907     return arabic_combine(utf_ptr2char(p1), c2);
1908 }
1909 #endif
1910 
1911 /*
1912  * Convert a UTF-8 byte string to a wide character.  Also get up to MAX_MCO
1913  * composing characters.
1914  */
1915     int
1916 utfc_ptr2char(
1917     char_u	*p,
1918     int		*pcc)	/* return: composing chars, last one is 0 */
1919 {
1920     int		len;
1921     int		c;
1922     int		cc;
1923     int		i = 0;
1924 
1925     c = utf_ptr2char(p);
1926     len = utf_ptr2len(p);
1927 
1928     /* Only accept a composing char when the first char isn't illegal. */
1929     if ((len > 1 || *p < 0x80)
1930 	    && p[len] >= 0x80
1931 	    && UTF_COMPOSINGLIKE(p, p + len))
1932     {
1933 	cc = utf_ptr2char(p + len);
1934 	for (;;)
1935 	{
1936 	    pcc[i++] = cc;
1937 	    if (i == MAX_MCO)
1938 		break;
1939 	    len += utf_ptr2len(p + len);
1940 	    if (p[len] < 0x80 || !utf_iscomposing(cc = utf_ptr2char(p + len)))
1941 		break;
1942 	}
1943     }
1944 
1945     if (i < MAX_MCO)	/* last composing char must be 0 */
1946 	pcc[i] = 0;
1947 
1948     return c;
1949 }
1950 
1951 /*
1952  * Convert a UTF-8 byte string to a wide character.  Also get up to MAX_MCO
1953  * composing characters.  Use no more than p[maxlen].
1954  */
1955     int
1956 utfc_ptr2char_len(
1957     char_u	*p,
1958     int		*pcc,	/* return: composing chars, last one is 0 */
1959     int		maxlen)
1960 {
1961     int		len;
1962     int		c;
1963     int		cc;
1964     int		i = 0;
1965 
1966     c = utf_ptr2char(p);
1967     len = utf_ptr2len_len(p, maxlen);
1968     /* Only accept a composing char when the first char isn't illegal. */
1969     if ((len > 1 || *p < 0x80)
1970 	    && len < maxlen
1971 	    && p[len] >= 0x80
1972 	    && UTF_COMPOSINGLIKE(p, p + len))
1973     {
1974 	cc = utf_ptr2char(p + len);
1975 	for (;;)
1976 	{
1977 	    pcc[i++] = cc;
1978 	    if (i == MAX_MCO)
1979 		break;
1980 	    len += utf_ptr2len_len(p + len, maxlen - len);
1981 	    if (len >= maxlen
1982 		    || p[len] < 0x80
1983 		    || !utf_iscomposing(cc = utf_ptr2char(p + len)))
1984 		break;
1985 	}
1986     }
1987 
1988     if (i < MAX_MCO)	/* last composing char must be 0 */
1989 	pcc[i] = 0;
1990 
1991     return c;
1992 }
1993 
1994 /*
1995  * Convert the character at screen position "off" to a sequence of bytes.
1996  * Includes the composing characters.
1997  * "buf" must at least have the length MB_MAXBYTES + 1.
1998  * Only to be used when ScreenLinesUC[off] != 0.
1999  * Returns the produced number of bytes.
2000  */
2001     int
2002 utfc_char2bytes(int off, char_u *buf)
2003 {
2004     int		len;
2005     int		i;
2006 
2007     len = utf_char2bytes(ScreenLinesUC[off], buf);
2008     for (i = 0; i < Screen_mco; ++i)
2009     {
2010 	if (ScreenLinesC[i][off] == 0)
2011 	    break;
2012 	len += utf_char2bytes(ScreenLinesC[i][off], buf + len);
2013     }
2014     return len;
2015 }
2016 
2017 /*
2018  * Get the length of a UTF-8 byte sequence, not including any following
2019  * composing characters.
2020  * Returns 0 for "".
2021  * Returns 1 for an illegal byte sequence.
2022  */
2023     int
2024 utf_ptr2len(char_u *p)
2025 {
2026     int		len;
2027     int		i;
2028 
2029     if (*p == NUL)
2030 	return 0;
2031     len = utf8len_tab[*p];
2032     for (i = 1; i < len; ++i)
2033 	if ((p[i] & 0xc0) != 0x80)
2034 	    return 1;
2035     return len;
2036 }
2037 
2038 /*
2039  * Return length of UTF-8 character, obtained from the first byte.
2040  * "b" must be between 0 and 255!
2041  * Returns 1 for an invalid first byte value.
2042  */
2043     int
2044 utf_byte2len(int b)
2045 {
2046     return utf8len_tab[b];
2047 }
2048 
2049 /*
2050  * Get the length of UTF-8 byte sequence "p[size]".  Does not include any
2051  * following composing characters.
2052  * Returns 1 for "".
2053  * Returns 1 for an illegal byte sequence (also in incomplete byte seq.).
2054  * Returns number > "size" for an incomplete byte sequence.
2055  * Never returns zero.
2056  */
2057     int
2058 utf_ptr2len_len(char_u *p, int size)
2059 {
2060     int		len;
2061     int		i;
2062     int		m;
2063 
2064     len = utf8len_tab[*p];
2065     if (len == 1)
2066 	return 1;	/* NUL, ascii or illegal lead byte */
2067     if (len > size)
2068 	m = size;	/* incomplete byte sequence. */
2069     else
2070 	m = len;
2071     for (i = 1; i < m; ++i)
2072 	if ((p[i] & 0xc0) != 0x80)
2073 	    return 1;
2074     return len;
2075 }
2076 
2077 /*
2078  * Return the number of bytes the UTF-8 encoding of the character at "p" takes.
2079  * This includes following composing characters.
2080  */
2081     int
2082 utfc_ptr2len(char_u *p)
2083 {
2084     int		len;
2085     int		b0 = *p;
2086 #ifdef FEAT_ARABIC
2087     int		prevlen;
2088 #endif
2089 
2090     if (b0 == NUL)
2091 	return 0;
2092     if (b0 < 0x80 && p[1] < 0x80)	/* be quick for ASCII */
2093 	return 1;
2094 
2095     /* Skip over first UTF-8 char, stopping at a NUL byte. */
2096     len = utf_ptr2len(p);
2097 
2098     /* Check for illegal byte. */
2099     if (len == 1 && b0 >= 0x80)
2100 	return 1;
2101 
2102     /*
2103      * Check for composing characters.  We can handle only the first six, but
2104      * skip all of them (otherwise the cursor would get stuck).
2105      */
2106 #ifdef FEAT_ARABIC
2107     prevlen = 0;
2108 #endif
2109     for (;;)
2110     {
2111 	if (p[len] < 0x80 || !UTF_COMPOSINGLIKE(p + prevlen, p + len))
2112 	    return len;
2113 
2114 	/* Skip over composing char */
2115 #ifdef FEAT_ARABIC
2116 	prevlen = len;
2117 #endif
2118 	len += utf_ptr2len(p + len);
2119     }
2120 }
2121 
2122 /*
2123  * Return the number of bytes the UTF-8 encoding of the character at "p[size]"
2124  * takes.  This includes following composing characters.
2125  * Returns 0 for an empty string.
2126  * Returns 1 for an illegal char or an incomplete byte sequence.
2127  */
2128     int
2129 utfc_ptr2len_len(char_u *p, int size)
2130 {
2131     int		len;
2132 #ifdef FEAT_ARABIC
2133     int		prevlen;
2134 #endif
2135 
2136     if (size < 1 || *p == NUL)
2137 	return 0;
2138     if (p[0] < 0x80 && (size == 1 || p[1] < 0x80)) /* be quick for ASCII */
2139 	return 1;
2140 
2141     /* Skip over first UTF-8 char, stopping at a NUL byte. */
2142     len = utf_ptr2len_len(p, size);
2143 
2144     /* Check for illegal byte and incomplete byte sequence. */
2145     if ((len == 1 && p[0] >= 0x80) || len > size)
2146 	return 1;
2147 
2148     /*
2149      * Check for composing characters.  We can handle only the first six, but
2150      * skip all of them (otherwise the cursor would get stuck).
2151      */
2152 #ifdef FEAT_ARABIC
2153     prevlen = 0;
2154 #endif
2155     while (len < size)
2156     {
2157 	int	len_next_char;
2158 
2159 	if (p[len] < 0x80)
2160 	    break;
2161 
2162 	/*
2163 	 * Next character length should not go beyond size to ensure that
2164 	 * UTF_COMPOSINGLIKE(...) does not read beyond size.
2165 	 */
2166 	len_next_char = utf_ptr2len_len(p + len, size - len);
2167 	if (len_next_char > size - len)
2168 	    break;
2169 
2170 	if (!UTF_COMPOSINGLIKE(p + prevlen, p + len))
2171 	    break;
2172 
2173 	/* Skip over composing char */
2174 #ifdef FEAT_ARABIC
2175 	prevlen = len;
2176 #endif
2177 	len += len_next_char;
2178     }
2179     return len;
2180 }
2181 
2182 /*
2183  * Return the number of bytes the UTF-8 encoding of character "c" takes.
2184  * This does not include composing characters.
2185  */
2186     int
2187 utf_char2len(int c)
2188 {
2189     if (c < 0x80)
2190 	return 1;
2191     if (c < 0x800)
2192 	return 2;
2193     if (c < 0x10000)
2194 	return 3;
2195     if (c < 0x200000)
2196 	return 4;
2197     if (c < 0x4000000)
2198 	return 5;
2199     return 6;
2200 }
2201 
2202 /*
2203  * Convert Unicode character "c" to UTF-8 string in "buf[]".
2204  * Returns the number of bytes.
2205  * This does not include composing characters.
2206  */
2207     int
2208 utf_char2bytes(int c, char_u *buf)
2209 {
2210     if (c < 0x80)		/* 7 bits */
2211     {
2212 	buf[0] = c;
2213 	return 1;
2214     }
2215     if (c < 0x800)		/* 11 bits */
2216     {
2217 	buf[0] = 0xc0 + ((unsigned)c >> 6);
2218 	buf[1] = 0x80 + (c & 0x3f);
2219 	return 2;
2220     }
2221     if (c < 0x10000)		/* 16 bits */
2222     {
2223 	buf[0] = 0xe0 + ((unsigned)c >> 12);
2224 	buf[1] = 0x80 + (((unsigned)c >> 6) & 0x3f);
2225 	buf[2] = 0x80 + (c & 0x3f);
2226 	return 3;
2227     }
2228     if (c < 0x200000)		/* 21 bits */
2229     {
2230 	buf[0] = 0xf0 + ((unsigned)c >> 18);
2231 	buf[1] = 0x80 + (((unsigned)c >> 12) & 0x3f);
2232 	buf[2] = 0x80 + (((unsigned)c >> 6) & 0x3f);
2233 	buf[3] = 0x80 + (c & 0x3f);
2234 	return 4;
2235     }
2236     if (c < 0x4000000)		/* 26 bits */
2237     {
2238 	buf[0] = 0xf8 + ((unsigned)c >> 24);
2239 	buf[1] = 0x80 + (((unsigned)c >> 18) & 0x3f);
2240 	buf[2] = 0x80 + (((unsigned)c >> 12) & 0x3f);
2241 	buf[3] = 0x80 + (((unsigned)c >> 6) & 0x3f);
2242 	buf[4] = 0x80 + (c & 0x3f);
2243 	return 5;
2244     }
2245 				/* 31 bits */
2246     buf[0] = 0xfc + ((unsigned)c >> 30);
2247     buf[1] = 0x80 + (((unsigned)c >> 24) & 0x3f);
2248     buf[2] = 0x80 + (((unsigned)c >> 18) & 0x3f);
2249     buf[3] = 0x80 + (((unsigned)c >> 12) & 0x3f);
2250     buf[4] = 0x80 + (((unsigned)c >> 6) & 0x3f);
2251     buf[5] = 0x80 + (c & 0x3f);
2252     return 6;
2253 }
2254 
2255 /*
2256  * Return TRUE if "c" is a composing UTF-8 character.  This means it will be
2257  * drawn on top of the preceding character.
2258  * Based on code from Markus Kuhn.
2259  */
2260     int
2261 utf_iscomposing(int c)
2262 {
2263     /* Sorted list of non-overlapping intervals.
2264      * Generated by ../runtime/tools/unicode.vim. */
2265     static struct interval combining[] =
2266     {
2267 	{0x0300, 0x036f},
2268 	{0x0483, 0x0489},
2269 	{0x0591, 0x05bd},
2270 	{0x05bf, 0x05bf},
2271 	{0x05c1, 0x05c2},
2272 	{0x05c4, 0x05c5},
2273 	{0x05c7, 0x05c7},
2274 	{0x0610, 0x061a},
2275 	{0x064b, 0x065f},
2276 	{0x0670, 0x0670},
2277 	{0x06d6, 0x06dc},
2278 	{0x06df, 0x06e4},
2279 	{0x06e7, 0x06e8},
2280 	{0x06ea, 0x06ed},
2281 	{0x0711, 0x0711},
2282 	{0x0730, 0x074a},
2283 	{0x07a6, 0x07b0},
2284 	{0x07eb, 0x07f3},
2285 	{0x0816, 0x0819},
2286 	{0x081b, 0x0823},
2287 	{0x0825, 0x0827},
2288 	{0x0829, 0x082d},
2289 	{0x0859, 0x085b},
2290 	{0x08e3, 0x0903},
2291 	{0x093a, 0x093c},
2292 	{0x093e, 0x094f},
2293 	{0x0951, 0x0957},
2294 	{0x0962, 0x0963},
2295 	{0x0981, 0x0983},
2296 	{0x09bc, 0x09bc},
2297 	{0x09be, 0x09c4},
2298 	{0x09c7, 0x09c8},
2299 	{0x09cb, 0x09cd},
2300 	{0x09d7, 0x09d7},
2301 	{0x09e2, 0x09e3},
2302 	{0x0a01, 0x0a03},
2303 	{0x0a3c, 0x0a3c},
2304 	{0x0a3e, 0x0a42},
2305 	{0x0a47, 0x0a48},
2306 	{0x0a4b, 0x0a4d},
2307 	{0x0a51, 0x0a51},
2308 	{0x0a70, 0x0a71},
2309 	{0x0a75, 0x0a75},
2310 	{0x0a81, 0x0a83},
2311 	{0x0abc, 0x0abc},
2312 	{0x0abe, 0x0ac5},
2313 	{0x0ac7, 0x0ac9},
2314 	{0x0acb, 0x0acd},
2315 	{0x0ae2, 0x0ae3},
2316 	{0x0b01, 0x0b03},
2317 	{0x0b3c, 0x0b3c},
2318 	{0x0b3e, 0x0b44},
2319 	{0x0b47, 0x0b48},
2320 	{0x0b4b, 0x0b4d},
2321 	{0x0b56, 0x0b57},
2322 	{0x0b62, 0x0b63},
2323 	{0x0b82, 0x0b82},
2324 	{0x0bbe, 0x0bc2},
2325 	{0x0bc6, 0x0bc8},
2326 	{0x0bca, 0x0bcd},
2327 	{0x0bd7, 0x0bd7},
2328 	{0x0c00, 0x0c03},
2329 	{0x0c3e, 0x0c44},
2330 	{0x0c46, 0x0c48},
2331 	{0x0c4a, 0x0c4d},
2332 	{0x0c55, 0x0c56},
2333 	{0x0c62, 0x0c63},
2334 	{0x0c81, 0x0c83},
2335 	{0x0cbc, 0x0cbc},
2336 	{0x0cbe, 0x0cc4},
2337 	{0x0cc6, 0x0cc8},
2338 	{0x0cca, 0x0ccd},
2339 	{0x0cd5, 0x0cd6},
2340 	{0x0ce2, 0x0ce3},
2341 	{0x0d01, 0x0d03},
2342 	{0x0d3e, 0x0d44},
2343 	{0x0d46, 0x0d48},
2344 	{0x0d4a, 0x0d4d},
2345 	{0x0d57, 0x0d57},
2346 	{0x0d62, 0x0d63},
2347 	{0x0d82, 0x0d83},
2348 	{0x0dca, 0x0dca},
2349 	{0x0dcf, 0x0dd4},
2350 	{0x0dd6, 0x0dd6},
2351 	{0x0dd8, 0x0ddf},
2352 	{0x0df2, 0x0df3},
2353 	{0x0e31, 0x0e31},
2354 	{0x0e34, 0x0e3a},
2355 	{0x0e47, 0x0e4e},
2356 	{0x0eb1, 0x0eb1},
2357 	{0x0eb4, 0x0eb9},
2358 	{0x0ebb, 0x0ebc},
2359 	{0x0ec8, 0x0ecd},
2360 	{0x0f18, 0x0f19},
2361 	{0x0f35, 0x0f35},
2362 	{0x0f37, 0x0f37},
2363 	{0x0f39, 0x0f39},
2364 	{0x0f3e, 0x0f3f},
2365 	{0x0f71, 0x0f84},
2366 	{0x0f86, 0x0f87},
2367 	{0x0f8d, 0x0f97},
2368 	{0x0f99, 0x0fbc},
2369 	{0x0fc6, 0x0fc6},
2370 	{0x102b, 0x103e},
2371 	{0x1056, 0x1059},
2372 	{0x105e, 0x1060},
2373 	{0x1062, 0x1064},
2374 	{0x1067, 0x106d},
2375 	{0x1071, 0x1074},
2376 	{0x1082, 0x108d},
2377 	{0x108f, 0x108f},
2378 	{0x109a, 0x109d},
2379 	{0x135d, 0x135f},
2380 	{0x1712, 0x1714},
2381 	{0x1732, 0x1734},
2382 	{0x1752, 0x1753},
2383 	{0x1772, 0x1773},
2384 	{0x17b4, 0x17d3},
2385 	{0x17dd, 0x17dd},
2386 	{0x180b, 0x180d},
2387 	{0x18a9, 0x18a9},
2388 	{0x1920, 0x192b},
2389 	{0x1930, 0x193b},
2390 	{0x1a17, 0x1a1b},
2391 	{0x1a55, 0x1a5e},
2392 	{0x1a60, 0x1a7c},
2393 	{0x1a7f, 0x1a7f},
2394 	{0x1ab0, 0x1abe},
2395 	{0x1b00, 0x1b04},
2396 	{0x1b34, 0x1b44},
2397 	{0x1b6b, 0x1b73},
2398 	{0x1b80, 0x1b82},
2399 	{0x1ba1, 0x1bad},
2400 	{0x1be6, 0x1bf3},
2401 	{0x1c24, 0x1c37},
2402 	{0x1cd0, 0x1cd2},
2403 	{0x1cd4, 0x1ce8},
2404 	{0x1ced, 0x1ced},
2405 	{0x1cf2, 0x1cf4},
2406 	{0x1cf8, 0x1cf9},
2407 	{0x1dc0, 0x1df5},
2408 	{0x1dfc, 0x1dff},
2409 	{0x20d0, 0x20f0},
2410 	{0x2cef, 0x2cf1},
2411 	{0x2d7f, 0x2d7f},
2412 	{0x2de0, 0x2dff},
2413 	{0x302a, 0x302f},
2414 	{0x3099, 0x309a},
2415 	{0xa66f, 0xa672},
2416 	{0xa674, 0xa67d},
2417 	{0xa69e, 0xa69f},
2418 	{0xa6f0, 0xa6f1},
2419 	{0xa802, 0xa802},
2420 	{0xa806, 0xa806},
2421 	{0xa80b, 0xa80b},
2422 	{0xa823, 0xa827},
2423 	{0xa880, 0xa881},
2424 	{0xa8b4, 0xa8c4},
2425 	{0xa8e0, 0xa8f1},
2426 	{0xa926, 0xa92d},
2427 	{0xa947, 0xa953},
2428 	{0xa980, 0xa983},
2429 	{0xa9b3, 0xa9c0},
2430 	{0xa9e5, 0xa9e5},
2431 	{0xaa29, 0xaa36},
2432 	{0xaa43, 0xaa43},
2433 	{0xaa4c, 0xaa4d},
2434 	{0xaa7b, 0xaa7d},
2435 	{0xaab0, 0xaab0},
2436 	{0xaab2, 0xaab4},
2437 	{0xaab7, 0xaab8},
2438 	{0xaabe, 0xaabf},
2439 	{0xaac1, 0xaac1},
2440 	{0xaaeb, 0xaaef},
2441 	{0xaaf5, 0xaaf6},
2442 	{0xabe3, 0xabea},
2443 	{0xabec, 0xabed},
2444 	{0xfb1e, 0xfb1e},
2445 	{0xfe00, 0xfe0f},
2446 	{0xfe20, 0xfe2f},
2447 	{0x101fd, 0x101fd},
2448 	{0x102e0, 0x102e0},
2449 	{0x10376, 0x1037a},
2450 	{0x10a01, 0x10a03},
2451 	{0x10a05, 0x10a06},
2452 	{0x10a0c, 0x10a0f},
2453 	{0x10a38, 0x10a3a},
2454 	{0x10a3f, 0x10a3f},
2455 	{0x10ae5, 0x10ae6},
2456 	{0x11000, 0x11002},
2457 	{0x11038, 0x11046},
2458 	{0x1107f, 0x11082},
2459 	{0x110b0, 0x110ba},
2460 	{0x11100, 0x11102},
2461 	{0x11127, 0x11134},
2462 	{0x11173, 0x11173},
2463 	{0x11180, 0x11182},
2464 	{0x111b3, 0x111c0},
2465 	{0x111ca, 0x111cc},
2466 	{0x1122c, 0x11237},
2467 	{0x112df, 0x112ea},
2468 	{0x11300, 0x11303},
2469 	{0x1133c, 0x1133c},
2470 	{0x1133e, 0x11344},
2471 	{0x11347, 0x11348},
2472 	{0x1134b, 0x1134d},
2473 	{0x11357, 0x11357},
2474 	{0x11362, 0x11363},
2475 	{0x11366, 0x1136c},
2476 	{0x11370, 0x11374},
2477 	{0x114b0, 0x114c3},
2478 	{0x115af, 0x115b5},
2479 	{0x115b8, 0x115c0},
2480 	{0x115dc, 0x115dd},
2481 	{0x11630, 0x11640},
2482 	{0x116ab, 0x116b7},
2483 	{0x1171d, 0x1172b},
2484 	{0x16af0, 0x16af4},
2485 	{0x16b30, 0x16b36},
2486 	{0x16f51, 0x16f7e},
2487 	{0x16f8f, 0x16f92},
2488 	{0x1bc9d, 0x1bc9e},
2489 	{0x1d165, 0x1d169},
2490 	{0x1d16d, 0x1d172},
2491 	{0x1d17b, 0x1d182},
2492 	{0x1d185, 0x1d18b},
2493 	{0x1d1aa, 0x1d1ad},
2494 	{0x1d242, 0x1d244},
2495 	{0x1da00, 0x1da36},
2496 	{0x1da3b, 0x1da6c},
2497 	{0x1da75, 0x1da75},
2498 	{0x1da84, 0x1da84},
2499 	{0x1da9b, 0x1da9f},
2500 	{0x1daa1, 0x1daaf},
2501 	{0x1e8d0, 0x1e8d6},
2502 	{0xe0100, 0xe01ef}
2503     };
2504 
2505     return intable(combining, sizeof(combining), c);
2506 }
2507 
2508 /*
2509  * Return TRUE for characters that can be displayed in a normal way.
2510  * Only for characters of 0x100 and above!
2511  */
2512     int
2513 utf_printable(int c)
2514 {
2515 #ifdef USE_WCHAR_FUNCTIONS
2516     /*
2517      * Assume the iswprint() library function works better than our own stuff.
2518      */
2519     return iswprint(c);
2520 #else
2521     /* Sorted list of non-overlapping intervals.
2522      * 0xd800-0xdfff is reserved for UTF-16, actually illegal. */
2523     static struct interval nonprint[] =
2524     {
2525 	{0x070f, 0x070f}, {0x180b, 0x180e}, {0x200b, 0x200f}, {0x202a, 0x202e},
2526 	{0x206a, 0x206f}, {0xd800, 0xdfff}, {0xfeff, 0xfeff}, {0xfff9, 0xfffb},
2527 	{0xfffe, 0xffff}
2528     };
2529 
2530     return !intable(nonprint, sizeof(nonprint), c);
2531 #endif
2532 }
2533 
2534 /*
2535  * Get class of a Unicode character.
2536  * 0: white space
2537  * 1: punctuation
2538  * 2 or bigger: some class of word character.
2539  */
2540     int
2541 utf_class(int c)
2542 {
2543     /* sorted list of non-overlapping intervals */
2544     static struct clinterval
2545     {
2546 	unsigned int first;
2547 	unsigned int last;
2548 	unsigned int class;
2549     } classes[] =
2550     {
2551 	{0x037e, 0x037e, 1},		/* Greek question mark */
2552 	{0x0387, 0x0387, 1},		/* Greek ano teleia */
2553 	{0x055a, 0x055f, 1},		/* Armenian punctuation */
2554 	{0x0589, 0x0589, 1},		/* Armenian full stop */
2555 	{0x05be, 0x05be, 1},
2556 	{0x05c0, 0x05c0, 1},
2557 	{0x05c3, 0x05c3, 1},
2558 	{0x05f3, 0x05f4, 1},
2559 	{0x060c, 0x060c, 1},
2560 	{0x061b, 0x061b, 1},
2561 	{0x061f, 0x061f, 1},
2562 	{0x066a, 0x066d, 1},
2563 	{0x06d4, 0x06d4, 1},
2564 	{0x0700, 0x070d, 1},		/* Syriac punctuation */
2565 	{0x0964, 0x0965, 1},
2566 	{0x0970, 0x0970, 1},
2567 	{0x0df4, 0x0df4, 1},
2568 	{0x0e4f, 0x0e4f, 1},
2569 	{0x0e5a, 0x0e5b, 1},
2570 	{0x0f04, 0x0f12, 1},
2571 	{0x0f3a, 0x0f3d, 1},
2572 	{0x0f85, 0x0f85, 1},
2573 	{0x104a, 0x104f, 1},		/* Myanmar punctuation */
2574 	{0x10fb, 0x10fb, 1},		/* Georgian punctuation */
2575 	{0x1361, 0x1368, 1},		/* Ethiopic punctuation */
2576 	{0x166d, 0x166e, 1},		/* Canadian Syl. punctuation */
2577 	{0x1680, 0x1680, 0},
2578 	{0x169b, 0x169c, 1},
2579 	{0x16eb, 0x16ed, 1},
2580 	{0x1735, 0x1736, 1},
2581 	{0x17d4, 0x17dc, 1},		/* Khmer punctuation */
2582 	{0x1800, 0x180a, 1},		/* Mongolian punctuation */
2583 	{0x2000, 0x200b, 0},		/* spaces */
2584 	{0x200c, 0x2027, 1},		/* punctuation and symbols */
2585 	{0x2028, 0x2029, 0},
2586 	{0x202a, 0x202e, 1},		/* punctuation and symbols */
2587 	{0x202f, 0x202f, 0},
2588 	{0x2030, 0x205e, 1},		/* punctuation and symbols */
2589 	{0x205f, 0x205f, 0},
2590 	{0x2060, 0x27ff, 1},		/* punctuation and symbols */
2591 	{0x2070, 0x207f, 0x2070},	/* superscript */
2592 	{0x2080, 0x2094, 0x2080},	/* subscript */
2593 	{0x20a0, 0x27ff, 1},		/* all kinds of symbols */
2594 	{0x2800, 0x28ff, 0x2800},	/* braille */
2595 	{0x2900, 0x2998, 1},		/* arrows, brackets, etc. */
2596 	{0x29d8, 0x29db, 1},
2597 	{0x29fc, 0x29fd, 1},
2598 	{0x2e00, 0x2e7f, 1},		/* supplemental punctuation */
2599 	{0x3000, 0x3000, 0},		/* ideographic space */
2600 	{0x3001, 0x3020, 1},		/* ideographic punctuation */
2601 	{0x3030, 0x3030, 1},
2602 	{0x303d, 0x303d, 1},
2603 	{0x3040, 0x309f, 0x3040},	/* Hiragana */
2604 	{0x30a0, 0x30ff, 0x30a0},	/* Katakana */
2605 	{0x3300, 0x9fff, 0x4e00},	/* CJK Ideographs */
2606 	{0xac00, 0xd7a3, 0xac00},	/* Hangul Syllables */
2607 	{0xf900, 0xfaff, 0x4e00},	/* CJK Ideographs */
2608 	{0xfd3e, 0xfd3f, 1},
2609 	{0xfe30, 0xfe6b, 1},		/* punctuation forms */
2610 	{0xff00, 0xff0f, 1},		/* half/fullwidth ASCII */
2611 	{0xff1a, 0xff20, 1},		/* half/fullwidth ASCII */
2612 	{0xff3b, 0xff40, 1},		/* half/fullwidth ASCII */
2613 	{0xff5b, 0xff65, 1},		/* half/fullwidth ASCII */
2614 	{0x20000, 0x2a6df, 0x4e00},	/* CJK Ideographs */
2615 	{0x2a700, 0x2b73f, 0x4e00},	/* CJK Ideographs */
2616 	{0x2b740, 0x2b81f, 0x4e00},	/* CJK Ideographs */
2617 	{0x2f800, 0x2fa1f, 0x4e00},	/* CJK Ideographs */
2618     };
2619 
2620     /* Sorted list of non-overlapping intervals of all Emoji characters,
2621      * based on http://unicode.org/emoji/charts/emoji-list.html */
2622     static struct interval emoji_all[] =
2623     {
2624 	{0x203c, 0x203c},
2625 	{0x2049, 0x2049},
2626 	{0x2122, 0x2122},
2627 	{0x2139, 0x2139},
2628 	{0x2194, 0x2199},
2629 	{0x21a9, 0x21aa},
2630 	{0x231a, 0x231b},
2631 	{0x2328, 0x2328},
2632 	{0x23cf, 0x23cf},
2633 	{0x23e9, 0x23f3},
2634 	{0x24c2, 0x24c2},
2635 	{0x25aa, 0x25ab},
2636 	{0x25b6, 0x25b6},
2637 	{0x25c0, 0x25c0},
2638 	{0x25fb, 0x25fe},
2639 	{0x2600, 0x2604},
2640 	{0x260e, 0x260e},
2641 	{0x2611, 0x2611},
2642 	{0x2614, 0x2615},
2643 	{0x2618, 0x2618},
2644 	{0x261d, 0x261d},
2645 	{0x2620, 0x2620},
2646 	{0x2622, 0x2623},
2647 	{0x2626, 0x2626},
2648 	{0x262a, 0x262a},
2649 	{0x262e, 0x262f},
2650 	{0x2638, 0x263a},
2651 	{0x2648, 0x2653},
2652 	{0x2660, 0x2660},
2653 	{0x2663, 0x2663},
2654 	{0x2665, 0x2666},
2655 	{0x2668, 0x2668},
2656 	{0x267b, 0x267b},
2657 	{0x267f, 0x267f},
2658 	{0x2692, 0x2694},
2659 	{0x2696, 0x2697},
2660 	{0x2699, 0x2699},
2661 	{0x269b, 0x269c},
2662 	{0x26a0, 0x26a1},
2663 	{0x26aa, 0x26ab},
2664 	{0x26b0, 0x26b1},
2665 	{0x26bd, 0x26be},
2666 	{0x26c4, 0x26c5},
2667 	{0x26c8, 0x26c8},
2668 	{0x26ce, 0x26cf},
2669 	{0x26d1, 0x26d1},
2670 	{0x26d3, 0x26d4},
2671 	{0x26e9, 0x26ea},
2672 	{0x26f0, 0x26f5},
2673 	{0x26f7, 0x26fa},
2674 	{0x26fd, 0x26fd},
2675 	{0x2702, 0x2702},
2676 	{0x2705, 0x2705},
2677 	{0x2708, 0x270d},
2678 	{0x270f, 0x270f},
2679 	{0x2712, 0x2712},
2680 	{0x2714, 0x2714},
2681 	{0x2716, 0x2716},
2682 	{0x271d, 0x271d},
2683 	{0x2721, 0x2721},
2684 	{0x2728, 0x2728},
2685 	{0x2733, 0x2734},
2686 	{0x2744, 0x2744},
2687 	{0x2747, 0x2747},
2688 	{0x274c, 0x274c},
2689 	{0x274e, 0x274e},
2690 	{0x2753, 0x2755},
2691 	{0x2757, 0x2757},
2692 	{0x2763, 0x2764},
2693 	{0x2795, 0x2797},
2694 	{0x27a1, 0x27a1},
2695 	{0x27b0, 0x27b0},
2696 	{0x27bf, 0x27bf},
2697 	{0x2934, 0x2935},
2698 	{0x2b05, 0x2b07},
2699 	{0x2b1b, 0x2b1c},
2700 	{0x2b50, 0x2b50},
2701 	{0x2b55, 0x2b55},
2702 	{0x3030, 0x3030},
2703 	{0x303d, 0x303d},
2704 	{0x3297, 0x3297},
2705 	{0x3299, 0x3299},
2706 	{0x1f004, 0x1f004},
2707 	{0x1f0cf, 0x1f0cf},
2708 	{0x1f170, 0x1f171},
2709 	{0x1f17e, 0x1f17f},
2710 	{0x1f18e, 0x1f18e},
2711 	{0x1f191, 0x1f19a},
2712 	{0x1f1e6, 0x1f1ff},
2713 	{0x1f201, 0x1f202},
2714 	{0x1f21a, 0x1f21a},
2715 	{0x1f22f, 0x1f22f},
2716 	{0x1f232, 0x1f23a},
2717 	{0x1f250, 0x1f251},
2718 	{0x1f300, 0x1f320},
2719 	{0x1f330, 0x1f335},
2720 	{0x1f337, 0x1f37c},
2721 	{0x1f380, 0x1f393},
2722 	{0x1f3a0, 0x1f3c4},
2723 	{0x1f3c6, 0x1f3ca},
2724 	{0x1f3e0, 0x1f3f0},
2725 	{0x1f400, 0x1f43e},
2726 	{0x1f440, 0x1f440},
2727 	{0x1f442, 0x1f4f7},
2728 	{0x1f4f9, 0x1f4fc},
2729 	{0x1f500, 0x1f53d},
2730 	{0x1f550, 0x1f567},
2731 	{0x1f5fb, 0x1f640},
2732 	{0x1f645, 0x1f64f},
2733 	{0x1f680, 0x1f6c5}
2734     };
2735 
2736     int bot = 0;
2737     int top = sizeof(classes) / sizeof(struct clinterval) - 1;
2738     int mid;
2739 
2740     /* First quick check for Latin1 characters, use 'iskeyword'. */
2741     if (c < 0x100)
2742     {
2743 	if (c == ' ' || c == '\t' || c == NUL || c == 0xa0)
2744 	    return 0;	    /* blank */
2745 	if (vim_iswordc(c))
2746 	    return 2;	    /* word character */
2747 	return 1;	    /* punctuation */
2748     }
2749 
2750     /* binary search in table */
2751     while (top >= bot)
2752     {
2753 	mid = (bot + top) / 2;
2754 	if (classes[mid].last < (unsigned int)c)
2755 	    bot = mid + 1;
2756 	else if (classes[mid].first > (unsigned int)c)
2757 	    top = mid - 1;
2758 	else
2759 	    return (int)classes[mid].class;
2760     }
2761 
2762     /* emoji */
2763     if (intable(emoji_all, sizeof(emoji_all), c))
2764 	return 3;
2765 
2766     /* most other characters are "word" characters */
2767     return 2;
2768 }
2769 
2770 /*
2771  * Code for Unicode case-dependent operations.  Based on notes in
2772  * http://www.unicode.org/Public/UNIDATA/CaseFolding.txt
2773  * This code uses simple case folding, not full case folding.
2774  * Last updated for Unicode 5.2.
2775  */
2776 
2777 /*
2778  * The following tables are built by ../runtime/tools/unicode.vim.
2779  * They must be in numeric order, because we use binary search.
2780  * An entry such as {0x41,0x5a,1,32} means that Unicode characters in the
2781  * range from 0x41 to 0x5a inclusive, stepping by 1, are changed to
2782  * folded/upper/lower by adding 32.
2783  */
2784 typedef struct
2785 {
2786     int rangeStart;
2787     int rangeEnd;
2788     int step;
2789     int offset;
2790 } convertStruct;
2791 
2792 static convertStruct foldCase[] =
2793 {
2794 	{0x41,0x5a,1,32},
2795 	{0xb5,0xb5,-1,775},
2796 	{0xc0,0xd6,1,32},
2797 	{0xd8,0xde,1,32},
2798 	{0x100,0x12e,2,1},
2799 	{0x132,0x136,2,1},
2800 	{0x139,0x147,2,1},
2801 	{0x14a,0x176,2,1},
2802 	{0x178,0x178,-1,-121},
2803 	{0x179,0x17d,2,1},
2804 	{0x17f,0x17f,-1,-268},
2805 	{0x181,0x181,-1,210},
2806 	{0x182,0x184,2,1},
2807 	{0x186,0x186,-1,206},
2808 	{0x187,0x187,-1,1},
2809 	{0x189,0x18a,1,205},
2810 	{0x18b,0x18b,-1,1},
2811 	{0x18e,0x18e,-1,79},
2812 	{0x18f,0x18f,-1,202},
2813 	{0x190,0x190,-1,203},
2814 	{0x191,0x191,-1,1},
2815 	{0x193,0x193,-1,205},
2816 	{0x194,0x194,-1,207},
2817 	{0x196,0x196,-1,211},
2818 	{0x197,0x197,-1,209},
2819 	{0x198,0x198,-1,1},
2820 	{0x19c,0x19c,-1,211},
2821 	{0x19d,0x19d,-1,213},
2822 	{0x19f,0x19f,-1,214},
2823 	{0x1a0,0x1a4,2,1},
2824 	{0x1a6,0x1a6,-1,218},
2825 	{0x1a7,0x1a7,-1,1},
2826 	{0x1a9,0x1a9,-1,218},
2827 	{0x1ac,0x1ac,-1,1},
2828 	{0x1ae,0x1ae,-1,218},
2829 	{0x1af,0x1af,-1,1},
2830 	{0x1b1,0x1b2,1,217},
2831 	{0x1b3,0x1b5,2,1},
2832 	{0x1b7,0x1b7,-1,219},
2833 	{0x1b8,0x1bc,4,1},
2834 	{0x1c4,0x1c4,-1,2},
2835 	{0x1c5,0x1c5,-1,1},
2836 	{0x1c7,0x1c7,-1,2},
2837 	{0x1c8,0x1c8,-1,1},
2838 	{0x1ca,0x1ca,-1,2},
2839 	{0x1cb,0x1db,2,1},
2840 	{0x1de,0x1ee,2,1},
2841 	{0x1f1,0x1f1,-1,2},
2842 	{0x1f2,0x1f4,2,1},
2843 	{0x1f6,0x1f6,-1,-97},
2844 	{0x1f7,0x1f7,-1,-56},
2845 	{0x1f8,0x21e,2,1},
2846 	{0x220,0x220,-1,-130},
2847 	{0x222,0x232,2,1},
2848 	{0x23a,0x23a,-1,10795},
2849 	{0x23b,0x23b,-1,1},
2850 	{0x23d,0x23d,-1,-163},
2851 	{0x23e,0x23e,-1,10792},
2852 	{0x241,0x241,-1,1},
2853 	{0x243,0x243,-1,-195},
2854 	{0x244,0x244,-1,69},
2855 	{0x245,0x245,-1,71},
2856 	{0x246,0x24e,2,1},
2857 	{0x345,0x345,-1,116},
2858 	{0x370,0x372,2,1},
2859 	{0x376,0x376,-1,1},
2860 	{0x37f,0x37f,-1,116},
2861 	{0x386,0x386,-1,38},
2862 	{0x388,0x38a,1,37},
2863 	{0x38c,0x38c,-1,64},
2864 	{0x38e,0x38f,1,63},
2865 	{0x391,0x3a1,1,32},
2866 	{0x3a3,0x3ab,1,32},
2867 	{0x3c2,0x3c2,-1,1},
2868 	{0x3cf,0x3cf,-1,8},
2869 	{0x3d0,0x3d0,-1,-30},
2870 	{0x3d1,0x3d1,-1,-25},
2871 	{0x3d5,0x3d5,-1,-15},
2872 	{0x3d6,0x3d6,-1,-22},
2873 	{0x3d8,0x3ee,2,1},
2874 	{0x3f0,0x3f0,-1,-54},
2875 	{0x3f1,0x3f1,-1,-48},
2876 	{0x3f4,0x3f4,-1,-60},
2877 	{0x3f5,0x3f5,-1,-64},
2878 	{0x3f7,0x3f7,-1,1},
2879 	{0x3f9,0x3f9,-1,-7},
2880 	{0x3fa,0x3fa,-1,1},
2881 	{0x3fd,0x3ff,1,-130},
2882 	{0x400,0x40f,1,80},
2883 	{0x410,0x42f,1,32},
2884 	{0x460,0x480,2,1},
2885 	{0x48a,0x4be,2,1},
2886 	{0x4c0,0x4c0,-1,15},
2887 	{0x4c1,0x4cd,2,1},
2888 	{0x4d0,0x52e,2,1},
2889 	{0x531,0x556,1,48},
2890 	{0x10a0,0x10c5,1,7264},
2891 	{0x10c7,0x10cd,6,7264},
2892 	{0x13f8,0x13fd,1,-8},
2893 	{0x1e00,0x1e94,2,1},
2894 	{0x1e9b,0x1e9b,-1,-58},
2895 	{0x1e9e,0x1e9e,-1,-7615},
2896 	{0x1ea0,0x1efe,2,1},
2897 	{0x1f08,0x1f0f,1,-8},
2898 	{0x1f18,0x1f1d,1,-8},
2899 	{0x1f28,0x1f2f,1,-8},
2900 	{0x1f38,0x1f3f,1,-8},
2901 	{0x1f48,0x1f4d,1,-8},
2902 	{0x1f59,0x1f5f,2,-8},
2903 	{0x1f68,0x1f6f,1,-8},
2904 	{0x1f88,0x1f8f,1,-8},
2905 	{0x1f98,0x1f9f,1,-8},
2906 	{0x1fa8,0x1faf,1,-8},
2907 	{0x1fb8,0x1fb9,1,-8},
2908 	{0x1fba,0x1fbb,1,-74},
2909 	{0x1fbc,0x1fbc,-1,-9},
2910 	{0x1fbe,0x1fbe,-1,-7173},
2911 	{0x1fc8,0x1fcb,1,-86},
2912 	{0x1fcc,0x1fcc,-1,-9},
2913 	{0x1fd8,0x1fd9,1,-8},
2914 	{0x1fda,0x1fdb,1,-100},
2915 	{0x1fe8,0x1fe9,1,-8},
2916 	{0x1fea,0x1feb,1,-112},
2917 	{0x1fec,0x1fec,-1,-7},
2918 	{0x1ff8,0x1ff9,1,-128},
2919 	{0x1ffa,0x1ffb,1,-126},
2920 	{0x1ffc,0x1ffc,-1,-9},
2921 	{0x2126,0x2126,-1,-7517},
2922 	{0x212a,0x212a,-1,-8383},
2923 	{0x212b,0x212b,-1,-8262},
2924 	{0x2132,0x2132,-1,28},
2925 	{0x2160,0x216f,1,16},
2926 	{0x2183,0x2183,-1,1},
2927 	{0x24b6,0x24cf,1,26},
2928 	{0x2c00,0x2c2e,1,48},
2929 	{0x2c60,0x2c60,-1,1},
2930 	{0x2c62,0x2c62,-1,-10743},
2931 	{0x2c63,0x2c63,-1,-3814},
2932 	{0x2c64,0x2c64,-1,-10727},
2933 	{0x2c67,0x2c6b,2,1},
2934 	{0x2c6d,0x2c6d,-1,-10780},
2935 	{0x2c6e,0x2c6e,-1,-10749},
2936 	{0x2c6f,0x2c6f,-1,-10783},
2937 	{0x2c70,0x2c70,-1,-10782},
2938 	{0x2c72,0x2c75,3,1},
2939 	{0x2c7e,0x2c7f,1,-10815},
2940 	{0x2c80,0x2ce2,2,1},
2941 	{0x2ceb,0x2ced,2,1},
2942 	{0x2cf2,0xa640,31054,1},
2943 	{0xa642,0xa66c,2,1},
2944 	{0xa680,0xa69a,2,1},
2945 	{0xa722,0xa72e,2,1},
2946 	{0xa732,0xa76e,2,1},
2947 	{0xa779,0xa77b,2,1},
2948 	{0xa77d,0xa77d,-1,-35332},
2949 	{0xa77e,0xa786,2,1},
2950 	{0xa78b,0xa78b,-1,1},
2951 	{0xa78d,0xa78d,-1,-42280},
2952 	{0xa790,0xa792,2,1},
2953 	{0xa796,0xa7a8,2,1},
2954 	{0xa7aa,0xa7aa,-1,-42308},
2955 	{0xa7ab,0xa7ab,-1,-42319},
2956 	{0xa7ac,0xa7ac,-1,-42315},
2957 	{0xa7ad,0xa7ad,-1,-42305},
2958 	{0xa7b0,0xa7b0,-1,-42258},
2959 	{0xa7b1,0xa7b1,-1,-42282},
2960 	{0xa7b2,0xa7b2,-1,-42261},
2961 	{0xa7b3,0xa7b3,-1,928},
2962 	{0xa7b4,0xa7b6,2,1},
2963 	{0xab70,0xabbf,1,-38864},
2964 	{0xff21,0xff3a,1,32},
2965 	{0x10400,0x10427,1,40},
2966 	{0x10c80,0x10cb2,1,64},
2967 	{0x118a0,0x118bf,1,32}
2968 };
2969 
2970 static int utf_convert(int a, convertStruct table[], int tableSize);
2971 static int utf_strnicmp(char_u *s1, char_u *s2, size_t n1, size_t n2);
2972 
2973 /*
2974  * Generic conversion function for case operations.
2975  * Return the converted equivalent of "a", which is a UCS-4 character.  Use
2976  * the given conversion "table".  Uses binary search on "table".
2977  */
2978     static int
2979 utf_convert(
2980     int			a,
2981     convertStruct	table[],
2982     int			tableSize)
2983 {
2984     int start, mid, end; /* indices into table */
2985     int entries = tableSize / sizeof(convertStruct);
2986 
2987     start = 0;
2988     end = entries;
2989     while (start < end)
2990     {
2991 	/* need to search further */
2992 	mid = (end + start) / 2;
2993 	if (table[mid].rangeEnd < a)
2994 	    start = mid + 1;
2995 	else
2996 	    end = mid;
2997     }
2998     if (start < entries
2999 	    && table[start].rangeStart <= a
3000 	    && a <= table[start].rangeEnd
3001 	    && (a - table[start].rangeStart) % table[start].step == 0)
3002 	return (a + table[start].offset);
3003     else
3004 	return a;
3005 }
3006 
3007 /*
3008  * Return the folded-case equivalent of "a", which is a UCS-4 character.  Uses
3009  * simple case folding.
3010  */
3011     int
3012 utf_fold(int a)
3013 {
3014     return utf_convert(a, foldCase, (int)sizeof(foldCase));
3015 }
3016 
3017 static convertStruct toLower[] =
3018 {
3019 	{0x41,0x5a,1,32},
3020 	{0xc0,0xd6,1,32},
3021 	{0xd8,0xde,1,32},
3022 	{0x100,0x12e,2,1},
3023 	{0x130,0x130,-1,-199},
3024 	{0x132,0x136,2,1},
3025 	{0x139,0x147,2,1},
3026 	{0x14a,0x176,2,1},
3027 	{0x178,0x178,-1,-121},
3028 	{0x179,0x17d,2,1},
3029 	{0x181,0x181,-1,210},
3030 	{0x182,0x184,2,1},
3031 	{0x186,0x186,-1,206},
3032 	{0x187,0x187,-1,1},
3033 	{0x189,0x18a,1,205},
3034 	{0x18b,0x18b,-1,1},
3035 	{0x18e,0x18e,-1,79},
3036 	{0x18f,0x18f,-1,202},
3037 	{0x190,0x190,-1,203},
3038 	{0x191,0x191,-1,1},
3039 	{0x193,0x193,-1,205},
3040 	{0x194,0x194,-1,207},
3041 	{0x196,0x196,-1,211},
3042 	{0x197,0x197,-1,209},
3043 	{0x198,0x198,-1,1},
3044 	{0x19c,0x19c,-1,211},
3045 	{0x19d,0x19d,-1,213},
3046 	{0x19f,0x19f,-1,214},
3047 	{0x1a0,0x1a4,2,1},
3048 	{0x1a6,0x1a6,-1,218},
3049 	{0x1a7,0x1a7,-1,1},
3050 	{0x1a9,0x1a9,-1,218},
3051 	{0x1ac,0x1ac,-1,1},
3052 	{0x1ae,0x1ae,-1,218},
3053 	{0x1af,0x1af,-1,1},
3054 	{0x1b1,0x1b2,1,217},
3055 	{0x1b3,0x1b5,2,1},
3056 	{0x1b7,0x1b7,-1,219},
3057 	{0x1b8,0x1bc,4,1},
3058 	{0x1c4,0x1c4,-1,2},
3059 	{0x1c5,0x1c5,-1,1},
3060 	{0x1c7,0x1c7,-1,2},
3061 	{0x1c8,0x1c8,-1,1},
3062 	{0x1ca,0x1ca,-1,2},
3063 	{0x1cb,0x1db,2,1},
3064 	{0x1de,0x1ee,2,1},
3065 	{0x1f1,0x1f1,-1,2},
3066 	{0x1f2,0x1f4,2,1},
3067 	{0x1f6,0x1f6,-1,-97},
3068 	{0x1f7,0x1f7,-1,-56},
3069 	{0x1f8,0x21e,2,1},
3070 	{0x220,0x220,-1,-130},
3071 	{0x222,0x232,2,1},
3072 	{0x23a,0x23a,-1,10795},
3073 	{0x23b,0x23b,-1,1},
3074 	{0x23d,0x23d,-1,-163},
3075 	{0x23e,0x23e,-1,10792},
3076 	{0x241,0x241,-1,1},
3077 	{0x243,0x243,-1,-195},
3078 	{0x244,0x244,-1,69},
3079 	{0x245,0x245,-1,71},
3080 	{0x246,0x24e,2,1},
3081 	{0x370,0x372,2,1},
3082 	{0x376,0x376,-1,1},
3083 	{0x37f,0x37f,-1,116},
3084 	{0x386,0x386,-1,38},
3085 	{0x388,0x38a,1,37},
3086 	{0x38c,0x38c,-1,64},
3087 	{0x38e,0x38f,1,63},
3088 	{0x391,0x3a1,1,32},
3089 	{0x3a3,0x3ab,1,32},
3090 	{0x3cf,0x3cf,-1,8},
3091 	{0x3d8,0x3ee,2,1},
3092 	{0x3f4,0x3f4,-1,-60},
3093 	{0x3f7,0x3f7,-1,1},
3094 	{0x3f9,0x3f9,-1,-7},
3095 	{0x3fa,0x3fa,-1,1},
3096 	{0x3fd,0x3ff,1,-130},
3097 	{0x400,0x40f,1,80},
3098 	{0x410,0x42f,1,32},
3099 	{0x460,0x480,2,1},
3100 	{0x48a,0x4be,2,1},
3101 	{0x4c0,0x4c0,-1,15},
3102 	{0x4c1,0x4cd,2,1},
3103 	{0x4d0,0x52e,2,1},
3104 	{0x531,0x556,1,48},
3105 	{0x10a0,0x10c5,1,7264},
3106 	{0x10c7,0x10cd,6,7264},
3107 	{0x13a0,0x13ef,1,38864},
3108 	{0x13f0,0x13f5,1,8},
3109 	{0x1e00,0x1e94,2,1},
3110 	{0x1e9e,0x1e9e,-1,-7615},
3111 	{0x1ea0,0x1efe,2,1},
3112 	{0x1f08,0x1f0f,1,-8},
3113 	{0x1f18,0x1f1d,1,-8},
3114 	{0x1f28,0x1f2f,1,-8},
3115 	{0x1f38,0x1f3f,1,-8},
3116 	{0x1f48,0x1f4d,1,-8},
3117 	{0x1f59,0x1f5f,2,-8},
3118 	{0x1f68,0x1f6f,1,-8},
3119 	{0x1f88,0x1f8f,1,-8},
3120 	{0x1f98,0x1f9f,1,-8},
3121 	{0x1fa8,0x1faf,1,-8},
3122 	{0x1fb8,0x1fb9,1,-8},
3123 	{0x1fba,0x1fbb,1,-74},
3124 	{0x1fbc,0x1fbc,-1,-9},
3125 	{0x1fc8,0x1fcb,1,-86},
3126 	{0x1fcc,0x1fcc,-1,-9},
3127 	{0x1fd8,0x1fd9,1,-8},
3128 	{0x1fda,0x1fdb,1,-100},
3129 	{0x1fe8,0x1fe9,1,-8},
3130 	{0x1fea,0x1feb,1,-112},
3131 	{0x1fec,0x1fec,-1,-7},
3132 	{0x1ff8,0x1ff9,1,-128},
3133 	{0x1ffa,0x1ffb,1,-126},
3134 	{0x1ffc,0x1ffc,-1,-9},
3135 	{0x2126,0x2126,-1,-7517},
3136 	{0x212a,0x212a,-1,-8383},
3137 	{0x212b,0x212b,-1,-8262},
3138 	{0x2132,0x2132,-1,28},
3139 	{0x2160,0x216f,1,16},
3140 	{0x2183,0x2183,-1,1},
3141 	{0x24b6,0x24cf,1,26},
3142 	{0x2c00,0x2c2e,1,48},
3143 	{0x2c60,0x2c60,-1,1},
3144 	{0x2c62,0x2c62,-1,-10743},
3145 	{0x2c63,0x2c63,-1,-3814},
3146 	{0x2c64,0x2c64,-1,-10727},
3147 	{0x2c67,0x2c6b,2,1},
3148 	{0x2c6d,0x2c6d,-1,-10780},
3149 	{0x2c6e,0x2c6e,-1,-10749},
3150 	{0x2c6f,0x2c6f,-1,-10783},
3151 	{0x2c70,0x2c70,-1,-10782},
3152 	{0x2c72,0x2c75,3,1},
3153 	{0x2c7e,0x2c7f,1,-10815},
3154 	{0x2c80,0x2ce2,2,1},
3155 	{0x2ceb,0x2ced,2,1},
3156 	{0x2cf2,0xa640,31054,1},
3157 	{0xa642,0xa66c,2,1},
3158 	{0xa680,0xa69a,2,1},
3159 	{0xa722,0xa72e,2,1},
3160 	{0xa732,0xa76e,2,1},
3161 	{0xa779,0xa77b,2,1},
3162 	{0xa77d,0xa77d,-1,-35332},
3163 	{0xa77e,0xa786,2,1},
3164 	{0xa78b,0xa78b,-1,1},
3165 	{0xa78d,0xa78d,-1,-42280},
3166 	{0xa790,0xa792,2,1},
3167 	{0xa796,0xa7a8,2,1},
3168 	{0xa7aa,0xa7aa,-1,-42308},
3169 	{0xa7ab,0xa7ab,-1,-42319},
3170 	{0xa7ac,0xa7ac,-1,-42315},
3171 	{0xa7ad,0xa7ad,-1,-42305},
3172 	{0xa7b0,0xa7b0,-1,-42258},
3173 	{0xa7b1,0xa7b1,-1,-42282},
3174 	{0xa7b2,0xa7b2,-1,-42261},
3175 	{0xa7b3,0xa7b3,-1,928},
3176 	{0xa7b4,0xa7b6,2,1},
3177 	{0xff21,0xff3a,1,32},
3178 	{0x10400,0x10427,1,40},
3179 	{0x10c80,0x10cb2,1,64},
3180 	{0x118a0,0x118bf,1,32}
3181 };
3182 
3183 static convertStruct toUpper[] =
3184 {
3185 	{0x61,0x7a,1,-32},
3186 	{0xb5,0xb5,-1,743},
3187 	{0xe0,0xf6,1,-32},
3188 	{0xf8,0xfe,1,-32},
3189 	{0xff,0xff,-1,121},
3190 	{0x101,0x12f,2,-1},
3191 	{0x131,0x131,-1,-232},
3192 	{0x133,0x137,2,-1},
3193 	{0x13a,0x148,2,-1},
3194 	{0x14b,0x177,2,-1},
3195 	{0x17a,0x17e,2,-1},
3196 	{0x17f,0x17f,-1,-300},
3197 	{0x180,0x180,-1,195},
3198 	{0x183,0x185,2,-1},
3199 	{0x188,0x18c,4,-1},
3200 	{0x192,0x192,-1,-1},
3201 	{0x195,0x195,-1,97},
3202 	{0x199,0x199,-1,-1},
3203 	{0x19a,0x19a,-1,163},
3204 	{0x19e,0x19e,-1,130},
3205 	{0x1a1,0x1a5,2,-1},
3206 	{0x1a8,0x1ad,5,-1},
3207 	{0x1b0,0x1b4,4,-1},
3208 	{0x1b6,0x1b9,3,-1},
3209 	{0x1bd,0x1bd,-1,-1},
3210 	{0x1bf,0x1bf,-1,56},
3211 	{0x1c5,0x1c5,-1,-1},
3212 	{0x1c6,0x1c6,-1,-2},
3213 	{0x1c8,0x1c8,-1,-1},
3214 	{0x1c9,0x1c9,-1,-2},
3215 	{0x1cb,0x1cb,-1,-1},
3216 	{0x1cc,0x1cc,-1,-2},
3217 	{0x1ce,0x1dc,2,-1},
3218 	{0x1dd,0x1dd,-1,-79},
3219 	{0x1df,0x1ef,2,-1},
3220 	{0x1f2,0x1f2,-1,-1},
3221 	{0x1f3,0x1f3,-1,-2},
3222 	{0x1f5,0x1f9,4,-1},
3223 	{0x1fb,0x21f,2,-1},
3224 	{0x223,0x233,2,-1},
3225 	{0x23c,0x23c,-1,-1},
3226 	{0x23f,0x240,1,10815},
3227 	{0x242,0x247,5,-1},
3228 	{0x249,0x24f,2,-1},
3229 	{0x250,0x250,-1,10783},
3230 	{0x251,0x251,-1,10780},
3231 	{0x252,0x252,-1,10782},
3232 	{0x253,0x253,-1,-210},
3233 	{0x254,0x254,-1,-206},
3234 	{0x256,0x257,1,-205},
3235 	{0x259,0x259,-1,-202},
3236 	{0x25b,0x25b,-1,-203},
3237 	{0x25c,0x25c,-1,42319},
3238 	{0x260,0x260,-1,-205},
3239 	{0x261,0x261,-1,42315},
3240 	{0x263,0x263,-1,-207},
3241 	{0x265,0x265,-1,42280},
3242 	{0x266,0x266,-1,42308},
3243 	{0x268,0x268,-1,-209},
3244 	{0x269,0x269,-1,-211},
3245 	{0x26b,0x26b,-1,10743},
3246 	{0x26c,0x26c,-1,42305},
3247 	{0x26f,0x26f,-1,-211},
3248 	{0x271,0x271,-1,10749},
3249 	{0x272,0x272,-1,-213},
3250 	{0x275,0x275,-1,-214},
3251 	{0x27d,0x27d,-1,10727},
3252 	{0x280,0x283,3,-218},
3253 	{0x287,0x287,-1,42282},
3254 	{0x288,0x288,-1,-218},
3255 	{0x289,0x289,-1,-69},
3256 	{0x28a,0x28b,1,-217},
3257 	{0x28c,0x28c,-1,-71},
3258 	{0x292,0x292,-1,-219},
3259 	{0x29d,0x29d,-1,42261},
3260 	{0x29e,0x29e,-1,42258},
3261 	{0x345,0x345,-1,84},
3262 	{0x371,0x373,2,-1},
3263 	{0x377,0x377,-1,-1},
3264 	{0x37b,0x37d,1,130},
3265 	{0x3ac,0x3ac,-1,-38},
3266 	{0x3ad,0x3af,1,-37},
3267 	{0x3b1,0x3c1,1,-32},
3268 	{0x3c2,0x3c2,-1,-31},
3269 	{0x3c3,0x3cb,1,-32},
3270 	{0x3cc,0x3cc,-1,-64},
3271 	{0x3cd,0x3ce,1,-63},
3272 	{0x3d0,0x3d0,-1,-62},
3273 	{0x3d1,0x3d1,-1,-57},
3274 	{0x3d5,0x3d5,-1,-47},
3275 	{0x3d6,0x3d6,-1,-54},
3276 	{0x3d7,0x3d7,-1,-8},
3277 	{0x3d9,0x3ef,2,-1},
3278 	{0x3f0,0x3f0,-1,-86},
3279 	{0x3f1,0x3f1,-1,-80},
3280 	{0x3f2,0x3f2,-1,7},
3281 	{0x3f3,0x3f3,-1,-116},
3282 	{0x3f5,0x3f5,-1,-96},
3283 	{0x3f8,0x3fb,3,-1},
3284 	{0x430,0x44f,1,-32},
3285 	{0x450,0x45f,1,-80},
3286 	{0x461,0x481,2,-1},
3287 	{0x48b,0x4bf,2,-1},
3288 	{0x4c2,0x4ce,2,-1},
3289 	{0x4cf,0x4cf,-1,-15},
3290 	{0x4d1,0x52f,2,-1},
3291 	{0x561,0x586,1,-48},
3292 	{0x13f8,0x13fd,1,-8},
3293 	{0x1d79,0x1d79,-1,35332},
3294 	{0x1d7d,0x1d7d,-1,3814},
3295 	{0x1e01,0x1e95,2,-1},
3296 	{0x1e9b,0x1e9b,-1,-59},
3297 	{0x1ea1,0x1eff,2,-1},
3298 	{0x1f00,0x1f07,1,8},
3299 	{0x1f10,0x1f15,1,8},
3300 	{0x1f20,0x1f27,1,8},
3301 	{0x1f30,0x1f37,1,8},
3302 	{0x1f40,0x1f45,1,8},
3303 	{0x1f51,0x1f57,2,8},
3304 	{0x1f60,0x1f67,1,8},
3305 	{0x1f70,0x1f71,1,74},
3306 	{0x1f72,0x1f75,1,86},
3307 	{0x1f76,0x1f77,1,100},
3308 	{0x1f78,0x1f79,1,128},
3309 	{0x1f7a,0x1f7b,1,112},
3310 	{0x1f7c,0x1f7d,1,126},
3311 	{0x1f80,0x1f87,1,8},
3312 	{0x1f90,0x1f97,1,8},
3313 	{0x1fa0,0x1fa7,1,8},
3314 	{0x1fb0,0x1fb1,1,8},
3315 	{0x1fb3,0x1fb3,-1,9},
3316 	{0x1fbe,0x1fbe,-1,-7205},
3317 	{0x1fc3,0x1fc3,-1,9},
3318 	{0x1fd0,0x1fd1,1,8},
3319 	{0x1fe0,0x1fe1,1,8},
3320 	{0x1fe5,0x1fe5,-1,7},
3321 	{0x1ff3,0x1ff3,-1,9},
3322 	{0x214e,0x214e,-1,-28},
3323 	{0x2170,0x217f,1,-16},
3324 	{0x2184,0x2184,-1,-1},
3325 	{0x24d0,0x24e9,1,-26},
3326 	{0x2c30,0x2c5e,1,-48},
3327 	{0x2c61,0x2c61,-1,-1},
3328 	{0x2c65,0x2c65,-1,-10795},
3329 	{0x2c66,0x2c66,-1,-10792},
3330 	{0x2c68,0x2c6c,2,-1},
3331 	{0x2c73,0x2c76,3,-1},
3332 	{0x2c81,0x2ce3,2,-1},
3333 	{0x2cec,0x2cee,2,-1},
3334 	{0x2cf3,0x2cf3,-1,-1},
3335 	{0x2d00,0x2d25,1,-7264},
3336 	{0x2d27,0x2d2d,6,-7264},
3337 	{0xa641,0xa66d,2,-1},
3338 	{0xa681,0xa69b,2,-1},
3339 	{0xa723,0xa72f,2,-1},
3340 	{0xa733,0xa76f,2,-1},
3341 	{0xa77a,0xa77c,2,-1},
3342 	{0xa77f,0xa787,2,-1},
3343 	{0xa78c,0xa791,5,-1},
3344 	{0xa793,0xa797,4,-1},
3345 	{0xa799,0xa7a9,2,-1},
3346 	{0xa7b5,0xa7b7,2,-1},
3347 	{0xab53,0xab53,-1,-928},
3348 	{0xab70,0xabbf,1,-38864},
3349 	{0xff41,0xff5a,1,-32},
3350 	{0x10428,0x1044f,1,-40},
3351 	{0x10cc0,0x10cf2,1,-64},
3352 	{0x118c0,0x118df,1,-32}
3353 };
3354 /*
3355  * Return the upper-case equivalent of "a", which is a UCS-4 character.  Use
3356  * simple case folding.
3357  */
3358     int
3359 utf_toupper(int a)
3360 {
3361     /* If 'casemap' contains "keepascii" use ASCII style toupper(). */
3362     if (a < 128 && (cmp_flags & CMP_KEEPASCII))
3363 	return TOUPPER_ASC(a);
3364 
3365 #if defined(HAVE_TOWUPPER) && defined(__STDC_ISO_10646__)
3366     /* If towupper() is available and handles Unicode, use it. */
3367     if (!(cmp_flags & CMP_INTERNAL))
3368 	return towupper(a);
3369 #endif
3370 
3371     /* For characters below 128 use locale sensitive toupper(). */
3372     if (a < 128)
3373 	return TOUPPER_LOC(a);
3374 
3375     /* For any other characters use the above mapping table. */
3376     return utf_convert(a, toUpper, (int)sizeof(toUpper));
3377 }
3378 
3379     int
3380 utf_islower(int a)
3381 {
3382     /* German sharp s is lower case but has no upper case equivalent. */
3383     return (utf_toupper(a) != a) || a == 0xdf;
3384 }
3385 
3386 /*
3387  * Return the lower-case equivalent of "a", which is a UCS-4 character.  Use
3388  * simple case folding.
3389  */
3390     int
3391 utf_tolower(int a)
3392 {
3393     /* If 'casemap' contains "keepascii" use ASCII style tolower(). */
3394     if (a < 128 && (cmp_flags & CMP_KEEPASCII))
3395 	return TOLOWER_ASC(a);
3396 
3397 #if defined(HAVE_TOWLOWER) && defined(__STDC_ISO_10646__)
3398     /* If towlower() is available and handles Unicode, use it. */
3399     if (!(cmp_flags & CMP_INTERNAL))
3400 	return towlower(a);
3401 #endif
3402 
3403     /* For characters below 128 use locale sensitive tolower(). */
3404     if (a < 128)
3405 	return TOLOWER_LOC(a);
3406 
3407     /* For any other characters use the above mapping table. */
3408     return utf_convert(a, toLower, (int)sizeof(toLower));
3409 }
3410 
3411     int
3412 utf_isupper(int a)
3413 {
3414     return (utf_tolower(a) != a);
3415 }
3416 
3417     static int
3418 utf_strnicmp(
3419     char_u      *s1,
3420     char_u      *s2,
3421     size_t      n1,
3422     size_t      n2)
3423 {
3424     int		c1, c2, cdiff;
3425     char_u	buffer[6];
3426 
3427     for (;;)
3428     {
3429 	c1 = utf_safe_read_char_adv(&s1, &n1);
3430 	c2 = utf_safe_read_char_adv(&s2, &n2);
3431 
3432 	if (c1 <= 0 || c2 <= 0)
3433 	    break;
3434 
3435 	if (c1 == c2)
3436 	    continue;
3437 
3438 	cdiff = utf_fold(c1) - utf_fold(c2);
3439 	if (cdiff != 0)
3440 	    return cdiff;
3441     }
3442 
3443     /* some string ended or has an incomplete/illegal character sequence */
3444 
3445     if (c1 == 0 || c2 == 0)
3446     {
3447 	/* some string ended. shorter string is smaller */
3448 	if (c1 == 0 && c2 == 0)
3449 	    return 0;
3450 	return c1 == 0 ? -1 : 1;
3451     }
3452 
3453     /* Continue with bytewise comparison to produce some result that
3454      * would make comparison operations involving this function transitive.
3455      *
3456      * If only one string had an error, comparison should be made with
3457      * folded version of the other string. In this case it is enough
3458      * to fold just one character to determine the result of comparison. */
3459 
3460     if (c1 != -1 && c2 == -1)
3461     {
3462 	n1 = utf_char2bytes(utf_fold(c1), buffer);
3463 	s1 = buffer;
3464     }
3465     else if (c2 != -1 && c1 == -1)
3466     {
3467 	n2 = utf_char2bytes(utf_fold(c2), buffer);
3468 	s2 = buffer;
3469     }
3470 
3471     while (n1 > 0 && n2 > 0 && *s1 != NUL && *s2 != NUL)
3472     {
3473 	cdiff = (int)(*s1) - (int)(*s2);
3474 	if (cdiff != 0)
3475 	    return cdiff;
3476 
3477 	s1++;
3478 	s2++;
3479 	n1--;
3480 	n2--;
3481     }
3482 
3483     if (n1 > 0 && *s1 == NUL)
3484 	n1 = 0;
3485     if (n2 > 0 && *s2 == NUL)
3486 	n2 = 0;
3487 
3488     if (n1 == 0 && n2 == 0)
3489 	return 0;
3490     return n1 == 0 ? -1 : 1;
3491 }
3492 
3493 /*
3494  * Version of strnicmp() that handles multi-byte characters.
3495  * Needed for Big5, Shift-JIS and UTF-8 encoding.  Other DBCS encodings can
3496  * probably use strnicmp(), because there are no ASCII characters in the
3497  * second byte.
3498  * Returns zero if s1 and s2 are equal (ignoring case), the difference between
3499  * two characters otherwise.
3500  */
3501     int
3502 mb_strnicmp(char_u *s1, char_u *s2, size_t nn)
3503 {
3504     int		i, l;
3505     int		cdiff;
3506     int		n = (int)nn;
3507 
3508     if (enc_utf8)
3509     {
3510 	return utf_strnicmp(s1, s2, nn, nn);
3511     }
3512     else
3513     {
3514 	for (i = 0; i < n; i += l)
3515 	{
3516 	    if (s1[i] == NUL && s2[i] == NUL)	/* both strings end */
3517 		return 0;
3518 
3519 	    l = (*mb_ptr2len)(s1 + i);
3520 	    if (l <= 1)
3521 	    {
3522 		/* Single byte: first check normally, then with ignore case. */
3523 		if (s1[i] != s2[i])
3524 		{
3525 		    cdiff = MB_TOLOWER(s1[i]) - MB_TOLOWER(s2[i]);
3526 		    if (cdiff != 0)
3527 			return cdiff;
3528 		}
3529 	    }
3530 	    else
3531 	    {
3532 		/* For non-Unicode multi-byte don't ignore case. */
3533 		if (l > n - i)
3534 		    l = n - i;
3535 		cdiff = STRNCMP(s1 + i, s2 + i, l);
3536 		if (cdiff != 0)
3537 		    return cdiff;
3538 	    }
3539 	}
3540     }
3541     return 0;
3542 }
3543 
3544 /*
3545  * "g8": show bytes of the UTF-8 char under the cursor.  Doesn't matter what
3546  * 'encoding' has been set to.
3547  */
3548     void
3549 show_utf8(void)
3550 {
3551     int		len;
3552     int		rlen = 0;
3553     char_u	*line;
3554     int		clen;
3555     int		i;
3556 
3557     /* Get the byte length of the char under the cursor, including composing
3558      * characters. */
3559     line = ml_get_cursor();
3560     len = utfc_ptr2len(line);
3561     if (len == 0)
3562     {
3563 	MSG("NUL");
3564 	return;
3565     }
3566 
3567     clen = 0;
3568     for (i = 0; i < len; ++i)
3569     {
3570 	if (clen == 0)
3571 	{
3572 	    /* start of (composing) character, get its length */
3573 	    if (i > 0)
3574 	    {
3575 		STRCPY(IObuff + rlen, "+ ");
3576 		rlen += 2;
3577 	    }
3578 	    clen = utf_ptr2len(line + i);
3579 	}
3580 	sprintf((char *)IObuff + rlen, "%02x ",
3581 		(line[i] == NL) ? NUL : line[i]);  /* NUL is stored as NL */
3582 	--clen;
3583 	rlen += (int)STRLEN(IObuff + rlen);
3584 	if (rlen > IOSIZE - 20)
3585 	    break;
3586     }
3587 
3588     msg(IObuff);
3589 }
3590 
3591 /*
3592  * mb_head_off() function pointer.
3593  * Return offset from "p" to the first byte of the character it points into.
3594  * If "p" points to the NUL at the end of the string return 0.
3595  * Returns 0 when already at the first byte of a character.
3596  */
3597     int
3598 latin_head_off(char_u *base UNUSED, char_u *p UNUSED)
3599 {
3600     return 0;
3601 }
3602 
3603     int
3604 dbcs_head_off(char_u *base, char_u *p)
3605 {
3606     char_u	*q;
3607 
3608     /* It can't be a trailing byte when not using DBCS, at the start of the
3609      * string or the previous byte can't start a double-byte. */
3610     if (p <= base || MB_BYTE2LEN(p[-1]) == 1 || *p == NUL)
3611 	return 0;
3612 
3613     /* This is slow: need to start at the base and go forward until the
3614      * byte we are looking for.  Return 1 when we went past it, 0 otherwise. */
3615     q = base;
3616     while (q < p)
3617 	q += dbcs_ptr2len(q);
3618     return (q == p) ? 0 : 1;
3619 }
3620 
3621 /*
3622  * Special version of dbcs_head_off() that works for ScreenLines[], where
3623  * single-width DBCS_JPNU characters are stored separately.
3624  */
3625     int
3626 dbcs_screen_head_off(char_u *base, char_u *p)
3627 {
3628     char_u	*q;
3629 
3630     /* It can't be a trailing byte when not using DBCS, at the start of the
3631      * string or the previous byte can't start a double-byte.
3632      * For euc-jp an 0x8e byte in the previous cell always means we have a
3633      * lead byte in the current cell. */
3634     if (p <= base
3635 	    || (enc_dbcs == DBCS_JPNU && p[-1] == 0x8e)
3636 	    || MB_BYTE2LEN(p[-1]) == 1
3637 	    || *p == NUL)
3638 	return 0;
3639 
3640     /* This is slow: need to start at the base and go forward until the
3641      * byte we are looking for.  Return 1 when we went past it, 0 otherwise.
3642      * For DBCS_JPNU look out for 0x8e, which means the second byte is not
3643      * stored as the next byte. */
3644     q = base;
3645     while (q < p)
3646     {
3647 	if (enc_dbcs == DBCS_JPNU && *q == 0x8e)
3648 	    ++q;
3649 	else
3650 	    q += dbcs_ptr2len(q);
3651     }
3652     return (q == p) ? 0 : 1;
3653 }
3654 
3655     int
3656 utf_head_off(char_u *base, char_u *p)
3657 {
3658     char_u	*q;
3659     char_u	*s;
3660     int		c;
3661     int		len;
3662 #ifdef FEAT_ARABIC
3663     char_u	*j;
3664 #endif
3665 
3666     if (*p < 0x80)		/* be quick for ASCII */
3667 	return 0;
3668 
3669     /* Skip backwards over trailing bytes: 10xx.xxxx
3670      * Skip backwards again if on a composing char. */
3671     for (q = p; ; --q)
3672     {
3673 	/* Move s to the last byte of this char. */
3674 	for (s = q; (s[1] & 0xc0) == 0x80; ++s)
3675 	    ;
3676 	/* Move q to the first byte of this char. */
3677 	while (q > base && (*q & 0xc0) == 0x80)
3678 	    --q;
3679 	/* Check for illegal sequence. Do allow an illegal byte after where we
3680 	 * started. */
3681 	len = utf8len_tab[*q];
3682 	if (len != (int)(s - q + 1) && len != (int)(p - q + 1))
3683 	    return 0;
3684 
3685 	if (q <= base)
3686 	    break;
3687 
3688 	c = utf_ptr2char(q);
3689 	if (utf_iscomposing(c))
3690 	    continue;
3691 
3692 #ifdef FEAT_ARABIC
3693 	if (arabic_maycombine(c))
3694 	{
3695 	    /* Advance to get a sneak-peak at the next char */
3696 	    j = q;
3697 	    --j;
3698 	    /* Move j to the first byte of this char. */
3699 	    while (j > base && (*j & 0xc0) == 0x80)
3700 		--j;
3701 	    if (arabic_combine(utf_ptr2char(j), c))
3702 		continue;
3703 	}
3704 #endif
3705 	break;
3706     }
3707 
3708     return (int)(p - q);
3709 }
3710 
3711 /*
3712  * Copy a character from "*fp" to "*tp" and advance the pointers.
3713  */
3714     void
3715 mb_copy_char(char_u **fp, char_u **tp)
3716 {
3717     int	    l = (*mb_ptr2len)(*fp);
3718 
3719     mch_memmove(*tp, *fp, (size_t)l);
3720     *tp += l;
3721     *fp += l;
3722 }
3723 
3724 /*
3725  * Return the offset from "p" to the first byte of a character.  When "p" is
3726  * at the start of a character 0 is returned, otherwise the offset to the next
3727  * character.  Can start anywhere in a stream of bytes.
3728  */
3729     int
3730 mb_off_next(char_u *base, char_u *p)
3731 {
3732     int		i;
3733     int		j;
3734 
3735     if (enc_utf8)
3736     {
3737 	if (*p < 0x80)		/* be quick for ASCII */
3738 	    return 0;
3739 
3740 	/* Find the next character that isn't 10xx.xxxx */
3741 	for (i = 0; (p[i] & 0xc0) == 0x80; ++i)
3742 	    ;
3743 	if (i > 0)
3744 	{
3745 	    /* Check for illegal sequence. */
3746 	    for (j = 0; p - j > base; ++j)
3747 		if ((p[-j] & 0xc0) != 0x80)
3748 		    break;
3749 	    if (utf8len_tab[p[-j]] != i + j)
3750 		return 0;
3751 	}
3752 	return i;
3753     }
3754 
3755     /* Only need to check if we're on a trail byte, it doesn't matter if we
3756      * want the offset to the next or current character. */
3757     return (*mb_head_off)(base, p);
3758 }
3759 
3760 /*
3761  * Return the offset from "p" to the last byte of the character it points
3762  * into.  Can start anywhere in a stream of bytes.
3763  */
3764     int
3765 mb_tail_off(char_u *base, char_u *p)
3766 {
3767     int		i;
3768     int		j;
3769 
3770     if (*p == NUL)
3771 	return 0;
3772 
3773     if (enc_utf8)
3774     {
3775 	/* Find the last character that is 10xx.xxxx */
3776 	for (i = 0; (p[i + 1] & 0xc0) == 0x80; ++i)
3777 	    ;
3778 	/* Check for illegal sequence. */
3779 	for (j = 0; p - j > base; ++j)
3780 	    if ((p[-j] & 0xc0) != 0x80)
3781 		break;
3782 	if (utf8len_tab[p[-j]] != i + j + 1)
3783 	    return 0;
3784 	return i;
3785     }
3786 
3787     /* It can't be the first byte if a double-byte when not using DBCS, at the
3788      * end of the string or the byte can't start a double-byte. */
3789     if (enc_dbcs == 0 || p[1] == NUL || MB_BYTE2LEN(*p) == 1)
3790 	return 0;
3791 
3792     /* Return 1 when on the lead byte, 0 when on the tail byte. */
3793     return 1 - dbcs_head_off(base, p);
3794 }
3795 
3796 /*
3797  * Find the next illegal byte sequence.
3798  */
3799     void
3800 utf_find_illegal(void)
3801 {
3802     pos_T	pos = curwin->w_cursor;
3803     char_u	*p;
3804     int		len;
3805     vimconv_T	vimconv;
3806     char_u	*tofree = NULL;
3807 
3808     vimconv.vc_type = CONV_NONE;
3809     if (enc_utf8 && (enc_canon_props(curbuf->b_p_fenc) & ENC_8BIT))
3810     {
3811 	/* 'encoding' is "utf-8" but we are editing a 8-bit encoded file,
3812 	 * possibly a utf-8 file with illegal bytes.  Setup for conversion
3813 	 * from utf-8 to 'fileencoding'. */
3814 	convert_setup(&vimconv, p_enc, curbuf->b_p_fenc);
3815     }
3816 
3817 #ifdef FEAT_VIRTUALEDIT
3818     curwin->w_cursor.coladd = 0;
3819 #endif
3820     for (;;)
3821     {
3822 	p = ml_get_cursor();
3823 	if (vimconv.vc_type != CONV_NONE)
3824 	{
3825 	    vim_free(tofree);
3826 	    tofree = string_convert(&vimconv, p, NULL);
3827 	    if (tofree == NULL)
3828 		break;
3829 	    p = tofree;
3830 	}
3831 
3832 	while (*p != NUL)
3833 	{
3834 	    /* Illegal means that there are not enough trail bytes (checked by
3835 	     * utf_ptr2len()) or too many of them (overlong sequence). */
3836 	    len = utf_ptr2len(p);
3837 	    if (*p >= 0x80 && (len == 1
3838 				     || utf_char2len(utf_ptr2char(p)) != len))
3839 	    {
3840 		if (vimconv.vc_type == CONV_NONE)
3841 		    curwin->w_cursor.col += (colnr_T)(p - ml_get_cursor());
3842 		else
3843 		{
3844 		    int	    l;
3845 
3846 		    len = (int)(p - tofree);
3847 		    for (p = ml_get_cursor(); *p != NUL && len-- > 0; p += l)
3848 		    {
3849 			l = utf_ptr2len(p);
3850 			curwin->w_cursor.col += l;
3851 		    }
3852 		}
3853 		goto theend;
3854 	    }
3855 	    p += len;
3856 	}
3857 	if (curwin->w_cursor.lnum == curbuf->b_ml.ml_line_count)
3858 	    break;
3859 	++curwin->w_cursor.lnum;
3860 	curwin->w_cursor.col = 0;
3861     }
3862 
3863     /* didn't find it: don't move and beep */
3864     curwin->w_cursor = pos;
3865     beep_flush();
3866 
3867 theend:
3868     vim_free(tofree);
3869     convert_setup(&vimconv, NULL, NULL);
3870 }
3871 
3872 #if defined(FEAT_GUI_GTK) || defined(PROTO)
3873 /*
3874  * Return TRUE if string "s" is a valid utf-8 string.
3875  * When "end" is NULL stop at the first NUL.
3876  * When "end" is positive stop there.
3877  */
3878     int
3879 utf_valid_string(char_u *s, char_u *end)
3880 {
3881     int		l;
3882     char_u	*p = s;
3883 
3884     while (end == NULL ? *p != NUL : p < end)
3885     {
3886 	l = utf8len_tab_zero[*p];
3887 	if (l == 0)
3888 	    return FALSE;	/* invalid lead byte */
3889 	if (end != NULL && p + l > end)
3890 	    return FALSE;	/* incomplete byte sequence */
3891 	++p;
3892 	while (--l > 0)
3893 	    if ((*p++ & 0xc0) != 0x80)
3894 		return FALSE;	/* invalid trail byte */
3895     }
3896     return TRUE;
3897 }
3898 #endif
3899 
3900 #if defined(FEAT_GUI) || defined(PROTO)
3901 /*
3902  * Special version of mb_tail_off() for use in ScreenLines[].
3903  */
3904     int
3905 dbcs_screen_tail_off(char_u *base, char_u *p)
3906 {
3907     /* It can't be the first byte if a double-byte when not using DBCS, at the
3908      * end of the string or the byte can't start a double-byte.
3909      * For euc-jp an 0x8e byte always means we have a lead byte in the current
3910      * cell. */
3911     if (*p == NUL || p[1] == NUL
3912 	    || (enc_dbcs == DBCS_JPNU && *p == 0x8e)
3913 	    || MB_BYTE2LEN(*p) == 1)
3914 	return 0;
3915 
3916     /* Return 1 when on the lead byte, 0 when on the tail byte. */
3917     return 1 - dbcs_screen_head_off(base, p);
3918 }
3919 #endif
3920 
3921 /*
3922  * If the cursor moves on an trail byte, set the cursor on the lead byte.
3923  * Thus it moves left if necessary.
3924  * Return TRUE when the cursor was adjusted.
3925  */
3926     void
3927 mb_adjust_cursor(void)
3928 {
3929     mb_adjustpos(curbuf, &curwin->w_cursor);
3930 }
3931 
3932 /*
3933  * Adjust position "*lp" to point to the first byte of a multi-byte character.
3934  * If it points to a tail byte it's moved backwards to the head byte.
3935  */
3936     void
3937 mb_adjustpos(buf_T *buf, pos_T *lp)
3938 {
3939     char_u	*p;
3940 
3941     if (lp->col > 0
3942 #ifdef FEAT_VIRTUALEDIT
3943 	    || lp->coladd > 1
3944 #endif
3945 	    )
3946     {
3947 	p = ml_get_buf(buf, lp->lnum, FALSE);
3948 	lp->col -= (*mb_head_off)(p, p + lp->col);
3949 #ifdef FEAT_VIRTUALEDIT
3950 	/* Reset "coladd" when the cursor would be on the right half of a
3951 	 * double-wide character. */
3952 	if (lp->coladd == 1
3953 		&& p[lp->col] != TAB
3954 		&& vim_isprintc((*mb_ptr2char)(p + lp->col))
3955 		&& ptr2cells(p + lp->col) > 1)
3956 	    lp->coladd = 0;
3957 #endif
3958     }
3959 }
3960 
3961 /*
3962  * Return a pointer to the character before "*p", if there is one.
3963  */
3964     char_u *
3965 mb_prevptr(
3966     char_u *line,	/* start of the string */
3967     char_u *p)
3968 {
3969     if (p > line)
3970 	mb_ptr_back(line, p);
3971     return p;
3972 }
3973 
3974 /*
3975  * Return the character length of "str".  Each multi-byte character (with
3976  * following composing characters) counts as one.
3977  */
3978     int
3979 mb_charlen(char_u *str)
3980 {
3981     char_u	*p = str;
3982     int		count;
3983 
3984     if (p == NULL)
3985 	return 0;
3986 
3987     for (count = 0; *p != NUL; count++)
3988 	p += (*mb_ptr2len)(p);
3989 
3990     return count;
3991 }
3992 
3993 #if defined(FEAT_SPELL) || defined(PROTO)
3994 /*
3995  * Like mb_charlen() but for a string with specified length.
3996  */
3997     int
3998 mb_charlen_len(char_u *str, int len)
3999 {
4000     char_u	*p = str;
4001     int		count;
4002 
4003     for (count = 0; *p != NUL && p < str + len; count++)
4004 	p += (*mb_ptr2len)(p);
4005 
4006     return count;
4007 }
4008 #endif
4009 
4010 /*
4011  * Try to un-escape a multi-byte character.
4012  * Used for the "to" and "from" part of a mapping.
4013  * Return the un-escaped string if it is a multi-byte character, and advance
4014  * "pp" to just after the bytes that formed it.
4015  * Return NULL if no multi-byte char was found.
4016  */
4017     char_u *
4018 mb_unescape(char_u **pp)
4019 {
4020     static char_u	buf[6];
4021     int			n;
4022     int			m = 0;
4023     char_u		*str = *pp;
4024 
4025     /* Must translate K_SPECIAL KS_SPECIAL KE_FILLER to K_SPECIAL and CSI
4026      * KS_EXTRA KE_CSI to CSI.
4027      * Maximum length of a utf-8 character is 4 bytes. */
4028     for (n = 0; str[n] != NUL && m < 4; ++n)
4029     {
4030 	if (str[n] == K_SPECIAL
4031 		&& str[n + 1] == KS_SPECIAL
4032 		&& str[n + 2] == KE_FILLER)
4033 	{
4034 	    buf[m++] = K_SPECIAL;
4035 	    n += 2;
4036 	}
4037 	else if ((str[n] == K_SPECIAL
4038 # ifdef FEAT_GUI
4039 		    || str[n] == CSI
4040 # endif
4041 		 )
4042 		&& str[n + 1] == KS_EXTRA
4043 		&& str[n + 2] == (int)KE_CSI)
4044 	{
4045 	    buf[m++] = CSI;
4046 	    n += 2;
4047 	}
4048 	else if (str[n] == K_SPECIAL
4049 # ifdef FEAT_GUI
4050 		|| str[n] == CSI
4051 # endif
4052 		)
4053 	    break;		/* a special key can't be a multibyte char */
4054 	else
4055 	    buf[m++] = str[n];
4056 	buf[m] = NUL;
4057 
4058 	/* Return a multi-byte character if it's found.  An illegal sequence
4059 	 * will result in a 1 here. */
4060 	if ((*mb_ptr2len)(buf) > 1)
4061 	{
4062 	    *pp = str + n + 1;
4063 	    return buf;
4064 	}
4065 
4066 	/* Bail out quickly for ASCII. */
4067 	if (buf[0] < 128)
4068 	    break;
4069     }
4070     return NULL;
4071 }
4072 
4073 /*
4074  * Return TRUE if the character at "row"/"col" on the screen is the left side
4075  * of a double-width character.
4076  * Caller must make sure "row" and "col" are not invalid!
4077  */
4078     int
4079 mb_lefthalve(int row, int col)
4080 {
4081 #ifdef FEAT_HANGULIN
4082     if (composing_hangul)
4083 	return TRUE;
4084 #endif
4085     return (*mb_off2cells)(LineOffset[row] + col,
4086 					LineOffset[row] + screen_Columns) > 1;
4087 }
4088 
4089 /*
4090  * Correct a position on the screen, if it's the right half of a double-wide
4091  * char move it to the left half.  Returns the corrected column.
4092  */
4093     int
4094 mb_fix_col(int col, int row)
4095 {
4096     col = check_col(col);
4097     row = check_row(row);
4098     if (has_mbyte && ScreenLines != NULL && col > 0
4099 	    && ((enc_dbcs
4100 		    && ScreenLines[LineOffset[row] + col] != NUL
4101 		    && dbcs_screen_head_off(ScreenLines + LineOffset[row],
4102 					 ScreenLines + LineOffset[row] + col))
4103 		|| (enc_utf8 && ScreenLines[LineOffset[row] + col] == 0)))
4104 	return col - 1;
4105     return col;
4106 }
4107 #endif
4108 
4109 #if defined(FEAT_MBYTE) || defined(FEAT_POSTSCRIPT) || defined(PROTO)
4110 static int enc_alias_search(char_u *name);
4111 
4112 /*
4113  * Skip the Vim specific head of a 'encoding' name.
4114  */
4115     char_u *
4116 enc_skip(char_u *p)
4117 {
4118     if (STRNCMP(p, "2byte-", 6) == 0)
4119 	return p + 6;
4120     if (STRNCMP(p, "8bit-", 5) == 0)
4121 	return p + 5;
4122     return p;
4123 }
4124 
4125 /*
4126  * Find the canonical name for encoding "enc".
4127  * When the name isn't recognized, returns "enc" itself, but with all lower
4128  * case characters and '_' replaced with '-'.
4129  * Returns an allocated string.  NULL for out-of-memory.
4130  */
4131     char_u *
4132 enc_canonize(char_u *enc)
4133 {
4134     char_u	*r;
4135     char_u	*p, *s;
4136     int		i;
4137 
4138 # ifdef FEAT_MBYTE
4139     if (STRCMP(enc, "default") == 0)
4140     {
4141 	/* Use the default encoding as it's found by set_init_1(). */
4142 	r = get_encoding_default();
4143 	if (r == NULL)
4144 	    r = (char_u *)"latin1";
4145 	return vim_strsave(r);
4146     }
4147 # endif
4148 
4149     /* copy "enc" to allocated memory, with room for two '-' */
4150     r = alloc((unsigned)(STRLEN(enc) + 3));
4151     if (r != NULL)
4152     {
4153 	/* Make it all lower case and replace '_' with '-'. */
4154 	p = r;
4155 	for (s = enc; *s != NUL; ++s)
4156 	{
4157 	    if (*s == '_')
4158 		*p++ = '-';
4159 	    else
4160 		*p++ = TOLOWER_ASC(*s);
4161 	}
4162 	*p = NUL;
4163 
4164 	/* Skip "2byte-" and "8bit-". */
4165 	p = enc_skip(r);
4166 
4167 	/* Change "microsoft-cp" to "cp".  Used in some spell files. */
4168 	if (STRNCMP(p, "microsoft-cp", 12) == 0)
4169 	    STRMOVE(p, p + 10);
4170 
4171 	/* "iso8859" -> "iso-8859" */
4172 	if (STRNCMP(p, "iso8859", 7) == 0)
4173 	{
4174 	    STRMOVE(p + 4, p + 3);
4175 	    p[3] = '-';
4176 	}
4177 
4178 	/* "iso-8859n" -> "iso-8859-n" */
4179 	if (STRNCMP(p, "iso-8859", 8) == 0 && p[8] != '-')
4180 	{
4181 	    STRMOVE(p + 9, p + 8);
4182 	    p[8] = '-';
4183 	}
4184 
4185 	/* "latin-N" -> "latinN" */
4186 	if (STRNCMP(p, "latin-", 6) == 0)
4187 	    STRMOVE(p + 5, p + 6);
4188 
4189 	if (enc_canon_search(p) >= 0)
4190 	{
4191 	    /* canonical name can be used unmodified */
4192 	    if (p != r)
4193 		STRMOVE(r, p);
4194 	}
4195 	else if ((i = enc_alias_search(p)) >= 0)
4196 	{
4197 	    /* alias recognized, get canonical name */
4198 	    vim_free(r);
4199 	    r = vim_strsave((char_u *)enc_canon_table[i].name);
4200 	}
4201     }
4202     return r;
4203 }
4204 
4205 /*
4206  * Search for an encoding alias of "name".
4207  * Returns -1 when not found.
4208  */
4209     static int
4210 enc_alias_search(char_u *name)
4211 {
4212     int		i;
4213 
4214     for (i = 0; enc_alias_table[i].name != NULL; ++i)
4215 	if (STRCMP(name, enc_alias_table[i].name) == 0)
4216 	    return enc_alias_table[i].canon;
4217     return -1;
4218 }
4219 #endif
4220 
4221 #if defined(FEAT_MBYTE) || defined(PROTO)
4222 
4223 #ifdef HAVE_LANGINFO_H
4224 # include <langinfo.h>
4225 #endif
4226 
4227 /*
4228  * Get the canonicalized encoding of the current locale.
4229  * Returns an allocated string when successful, NULL when not.
4230  */
4231     char_u *
4232 enc_locale(void)
4233 {
4234 #ifndef WIN3264
4235     char	*s;
4236     char	*p;
4237     int		i;
4238 #endif
4239     char	buf[50];
4240 #ifdef WIN3264
4241     long	acp = GetACP();
4242 
4243     if (acp == 1200)
4244 	STRCPY(buf, "ucs-2le");
4245     else if (acp == 1252)	    /* cp1252 is used as latin1 */
4246 	STRCPY(buf, "latin1");
4247     else
4248 	sprintf(buf, "cp%ld", acp);
4249 #else
4250 # ifdef HAVE_NL_LANGINFO_CODESET
4251     if ((s = nl_langinfo(CODESET)) == NULL || *s == NUL)
4252 # endif
4253 #  if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
4254 	if ((s = setlocale(LC_CTYPE, NULL)) == NULL || *s == NUL)
4255 #  endif
4256 	    if ((s = getenv("LC_ALL")) == NULL || *s == NUL)
4257 		if ((s = getenv("LC_CTYPE")) == NULL || *s == NUL)
4258 		    s = getenv("LANG");
4259 
4260     if (s == NULL || *s == NUL)
4261 	return FAIL;
4262 
4263     /* The most generic locale format is:
4264      * language[_territory][.codeset][@modifier][+special][,[sponsor][_revision]]
4265      * If there is a '.' remove the part before it.
4266      * if there is something after the codeset, remove it.
4267      * Make the name lowercase and replace '_' with '-'.
4268      * Exception: "ja_JP.EUC" == "euc-jp", "zh_CN.EUC" = "euc-cn",
4269      * "ko_KR.EUC" == "euc-kr"
4270      */
4271     if ((p = (char *)vim_strchr((char_u *)s, '.')) != NULL)
4272     {
4273 	if (p > s + 2 && STRNICMP(p + 1, "EUC", 3) == 0
4274 			&& !isalnum((int)p[4]) && p[4] != '-' && p[-3] == '_')
4275 	{
4276 	    /* copy "XY.EUC" to "euc-XY" to buf[10] */
4277 	    STRCPY(buf + 10, "euc-");
4278 	    buf[14] = p[-2];
4279 	    buf[15] = p[-1];
4280 	    buf[16] = 0;
4281 	    s = buf + 10;
4282 	}
4283 	else
4284 	    s = p + 1;
4285     }
4286     for (i = 0; s[i] != NUL && i < (int)sizeof(buf) - 1; ++i)
4287     {
4288 	if (s[i] == '_' || s[i] == '-')
4289 	    buf[i] = '-';
4290 	else if (isalnum((int)s[i]))
4291 	    buf[i] = TOLOWER_ASC(s[i]);
4292 	else
4293 	    break;
4294     }
4295     buf[i] = NUL;
4296 #endif
4297 
4298     return enc_canonize((char_u *)buf);
4299 }
4300 
4301 #if defined(WIN3264) || defined(PROTO) || defined(FEAT_CYGWIN_WIN32_CLIPBOARD)
4302 /*
4303  * Convert an encoding name to an MS-Windows codepage.
4304  * Returns zero if no codepage can be figured out.
4305  */
4306     int
4307 encname2codepage(char_u *name)
4308 {
4309     int		cp;
4310     char_u	*p = name;
4311     int		idx;
4312 
4313     if (STRNCMP(p, "8bit-", 5) == 0)
4314 	p += 5;
4315     else if (STRNCMP(p_enc, "2byte-", 6) == 0)
4316 	p += 6;
4317 
4318     if (p[0] == 'c' && p[1] == 'p')
4319 	cp = atoi((char *)p + 2);
4320     else if ((idx = enc_canon_search(p)) >= 0)
4321 	cp = enc_canon_table[idx].codepage;
4322     else
4323 	return 0;
4324     if (IsValidCodePage(cp))
4325 	return cp;
4326     return 0;
4327 }
4328 #endif
4329 
4330 # if defined(USE_ICONV) || defined(PROTO)
4331 
4332 static char_u *iconv_string(vimconv_T *vcp, char_u *str, int slen, int *unconvlenp, int *resultlenp);
4333 
4334 /*
4335  * Call iconv_open() with a check if iconv() works properly (there are broken
4336  * versions).
4337  * Returns (void *)-1 if failed.
4338  * (should return iconv_t, but that causes problems with prototypes).
4339  */
4340     void *
4341 my_iconv_open(char_u *to, char_u *from)
4342 {
4343     iconv_t	fd;
4344 #define ICONV_TESTLEN 400
4345     char_u	tobuf[ICONV_TESTLEN];
4346     char	*p;
4347     size_t	tolen;
4348     static int	iconv_ok = -1;
4349 
4350     if (iconv_ok == FALSE)
4351 	return (void *)-1;	/* detected a broken iconv() previously */
4352 
4353 #ifdef DYNAMIC_ICONV
4354     /* Check if the iconv.dll can be found. */
4355     if (!iconv_enabled(TRUE))
4356 	return (void *)-1;
4357 #endif
4358 
4359     fd = iconv_open((char *)enc_skip(to), (char *)enc_skip(from));
4360 
4361     if (fd != (iconv_t)-1 && iconv_ok == -1)
4362     {
4363 	/*
4364 	 * Do a dummy iconv() call to check if it actually works.  There is a
4365 	 * version of iconv() on Linux that is broken.  We can't ignore it,
4366 	 * because it's wide-spread.  The symptoms are that after outputting
4367 	 * the initial shift state the "to" pointer is NULL and conversion
4368 	 * stops for no apparent reason after about 8160 characters.
4369 	 */
4370 	p = (char *)tobuf;
4371 	tolen = ICONV_TESTLEN;
4372 	(void)iconv(fd, NULL, NULL, &p, &tolen);
4373 	if (p == NULL)
4374 	{
4375 	    iconv_ok = FALSE;
4376 	    iconv_close(fd);
4377 	    fd = (iconv_t)-1;
4378 	}
4379 	else
4380 	    iconv_ok = TRUE;
4381     }
4382 
4383     return (void *)fd;
4384 }
4385 
4386 /*
4387  * Convert the string "str[slen]" with iconv().
4388  * If "unconvlenp" is not NULL handle the string ending in an incomplete
4389  * sequence and set "*unconvlenp" to the length of it.
4390  * Returns the converted string in allocated memory.  NULL for an error.
4391  * If resultlenp is not NULL, sets it to the result length in bytes.
4392  */
4393     static char_u *
4394 iconv_string(
4395     vimconv_T	*vcp,
4396     char_u	*str,
4397     int		slen,
4398     int		*unconvlenp,
4399     int		*resultlenp)
4400 {
4401     const char	*from;
4402     size_t	fromlen;
4403     char	*to;
4404     size_t	tolen;
4405     size_t	len = 0;
4406     size_t	done = 0;
4407     char_u	*result = NULL;
4408     char_u	*p;
4409     int		l;
4410 
4411     from = (char *)str;
4412     fromlen = slen;
4413     for (;;)
4414     {
4415 	if (len == 0 || ICONV_ERRNO == ICONV_E2BIG)
4416 	{
4417 	    /* Allocate enough room for most conversions.  When re-allocating
4418 	     * increase the buffer size. */
4419 	    len = len + fromlen * 2 + 40;
4420 	    p = alloc((unsigned)len);
4421 	    if (p != NULL && done > 0)
4422 		mch_memmove(p, result, done);
4423 	    vim_free(result);
4424 	    result = p;
4425 	    if (result == NULL)	/* out of memory */
4426 		break;
4427 	}
4428 
4429 	to = (char *)result + done;
4430 	tolen = len - done - 2;
4431 	/* Avoid a warning for systems with a wrong iconv() prototype by
4432 	 * casting the second argument to void *. */
4433 	if (iconv(vcp->vc_fd, (void *)&from, &fromlen, &to, &tolen)
4434 								!= (size_t)-1)
4435 	{
4436 	    /* Finished, append a NUL. */
4437 	    *to = NUL;
4438 	    break;
4439 	}
4440 
4441 	/* Check both ICONV_EINVAL and EINVAL, because the dynamically loaded
4442 	 * iconv library may use one of them. */
4443 	if (!vcp->vc_fail && unconvlenp != NULL
4444 		&& (ICONV_ERRNO == ICONV_EINVAL || ICONV_ERRNO == EINVAL))
4445 	{
4446 	    /* Handle an incomplete sequence at the end. */
4447 	    *to = NUL;
4448 	    *unconvlenp = (int)fromlen;
4449 	    break;
4450 	}
4451 
4452 	/* Check both ICONV_EILSEQ and EILSEQ, because the dynamically loaded
4453 	 * iconv library may use one of them. */
4454 	else if (!vcp->vc_fail
4455 		&& (ICONV_ERRNO == ICONV_EILSEQ || ICONV_ERRNO == EILSEQ
4456 		    || ICONV_ERRNO == ICONV_EINVAL || ICONV_ERRNO == EINVAL))
4457 	{
4458 	    /* Can't convert: insert a '?' and skip a character.  This assumes
4459 	     * conversion from 'encoding' to something else.  In other
4460 	     * situations we don't know what to skip anyway. */
4461 	    *to++ = '?';
4462 	    if ((*mb_ptr2cells)((char_u *)from) > 1)
4463 		*to++ = '?';
4464 	    if (enc_utf8)
4465 		l = utfc_ptr2len_len((char_u *)from, (int)fromlen);
4466 	    else
4467 	    {
4468 		l = (*mb_ptr2len)((char_u *)from);
4469 		if (l > (int)fromlen)
4470 		    l = (int)fromlen;
4471 	    }
4472 	    from += l;
4473 	    fromlen -= l;
4474 	}
4475 	else if (ICONV_ERRNO != ICONV_E2BIG)
4476 	{
4477 	    /* conversion failed */
4478 	    vim_free(result);
4479 	    result = NULL;
4480 	    break;
4481 	}
4482 	/* Not enough room or skipping illegal sequence. */
4483 	done = to - (char *)result;
4484     }
4485 
4486     if (resultlenp != NULL && result != NULL)
4487 	*resultlenp = (int)(to - (char *)result);
4488     return result;
4489 }
4490 
4491 #  if defined(DYNAMIC_ICONV) || defined(PROTO)
4492 /*
4493  * Dynamically load the "iconv.dll" on Win32.
4494  */
4495 
4496 #   ifndef DYNAMIC_ICONV	    /* must be generating prototypes */
4497 #    define HINSTANCE int
4498 #   endif
4499 static HINSTANCE hIconvDLL = 0;
4500 static HINSTANCE hMsvcrtDLL = 0;
4501 
4502 #   ifndef DYNAMIC_ICONV_DLL
4503 #    define DYNAMIC_ICONV_DLL "iconv.dll"
4504 #    define DYNAMIC_ICONV_DLL_ALT1 "libiconv.dll"
4505 #    define DYNAMIC_ICONV_DLL_ALT2 "libiconv2.dll"
4506 #    define DYNAMIC_ICONV_DLL_ALT3 "libiconv-2.dll"
4507 #   endif
4508 #   ifndef DYNAMIC_MSVCRT_DLL
4509 #    define DYNAMIC_MSVCRT_DLL "msvcrt.dll"
4510 #   endif
4511 
4512 /*
4513  * Get the address of 'funcname' which is imported by 'hInst' DLL.
4514  */
4515     static void *
4516 get_iconv_import_func(HINSTANCE hInst, const char *funcname)
4517 {
4518     PBYTE			pImage = (PBYTE)hInst;
4519     PIMAGE_DOS_HEADER		pDOS = (PIMAGE_DOS_HEADER)hInst;
4520     PIMAGE_NT_HEADERS		pPE;
4521     PIMAGE_IMPORT_DESCRIPTOR	pImpDesc;
4522     PIMAGE_THUNK_DATA		pIAT;	    /* Import Address Table */
4523     PIMAGE_THUNK_DATA		pINT;	    /* Import Name Table */
4524     PIMAGE_IMPORT_BY_NAME	pImpName;
4525 
4526     if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
4527 	return NULL;
4528     pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
4529     if (pPE->Signature != IMAGE_NT_SIGNATURE)
4530 	return NULL;
4531     pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
4532 	    + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
4533 							    .VirtualAddress);
4534     for (; pImpDesc->FirstThunk; ++pImpDesc)
4535     {
4536 	if (!pImpDesc->OriginalFirstThunk)
4537 	    continue;
4538 	pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
4539 	pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
4540 	for (; pIAT->u1.Function; ++pIAT, ++pINT)
4541 	{
4542 	    if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
4543 		continue;
4544 	    pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
4545 					+ (UINT_PTR)(pINT->u1.AddressOfData));
4546 	    if (strcmp((char *)pImpName->Name, funcname) == 0)
4547 		return (void *)pIAT->u1.Function;
4548 	}
4549     }
4550     return NULL;
4551 }
4552 
4553 /*
4554  * Try opening the iconv.dll and return TRUE if iconv() can be used.
4555  */
4556     int
4557 iconv_enabled(int verbose)
4558 {
4559     if (hIconvDLL != 0 && hMsvcrtDLL != 0)
4560 	return TRUE;
4561 
4562     /* The iconv DLL file goes under different names, try them all.
4563      * Do the "2" version first, it's newer. */
4564 #ifdef DYNAMIC_ICONV_DLL_ALT2
4565     if (hIconvDLL == 0)
4566 	hIconvDLL = vimLoadLib(DYNAMIC_ICONV_DLL_ALT2);
4567 #endif
4568 #ifdef DYNAMIC_ICONV_DLL_ALT3
4569     if (hIconvDLL == 0)
4570 	hIconvDLL = vimLoadLib(DYNAMIC_ICONV_DLL_ALT3);
4571 #endif
4572     if (hIconvDLL == 0)
4573 	hIconvDLL = vimLoadLib(DYNAMIC_ICONV_DLL);
4574 #ifdef DYNAMIC_ICONV_DLL_ALT1
4575     if (hIconvDLL == 0)
4576 	hIconvDLL = vimLoadLib(DYNAMIC_ICONV_DLL_ALT1);
4577 #endif
4578 
4579     if (hIconvDLL != 0)
4580 	hMsvcrtDLL = vimLoadLib(DYNAMIC_MSVCRT_DLL);
4581     if (hIconvDLL == 0 || hMsvcrtDLL == 0)
4582     {
4583 	/* Only give the message when 'verbose' is set, otherwise it might be
4584 	 * done whenever a conversion is attempted. */
4585 	if (verbose && p_verbose > 0)
4586 	{
4587 	    verbose_enter();
4588 	    EMSG2(_(e_loadlib),
4589 		    hIconvDLL == 0 ? DYNAMIC_ICONV_DLL : DYNAMIC_MSVCRT_DLL);
4590 	    verbose_leave();
4591 	}
4592 	iconv_end();
4593 	return FALSE;
4594     }
4595 
4596     iconv	= (void *)GetProcAddress(hIconvDLL, "libiconv");
4597     iconv_open	= (void *)GetProcAddress(hIconvDLL, "libiconv_open");
4598     iconv_close	= (void *)GetProcAddress(hIconvDLL, "libiconv_close");
4599     iconvctl	= (void *)GetProcAddress(hIconvDLL, "libiconvctl");
4600     iconv_errno	= get_iconv_import_func(hIconvDLL, "_errno");
4601     if (iconv_errno == NULL)
4602 	iconv_errno = (void *)GetProcAddress(hMsvcrtDLL, "_errno");
4603     if (iconv == NULL || iconv_open == NULL || iconv_close == NULL
4604 	    || iconvctl == NULL || iconv_errno == NULL)
4605     {
4606 	iconv_end();
4607 	if (verbose && p_verbose > 0)
4608 	{
4609 	    verbose_enter();
4610 	    EMSG2(_(e_loadfunc), "for libiconv");
4611 	    verbose_leave();
4612 	}
4613 	return FALSE;
4614     }
4615     return TRUE;
4616 }
4617 
4618     void
4619 iconv_end(void)
4620 {
4621     /* Don't use iconv() when inputting or outputting characters. */
4622     if (input_conv.vc_type == CONV_ICONV)
4623 	convert_setup(&input_conv, NULL, NULL);
4624     if (output_conv.vc_type == CONV_ICONV)
4625 	convert_setup(&output_conv, NULL, NULL);
4626 
4627     if (hIconvDLL != 0)
4628 	FreeLibrary(hIconvDLL);
4629     if (hMsvcrtDLL != 0)
4630 	FreeLibrary(hMsvcrtDLL);
4631     hIconvDLL = 0;
4632     hMsvcrtDLL = 0;
4633 }
4634 #  endif /* DYNAMIC_ICONV */
4635 # endif /* USE_ICONV */
4636 
4637 #endif /* FEAT_MBYTE */
4638 
4639 #if defined(FEAT_XIM) || defined(PROTO)
4640 
4641 # if defined(FEAT_GUI_GTK) || defined(PROTO)
4642 static int xim_has_preediting INIT(= FALSE);  /* IM current status */
4643 
4644 /*
4645  * Set preedit_start_col to the current cursor position.
4646  */
4647     static void
4648 init_preedit_start_col(void)
4649 {
4650     if (State & CMDLINE)
4651 	preedit_start_col = cmdline_getvcol_cursor();
4652     else if (curwin != NULL && curwin->w_buffer != NULL)
4653 	getvcol(curwin, &curwin->w_cursor, &preedit_start_col, NULL, NULL);
4654     /* Prevent that preediting marks the buffer as changed. */
4655     xim_changed_while_preediting = curbuf->b_changed;
4656 }
4657 
4658 static int im_is_active	       = FALSE;	/* IM is enabled for current mode    */
4659 static int preedit_is_active   = FALSE;
4660 static int im_preedit_cursor   = 0;	/* cursor offset in characters       */
4661 static int im_preedit_trailing = 0;	/* number of characters after cursor */
4662 
4663 static unsigned long im_commit_handler_id  = 0;
4664 static unsigned int  im_activatekey_keyval = GDK_VoidSymbol;
4665 static unsigned int  im_activatekey_state  = 0;
4666 
4667     void
4668 im_set_active(int active)
4669 {
4670     int was_active;
4671 
4672     was_active = !!im_get_status();
4673     im_is_active = (active && !p_imdisable);
4674 
4675     if (im_is_active != was_active)
4676 	xim_reset();
4677 }
4678 
4679     void
4680 xim_set_focus(int focus)
4681 {
4682     if (xic != NULL)
4683     {
4684 	if (focus)
4685 	    gtk_im_context_focus_in(xic);
4686 	else
4687 	    gtk_im_context_focus_out(xic);
4688     }
4689 }
4690 
4691     void
4692 im_set_position(int row, int col)
4693 {
4694     if (xic != NULL)
4695     {
4696 	GdkRectangle area;
4697 
4698 	area.x = FILL_X(col);
4699 	area.y = FILL_Y(row);
4700 	area.width  = gui.char_width * (mb_lefthalve(row, col) ? 2 : 1);
4701 	area.height = gui.char_height;
4702 
4703 	gtk_im_context_set_cursor_location(xic, &area);
4704     }
4705 }
4706 
4707 #  if 0 || defined(PROTO) /* apparently only used in gui_x11.c */
4708     void
4709 xim_set_preedit(void)
4710 {
4711     im_set_position(gui.row, gui.col);
4712 }
4713 #  endif
4714 
4715     static void
4716 im_add_to_input(char_u *str, int len)
4717 {
4718     /* Convert from 'termencoding' (always "utf-8") to 'encoding' */
4719     if (input_conv.vc_type != CONV_NONE)
4720     {
4721 	str = string_convert(&input_conv, str, &len);
4722 	g_return_if_fail(str != NULL);
4723     }
4724 
4725     add_to_input_buf_csi(str, len);
4726 
4727     if (input_conv.vc_type != CONV_NONE)
4728 	vim_free(str);
4729 
4730     if (p_mh) /* blank out the pointer if necessary */
4731 	gui_mch_mousehide(TRUE);
4732 }
4733 
4734     static void
4735 im_delete_preedit(void)
4736 {
4737     char_u bskey[]  = {CSI, 'k', 'b'};
4738     char_u delkey[] = {CSI, 'k', 'D'};
4739 
4740     if (State & NORMAL)
4741     {
4742 	im_preedit_cursor = 0;
4743 	return;
4744     }
4745     for (; im_preedit_cursor > 0; --im_preedit_cursor)
4746 	add_to_input_buf(bskey, (int)sizeof(bskey));
4747 
4748     for (; im_preedit_trailing > 0; --im_preedit_trailing)
4749 	add_to_input_buf(delkey, (int)sizeof(delkey));
4750 }
4751 
4752 /*
4753  * Move the cursor left by "num_move_back" characters.
4754  * Note that ins_left() checks im_is_preediting() to avoid breaking undo for
4755  * these K_LEFT keys.
4756  */
4757     static void
4758 im_correct_cursor(int num_move_back)
4759 {
4760     char_u backkey[] = {CSI, 'k', 'l'};
4761 
4762     if (State & NORMAL)
4763 	return;
4764 #  ifdef FEAT_RIGHTLEFT
4765     if ((State & CMDLINE) == 0 && curwin != NULL && curwin->w_p_rl)
4766 	backkey[2] = 'r';
4767 #  endif
4768     for (; num_move_back > 0; --num_move_back)
4769 	add_to_input_buf(backkey, (int)sizeof(backkey));
4770 }
4771 
4772 static int xim_expected_char = NUL;
4773 static int xim_ignored_char = FALSE;
4774 
4775 /*
4776  * Update the mode and cursor while in an IM callback.
4777  */
4778     static void
4779 im_show_info(void)
4780 {
4781     int	    old_vgetc_busy;
4782 
4783     old_vgetc_busy = vgetc_busy;
4784     vgetc_busy = TRUE;
4785     showmode();
4786     vgetc_busy = old_vgetc_busy;
4787     if ((State & NORMAL) || (State & INSERT))
4788 	setcursor();
4789     out_flush();
4790 }
4791 
4792 /*
4793  * Callback invoked when the user finished preediting.
4794  * Put the final string into the input buffer.
4795  */
4796     static void
4797 im_commit_cb(GtkIMContext *context UNUSED,
4798 	     const gchar *str,
4799 	     gpointer data UNUSED)
4800 {
4801     int		slen = (int)STRLEN(str);
4802     int		add_to_input = TRUE;
4803     int		clen;
4804     int		len = slen;
4805     int		commit_with_preedit = TRUE;
4806     char_u	*im_str;
4807 
4808 #ifdef XIM_DEBUG
4809     xim_log("im_commit_cb(): %s\n", str);
4810 #endif
4811 
4812     /* The imhangul module doesn't reset the preedit string before
4813      * committing.  Call im_delete_preedit() to work around that. */
4814     im_delete_preedit();
4815 
4816     /* Indicate that preediting has finished. */
4817     if (preedit_start_col == MAXCOL)
4818     {
4819 	init_preedit_start_col();
4820 	commit_with_preedit = FALSE;
4821     }
4822 
4823     /* The thing which setting "preedit_start_col" to MAXCOL means that
4824      * "preedit_start_col" will be set forcedly when calling
4825      * preedit_changed_cb() next time.
4826      * "preedit_start_col" should not reset with MAXCOL on this part. Vim
4827      * is simulating the preediting by using add_to_input_str(). when
4828      * preedit begin immediately before committed, the typebuf is not
4829      * flushed to screen, then it can't get correct "preedit_start_col".
4830      * Thus, it should calculate the cells by adding cells of the committed
4831      * string. */
4832     if (input_conv.vc_type != CONV_NONE)
4833     {
4834 	im_str = string_convert(&input_conv, (char_u *)str, &len);
4835 	g_return_if_fail(im_str != NULL);
4836     }
4837     else
4838 	im_str = (char_u *)str;
4839 
4840     clen = mb_string2cells(im_str, len);
4841 
4842     if (input_conv.vc_type != CONV_NONE)
4843 	vim_free(im_str);
4844     preedit_start_col += clen;
4845 
4846     /* Is this a single character that matches a keypad key that's just
4847      * been pressed?  If so, we don't want it to be entered as such - let
4848      * us carry on processing the raw keycode so that it may be used in
4849      * mappings as <kSomething>. */
4850     if (xim_expected_char != NUL)
4851     {
4852 	/* We're currently processing a keypad or other special key */
4853 	if (slen == 1 && str[0] == xim_expected_char)
4854 	{
4855 	    /* It's a match - don't do it here */
4856 	    xim_ignored_char = TRUE;
4857 	    add_to_input = FALSE;
4858 	}
4859 	else
4860 	{
4861 	    /* Not a match */
4862 	    xim_ignored_char = FALSE;
4863 	}
4864     }
4865 
4866     if (add_to_input)
4867 	im_add_to_input((char_u *)str, slen);
4868 
4869     /* Inserting chars while "im_is_active" is set does not cause a change of
4870      * buffer.  When the chars are committed the buffer must be marked as
4871      * changed. */
4872     if (!commit_with_preedit)
4873 	preedit_start_col = MAXCOL;
4874 
4875     /* This flag is used in changed() at next call. */
4876     xim_changed_while_preediting = TRUE;
4877 
4878     if (gtk_main_level() > 0)
4879 	gtk_main_quit();
4880 }
4881 
4882 /*
4883  * Callback invoked after start to the preedit.
4884  */
4885     static void
4886 im_preedit_start_cb(GtkIMContext *context UNUSED, gpointer data UNUSED)
4887 {
4888 #ifdef XIM_DEBUG
4889     xim_log("im_preedit_start_cb()\n");
4890 #endif
4891 
4892     im_is_active = TRUE;
4893     preedit_is_active = TRUE;
4894     gui_update_cursor(TRUE, FALSE);
4895     im_show_info();
4896 }
4897 
4898 /*
4899  * Callback invoked after end to the preedit.
4900  */
4901     static void
4902 im_preedit_end_cb(GtkIMContext *context UNUSED, gpointer data UNUSED)
4903 {
4904 #ifdef XIM_DEBUG
4905     xim_log("im_preedit_end_cb()\n");
4906 #endif
4907     im_delete_preedit();
4908 
4909     /* Indicate that preediting has finished */
4910     preedit_start_col = MAXCOL;
4911     xim_has_preediting = FALSE;
4912 
4913 #if 0
4914     /* Removal of this line suggested by Takuhiro Nishioka.  Fixes that IM was
4915      * switched off unintentionally.  We now use preedit_is_active (added by
4916      * SungHyun Nam). */
4917     im_is_active = FALSE;
4918 #endif
4919     preedit_is_active = FALSE;
4920     gui_update_cursor(TRUE, FALSE);
4921     im_show_info();
4922 }
4923 
4924 /*
4925  * Callback invoked after changes to the preedit string.  If the preedit
4926  * string was empty before, remember the preedit start column so we know
4927  * where to apply feedback attributes.  Delete the previous preedit string
4928  * if there was one, save the new preedit cursor offset, and put the new
4929  * string into the input buffer.
4930  *
4931  * TODO: The pragmatic "put into input buffer" approach used here has
4932  *       several fundamental problems:
4933  *
4934  * - The characters in the preedit string are subject to remapping.
4935  *   That's broken, only the finally committed string should be remapped.
4936  *
4937  * - There is a race condition involved:  The retrieved value for the
4938  *   current cursor position will be wrong if any unprocessed characters
4939  *   are still queued in the input buffer.
4940  *
4941  * - Due to the lack of synchronization between the file buffer in memory
4942  *   and any typed characters, it's practically impossible to implement the
4943  *   "retrieve_surrounding" and "delete_surrounding" signals reliably.  IM
4944  *   modules for languages such as Thai are likely to rely on this feature
4945  *   for proper operation.
4946  *
4947  * Conclusions:  I think support for preediting needs to be moved to the
4948  * core parts of Vim.  Ideally, until it has been committed, the preediting
4949  * string should only be displayed and not affect the buffer content at all.
4950  * The question how to deal with the synchronization issue still remains.
4951  * Circumventing the input buffer is probably not desirable.  Anyway, I think
4952  * implementing "retrieve_surrounding" is the only hard problem.
4953  *
4954  * One way to solve all of this in a clean manner would be to queue all key
4955  * press/release events "as is" in the input buffer, and apply the IM filtering
4956  * at the receiving end of the queue.  This, however, would have a rather large
4957  * impact on the code base.  If there is an easy way to force processing of all
4958  * remaining input from within the "retrieve_surrounding" signal handler, this
4959  * might not be necessary.  Gotta ask on vim-dev for opinions.
4960  */
4961     static void
4962 im_preedit_changed_cb(GtkIMContext *context, gpointer data UNUSED)
4963 {
4964     char    *preedit_string = NULL;
4965     int	    cursor_index    = 0;
4966     int	    num_move_back   = 0;
4967     char_u  *str;
4968     char_u  *p;
4969     int	    i;
4970 
4971     gtk_im_context_get_preedit_string(context,
4972 				      &preedit_string, NULL,
4973 				      &cursor_index);
4974 
4975 #ifdef XIM_DEBUG
4976     xim_log("im_preedit_changed_cb(): %s\n", preedit_string);
4977 #endif
4978 
4979     g_return_if_fail(preedit_string != NULL); /* just in case */
4980 
4981     /* If preedit_start_col is MAXCOL set it to the current cursor position. */
4982     if (preedit_start_col == MAXCOL && preedit_string[0] != '\0')
4983     {
4984 	xim_has_preediting = TRUE;
4985 
4986 	/* Urgh, this breaks if the input buffer isn't empty now */
4987 	init_preedit_start_col();
4988     }
4989     else if (cursor_index == 0 && preedit_string[0] == '\0')
4990     {
4991 	xim_has_preediting = FALSE;
4992 
4993 	/* If at the start position (after typing backspace)
4994 	 * preedit_start_col must be reset. */
4995 	preedit_start_col = MAXCOL;
4996     }
4997 
4998     im_delete_preedit();
4999 
5000     /*
5001      * Compute the end of the preediting area: "preedit_end_col".
5002      * According to the documentation of gtk_im_context_get_preedit_string(),
5003      * the cursor_pos output argument returns the offset in bytes.  This is
5004      * unfortunately not true -- real life shows the offset is in characters,
5005      * and the GTK+ source code agrees with me.  Will file a bug later.
5006      */
5007     if (preedit_start_col != MAXCOL)
5008 	preedit_end_col = preedit_start_col;
5009     str = (char_u *)preedit_string;
5010     for (p = str, i = 0; *p != NUL; p += utf_byte2len(*p), ++i)
5011     {
5012 	int is_composing;
5013 
5014 	is_composing = ((*p & 0x80) != 0 && utf_iscomposing(utf_ptr2char(p)));
5015 	/*
5016 	 * These offsets are used as counters when generating <BS> and <Del>
5017 	 * to delete the preedit string.  So don't count composing characters
5018 	 * unless 'delcombine' is enabled.
5019 	 */
5020 	if (!is_composing || p_deco)
5021 	{
5022 	    if (i < cursor_index)
5023 		++im_preedit_cursor;
5024 	    else
5025 		++im_preedit_trailing;
5026 	}
5027 	if (!is_composing && i >= cursor_index)
5028 	{
5029 	    /* This is essentially the same as im_preedit_trailing, except
5030 	     * composing characters are not counted even if p_deco is set. */
5031 	    ++num_move_back;
5032 	}
5033 	if (preedit_start_col != MAXCOL)
5034 	    preedit_end_col += utf_ptr2cells(p);
5035     }
5036 
5037     if (p > str)
5038     {
5039 	im_add_to_input(str, (int)(p - str));
5040 	im_correct_cursor(num_move_back);
5041     }
5042 
5043     g_free(preedit_string);
5044 
5045     if (gtk_main_level() > 0)
5046 	gtk_main_quit();
5047 }
5048 
5049 /*
5050  * Translate the Pango attributes at iter to Vim highlighting attributes.
5051  * Ignore attributes not supported by Vim highlighting.  This shouldn't have
5052  * too much impact -- right now we handle even more attributes than necessary
5053  * for the IM modules I tested with.
5054  */
5055     static int
5056 translate_pango_attributes(PangoAttrIterator *iter)
5057 {
5058     PangoAttribute  *attr;
5059     int		    char_attr = HL_NORMAL;
5060 
5061     attr = pango_attr_iterator_get(iter, PANGO_ATTR_UNDERLINE);
5062     if (attr != NULL && ((PangoAttrInt *)attr)->value
5063 						 != (int)PANGO_UNDERLINE_NONE)
5064 	char_attr |= HL_UNDERLINE;
5065 
5066     attr = pango_attr_iterator_get(iter, PANGO_ATTR_WEIGHT);
5067     if (attr != NULL && ((PangoAttrInt *)attr)->value >= (int)PANGO_WEIGHT_BOLD)
5068 	char_attr |= HL_BOLD;
5069 
5070     attr = pango_attr_iterator_get(iter, PANGO_ATTR_STYLE);
5071     if (attr != NULL && ((PangoAttrInt *)attr)->value
5072 						   != (int)PANGO_STYLE_NORMAL)
5073 	char_attr |= HL_ITALIC;
5074 
5075     attr = pango_attr_iterator_get(iter, PANGO_ATTR_BACKGROUND);
5076     if (attr != NULL)
5077     {
5078 	const PangoColor *color = &((PangoAttrColor *)attr)->color;
5079 
5080 	/* Assume inverse if black background is requested */
5081 	if ((color->red | color->green | color->blue) == 0)
5082 	    char_attr |= HL_INVERSE;
5083     }
5084 
5085     return char_attr;
5086 }
5087 
5088 /*
5089  * Retrieve the highlighting attributes at column col in the preedit string.
5090  * Return -1 if not in preediting mode or if col is out of range.
5091  */
5092     int
5093 im_get_feedback_attr(int col)
5094 {
5095     char	    *preedit_string = NULL;
5096     PangoAttrList   *attr_list	    = NULL;
5097     int		    char_attr	    = -1;
5098 
5099     if (xic == NULL)
5100 	return char_attr;
5101 
5102     gtk_im_context_get_preedit_string(xic, &preedit_string, &attr_list, NULL);
5103 
5104     if (preedit_string != NULL && attr_list != NULL)
5105     {
5106 	int idx;
5107 
5108 	/* Get the byte index as used by PangoAttrIterator */
5109 	for (idx = 0; col > 0 && preedit_string[idx] != '\0'; --col)
5110 	    idx += utfc_ptr2len((char_u *)preedit_string + idx);
5111 
5112 	if (preedit_string[idx] != '\0')
5113 	{
5114 	    PangoAttrIterator	*iter;
5115 	    int			start, end;
5116 
5117 	    char_attr = HL_NORMAL;
5118 	    iter = pango_attr_list_get_iterator(attr_list);
5119 
5120 	    /* Extract all relevant attributes from the list. */
5121 	    do
5122 	    {
5123 		pango_attr_iterator_range(iter, &start, &end);
5124 
5125 		if (idx >= start && idx < end)
5126 		    char_attr |= translate_pango_attributes(iter);
5127 	    }
5128 	    while (pango_attr_iterator_next(iter));
5129 
5130 	    pango_attr_iterator_destroy(iter);
5131 	}
5132     }
5133 
5134     if (attr_list != NULL)
5135 	pango_attr_list_unref(attr_list);
5136     g_free(preedit_string);
5137 
5138     return char_attr;
5139 }
5140 
5141     void
5142 xim_init(void)
5143 {
5144 #ifdef XIM_DEBUG
5145     xim_log("xim_init()\n");
5146 #endif
5147 
5148     g_return_if_fail(gui.drawarea != NULL);
5149 #if GTK_CHECK_VERSION(3,0,0)
5150     g_return_if_fail(gtk_widget_get_window(gui.drawarea) != NULL);
5151 #else
5152     g_return_if_fail(gui.drawarea->window != NULL);
5153 #endif
5154 
5155     xic = gtk_im_multicontext_new();
5156     g_object_ref(xic);
5157 
5158     im_commit_handler_id = g_signal_connect(G_OBJECT(xic), "commit",
5159 					    G_CALLBACK(&im_commit_cb), NULL);
5160     g_signal_connect(G_OBJECT(xic), "preedit_changed",
5161 		     G_CALLBACK(&im_preedit_changed_cb), NULL);
5162     g_signal_connect(G_OBJECT(xic), "preedit_start",
5163 		     G_CALLBACK(&im_preedit_start_cb), NULL);
5164     g_signal_connect(G_OBJECT(xic), "preedit_end",
5165 		     G_CALLBACK(&im_preedit_end_cb), NULL);
5166 
5167 #if GTK_CHECK_VERSION(3,0,0)
5168     gtk_im_context_set_client_window(xic, gtk_widget_get_window(gui.drawarea));
5169 #else
5170     gtk_im_context_set_client_window(xic, gui.drawarea->window);
5171 #endif
5172 }
5173 
5174     void
5175 im_shutdown(void)
5176 {
5177 #ifdef XIM_DEBUG
5178     xim_log("im_shutdown()\n");
5179 #endif
5180 
5181     if (xic != NULL)
5182     {
5183 	gtk_im_context_focus_out(xic);
5184 	g_object_unref(xic);
5185 	xic = NULL;
5186     }
5187     im_is_active = FALSE;
5188     im_commit_handler_id = 0;
5189     preedit_start_col = MAXCOL;
5190     xim_has_preediting = FALSE;
5191 }
5192 
5193 /*
5194  * Convert the string argument to keyval and state for GdkEventKey.
5195  * If str is valid return TRUE, otherwise FALSE.
5196  *
5197  * See 'imactivatekey' for documentation of the format.
5198  */
5199     static int
5200 im_string_to_keyval(const char *str, unsigned int *keyval, unsigned int *state)
5201 {
5202     const char	    *mods_end;
5203     unsigned	    tmp_keyval;
5204     unsigned	    tmp_state = 0;
5205 
5206     mods_end = strrchr(str, '-');
5207     mods_end = (mods_end != NULL) ? mods_end + 1 : str;
5208 
5209     /* Parse modifier keys */
5210     while (str < mods_end)
5211 	switch (*str++)
5212 	{
5213 	    case '-':							break;
5214 	    case 'S': case 's': tmp_state |= (unsigned)GDK_SHIFT_MASK;	break;
5215 	    case 'L': case 'l': tmp_state |= (unsigned)GDK_LOCK_MASK;	break;
5216 	    case 'C': case 'c': tmp_state |= (unsigned)GDK_CONTROL_MASK;break;
5217 	    case '1':		tmp_state |= (unsigned)GDK_MOD1_MASK;	break;
5218 	    case '2':		tmp_state |= (unsigned)GDK_MOD2_MASK;	break;
5219 	    case '3':		tmp_state |= (unsigned)GDK_MOD3_MASK;	break;
5220 	    case '4':		tmp_state |= (unsigned)GDK_MOD4_MASK;	break;
5221 	    case '5':		tmp_state |= (unsigned)GDK_MOD5_MASK;	break;
5222 	    default:
5223 		return FALSE;
5224 	}
5225 
5226     tmp_keyval = gdk_keyval_from_name(str);
5227 
5228     if (tmp_keyval == 0 || tmp_keyval == GDK_VoidSymbol)
5229 	return FALSE;
5230 
5231     if (keyval != NULL)
5232 	*keyval = tmp_keyval;
5233     if (state != NULL)
5234 	*state = tmp_state;
5235 
5236     return TRUE;
5237 }
5238 
5239 /*
5240  * Return TRUE if p_imak is valid, otherwise FALSE.  As a special case, an
5241  * empty string is also regarded as valid.
5242  *
5243  * Note: The numerical key value of p_imak is cached if it was valid; thus
5244  * boldly assuming im_xim_isvalid_imactivate() will always be called whenever
5245  * 'imak' changes.  This is currently the case but not obvious -- should
5246  * probably rename the function for clarity.
5247  */
5248     int
5249 im_xim_isvalid_imactivate(void)
5250 {
5251     if (p_imak[0] == NUL)
5252     {
5253 	im_activatekey_keyval = GDK_VoidSymbol;
5254 	im_activatekey_state  = 0;
5255 	return TRUE;
5256     }
5257 
5258     return im_string_to_keyval((const char *)p_imak,
5259 			       &im_activatekey_keyval,
5260 			       &im_activatekey_state);
5261 }
5262 
5263     static void
5264 im_synthesize_keypress(unsigned int keyval, unsigned int state)
5265 {
5266     GdkEventKey *event;
5267 
5268 #  ifdef HAVE_GTK_MULTIHEAD
5269     event = (GdkEventKey *)gdk_event_new(GDK_KEY_PRESS);
5270 #   if GTK_CHECK_VERSION(3,0,0)
5271     g_object_ref(gtk_widget_get_window(gui.drawarea));
5272 					/* unreffed by gdk_event_free() */
5273 #   else
5274     g_object_ref(gui.drawarea->window); /* unreffed by gdk_event_free() */
5275 #   endif
5276 #  else
5277     event = (GdkEventKey *)g_malloc0((gulong)sizeof(GdkEvent));
5278     event->type = GDK_KEY_PRESS;
5279 #  endif
5280 #  if GTK_CHECK_VERSION(3,0,0)
5281     event->window = gtk_widget_get_window(gui.drawarea);
5282 #  else
5283     event->window = gui.drawarea->window;
5284 #  endif
5285     event->send_event = TRUE;
5286     event->time = GDK_CURRENT_TIME;
5287     event->state  = state;
5288     event->keyval = keyval;
5289     event->hardware_keycode = /* needed for XIM */
5290 	XKeysymToKeycode(GDK_WINDOW_XDISPLAY(event->window), (KeySym)keyval);
5291     event->length = 0;
5292     event->string = NULL;
5293 
5294     gtk_im_context_filter_keypress(xic, event);
5295 
5296     /* For consistency, also send the corresponding release event. */
5297     event->type = GDK_KEY_RELEASE;
5298     event->send_event = FALSE;
5299     gtk_im_context_filter_keypress(xic, event);
5300 
5301 #  ifdef HAVE_GTK_MULTIHEAD
5302     gdk_event_free((GdkEvent *)event);
5303 #  else
5304     g_free(event);
5305 #  endif
5306 }
5307 
5308     void
5309 xim_reset(void)
5310 {
5311     if (xic != NULL)
5312     {
5313 	gtk_im_context_reset(xic);
5314 
5315 	if (p_imdisable)
5316 	    im_shutdown();
5317 	else
5318 	{
5319 	    xim_set_focus(gui.in_focus);
5320 
5321 #  ifdef FEAT_EVAL
5322 	    if (p_imaf[0] != NUL)
5323 	    {
5324 		char_u *argv[1];
5325 
5326 		if (im_is_active)
5327 		    argv[0] = (char_u *)"1";
5328 		else
5329 		    argv[0] = (char_u *)"0";
5330 		(void)call_func_retnr(p_imaf, 1, argv, FALSE);
5331 	    }
5332 	    else
5333 #  endif
5334 		if (im_activatekey_keyval != GDK_VoidSymbol)
5335 	    {
5336 		if (im_is_active)
5337 		{
5338 		    g_signal_handler_block(xic, im_commit_handler_id);
5339 		    im_synthesize_keypress(im_activatekey_keyval,
5340 						    im_activatekey_state);
5341 		    g_signal_handler_unblock(xic, im_commit_handler_id);
5342 		}
5343 	    }
5344 	    else
5345 	    {
5346 		im_shutdown();
5347 		xim_init();
5348 		xim_set_focus(gui.in_focus);
5349 	    }
5350 	}
5351     }
5352 
5353     preedit_start_col = MAXCOL;
5354     xim_has_preediting = FALSE;
5355 }
5356 
5357     int
5358 xim_queue_key_press_event(GdkEventKey *event, int down)
5359 {
5360     if (down)
5361     {
5362 	/*
5363 	 * Workaround GTK2 XIM 'feature' that always converts keypad keys to
5364 	 * chars., even when not part of an IM sequence (ref. feature of
5365 	 * gdk/gdkkeyuni.c).
5366 	 * Flag any keypad keys that might represent a single char.
5367 	 * If this (on its own - i.e., not part of an IM sequence) is
5368 	 * committed while we're processing one of these keys, we can ignore
5369 	 * that commit and go ahead & process it ourselves.  That way we can
5370 	 * still distinguish keypad keys for use in mappings.
5371 	 * Also add GDK_space to make <S-Space> work.
5372 	 */
5373 	switch (event->keyval)
5374 	{
5375 	    case GDK_KP_Add:      xim_expected_char = '+';  break;
5376 	    case GDK_KP_Subtract: xim_expected_char = '-';  break;
5377 	    case GDK_KP_Divide:   xim_expected_char = '/';  break;
5378 	    case GDK_KP_Multiply: xim_expected_char = '*';  break;
5379 	    case GDK_KP_Decimal:  xim_expected_char = '.';  break;
5380 	    case GDK_KP_Equal:    xim_expected_char = '=';  break;
5381 	    case GDK_KP_0:	  xim_expected_char = '0';  break;
5382 	    case GDK_KP_1:	  xim_expected_char = '1';  break;
5383 	    case GDK_KP_2:	  xim_expected_char = '2';  break;
5384 	    case GDK_KP_3:	  xim_expected_char = '3';  break;
5385 	    case GDK_KP_4:	  xim_expected_char = '4';  break;
5386 	    case GDK_KP_5:	  xim_expected_char = '5';  break;
5387 	    case GDK_KP_6:	  xim_expected_char = '6';  break;
5388 	    case GDK_KP_7:	  xim_expected_char = '7';  break;
5389 	    case GDK_KP_8:	  xim_expected_char = '8';  break;
5390 	    case GDK_KP_9:	  xim_expected_char = '9';  break;
5391 	    case GDK_space:	  xim_expected_char = ' ';  break;
5392 	    default:		  xim_expected_char = NUL;
5393 	}
5394 	xim_ignored_char = FALSE;
5395     }
5396 
5397     /*
5398      * When typing fFtT, XIM may be activated. Thus it must pass
5399      * gtk_im_context_filter_keypress() in Normal mode.
5400      * And while doing :sh too.
5401      */
5402     if (xic != NULL && !p_imdisable
5403 		    && (State & (INSERT | CMDLINE | NORMAL | EXTERNCMD)) != 0)
5404     {
5405 	/*
5406 	 * Filter 'imactivatekey' and map it to CTRL-^.  This way, Vim is
5407 	 * always aware of the current status of IM, and can even emulate
5408 	 * the activation key for modules that don't support one.
5409 	 */
5410 	if (event->keyval == im_activatekey_keyval
5411 	     && (event->state & im_activatekey_state) == im_activatekey_state)
5412 	{
5413 	    unsigned int state_mask;
5414 
5415 	    /* Require the state of the 3 most used modifiers to match exactly.
5416 	     * Otherwise e.g. <S-C-space> would be unusable for other purposes
5417 	     * if the IM activate key is <S-space>. */
5418 	    state_mask  = im_activatekey_state;
5419 	    state_mask |= ((int)GDK_SHIFT_MASK | (int)GDK_CONTROL_MASK
5420 							| (int)GDK_MOD1_MASK);
5421 
5422 	    if ((event->state & state_mask) != im_activatekey_state)
5423 		return FALSE;
5424 
5425 	    /* Don't send it a second time on GDK_KEY_RELEASE. */
5426 	    if (event->type != GDK_KEY_PRESS)
5427 		return TRUE;
5428 
5429 	    if (map_to_exists_mode((char_u *)"", LANGMAP, FALSE))
5430 	    {
5431 		im_set_active(FALSE);
5432 
5433 		/* ":lmap" mappings exists, toggle use of mappings. */
5434 		State ^= LANGMAP;
5435 		if (State & LANGMAP)
5436 		{
5437 		    curbuf->b_p_iminsert = B_IMODE_NONE;
5438 		    State &= ~LANGMAP;
5439 		}
5440 		else
5441 		{
5442 		    curbuf->b_p_iminsert = B_IMODE_LMAP;
5443 		    State |= LANGMAP;
5444 		}
5445 		return TRUE;
5446 	    }
5447 
5448 	    return gtk_im_context_filter_keypress(xic, event);
5449 	}
5450 
5451 	/* Don't filter events through the IM context if IM isn't active
5452 	 * right now.  Unlike with GTK+ 1.2 we cannot rely on the IM module
5453 	 * not doing anything before the activation key was sent. */
5454 	if (im_activatekey_keyval == GDK_VoidSymbol || im_is_active)
5455 	{
5456 	    int imresult = gtk_im_context_filter_keypress(xic, event);
5457 
5458 	    /* Some XIM send following sequence:
5459 	     * 1. preedited string.
5460 	     * 2. committed string.
5461 	     * 3. line changed key.
5462 	     * 4. preedited string.
5463 	     * 5. remove preedited string.
5464 	     * if 3, Vim can't move back the above line for 5.
5465 	     * thus, this part should not parse the key. */
5466 	    if (!imresult && preedit_start_col != MAXCOL
5467 					       && event->keyval == GDK_Return)
5468 	    {
5469 		im_synthesize_keypress(GDK_Return, 0U);
5470 		return FALSE;
5471 	    }
5472 
5473 	    /* If XIM tried to commit a keypad key as a single char.,
5474 	     * ignore it so we can use the keypad key 'raw', for mappings. */
5475 	    if (xim_expected_char != NUL && xim_ignored_char)
5476 		/* We had a keypad key, and XIM tried to thieve it */
5477 		return FALSE;
5478 
5479 	    /* This is supposed to fix a problem with iBus, that space
5480 	     * characters don't work in input mode. */
5481 	    xim_expected_char = NUL;
5482 
5483 	    /* Normal processing */
5484 	    return imresult;
5485 	}
5486     }
5487 
5488     return FALSE;
5489 }
5490 
5491     int
5492 im_get_status(void)
5493 {
5494 #  ifdef FEAT_EVAL
5495     if (p_imsf[0] != NUL)
5496     {
5497 	int is_active;
5498 
5499 	/* FIXME: Don't execute user function in unsafe situation. */
5500 	if (exiting
5501 #   ifdef FEAT_AUTOCMD
5502 		|| is_autocmd_blocked()
5503 #   endif
5504 		)
5505 	    return FALSE;
5506 	/* FIXME: :py print 'xxx' is shown duplicate result.
5507 	 * Use silent to avoid it. */
5508 	++msg_silent;
5509 	is_active = call_func_retnr(p_imsf, 0, NULL, FALSE);
5510 	--msg_silent;
5511 	return (is_active > 0);
5512     }
5513 #  endif
5514     return im_is_active;
5515 }
5516 
5517     int
5518 preedit_get_status(void)
5519 {
5520     return preedit_is_active;
5521 }
5522 
5523     int
5524 im_is_preediting(void)
5525 {
5526     return xim_has_preediting;
5527 }
5528 
5529 # else /* !FEAT_GUI_GTK */
5530 
5531 static int	xim_is_active = FALSE;  /* XIM should be active in the current
5532 					   mode */
5533 static int	xim_has_focus = FALSE;	/* XIM is really being used for Vim */
5534 #ifdef FEAT_GUI_X11
5535 static XIMStyle	input_style;
5536 static int	status_area_enabled = TRUE;
5537 #endif
5538 
5539 /*
5540  * Switch using XIM on/off.  This is used by the code that changes "State".
5541  */
5542     void
5543 im_set_active(int active)
5544 {
5545     if (xic == NULL)
5546 	return;
5547 
5548     /* If 'imdisable' is set, XIM is never active. */
5549     if (p_imdisable)
5550 	active = FALSE;
5551 #if !defined(FEAT_GUI_GTK)
5552     else if (input_style & XIMPreeditPosition)
5553 	/* There is a problem in switching XIM off when preediting is used,
5554 	 * and it is not clear how this can be solved.  For now, keep XIM on
5555 	 * all the time, like it was done in Vim 5.8. */
5556 	active = TRUE;
5557 #endif
5558 
5559     /* Remember the active state, it is needed when Vim gets keyboard focus. */
5560     xim_is_active = active;
5561     xim_set_preedit();
5562 }
5563 
5564 /*
5565  * Adjust using XIM for gaining or losing keyboard focus.  Also called when
5566  * "xim_is_active" changes.
5567  */
5568     void
5569 xim_set_focus(int focus)
5570 {
5571     if (xic == NULL)
5572 	return;
5573 
5574     /*
5575      * XIM only gets focus when the Vim window has keyboard focus and XIM has
5576      * been set active for the current mode.
5577      */
5578     if (focus && xim_is_active)
5579     {
5580 	if (!xim_has_focus)
5581 	{
5582 	    xim_has_focus = TRUE;
5583 	    XSetICFocus(xic);
5584 	}
5585     }
5586     else
5587     {
5588 	if (xim_has_focus)
5589 	{
5590 	    xim_has_focus = FALSE;
5591 	    XUnsetICFocus(xic);
5592 	}
5593     }
5594 }
5595 
5596     void
5597 im_set_position(int row UNUSED, int col UNUSED)
5598 {
5599     xim_set_preedit();
5600 }
5601 
5602 /*
5603  * Set the XIM to the current cursor position.
5604  */
5605     void
5606 xim_set_preedit(void)
5607 {
5608     XVaNestedList attr_list;
5609     XRectangle spot_area;
5610     XPoint over_spot;
5611     int line_space;
5612 
5613     if (xic == NULL)
5614 	return;
5615 
5616     xim_set_focus(TRUE);
5617 
5618     if (!xim_has_focus)
5619     {
5620 	/* hide XIM cursor */
5621 	over_spot.x = 0;
5622 	over_spot.y = -100; /* arbitrary invisible position */
5623 	attr_list = (XVaNestedList) XVaCreateNestedList(0,
5624 							XNSpotLocation,
5625 							&over_spot,
5626 							NULL);
5627 	XSetICValues(xic, XNPreeditAttributes, attr_list, NULL);
5628 	XFree(attr_list);
5629 	return;
5630     }
5631 
5632     if (input_style & XIMPreeditPosition)
5633     {
5634 	if (xim_fg_color == INVALCOLOR)
5635 	{
5636 	    xim_fg_color = gui.def_norm_pixel;
5637 	    xim_bg_color = gui.def_back_pixel;
5638 	}
5639 	over_spot.x = TEXT_X(gui.col);
5640 	over_spot.y = TEXT_Y(gui.row);
5641 	spot_area.x = 0;
5642 	spot_area.y = 0;
5643 	spot_area.height = gui.char_height * Rows;
5644 	spot_area.width  = gui.char_width * Columns;
5645 	line_space = gui.char_height;
5646 	attr_list = (XVaNestedList) XVaCreateNestedList(0,
5647 					XNSpotLocation, &over_spot,
5648 					XNForeground, (Pixel) xim_fg_color,
5649 					XNBackground, (Pixel) xim_bg_color,
5650 					XNArea, &spot_area,
5651 					XNLineSpace, line_space,
5652 					NULL);
5653 	if (XSetICValues(xic, XNPreeditAttributes, attr_list, NULL))
5654 	    EMSG(_("E284: Cannot set IC values"));
5655 	XFree(attr_list);
5656     }
5657 }
5658 
5659 #if defined(FEAT_GUI_X11)
5660 static char e_xim[] = N_("E285: Failed to create input context");
5661 #endif
5662 
5663 #if defined(FEAT_GUI_X11) || defined(PROTO)
5664 # if defined(XtSpecificationRelease) && XtSpecificationRelease >= 6 && !defined(sun)
5665 #  define USE_X11R6_XIM
5666 # endif
5667 
5668 static int xim_real_init(Window x11_window, Display *x11_display);
5669 
5670 
5671 #ifdef USE_X11R6_XIM
5672 static void xim_instantiate_cb(Display *display, XPointer client_data, XPointer	call_data);
5673 static void xim_destroy_cb(XIM im, XPointer client_data, XPointer call_data);
5674 
5675     static void
5676 xim_instantiate_cb(
5677     Display	*display,
5678     XPointer	client_data UNUSED,
5679     XPointer	call_data UNUSED)
5680 {
5681     Window	x11_window;
5682     Display	*x11_display;
5683 
5684 #ifdef XIM_DEBUG
5685     xim_log("xim_instantiate_cb()\n");
5686 #endif
5687 
5688     gui_get_x11_windis(&x11_window, &x11_display);
5689     if (display != x11_display)
5690 	return;
5691 
5692     xim_real_init(x11_window, x11_display);
5693     gui_set_shellsize(FALSE, FALSE, RESIZE_BOTH);
5694     if (xic != NULL)
5695 	XUnregisterIMInstantiateCallback(x11_display, NULL, NULL, NULL,
5696 					 xim_instantiate_cb, NULL);
5697 }
5698 
5699     static void
5700 xim_destroy_cb(
5701     XIM		im UNUSED,
5702     XPointer	client_data UNUSED,
5703     XPointer	call_data UNUSED)
5704 {
5705     Window	x11_window;
5706     Display	*x11_display;
5707 
5708 #ifdef XIM_DEBUG
5709     xim_log("xim_destroy_cb()\n");
5710 #endif
5711     gui_get_x11_windis(&x11_window, &x11_display);
5712 
5713     xic = NULL;
5714     status_area_enabled = FALSE;
5715 
5716     gui_set_shellsize(FALSE, FALSE, RESIZE_BOTH);
5717 
5718     XRegisterIMInstantiateCallback(x11_display, NULL, NULL, NULL,
5719 				   xim_instantiate_cb, NULL);
5720 }
5721 #endif
5722 
5723     void
5724 xim_init(void)
5725 {
5726     Window	x11_window;
5727     Display	*x11_display;
5728 
5729 #ifdef XIM_DEBUG
5730     xim_log("xim_init()\n");
5731 #endif
5732 
5733     gui_get_x11_windis(&x11_window, &x11_display);
5734 
5735     xic = NULL;
5736 
5737     if (xim_real_init(x11_window, x11_display))
5738 	return;
5739 
5740     gui_set_shellsize(FALSE, FALSE, RESIZE_BOTH);
5741 
5742 #ifdef USE_X11R6_XIM
5743     XRegisterIMInstantiateCallback(x11_display, NULL, NULL, NULL,
5744 				   xim_instantiate_cb, NULL);
5745 #endif
5746 }
5747 
5748     static int
5749 xim_real_init(Window x11_window, Display *x11_display)
5750 {
5751     int		i;
5752     char	*p,
5753 		*s,
5754 		*ns,
5755 		*end,
5756 		tmp[1024];
5757 #define IMLEN_MAX 40
5758     char	buf[IMLEN_MAX + 7];
5759     XIM		xim = NULL;
5760     XIMStyles	*xim_styles;
5761     XIMStyle	this_input_style = 0;
5762     Boolean	found;
5763     XPoint	over_spot;
5764     XVaNestedList preedit_list, status_list;
5765 
5766     input_style = 0;
5767     status_area_enabled = FALSE;
5768 
5769     if (xic != NULL)
5770 	return FALSE;
5771 
5772     if (gui.rsrc_input_method != NULL && *gui.rsrc_input_method != NUL)
5773     {
5774 	strcpy(tmp, gui.rsrc_input_method);
5775 	for (ns = s = tmp; ns != NULL && *s != NUL;)
5776 	{
5777 	    s = (char *)skipwhite((char_u *)s);
5778 	    if (*s == NUL)
5779 		break;
5780 	    if ((ns = end = strchr(s, ',')) == NULL)
5781 		end = s + strlen(s);
5782 	    while (isspace(((char_u *)end)[-1]))
5783 		end--;
5784 	    *end = NUL;
5785 
5786 	    if (strlen(s) <= IMLEN_MAX)
5787 	    {
5788 		strcpy(buf, "@im=");
5789 		strcat(buf, s);
5790 		if ((p = XSetLocaleModifiers(buf)) != NULL && *p != NUL
5791 			&& (xim = XOpenIM(x11_display, NULL, NULL, NULL))
5792 								      != NULL)
5793 		    break;
5794 	    }
5795 
5796 	    s = ns + 1;
5797 	}
5798     }
5799 
5800     if (xim == NULL && (p = XSetLocaleModifiers("")) != NULL && *p != NUL)
5801 	xim = XOpenIM(x11_display, NULL, NULL, NULL);
5802 
5803     /* This is supposed to be useful to obtain characters through
5804      * XmbLookupString() without really using a XIM. */
5805     if (xim == NULL && (p = XSetLocaleModifiers("@im=none")) != NULL
5806 								 && *p != NUL)
5807 	xim = XOpenIM(x11_display, NULL, NULL, NULL);
5808 
5809     if (xim == NULL)
5810     {
5811 	/* Only give this message when verbose is set, because too many people
5812 	 * got this message when they didn't want to use a XIM. */
5813 	if (p_verbose > 0)
5814 	{
5815 	    verbose_enter();
5816 	    EMSG(_("E286: Failed to open input method"));
5817 	    verbose_leave();
5818 	}
5819 	return FALSE;
5820     }
5821 
5822 #ifdef USE_X11R6_XIM
5823     {
5824 	XIMCallback destroy_cb;
5825 
5826 	destroy_cb.callback = xim_destroy_cb;
5827 	destroy_cb.client_data = NULL;
5828 	if (XSetIMValues(xim, XNDestroyCallback, &destroy_cb, NULL))
5829 	    EMSG(_("E287: Warning: Could not set destroy callback to IM"));
5830     }
5831 #endif
5832 
5833     if (XGetIMValues(xim, XNQueryInputStyle, &xim_styles, NULL) || !xim_styles)
5834     {
5835 	EMSG(_("E288: input method doesn't support any style"));
5836 	XCloseIM(xim);
5837 	return FALSE;
5838     }
5839 
5840     found = False;
5841     strcpy(tmp, gui.rsrc_preedit_type_name);
5842     for (s = tmp; s && !found; )
5843     {
5844 	while (*s && isspace((unsigned char)*s))
5845 	    s++;
5846 	if (!*s)
5847 	    break;
5848 	if ((ns = end = strchr(s, ',')) != 0)
5849 	    ns++;
5850 	else
5851 	    end = s + strlen(s);
5852 	while (isspace((unsigned char)*end))
5853 	    end--;
5854 	*end = '\0';
5855 
5856 	if (!strcmp(s, "OverTheSpot"))
5857 	    this_input_style = (XIMPreeditPosition | XIMStatusArea);
5858 	else if (!strcmp(s, "OffTheSpot"))
5859 	    this_input_style = (XIMPreeditArea | XIMStatusArea);
5860 	else if (!strcmp(s, "Root"))
5861 	    this_input_style = (XIMPreeditNothing | XIMStatusNothing);
5862 
5863 	for (i = 0; (unsigned short)i < xim_styles->count_styles; i++)
5864 	{
5865 	    if (this_input_style == xim_styles->supported_styles[i])
5866 	    {
5867 		found = True;
5868 		break;
5869 	    }
5870 	}
5871 	if (!found)
5872 	    for (i = 0; (unsigned short)i < xim_styles->count_styles; i++)
5873 	    {
5874 		if ((xim_styles->supported_styles[i] & this_input_style)
5875 			== (this_input_style & ~XIMStatusArea))
5876 		{
5877 		    this_input_style &= ~XIMStatusArea;
5878 		    found = True;
5879 		    break;
5880 		}
5881 	    }
5882 
5883 	s = ns;
5884     }
5885     XFree(xim_styles);
5886 
5887     if (!found)
5888     {
5889 	/* Only give this message when verbose is set, because too many people
5890 	 * got this message when they didn't want to use a XIM. */
5891 	if (p_verbose > 0)
5892 	{
5893 	    verbose_enter();
5894 	    EMSG(_("E289: input method doesn't support my preedit type"));
5895 	    verbose_leave();
5896 	}
5897 	XCloseIM(xim);
5898 	return FALSE;
5899     }
5900 
5901     over_spot.x = TEXT_X(gui.col);
5902     over_spot.y = TEXT_Y(gui.row);
5903     input_style = this_input_style;
5904 
5905     /* A crash was reported when trying to pass gui.norm_font as XNFontSet,
5906      * thus that has been removed.  Hopefully the default works... */
5907 #ifdef FEAT_XFONTSET
5908     if (gui.fontset != NOFONTSET)
5909     {
5910 	preedit_list = XVaCreateNestedList(0,
5911 				XNSpotLocation, &over_spot,
5912 				XNForeground, (Pixel)gui.def_norm_pixel,
5913 				XNBackground, (Pixel)gui.def_back_pixel,
5914 				XNFontSet, (XFontSet)gui.fontset,
5915 				NULL);
5916 	status_list = XVaCreateNestedList(0,
5917 				XNForeground, (Pixel)gui.def_norm_pixel,
5918 				XNBackground, (Pixel)gui.def_back_pixel,
5919 				XNFontSet, (XFontSet)gui.fontset,
5920 				NULL);
5921     }
5922     else
5923 #endif
5924     {
5925 	preedit_list = XVaCreateNestedList(0,
5926 				XNSpotLocation, &over_spot,
5927 				XNForeground, (Pixel)gui.def_norm_pixel,
5928 				XNBackground, (Pixel)gui.def_back_pixel,
5929 				NULL);
5930 	status_list = XVaCreateNestedList(0,
5931 				XNForeground, (Pixel)gui.def_norm_pixel,
5932 				XNBackground, (Pixel)gui.def_back_pixel,
5933 				NULL);
5934     }
5935 
5936     xic = XCreateIC(xim,
5937 		    XNInputStyle, input_style,
5938 		    XNClientWindow, x11_window,
5939 		    XNFocusWindow, gui.wid,
5940 		    XNPreeditAttributes, preedit_list,
5941 		    XNStatusAttributes, status_list,
5942 		    NULL);
5943     XFree(status_list);
5944     XFree(preedit_list);
5945     if (xic != NULL)
5946     {
5947 	if (input_style & XIMStatusArea)
5948 	{
5949 	    xim_set_status_area();
5950 	    status_area_enabled = TRUE;
5951 	}
5952 	else
5953 	    gui_set_shellsize(FALSE, FALSE, RESIZE_BOTH);
5954     }
5955     else
5956     {
5957 	EMSG(_(e_xim));
5958 	XCloseIM(xim);
5959 	return FALSE;
5960     }
5961 
5962     return TRUE;
5963 }
5964 
5965 #endif /* FEAT_GUI_X11 */
5966 
5967 /*
5968  * Get IM status.  When IM is on, return TRUE.  Else return FALSE.
5969  * FIXME: This doesn't work correctly: Having focus doesn't always mean XIM is
5970  * active, when not having focus XIM may still be active (e.g., when using a
5971  * tear-off menu item).
5972  */
5973     int
5974 im_get_status(void)
5975 {
5976     return xim_has_focus;
5977 }
5978 
5979 # endif /* !FEAT_GUI_GTK */
5980 
5981 # if !defined(FEAT_GUI_GTK) || defined(PROTO)
5982 /*
5983  * Set up the status area.
5984  *
5985  * This should use a separate Widget, but that seems not possible, because
5986  * preedit_area and status_area should be set to the same window as for the
5987  * text input.  Unfortunately this means the status area pollutes the text
5988  * window...
5989  */
5990     void
5991 xim_set_status_area(void)
5992 {
5993     XVaNestedList preedit_list = 0, status_list = 0, list = 0;
5994     XRectangle pre_area, status_area;
5995 
5996     if (xic == NULL)
5997 	return;
5998 
5999     if (input_style & XIMStatusArea)
6000     {
6001 	if (input_style & XIMPreeditArea)
6002 	{
6003 	    XRectangle *needed_rect;
6004 
6005 	    /* to get status_area width */
6006 	    status_list = XVaCreateNestedList(0, XNAreaNeeded,
6007 					      &needed_rect, NULL);
6008 	    XGetICValues(xic, XNStatusAttributes, status_list, NULL);
6009 	    XFree(status_list);
6010 
6011 	    status_area.width = needed_rect->width;
6012 	}
6013 	else
6014 	    status_area.width = gui.char_width * Columns;
6015 
6016 	status_area.x = 0;
6017 	status_area.y = gui.char_height * Rows + gui.border_offset;
6018 	if (gui.which_scrollbars[SBAR_BOTTOM])
6019 	    status_area.y += gui.scrollbar_height;
6020 #ifdef FEAT_MENU
6021 	if (gui.menu_is_active)
6022 	    status_area.y += gui.menu_height;
6023 #endif
6024 	status_area.height = gui.char_height;
6025 	status_list = XVaCreateNestedList(0, XNArea, &status_area, NULL);
6026     }
6027     else
6028     {
6029 	status_area.x = 0;
6030 	status_area.y = gui.char_height * Rows + gui.border_offset;
6031 	if (gui.which_scrollbars[SBAR_BOTTOM])
6032 	    status_area.y += gui.scrollbar_height;
6033 #ifdef FEAT_MENU
6034 	if (gui.menu_is_active)
6035 	    status_area.y += gui.menu_height;
6036 #endif
6037 	status_area.width = 0;
6038 	status_area.height = gui.char_height;
6039     }
6040 
6041     if (input_style & XIMPreeditArea)   /* off-the-spot */
6042     {
6043 	pre_area.x = status_area.x + status_area.width;
6044 	pre_area.y = gui.char_height * Rows + gui.border_offset;
6045 	pre_area.width = gui.char_width * Columns - pre_area.x;
6046 	if (gui.which_scrollbars[SBAR_BOTTOM])
6047 	    pre_area.y += gui.scrollbar_height;
6048 #ifdef FEAT_MENU
6049 	if (gui.menu_is_active)
6050 	    pre_area.y += gui.menu_height;
6051 #endif
6052 	pre_area.height = gui.char_height;
6053 	preedit_list = XVaCreateNestedList(0, XNArea, &pre_area, NULL);
6054     }
6055     else if (input_style & XIMPreeditPosition)   /* over-the-spot */
6056     {
6057 	pre_area.x = 0;
6058 	pre_area.y = 0;
6059 	pre_area.height = gui.char_height * Rows;
6060 	pre_area.width = gui.char_width * Columns;
6061 	preedit_list = XVaCreateNestedList(0, XNArea, &pre_area, NULL);
6062     }
6063 
6064     if (preedit_list && status_list)
6065 	list = XVaCreateNestedList(0, XNPreeditAttributes, preedit_list,
6066 				   XNStatusAttributes, status_list, NULL);
6067     else if (preedit_list)
6068 	list = XVaCreateNestedList(0, XNPreeditAttributes, preedit_list,
6069 				   NULL);
6070     else if (status_list)
6071 	list = XVaCreateNestedList(0, XNStatusAttributes, status_list,
6072 				   NULL);
6073     else
6074 	list = NULL;
6075 
6076     if (list)
6077     {
6078 	XSetICValues(xic, XNVaNestedList, list, NULL);
6079 	XFree(list);
6080     }
6081     if (status_list)
6082 	XFree(status_list);
6083     if (preedit_list)
6084 	XFree(preedit_list);
6085 }
6086 
6087     int
6088 xim_get_status_area_height(void)
6089 {
6090     if (status_area_enabled)
6091 	return gui.char_height;
6092     return 0;
6093 }
6094 # endif
6095 
6096 #endif /* FEAT_XIM */
6097 
6098 #if defined(FEAT_MBYTE) || defined(PROTO)
6099 
6100 /*
6101  * Setup "vcp" for conversion from "from" to "to".
6102  * The names must have been made canonical with enc_canonize().
6103  * vcp->vc_type must have been initialized to CONV_NONE.
6104  * Note: cannot be used for conversion from/to ucs-2 and ucs-4 (will use utf-8
6105  * instead).
6106  * Afterwards invoke with "from" and "to" equal to NULL to cleanup.
6107  * Return FAIL when conversion is not supported, OK otherwise.
6108  */
6109     int
6110 convert_setup(vimconv_T *vcp, char_u *from, char_u *to)
6111 {
6112     return convert_setup_ext(vcp, from, TRUE, to, TRUE);
6113 }
6114 
6115 /*
6116  * As convert_setup(), but only when from_unicode_is_utf8 is TRUE will all
6117  * "from" unicode charsets be considered utf-8.  Same for "to".
6118  */
6119     int
6120 convert_setup_ext(
6121     vimconv_T	*vcp,
6122     char_u	*from,
6123     int		from_unicode_is_utf8,
6124     char_u	*to,
6125     int		to_unicode_is_utf8)
6126 {
6127     int		from_prop;
6128     int		to_prop;
6129     int		from_is_utf8;
6130     int		to_is_utf8;
6131 
6132     /* Reset to no conversion. */
6133 # ifdef USE_ICONV
6134     if (vcp->vc_type == CONV_ICONV && vcp->vc_fd != (iconv_t)-1)
6135 	iconv_close(vcp->vc_fd);
6136 # endif
6137     vcp->vc_type = CONV_NONE;
6138     vcp->vc_factor = 1;
6139     vcp->vc_fail = FALSE;
6140 
6141     /* No conversion when one of the names is empty or they are equal. */
6142     if (from == NULL || *from == NUL || to == NULL || *to == NUL
6143 						     || STRCMP(from, to) == 0)
6144 	return OK;
6145 
6146     from_prop = enc_canon_props(from);
6147     to_prop = enc_canon_props(to);
6148     if (from_unicode_is_utf8)
6149 	from_is_utf8 = from_prop & ENC_UNICODE;
6150     else
6151 	from_is_utf8 = from_prop == ENC_UNICODE;
6152     if (to_unicode_is_utf8)
6153 	to_is_utf8 = to_prop & ENC_UNICODE;
6154     else
6155 	to_is_utf8 = to_prop == ENC_UNICODE;
6156 
6157     if ((from_prop & ENC_LATIN1) && to_is_utf8)
6158     {
6159 	/* Internal latin1 -> utf-8 conversion. */
6160 	vcp->vc_type = CONV_TO_UTF8;
6161 	vcp->vc_factor = 2;	/* up to twice as long */
6162     }
6163     else if ((from_prop & ENC_LATIN9) && to_is_utf8)
6164     {
6165 	/* Internal latin9 -> utf-8 conversion. */
6166 	vcp->vc_type = CONV_9_TO_UTF8;
6167 	vcp->vc_factor = 3;	/* up to three as long (euro sign) */
6168     }
6169     else if (from_is_utf8 && (to_prop & ENC_LATIN1))
6170     {
6171 	/* Internal utf-8 -> latin1 conversion. */
6172 	vcp->vc_type = CONV_TO_LATIN1;
6173     }
6174     else if (from_is_utf8 && (to_prop & ENC_LATIN9))
6175     {
6176 	/* Internal utf-8 -> latin9 conversion. */
6177 	vcp->vc_type = CONV_TO_LATIN9;
6178     }
6179 #ifdef WIN3264
6180     /* Win32-specific codepage <-> codepage conversion without iconv. */
6181     else if ((from_is_utf8 || encname2codepage(from) > 0)
6182 	    && (to_is_utf8 || encname2codepage(to) > 0))
6183     {
6184 	vcp->vc_type = CONV_CODEPAGE;
6185 	vcp->vc_factor = 2;	/* up to twice as long */
6186 	vcp->vc_cpfrom = from_is_utf8 ? 0 : encname2codepage(from);
6187 	vcp->vc_cpto = to_is_utf8 ? 0 : encname2codepage(to);
6188     }
6189 #endif
6190 #ifdef MACOS_X
6191     else if ((from_prop & ENC_MACROMAN) && (to_prop & ENC_LATIN1))
6192     {
6193 	vcp->vc_type = CONV_MAC_LATIN1;
6194     }
6195     else if ((from_prop & ENC_MACROMAN) && to_is_utf8)
6196     {
6197 	vcp->vc_type = CONV_MAC_UTF8;
6198 	vcp->vc_factor = 2;	/* up to twice as long */
6199     }
6200     else if ((from_prop & ENC_LATIN1) && (to_prop & ENC_MACROMAN))
6201     {
6202 	vcp->vc_type = CONV_LATIN1_MAC;
6203     }
6204     else if (from_is_utf8 && (to_prop & ENC_MACROMAN))
6205     {
6206 	vcp->vc_type = CONV_UTF8_MAC;
6207     }
6208 #endif
6209 # ifdef USE_ICONV
6210     else
6211     {
6212 	/* Use iconv() for conversion. */
6213 	vcp->vc_fd = (iconv_t)my_iconv_open(
6214 		to_is_utf8 ? (char_u *)"utf-8" : to,
6215 		from_is_utf8 ? (char_u *)"utf-8" : from);
6216 	if (vcp->vc_fd != (iconv_t)-1)
6217 	{
6218 	    vcp->vc_type = CONV_ICONV;
6219 	    vcp->vc_factor = 4;	/* could be longer too... */
6220 	}
6221     }
6222 # endif
6223     if (vcp->vc_type == CONV_NONE)
6224 	return FAIL;
6225 
6226     return OK;
6227 }
6228 
6229 #if defined(FEAT_GUI) || defined(AMIGA) || defined(WIN3264) \
6230 	|| defined(PROTO)
6231 /*
6232  * Do conversion on typed input characters in-place.
6233  * The input and output are not NUL terminated!
6234  * Returns the length after conversion.
6235  */
6236     int
6237 convert_input(char_u *ptr, int len, int maxlen)
6238 {
6239     return convert_input_safe(ptr, len, maxlen, NULL, NULL);
6240 }
6241 #endif
6242 
6243 /*
6244  * Like convert_input(), but when there is an incomplete byte sequence at the
6245  * end return that as an allocated string in "restp" and set "*restlenp" to
6246  * the length.  If "restp" is NULL it is not used.
6247  */
6248     int
6249 convert_input_safe(
6250     char_u	*ptr,
6251     int		len,
6252     int		maxlen,
6253     char_u	**restp,
6254     int		*restlenp)
6255 {
6256     char_u	*d;
6257     int		dlen = len;
6258     int		unconvertlen = 0;
6259 
6260     d = string_convert_ext(&input_conv, ptr, &dlen,
6261 					restp == NULL ? NULL : &unconvertlen);
6262     if (d != NULL)
6263     {
6264 	if (dlen <= maxlen)
6265 	{
6266 	    if (unconvertlen > 0)
6267 	    {
6268 		/* Move the unconverted characters to allocated memory. */
6269 		*restp = alloc(unconvertlen);
6270 		if (*restp != NULL)
6271 		    mch_memmove(*restp, ptr + len - unconvertlen, unconvertlen);
6272 		*restlenp = unconvertlen;
6273 	    }
6274 	    mch_memmove(ptr, d, dlen);
6275 	}
6276 	else
6277 	    /* result is too long, keep the unconverted text (the caller must
6278 	     * have done something wrong!) */
6279 	    dlen = len;
6280 	vim_free(d);
6281     }
6282     return dlen;
6283 }
6284 
6285 /*
6286  * Convert text "ptr[*lenp]" according to "vcp".
6287  * Returns the result in allocated memory and sets "*lenp".
6288  * When "lenp" is NULL, use NUL terminated strings.
6289  * Illegal chars are often changed to "?", unless vcp->vc_fail is set.
6290  * When something goes wrong, NULL is returned and "*lenp" is unchanged.
6291  */
6292     char_u *
6293 string_convert(
6294     vimconv_T	*vcp,
6295     char_u	*ptr,
6296     int		*lenp)
6297 {
6298     return string_convert_ext(vcp, ptr, lenp, NULL);
6299 }
6300 
6301 /*
6302  * Like string_convert(), but when "unconvlenp" is not NULL and there are is
6303  * an incomplete sequence at the end it is not converted and "*unconvlenp" is
6304  * set to the number of remaining bytes.
6305  */
6306     char_u *
6307 string_convert_ext(
6308     vimconv_T	*vcp,
6309     char_u	*ptr,
6310     int		*lenp,
6311     int		*unconvlenp)
6312 {
6313     char_u	*retval = NULL;
6314     char_u	*d;
6315     int		len;
6316     int		i;
6317     int		l;
6318     int		c;
6319 
6320     if (lenp == NULL)
6321 	len = (int)STRLEN(ptr);
6322     else
6323 	len = *lenp;
6324     if (len == 0)
6325 	return vim_strsave((char_u *)"");
6326 
6327     switch (vcp->vc_type)
6328     {
6329 	case CONV_TO_UTF8:	/* latin1 to utf-8 conversion */
6330 	    retval = alloc(len * 2 + 1);
6331 	    if (retval == NULL)
6332 		break;
6333 	    d = retval;
6334 	    for (i = 0; i < len; ++i)
6335 	    {
6336 		c = ptr[i];
6337 		if (c < 0x80)
6338 		    *d++ = c;
6339 		else
6340 		{
6341 		    *d++ = 0xc0 + ((unsigned)c >> 6);
6342 		    *d++ = 0x80 + (c & 0x3f);
6343 		}
6344 	    }
6345 	    *d = NUL;
6346 	    if (lenp != NULL)
6347 		*lenp = (int)(d - retval);
6348 	    break;
6349 
6350 	case CONV_9_TO_UTF8:	/* latin9 to utf-8 conversion */
6351 	    retval = alloc(len * 3 + 1);
6352 	    if (retval == NULL)
6353 		break;
6354 	    d = retval;
6355 	    for (i = 0; i < len; ++i)
6356 	    {
6357 		c = ptr[i];
6358 		switch (c)
6359 		{
6360 		    case 0xa4: c = 0x20ac; break;   /* euro */
6361 		    case 0xa6: c = 0x0160; break;   /* S hat */
6362 		    case 0xa8: c = 0x0161; break;   /* S -hat */
6363 		    case 0xb4: c = 0x017d; break;   /* Z hat */
6364 		    case 0xb8: c = 0x017e; break;   /* Z -hat */
6365 		    case 0xbc: c = 0x0152; break;   /* OE */
6366 		    case 0xbd: c = 0x0153; break;   /* oe */
6367 		    case 0xbe: c = 0x0178; break;   /* Y */
6368 		}
6369 		d += utf_char2bytes(c, d);
6370 	    }
6371 	    *d = NUL;
6372 	    if (lenp != NULL)
6373 		*lenp = (int)(d - retval);
6374 	    break;
6375 
6376 	case CONV_TO_LATIN1:	/* utf-8 to latin1 conversion */
6377 	case CONV_TO_LATIN9:	/* utf-8 to latin9 conversion */
6378 	    retval = alloc(len + 1);
6379 	    if (retval == NULL)
6380 		break;
6381 	    d = retval;
6382 	    for (i = 0; i < len; ++i)
6383 	    {
6384 		l = utf_ptr2len_len(ptr + i, len - i);
6385 		if (l == 0)
6386 		    *d++ = NUL;
6387 		else if (l == 1)
6388 		{
6389 		    int l_w = utf8len_tab_zero[ptr[i]];
6390 
6391 		    if (l_w == 0)
6392 		    {
6393 			/* Illegal utf-8 byte cannot be converted */
6394 			vim_free(retval);
6395 			return NULL;
6396 		    }
6397 		    if (unconvlenp != NULL && l_w > len - i)
6398 		    {
6399 			/* Incomplete sequence at the end. */
6400 			*unconvlenp = len - i;
6401 			break;
6402 		    }
6403 		    *d++ = ptr[i];
6404 		}
6405 		else
6406 		{
6407 		    c = utf_ptr2char(ptr + i);
6408 		    if (vcp->vc_type == CONV_TO_LATIN9)
6409 			switch (c)
6410 			{
6411 			    case 0x20ac: c = 0xa4; break;   /* euro */
6412 			    case 0x0160: c = 0xa6; break;   /* S hat */
6413 			    case 0x0161: c = 0xa8; break;   /* S -hat */
6414 			    case 0x017d: c = 0xb4; break;   /* Z hat */
6415 			    case 0x017e: c = 0xb8; break;   /* Z -hat */
6416 			    case 0x0152: c = 0xbc; break;   /* OE */
6417 			    case 0x0153: c = 0xbd; break;   /* oe */
6418 			    case 0x0178: c = 0xbe; break;   /* Y */
6419 			    case 0xa4:
6420 			    case 0xa6:
6421 			    case 0xa8:
6422 			    case 0xb4:
6423 			    case 0xb8:
6424 			    case 0xbc:
6425 			    case 0xbd:
6426 			    case 0xbe: c = 0x100; break; /* not in latin9 */
6427 			}
6428 		    if (!utf_iscomposing(c))	/* skip composing chars */
6429 		    {
6430 			if (c < 0x100)
6431 			    *d++ = c;
6432 			else if (vcp->vc_fail)
6433 			{
6434 			    vim_free(retval);
6435 			    return NULL;
6436 			}
6437 			else
6438 			{
6439 			    *d++ = 0xbf;
6440 			    if (utf_char2cells(c) > 1)
6441 				*d++ = '?';
6442 			}
6443 		    }
6444 		    i += l - 1;
6445 		}
6446 	    }
6447 	    *d = NUL;
6448 	    if (lenp != NULL)
6449 		*lenp = (int)(d - retval);
6450 	    break;
6451 
6452 # ifdef MACOS_CONVERT
6453 	case CONV_MAC_LATIN1:
6454 	    retval = mac_string_convert(ptr, len, lenp, vcp->vc_fail,
6455 					'm', 'l', unconvlenp);
6456 	    break;
6457 
6458 	case CONV_LATIN1_MAC:
6459 	    retval = mac_string_convert(ptr, len, lenp, vcp->vc_fail,
6460 					'l', 'm', unconvlenp);
6461 	    break;
6462 
6463 	case CONV_MAC_UTF8:
6464 	    retval = mac_string_convert(ptr, len, lenp, vcp->vc_fail,
6465 					'm', 'u', unconvlenp);
6466 	    break;
6467 
6468 	case CONV_UTF8_MAC:
6469 	    retval = mac_string_convert(ptr, len, lenp, vcp->vc_fail,
6470 					'u', 'm', unconvlenp);
6471 	    break;
6472 # endif
6473 
6474 # ifdef USE_ICONV
6475 	case CONV_ICONV:	/* conversion with output_conv.vc_fd */
6476 	    retval = iconv_string(vcp, ptr, len, unconvlenp, lenp);
6477 	    break;
6478 # endif
6479 # ifdef WIN3264
6480 	case CONV_CODEPAGE:		/* codepage -> codepage */
6481 	{
6482 	    int		retlen;
6483 	    int		tmp_len;
6484 	    short_u	*tmp;
6485 
6486 	    /* 1. codepage/UTF-8  ->  ucs-2. */
6487 	    if (vcp->vc_cpfrom == 0)
6488 		tmp_len = utf8_to_utf16(ptr, len, NULL, NULL);
6489 	    else
6490 	    {
6491 		tmp_len = MultiByteToWideChar(vcp->vc_cpfrom,
6492 					unconvlenp ? MB_ERR_INVALID_CHARS : 0,
6493 					(char *)ptr, len, 0, 0);
6494 		if (tmp_len == 0
6495 			&& GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6496 		{
6497 		    if (lenp != NULL)
6498 			*lenp = 0;
6499 		    if (unconvlenp != NULL)
6500 			*unconvlenp = len;
6501 		    retval = alloc(1);
6502 		    if (retval)
6503 			retval[0] = NUL;
6504 		    return retval;
6505 		}
6506 	    }
6507 	    tmp = (short_u *)alloc(sizeof(short_u) * tmp_len);
6508 	    if (tmp == NULL)
6509 		break;
6510 	    if (vcp->vc_cpfrom == 0)
6511 		utf8_to_utf16(ptr, len, tmp, unconvlenp);
6512 	    else
6513 		MultiByteToWideChar(vcp->vc_cpfrom, 0,
6514 			(char *)ptr, len, tmp, tmp_len);
6515 
6516 	    /* 2. ucs-2  ->  codepage/UTF-8. */
6517 	    if (vcp->vc_cpto == 0)
6518 		retlen = utf16_to_utf8(tmp, tmp_len, NULL);
6519 	    else
6520 		retlen = WideCharToMultiByte(vcp->vc_cpto, 0,
6521 						    tmp, tmp_len, 0, 0, 0, 0);
6522 	    retval = alloc(retlen + 1);
6523 	    if (retval != NULL)
6524 	    {
6525 		if (vcp->vc_cpto == 0)
6526 		    utf16_to_utf8(tmp, tmp_len, retval);
6527 		else
6528 		    WideCharToMultiByte(vcp->vc_cpto, 0,
6529 					  tmp, tmp_len,
6530 					  (char *)retval, retlen, 0, 0);
6531 		retval[retlen] = NUL;
6532 		if (lenp != NULL)
6533 		    *lenp = retlen;
6534 	    }
6535 	    vim_free(tmp);
6536 	    break;
6537 	}
6538 # endif
6539     }
6540 
6541     return retval;
6542 }
6543 #endif
6544