vim72-20100325-kaoriya-w64j.zip
[MacVim/KaoriYa.git] / src / mbyte.c
blobc04d1d52c22eb14b52d87508631a1b115806b0d9
1 /* vi:set ts=8 sts=4 sw=4:
3 * VIM - Vi IMproved by Bram Moolenaar
4 * Multibyte extensions partly by Sung-Hoon Baek
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 */
11 * mbyte.c: Code specifically for handling multi-byte characters.
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:
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.
39 * "has_mbyte" is set when "enc_dbcs" or "enc_utf8" is non-zero.
41 * If none of these is TRUE, 8-bit bytes are used for a character. The
42 * encoding isn't currently specified (TODO).
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:
48 * clipboard
49 * ^
50 * | (2)
51 * V
52 * +---------------+
53 * (1) | | (3)
54 * keyboard ----->| core |-----> display
55 * | |
56 * +---------------+
57 * ^
58 * | (4)
59 * V
60 * file
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'.
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"
80 #include "vim.h"
82 #ifdef WIN32UNIX
83 # ifndef WIN32_LEAN_AND_MEAN
84 # define WIN32_LEAN_AND_MEAN
85 # endif
86 # include <windows.h>
87 # ifdef WIN32
88 # undef WIN32 /* Some windows.h define WIN32, we don't want that here. */
89 # endif
90 #endif
92 #if (defined(WIN3264) || defined(WIN32UNIX)) && !defined(__MINGW32__)
93 # include <winnls.h>
94 #endif
96 #ifdef FEAT_GUI_X11
97 # include <X11/Intrinsic.h>
98 #endif
99 #ifdef X_LOCALE
100 #include <X11/Xlocale.h>
101 #endif
103 #if defined(FEAT_GUI_GTK) && defined(FEAT_XIM) && defined(HAVE_GTK2)
104 # include <gdk/gdkkeysyms.h>
105 # ifdef WIN3264
106 # include <gdk/gdkwin32.h>
107 # else
108 # include <gdk/gdkx.h>
109 # endif
110 #endif
112 #ifdef HAVE_WCHAR_H
113 # include <wchar.h>
114 #endif
116 #if defined(FEAT_UIMFEP) || defined(PROTO)
117 static int uimfep_lastmode = 1;
118 static void uimfep_set_active __ARGS((int active));
119 static int uimfep_get_status __ARGS((void));
120 #endif
122 #if 0
123 /* This has been disabled, because several people reported problems with the
124 * wcwidth() and iswprint() library functions, esp. for Hebrew. */
125 # ifdef __STDC_ISO_10646__
126 # define USE_WCHAR_FUNCTIONS
127 # endif
128 #endif
130 #if defined(FEAT_MBYTE) || defined(PROTO)
132 static int enc_canon_search __ARGS((char_u *name));
133 static int dbcs_char2len __ARGS((int c));
134 static int dbcs_char2bytes __ARGS((int c, char_u *buf));
135 static int dbcs_ptr2len __ARGS((char_u *p));
136 static int dbcs_ptr2len_len __ARGS((char_u *p, int size));
137 static int utf_ptr2cells_len __ARGS((char_u *p, int size));
138 static int dbcs_char2cells __ARGS((int c));
139 static int dbcs_ptr2cells_len __ARGS((char_u *p, int size));
140 static int dbcs_ptr2char __ARGS((char_u *p));
143 * Lookup table to quickly get the length in bytes of a UTF-8 character from
144 * the first byte of a UTF-8 string.
145 * Bytes which are illegal when used as the first byte have a 1.
146 * The NUL byte has length 1.
148 static char utf8len_tab[256] =
150 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,
151 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,
152 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,
153 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,
154 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,
155 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,
156 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,
157 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,
161 * Like utf8len_tab above, but using a zero for illegal lead bytes.
163 static char utf8len_tab_zero[256] =
165 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,
166 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,
167 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,
168 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,
169 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,
170 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,
171 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,
172 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,
176 * XIM often causes trouble. Define XIM_DEBUG to get a log of XIM callbacks
177 * in the "xim.log" file.
179 /* #define XIM_DEBUG */
180 #ifdef XIM_DEBUG
181 static void
182 xim_log(char *s, ...)
184 va_list arglist;
185 static FILE *fd = NULL;
187 if (fd == (FILE *)-1)
188 return;
189 if (fd == NULL)
191 fd = mch_fopen("xim.log", "w");
192 if (fd == NULL)
194 EMSG("Cannot open xim.log");
195 fd = (FILE *)-1;
196 return;
200 va_start(arglist, s);
201 vfprintf(fd, s, arglist);
202 va_end(arglist);
204 #endif
206 #endif
208 #if defined(FEAT_MBYTE) || defined(FEAT_POSTSCRIPT) || defined(PROTO)
210 * Canonical encoding names and their properties.
211 * "iso-8859-n" is handled by enc_canonize() directly.
213 static struct
214 { char *name; int prop; int codepage;}
215 enc_canon_table[] =
217 #define IDX_LATIN_1 0
218 {"latin1", ENC_8BIT + ENC_LATIN1, 1252},
219 #define IDX_ISO_2 1
220 {"iso-8859-2", ENC_8BIT, 0},
221 #define IDX_ISO_3 2
222 {"iso-8859-3", ENC_8BIT, 0},
223 #define IDX_ISO_4 3
224 {"iso-8859-4", ENC_8BIT, 0},
225 #define IDX_ISO_5 4
226 {"iso-8859-5", ENC_8BIT, 0},
227 #define IDX_ISO_6 5
228 {"iso-8859-6", ENC_8BIT, 0},
229 #define IDX_ISO_7 6
230 {"iso-8859-7", ENC_8BIT, 0},
231 #define IDX_ISO_8 7
232 {"iso-8859-8", ENC_8BIT, 0},
233 #define IDX_ISO_9 8
234 {"iso-8859-9", ENC_8BIT, 0},
235 #define IDX_ISO_10 9
236 {"iso-8859-10", ENC_8BIT, 0},
237 #define IDX_ISO_11 10
238 {"iso-8859-11", ENC_8BIT, 0},
239 #define IDX_ISO_13 11
240 {"iso-8859-13", ENC_8BIT, 0},
241 #define IDX_ISO_14 12
242 {"iso-8859-14", ENC_8BIT, 0},
243 #define IDX_ISO_15 13
244 {"iso-8859-15", ENC_8BIT + ENC_LATIN9, 0},
245 #define IDX_KOI8_R 14
246 {"koi8-r", ENC_8BIT, 0},
247 #define IDX_KOI8_U 15
248 {"koi8-u", ENC_8BIT, 0},
249 #define IDX_UTF8 16
250 {"utf-8", ENC_UNICODE, 0},
251 #define IDX_UCS2 17
252 {"ucs-2", ENC_UNICODE + ENC_ENDIAN_B + ENC_2BYTE, 0},
253 #define IDX_UCS2LE 18
254 {"ucs-2le", ENC_UNICODE + ENC_ENDIAN_L + ENC_2BYTE, 0},
255 #define IDX_UTF16 19
256 {"utf-16", ENC_UNICODE + ENC_ENDIAN_B + ENC_2WORD, 0},
257 #define IDX_UTF16LE 20
258 {"utf-16le", ENC_UNICODE + ENC_ENDIAN_L + ENC_2WORD, 0},
259 #define IDX_UCS4 21
260 {"ucs-4", ENC_UNICODE + ENC_ENDIAN_B + ENC_4BYTE, 0},
261 #define IDX_UCS4LE 22
262 {"ucs-4le", ENC_UNICODE + ENC_ENDIAN_L + ENC_4BYTE, 0},
264 /* For debugging DBCS encoding on Unix. */
265 #define IDX_DEBUG 23
266 {"debug", ENC_DBCS, DBCS_DEBUG},
267 #define IDX_EUC_JP 24
268 {"euc-jp", ENC_DBCS, DBCS_JPNU},
269 #define IDX_SJIS 25
270 {"sjis", ENC_DBCS, DBCS_JPN},
271 #define IDX_EUC_KR 26
272 {"euc-kr", ENC_DBCS, DBCS_KORU},
273 #define IDX_EUC_CN 27
274 {"euc-cn", ENC_DBCS, DBCS_CHSU},
275 #define IDX_EUC_TW 28
276 {"euc-tw", ENC_DBCS, DBCS_CHTU},
277 #define IDX_BIG5 29
278 {"big5", ENC_DBCS, DBCS_CHT},
280 /* MS-DOS and MS-Windows codepages are included here, so that they can be
281 * used on Unix too. Most of them are similar to ISO-8859 encodings, but
282 * not exactly the same. */
283 #define IDX_CP437 30
284 {"cp437", ENC_8BIT, 437}, /* like iso-8859-1 */
285 #define IDX_CP737 31
286 {"cp737", ENC_8BIT, 737}, /* like iso-8859-7 */
287 #define IDX_CP775 32
288 {"cp775", ENC_8BIT, 775}, /* Baltic */
289 #define IDX_CP850 33
290 {"cp850", ENC_8BIT, 850}, /* like iso-8859-4 */
291 #define IDX_CP852 34
292 {"cp852", ENC_8BIT, 852}, /* like iso-8859-1 */
293 #define IDX_CP855 35
294 {"cp855", ENC_8BIT, 855}, /* like iso-8859-2 */
295 #define IDX_CP857 36
296 {"cp857", ENC_8BIT, 857}, /* like iso-8859-5 */
297 #define IDX_CP860 37
298 {"cp860", ENC_8BIT, 860}, /* like iso-8859-9 */
299 #define IDX_CP861 38
300 {"cp861", ENC_8BIT, 861}, /* like iso-8859-1 */
301 #define IDX_CP862 39
302 {"cp862", ENC_8BIT, 862}, /* like iso-8859-1 */
303 #define IDX_CP863 40
304 {"cp863", ENC_8BIT, 863}, /* like iso-8859-8 */
305 #define IDX_CP865 41
306 {"cp865", ENC_8BIT, 865}, /* like iso-8859-1 */
307 #define IDX_CP866 42
308 {"cp866", ENC_8BIT, 866}, /* like iso-8859-5 */
309 #define IDX_CP869 43
310 {"cp869", ENC_8BIT, 869}, /* like iso-8859-7 */
311 #define IDX_CP874 44
312 {"cp874", ENC_8BIT, 874}, /* Thai */
313 #define IDX_CP932 45
314 {"cp932", ENC_DBCS, DBCS_JPN},
315 #define IDX_CP936 46
316 {"cp936", ENC_DBCS, DBCS_CHS},
317 #define IDX_CP949 47
318 {"cp949", ENC_DBCS, DBCS_KOR},
319 #define IDX_CP950 48
320 {"cp950", ENC_DBCS, DBCS_CHT},
321 #define IDX_CP1250 49
322 {"cp1250", ENC_8BIT, 1250}, /* Czech, Polish, etc. */
323 #define IDX_CP1251 50
324 {"cp1251", ENC_8BIT, 1251}, /* Cyrillic */
325 /* cp1252 is considered to be equal to latin1 */
326 #define IDX_CP1253 51
327 {"cp1253", ENC_8BIT, 1253}, /* Greek */
328 #define IDX_CP1254 52
329 {"cp1254", ENC_8BIT, 1254}, /* Turkish */
330 #define IDX_CP1255 53
331 {"cp1255", ENC_8BIT, 1255}, /* Hebrew */
332 #define IDX_CP1256 54
333 {"cp1256", ENC_8BIT, 1256}, /* Arabic */
334 #define IDX_CP1257 55
335 {"cp1257", ENC_8BIT, 1257}, /* Baltic */
336 #define IDX_CP1258 56
337 {"cp1258", ENC_8BIT, 1258}, /* Vietnamese */
339 #define IDX_MACROMAN 57
340 {"macroman", ENC_8BIT + ENC_MACROMAN, 0}, /* Mac OS */
341 #define IDX_DECMCS 58
342 {"dec-mcs", ENC_8BIT, 0}, /* DEC MCS */
343 #define IDX_HPROMAN8 59
344 {"hp-roman8", ENC_8BIT, 0}, /* HP Roman8 */
345 #define IDX_COUNT 60
349 * Aliases for encoding names.
351 static struct
352 { char *name; int canon;}
353 enc_alias_table[] =
355 {"ansi", IDX_LATIN_1},
356 {"iso-8859-1", IDX_LATIN_1},
357 {"latin2", IDX_ISO_2},
358 {"latin3", IDX_ISO_3},
359 {"latin4", IDX_ISO_4},
360 {"cyrillic", IDX_ISO_5},
361 {"arabic", IDX_ISO_6},
362 {"greek", IDX_ISO_7},
363 #ifdef WIN3264
364 {"hebrew", IDX_CP1255},
365 #else
366 {"hebrew", IDX_ISO_8},
367 #endif
368 {"latin5", IDX_ISO_9},
369 {"turkish", IDX_ISO_9}, /* ? */
370 {"latin6", IDX_ISO_10},
371 {"nordic", IDX_ISO_10}, /* ? */
372 {"thai", IDX_ISO_11}, /* ? */
373 {"latin7", IDX_ISO_13},
374 {"latin8", IDX_ISO_14},
375 {"latin9", IDX_ISO_15},
376 {"utf8", IDX_UTF8},
377 {"unicode", IDX_UCS2},
378 {"ucs2", IDX_UCS2},
379 {"ucs2be", IDX_UCS2},
380 {"ucs-2be", IDX_UCS2},
381 {"ucs2le", IDX_UCS2LE},
382 {"utf16", IDX_UTF16},
383 {"utf16be", IDX_UTF16},
384 {"utf-16be", IDX_UTF16},
385 {"utf16le", IDX_UTF16LE},
386 {"ucs4", IDX_UCS4},
387 {"ucs4be", IDX_UCS4},
388 {"ucs-4be", IDX_UCS4},
389 {"ucs4le", IDX_UCS4LE},
390 {"utf32", IDX_UCS4},
391 {"utf-32", IDX_UCS4},
392 {"utf32be", IDX_UCS4},
393 {"utf-32be", IDX_UCS4},
394 {"utf32le", IDX_UCS4LE},
395 {"utf-32le", IDX_UCS4LE},
396 {"932", IDX_CP932},
397 {"949", IDX_CP949},
398 {"936", IDX_CP936},
399 {"gbk", IDX_CP936},
400 {"950", IDX_CP950},
401 {"eucjp", IDX_EUC_JP},
402 {"unix-jis", IDX_EUC_JP},
403 {"ujis", IDX_EUC_JP},
404 {"shift-jis", IDX_SJIS},
405 {"euckr", IDX_EUC_KR},
406 {"5601", IDX_EUC_KR}, /* Sun: KS C 5601 */
407 {"euccn", IDX_EUC_CN},
408 {"gb2312", IDX_EUC_CN},
409 {"euctw", IDX_EUC_TW},
410 #if defined(WIN3264) || defined(WIN32UNIX) || defined(MACOS)
411 {"japan", IDX_CP932},
412 {"korea", IDX_CP949},
413 {"prc", IDX_CP936},
414 {"chinese", IDX_CP936},
415 {"taiwan", IDX_CP950},
416 {"big5", IDX_CP950},
417 #else
418 {"japan", IDX_EUC_JP},
419 {"korea", IDX_EUC_KR},
420 {"prc", IDX_EUC_CN},
421 {"chinese", IDX_EUC_CN},
422 {"taiwan", IDX_EUC_TW},
423 {"cp950", IDX_BIG5},
424 {"950", IDX_BIG5},
425 #endif
426 {"mac", IDX_MACROMAN},
427 {"mac-roman", IDX_MACROMAN},
428 {NULL, 0}
431 #ifndef CP_UTF8
432 # define CP_UTF8 65001 /* magic number from winnls.h */
433 #endif
436 * Find encoding "name" in the list of canonical encoding names.
437 * Returns -1 if not found.
439 static int
440 enc_canon_search(name)
441 char_u *name;
443 int i;
445 for (i = 0; i < IDX_COUNT; ++i)
446 if (STRCMP(name, enc_canon_table[i].name) == 0)
447 return i;
448 return -1;
451 #endif
453 #if defined(FEAT_MBYTE) || defined(PROTO)
456 * Find canonical encoding "name" in the list and return its properties.
457 * Returns 0 if not found.
460 enc_canon_props(name)
461 char_u *name;
463 int i;
465 i = enc_canon_search(name);
466 if (i >= 0)
467 return enc_canon_table[i].prop;
468 #ifdef WIN3264
469 if (name[0] == 'c' && name[1] == 'p' && VIM_ISDIGIT(name[2]))
471 CPINFO cpinfo;
473 /* Get info on this codepage to find out what it is. */
474 if (GetCPInfo(atoi(name + 2), &cpinfo) != 0)
476 if (cpinfo.MaxCharSize == 1) /* some single-byte encoding */
477 return ENC_8BIT;
478 if (cpinfo.MaxCharSize == 2
479 && (cpinfo.LeadByte[0] != 0 || cpinfo.LeadByte[1] != 0))
480 /* must be a DBCS encoding */
481 return ENC_DBCS;
483 return 0;
485 #endif
486 if (STRNCMP(name, "2byte-", 6) == 0)
487 return ENC_DBCS;
488 if (STRNCMP(name, "8bit-", 5) == 0 || STRNCMP(name, "iso-8859-", 9) == 0)
489 return ENC_8BIT;
490 return 0;
494 * Set up for using multi-byte characters.
495 * Called in three cases:
496 * - by main() to initialize (p_enc == NULL)
497 * - by set_init_1() after 'encoding' was set to its default.
498 * - by do_set() when 'encoding' has been set.
499 * p_enc must have been passed through enc_canonize() already.
500 * Sets the "enc_unicode", "enc_utf8", "enc_dbcs" and "has_mbyte" flags.
501 * Fills mb_bytelen_tab[] and returns NULL when there are no problems.
502 * When there is something wrong: Returns an error message and doesn't change
503 * anything.
505 char_u *
506 mb_init()
508 int i;
509 int idx;
510 int n;
511 int enc_dbcs_new = 0;
512 #if defined(USE_ICONV) && !defined(WIN3264) && !defined(WIN32UNIX) \
513 && !defined(MACOS)
514 # define LEN_FROM_CONV
515 vimconv_T vimconv;
516 char_u *p;
517 #endif
519 if (p_enc == NULL)
521 /* Just starting up: set the whole table to one's. */
522 for (i = 0; i < 256; ++i)
523 mb_bytelen_tab[i] = 1;
524 input_conv.vc_type = CONV_NONE;
525 input_conv.vc_factor = 1;
526 output_conv.vc_type = CONV_NONE;
527 return NULL;
530 #ifdef WIN3264
531 if (p_enc[0] == 'c' && p_enc[1] == 'p' && VIM_ISDIGIT(p_enc[2]))
533 CPINFO cpinfo;
535 /* Get info on this codepage to find out what it is. */
536 if (GetCPInfo(atoi(p_enc + 2), &cpinfo) != 0)
538 if (cpinfo.MaxCharSize == 1)
540 /* some single-byte encoding */
541 enc_unicode = 0;
542 enc_utf8 = FALSE;
544 else if (cpinfo.MaxCharSize == 2
545 && (cpinfo.LeadByte[0] != 0 || cpinfo.LeadByte[1] != 0))
547 /* must be a DBCS encoding, check below */
548 enc_dbcs_new = atoi(p_enc + 2);
550 else
551 goto codepage_invalid;
553 else if (GetLastError() == ERROR_INVALID_PARAMETER)
555 codepage_invalid:
556 return (char_u *)N_("E543: Not a valid codepage");
559 #endif
560 else if (STRNCMP(p_enc, "8bit-", 5) == 0
561 || STRNCMP(p_enc, "iso-8859-", 9) == 0)
563 /* Accept any "8bit-" or "iso-8859-" name. */
564 enc_unicode = 0;
565 enc_utf8 = FALSE;
567 else if (STRNCMP(p_enc, "2byte-", 6) == 0)
569 #ifdef WIN3264
570 /* Windows: accept only valid codepage numbers, check below. */
571 if (p_enc[6] != 'c' || p_enc[7] != 'p'
572 || (enc_dbcs_new = atoi(p_enc + 8)) == 0)
573 return e_invarg;
574 #else
575 /* Unix: accept any "2byte-" name, assume current locale. */
576 enc_dbcs_new = DBCS_2BYTE;
577 #endif
579 else if ((idx = enc_canon_search(p_enc)) >= 0)
581 i = enc_canon_table[idx].prop;
582 if (i & ENC_UNICODE)
584 /* Unicode */
585 enc_utf8 = TRUE;
586 if (i & (ENC_2BYTE | ENC_2WORD))
587 enc_unicode = 2;
588 else if (i & ENC_4BYTE)
589 enc_unicode = 4;
590 else
591 enc_unicode = 0;
593 else if (i & ENC_DBCS)
595 /* 2byte, handle below */
596 enc_dbcs_new = enc_canon_table[idx].codepage;
598 else
600 /* Must be 8-bit. */
601 enc_unicode = 0;
602 enc_utf8 = FALSE;
605 else /* Don't know what encoding this is, reject it. */
606 return e_invarg;
608 if (enc_dbcs_new != 0)
610 #ifdef WIN3264
611 /* Check if the DBCS code page is OK. */
612 if (!IsValidCodePage(enc_dbcs_new))
613 goto codepage_invalid;
614 #endif
615 enc_unicode = 0;
616 enc_utf8 = FALSE;
618 enc_dbcs = enc_dbcs_new;
619 has_mbyte = (enc_dbcs != 0 || enc_utf8);
621 #ifdef WIN3264
622 enc_codepage = encname2codepage(p_enc);
623 enc_latin9 = (STRCMP(p_enc, "iso-8859-15") == 0);
624 #endif
626 /* Detect an encoding that uses latin1 characters. */
627 enc_latin1like = (enc_utf8 || STRCMP(p_enc, "latin1") == 0
628 || STRCMP(p_enc, "iso-8859-15") == 0);
631 * Set the function pointers.
633 if (enc_utf8)
635 mb_ptr2len = utfc_ptr2len;
636 mb_ptr2len_len = utfc_ptr2len_len;
637 mb_char2len = utf_char2len;
638 mb_char2bytes = utf_char2bytes;
639 mb_ptr2cells = utf_ptr2cells;
640 mb_ptr2cells_len = utf_ptr2cells_len;
641 mb_char2cells = utf_char2cells;
642 mb_off2cells = utf_off2cells;
643 mb_ptr2char = utf_ptr2char;
644 mb_head_off = utf_head_off;
646 else if (enc_dbcs != 0)
648 mb_ptr2len = dbcs_ptr2len;
649 mb_ptr2len_len = dbcs_ptr2len_len;
650 mb_char2len = dbcs_char2len;
651 mb_char2bytes = dbcs_char2bytes;
652 mb_ptr2cells = dbcs_ptr2cells;
653 mb_ptr2cells_len = dbcs_ptr2cells_len;
654 mb_char2cells = dbcs_char2cells;
655 mb_off2cells = dbcs_off2cells;
656 mb_ptr2char = dbcs_ptr2char;
657 mb_head_off = dbcs_head_off;
659 else
661 mb_ptr2len = latin_ptr2len;
662 mb_ptr2len_len = latin_ptr2len_len;
663 mb_char2len = latin_char2len;
664 mb_char2bytes = latin_char2bytes;
665 mb_ptr2cells = latin_ptr2cells;
666 mb_ptr2cells_len = latin_ptr2cells_len;
667 mb_char2cells = latin_char2cells;
668 mb_off2cells = latin_off2cells;
669 mb_ptr2char = latin_ptr2char;
670 mb_head_off = latin_head_off;
674 * Fill the mb_bytelen_tab[] for MB_BYTE2LEN().
676 #ifdef LEN_FROM_CONV
677 /* When 'encoding' is different from the current locale mblen() won't
678 * work. Use conversion to "utf-8" instead. */
679 vimconv.vc_type = CONV_NONE;
680 if (enc_dbcs)
682 p = enc_locale();
683 if (p == NULL || STRCMP(p, p_enc) != 0)
685 convert_setup(&vimconv, p_enc, (char_u *)"utf-8");
686 vimconv.vc_fail = TRUE;
688 vim_free(p);
690 #endif
692 for (i = 0; i < 256; ++i)
694 /* Our own function to reliably check the length of UTF-8 characters,
695 * independent of mblen(). */
696 if (enc_utf8)
697 n = utf8len_tab[i];
698 else if (enc_dbcs == 0)
699 n = 1;
700 else
702 #if defined(WIN3264) || defined(WIN32UNIX)
703 /* enc_dbcs is set by setting 'fileencoding'. It becomes a Windows
704 * CodePage identifier, which we can pass directly in to Windows
705 * API */
706 n = IsDBCSLeadByteEx(enc_dbcs, (BYTE)i) ? 2 : 1;
707 #else
708 # if defined(MACOS) || defined(__amigaos4__)
710 * if mblen() is not available, character which MSB is turned on
711 * are treated as leading byte character. (note : This assumption
712 * is not always true.)
714 n = (i & 0x80) ? 2 : 1;
715 # else
716 char buf[MB_MAXBYTES];
717 # ifdef X_LOCALE
718 # ifndef mblen
719 # define mblen _Xmblen
720 # endif
721 # endif
722 if (i == NUL) /* just in case mblen() can't handle "" */
723 n = 1;
724 else
726 buf[0] = i;
727 buf[1] = 0;
728 #ifdef LEN_FROM_CONV
729 if (vimconv.vc_type != CONV_NONE)
732 * string_convert() should fail when converting the first
733 * byte of a double-byte character.
735 p = string_convert(&vimconv, (char_u *)buf, NULL);
736 if (p != NULL)
738 vim_free(p);
739 n = 1;
741 else
742 n = 2;
744 else
745 #endif
748 * mblen() should return -1 for invalid (means the leading
749 * multibyte) character. However there are some platforms
750 * where mblen() returns 0 for invalid character.
751 * Therefore, following condition includes 0.
753 ignored = mblen(NULL, 0); /* First reset the state. */
754 if (mblen(buf, (size_t)1) <= 0)
755 n = 2;
756 else
757 n = 1;
760 # endif
761 #endif
764 mb_bytelen_tab[i] = n;
767 #ifdef LEN_FROM_CONV
768 convert_setup(&vimconv, NULL, NULL);
769 #endif
771 /* The cell width depends on the type of multi-byte characters. */
772 (void)init_chartab();
774 /* When enc_utf8 is set or reset, (de)allocate ScreenLinesUC[] */
775 screenalloc(FALSE);
777 /* When using Unicode, set default for 'fileencodings'. */
778 if (enc_utf8 && !option_was_set((char_u *)"fencs"))
779 set_string_option_direct((char_u *)"fencs", -1,
780 (char_u *)"ucs-bom,utf-8,default,latin1", OPT_FREE, 0);
782 #if defined(HAVE_BIND_TEXTDOMAIN_CODESET) && defined(FEAT_GETTEXT)
783 /* GNU gettext 0.10.37 supports this feature: set the codeset used for
784 * translated messages independently from the current locale. */
785 (void)bind_textdomain_codeset(VIMPACKAGE,
786 enc_utf8 ? "utf-8" : (char *)p_enc);
787 #endif
789 #ifdef WIN32
790 /* When changing 'encoding' while starting up, then convert the command
791 * line arguments from the active codepage to 'encoding'. */
792 if (starting != 0)
793 fix_arg_enc();
794 #endif
796 #ifdef FEAT_AUTOCMD
797 /* Fire an autocommand to let people do custom font setup. This must be
798 * after Vim has been setup for the new encoding. */
799 apply_autocmds(EVENT_ENCODINGCHANGED, NULL, (char_u *)"", FALSE, curbuf);
800 #endif
802 #ifdef FEAT_SPELL
803 /* Need to reload spell dictionaries */
804 spell_reload();
805 #endif
807 return NULL;
811 * Return the size of the BOM for the current buffer:
812 * 0 - no BOM
813 * 2 - UCS-2 or UTF-16 BOM
814 * 4 - UCS-4 BOM
815 * 3 - UTF-8 BOM
818 bomb_size()
820 int n = 0;
822 if (curbuf->b_p_bomb && !curbuf->b_p_bin)
824 if (*curbuf->b_p_fenc == NUL)
826 if (enc_utf8)
828 if (enc_unicode != 0)
829 n = enc_unicode;
830 else
831 n = 3;
834 else if (STRCMP(curbuf->b_p_fenc, "utf-8") == 0)
835 n = 3;
836 else if (STRNCMP(curbuf->b_p_fenc, "ucs-2", 5) == 0
837 || STRNCMP(curbuf->b_p_fenc, "utf-16", 6) == 0)
838 n = 2;
839 else if (STRNCMP(curbuf->b_p_fenc, "ucs-4", 5) == 0)
840 n = 4;
842 return n;
846 * Get class of pointer:
847 * 0 for blank or NUL
848 * 1 for punctuation
849 * 2 for an (ASCII) word character
850 * >2 for other word characters
853 mb_get_class(p)
854 char_u *p;
856 if (MB_BYTE2LEN(p[0]) == 1)
858 if (p[0] == NUL || vim_iswhite(p[0]))
859 return 0;
860 if (vim_iswordc(p[0]))
861 return 2;
862 return 1;
864 if (enc_dbcs != 0 && p[0] != NUL && p[1] != NUL)
865 return dbcs_class(p[0], p[1]);
866 if (enc_utf8)
867 return utf_class(utf_ptr2char(p));
868 return 0;
872 * Get class of a double-byte character. This always returns 3 or bigger.
873 * TODO: Should return 1 for punctuation.
876 dbcs_class(lead, trail)
877 unsigned lead;
878 unsigned trail;
880 switch (enc_dbcs)
882 /* please add classfy routine for your language in here */
884 case DBCS_JPNU: /* ? */
885 case DBCS_JPN:
887 /* JIS code classification */
888 unsigned char lb = lead;
889 unsigned char tb = trail;
891 /* convert process code to JIS */
892 # if defined(WIN3264) || defined(WIN32UNIX) || defined(MACOS)
893 /* process code is SJIS */
894 if (lb <= 0x9f)
895 lb = (lb - 0x81) * 2 + 0x21;
896 else
897 lb = (lb - 0xc1) * 2 + 0x21;
898 if (tb <= 0x7e)
899 tb -= 0x1f;
900 else if (tb <= 0x9e)
901 tb -= 0x20;
902 else
904 tb -= 0x7e;
905 lb += 1;
907 # else
909 * XXX: Code page identification can not use with all
910 * system! So, some other encoding information
911 * will be needed.
912 * In japanese: SJIS,EUC,UNICODE,(JIS)
913 * Note that JIS-code system don't use as
914 * process code in most system because it uses
915 * escape sequences(JIS is context depend encoding).
917 /* assume process code is JAPANESE-EUC */
918 lb &= 0x7f;
919 tb &= 0x7f;
920 # endif
921 /* exceptions */
922 switch (lb << 8 | tb)
924 case 0x2121: /* ZENKAKU space */
925 return 0;
926 case 0x2122: /* KU-TEN (Japanese comma) */
927 case 0x2123: /* TOU-TEN (Japanese period) */
928 case 0x2124: /* ZENKAKU comma */
929 case 0x2125: /* ZENKAKU period */
930 return 1;
931 case 0x213c: /* prolongedsound handled as KATAKANA */
932 return 13;
934 /* sieved by KU code */
935 switch (lb)
937 case 0x21:
938 case 0x22:
939 /* special symbols */
940 return 10;
941 case 0x23:
942 /* alpha-numeric */
943 return 11;
944 case 0x24:
945 /* hiragana */
946 return 12;
947 case 0x25:
948 /* katakana */
949 return 13;
950 case 0x26:
951 /* greek */
952 return 14;
953 case 0x27:
954 /* russian */
955 return 15;
956 case 0x28:
957 /* lines */
958 return 16;
959 default:
960 /* kanji */
961 return 17;
965 case DBCS_KORU: /* ? */
966 case DBCS_KOR:
968 /* KS code classification */
969 unsigned char c1 = lead;
970 unsigned char c2 = trail;
973 * 20 : Hangul
974 * 21 : Hanja
975 * 22 : Symbols
976 * 23 : Alpha-numeric/Roman Letter (Full width)
977 * 24 : Hangul Letter(Alphabet)
978 * 25 : Roman Numeral/Greek Letter
979 * 26 : Box Drawings
980 * 27 : Unit Symbols
981 * 28 : Circled/Parenthesized Letter
982 * 29 : Hirigana/Katakana
983 * 30 : Cyrillic Letter
986 if (c1 >= 0xB0 && c1 <= 0xC8)
987 /* Hangul */
988 return 20;
989 #if defined(WIN3264) || defined(WIN32UNIX)
990 else if (c1 <= 0xA0 || c2 <= 0xA0)
991 /* Extended Hangul Region : MS UHC(Unified Hangul Code) */
992 /* c1: 0x81-0xA0 with c2: 0x41-0x5A, 0x61-0x7A, 0x81-0xFE
993 * c1: 0xA1-0xC6 with c2: 0x41-0x5A, 0x61-0x7A, 0x81-0xA0
995 return 20;
996 #endif
998 else if (c1 >= 0xCA && c1 <= 0xFD)
999 /* Hanja */
1000 return 21;
1001 else switch (c1)
1003 case 0xA1:
1004 case 0xA2:
1005 /* Symbols */
1006 return 22;
1007 case 0xA3:
1008 /* Alpha-numeric */
1009 return 23;
1010 case 0xA4:
1011 /* Hangul Letter(Alphabet) */
1012 return 24;
1013 case 0xA5:
1014 /* Roman Numeral/Greek Letter */
1015 return 25;
1016 case 0xA6:
1017 /* Box Drawings */
1018 return 26;
1019 case 0xA7:
1020 /* Unit Symbols */
1021 return 27;
1022 case 0xA8:
1023 case 0xA9:
1024 if (c2 <= 0xAF)
1025 return 25; /* Roman Letter */
1026 else if (c2 >= 0xF6)
1027 return 22; /* Symbols */
1028 else
1029 /* Circled/Parenthesized Letter */
1030 return 28;
1031 case 0xAA:
1032 case 0xAB:
1033 /* Hirigana/Katakana */
1034 return 29;
1035 case 0xAC:
1036 /* Cyrillic Letter */
1037 return 30;
1040 default:
1041 break;
1043 return 3;
1047 * mb_char2len() function pointer.
1048 * Return length in bytes of character "c".
1049 * Returns 1 for a single-byte character.
1052 latin_char2len(c)
1053 int c UNUSED;
1055 return 1;
1058 static int
1059 dbcs_char2len(c)
1060 int c;
1062 if (c >= 0x100)
1063 return 2;
1064 return 1;
1068 * mb_char2bytes() function pointer.
1069 * Convert a character to its bytes.
1070 * Returns the length in bytes.
1073 latin_char2bytes(c, buf)
1074 int c;
1075 char_u *buf;
1077 buf[0] = c;
1078 return 1;
1081 static int
1082 dbcs_char2bytes(c, buf)
1083 int c;
1084 char_u *buf;
1086 if (c >= 0x100)
1088 buf[0] = (unsigned)c >> 8;
1089 buf[1] = c;
1090 /* Never use a NUL byte, it causes lots of trouble. It's an invalid
1091 * character anyway. */
1092 if (buf[1] == NUL)
1093 buf[1] = '\n';
1094 return 2;
1096 buf[0] = c;
1097 return 1;
1101 * mb_ptr2len() function pointer.
1102 * Get byte length of character at "*p" but stop at a NUL.
1103 * For UTF-8 this includes following composing characters.
1104 * Returns 0 when *p is NUL.
1107 latin_ptr2len(p)
1108 char_u *p;
1110 return MB_BYTE2LEN(*p);
1113 static int
1114 dbcs_ptr2len(p)
1115 char_u *p;
1117 int len;
1119 /* Check if second byte is not missing. */
1120 len = MB_BYTE2LEN(*p);
1121 if (len == 2 && p[1] == NUL)
1122 len = 1;
1123 return len;
1127 * mb_ptr2len_len() function pointer.
1128 * Like mb_ptr2len(), but limit to read "size" bytes.
1129 * Returns 0 for an empty string.
1130 * Returns 1 for an illegal char or an incomplete byte sequence.
1133 latin_ptr2len_len(p, size)
1134 char_u *p;
1135 int size;
1137 if (size < 1 || *p == NUL)
1138 return 0;
1139 return 1;
1142 static int
1143 dbcs_ptr2len_len(p, size)
1144 char_u *p;
1145 int size;
1147 int len;
1149 if (size < 1 || *p == NUL)
1150 return 0;
1151 if (size == 1)
1152 return 1;
1153 /* Check that second byte is not missing. */
1154 len = MB_BYTE2LEN(*p);
1155 if (len == 2 && p[1] == NUL)
1156 len = 1;
1157 return len;
1160 struct interval
1162 long first;
1163 long last;
1165 static int intable __ARGS((struct interval *table, size_t size, int c));
1168 * Return TRUE if "c" is in "table[size / sizeof(struct interval)]".
1170 static int
1171 intable(table, size, c)
1172 struct interval *table;
1173 size_t size;
1174 int c;
1176 int mid, bot, top;
1178 /* first quick check for Latin1 etc. characters */
1179 if (c < table[0].first)
1180 return FALSE;
1182 /* binary search in table */
1183 bot = 0;
1184 top = (int)(size / sizeof(struct interval) - 1);
1185 while (top >= bot)
1187 mid = (bot + top) / 2;
1188 if (table[mid].last < c)
1189 bot = mid + 1;
1190 else if (table[mid].first > c)
1191 top = mid - 1;
1192 else
1193 return TRUE;
1195 return FALSE;
1199 * For UTF-8 character "c" return 2 for a double-width character, 1 for others.
1200 * Returns 4 or 6 for an unprintable character.
1201 * Is only correct for characters >= 0x80.
1202 * When p_ambw is "double", return 2 for a character with East Asian Width
1203 * class 'A'(mbiguous).
1206 utf_char2cells(c)
1207 int c;
1209 /* Sorted list of non-overlapping intervals of East Asian double width
1210 * characters, generated with ../runtime/tools/unicode.vim. */
1211 static struct interval doublewidth[] =
1213 {0x1100, 0x115f},
1214 {0x11a3, 0x11a7},
1215 {0x11fa, 0x11ff},
1216 {0x2329, 0x232a},
1217 {0x2e80, 0x2e99},
1218 {0x2e9b, 0x2ef3},
1219 {0x2f00, 0x2fd5},
1220 {0x2ff0, 0x2ffb},
1221 {0x3000, 0x3029},
1222 {0x3030, 0x303e},
1223 {0x3041, 0x3096},
1224 {0x309b, 0x30ff},
1225 {0x3105, 0x312d},
1226 {0x3131, 0x318e},
1227 {0x3190, 0x31b7},
1228 {0x31c0, 0x31e3},
1229 {0x31f0, 0x321e},
1230 {0x3220, 0x3247},
1231 {0x3250, 0x32fe},
1232 {0x3300, 0x4dbf},
1233 {0x4e00, 0xa48c},
1234 {0xa490, 0xa4c6},
1235 {0xa960, 0xa97c},
1236 {0xac00, 0xd7a3},
1237 {0xd7b0, 0xd7c6},
1238 {0xd7cb, 0xd7fb},
1239 {0xf900, 0xfaff},
1240 {0xfe10, 0xfe19},
1241 {0xfe30, 0xfe52},
1242 {0xfe54, 0xfe66},
1243 {0xfe68, 0xfe6b},
1244 {0xff01, 0xff60},
1245 {0xffe0, 0xffe6},
1246 {0x1f200, 0x1f200},
1247 {0x1f210, 0x1f231},
1248 {0x1f240, 0x1f248},
1249 {0x20000, 0x2fffd},
1250 {0x30000, 0x3fffd}
1252 /* Sorted list of non-overlapping intervals of East Asian Ambiguous
1253 * characters, generated with ../runtime/tools/unicode.vim. */
1254 static struct interval ambiguous[] =
1256 {0x00a1, 0x00a1},
1257 {0x00a4, 0x00a4},
1258 {0x00a7, 0x00a8},
1259 {0x00aa, 0x00aa},
1260 {0x00ad, 0x00ae},
1261 {0x00b0, 0x00b4},
1262 {0x00b6, 0x00ba},
1263 {0x00bc, 0x00bf},
1264 {0x00c6, 0x00c6},
1265 {0x00d0, 0x00d0},
1266 {0x00d7, 0x00d8},
1267 {0x00de, 0x00e1},
1268 {0x00e6, 0x00e6},
1269 {0x00e8, 0x00ea},
1270 {0x00ec, 0x00ed},
1271 {0x00f0, 0x00f0},
1272 {0x00f2, 0x00f3},
1273 {0x00f7, 0x00fa},
1274 {0x00fc, 0x00fc},
1275 {0x00fe, 0x00fe},
1276 {0x0101, 0x0101},
1277 {0x0111, 0x0111},
1278 {0x0113, 0x0113},
1279 {0x011b, 0x011b},
1280 {0x0126, 0x0127},
1281 {0x012b, 0x012b},
1282 {0x0131, 0x0133},
1283 {0x0138, 0x0138},
1284 {0x013f, 0x0142},
1285 {0x0144, 0x0144},
1286 {0x0148, 0x014b},
1287 {0x014d, 0x014d},
1288 {0x0152, 0x0153},
1289 {0x0166, 0x0167},
1290 {0x016b, 0x016b},
1291 {0x01ce, 0x01ce},
1292 {0x01d0, 0x01d0},
1293 {0x01d2, 0x01d2},
1294 {0x01d4, 0x01d4},
1295 {0x01d6, 0x01d6},
1296 {0x01d8, 0x01d8},
1297 {0x01da, 0x01da},
1298 {0x01dc, 0x01dc},
1299 {0x0251, 0x0251},
1300 {0x0261, 0x0261},
1301 {0x02c4, 0x02c4},
1302 {0x02c7, 0x02c7},
1303 {0x02c9, 0x02cb},
1304 {0x02cd, 0x02cd},
1305 {0x02d0, 0x02d0},
1306 {0x02d8, 0x02db},
1307 {0x02dd, 0x02dd},
1308 {0x02df, 0x02df},
1309 {0x0391, 0x03a1},
1310 {0x03a3, 0x03a9},
1311 {0x03b1, 0x03c1},
1312 {0x03c3, 0x03c9},
1313 {0x0401, 0x0401},
1314 {0x0410, 0x044f},
1315 {0x0451, 0x0451},
1316 {0x2010, 0x2010},
1317 {0x2013, 0x2016},
1318 {0x2018, 0x2019},
1319 {0x201c, 0x201d},
1320 {0x2020, 0x2022},
1321 {0x2024, 0x2027},
1322 {0x2030, 0x2030},
1323 {0x2032, 0x2033},
1324 {0x2035, 0x2035},
1325 {0x203b, 0x203b},
1326 {0x203e, 0x203e},
1327 {0x2074, 0x2074},
1328 {0x207f, 0x207f},
1329 {0x2081, 0x2084},
1330 {0x20ac, 0x20ac},
1331 {0x2103, 0x2103},
1332 {0x2105, 0x2105},
1333 {0x2109, 0x2109},
1334 {0x2113, 0x2113},
1335 {0x2116, 0x2116},
1336 {0x2121, 0x2122},
1337 {0x2126, 0x2126},
1338 {0x212b, 0x212b},
1339 {0x2153, 0x2154},
1340 {0x215b, 0x215e},
1341 {0x2160, 0x216b},
1342 {0x2170, 0x2179},
1343 {0x2189, 0x2189},
1344 {0x2190, 0x2199},
1345 {0x21b8, 0x21b9},
1346 {0x21d2, 0x21d2},
1347 {0x21d4, 0x21d4},
1348 {0x21e7, 0x21e7},
1349 {0x2200, 0x2200},
1350 {0x2202, 0x2203},
1351 {0x2207, 0x2208},
1352 {0x220b, 0x220b},
1353 {0x220f, 0x220f},
1354 {0x2211, 0x2211},
1355 {0x2215, 0x2215},
1356 {0x221a, 0x221a},
1357 {0x221d, 0x2220},
1358 {0x2223, 0x2223},
1359 {0x2225, 0x2225},
1360 {0x2227, 0x222c},
1361 {0x222e, 0x222e},
1362 {0x2234, 0x2237},
1363 {0x223c, 0x223d},
1364 {0x2248, 0x2248},
1365 {0x224c, 0x224c},
1366 {0x2252, 0x2252},
1367 {0x2260, 0x2261},
1368 {0x2264, 0x2267},
1369 {0x226a, 0x226b},
1370 {0x226e, 0x226f},
1371 {0x2282, 0x2283},
1372 {0x2286, 0x2287},
1373 {0x2295, 0x2295},
1374 {0x2299, 0x2299},
1375 {0x22a5, 0x22a5},
1376 {0x22bf, 0x22bf},
1377 {0x2312, 0x2312},
1378 {0x2460, 0x24e9},
1379 {0x24eb, 0x254b},
1380 {0x2550, 0x2573},
1381 {0x2580, 0x258f},
1382 {0x2592, 0x2595},
1383 {0x25a0, 0x25a1},
1384 {0x25a3, 0x25a9},
1385 {0x25b2, 0x25b3},
1386 {0x25b6, 0x25b7},
1387 {0x25bc, 0x25bd},
1388 {0x25c0, 0x25c1},
1389 {0x25c6, 0x25c8},
1390 {0x25cb, 0x25cb},
1391 {0x25ce, 0x25d1},
1392 {0x25e2, 0x25e5},
1393 {0x25ef, 0x25ef},
1394 {0x2605, 0x2606},
1395 {0x2609, 0x2609},
1396 {0x260e, 0x260f},
1397 {0x2614, 0x2615},
1398 {0x261c, 0x261c},
1399 {0x261e, 0x261e},
1400 {0x2640, 0x2640},
1401 {0x2642, 0x2642},
1402 {0x2660, 0x2661},
1403 {0x2663, 0x2665},
1404 {0x2667, 0x266a},
1405 {0x266c, 0x266d},
1406 {0x266f, 0x266f},
1407 {0x269e, 0x269f},
1408 {0x26be, 0x26bf},
1409 {0x26c4, 0x26cd},
1410 {0x26cf, 0x26e1},
1411 {0x26e3, 0x26e3},
1412 {0x26e8, 0x26ff},
1413 {0x273d, 0x273d},
1414 {0x2757, 0x2757},
1415 {0x2776, 0x277f},
1416 {0x2b55, 0x2b59},
1417 {0x3248, 0x324f},
1418 {0xe000, 0xf8ff},
1419 {0xfffd, 0xfffd},
1420 {0x1f100, 0x1f10a},
1421 {0x1f110, 0x1f12d},
1422 {0x1f131, 0x1f131},
1423 {0x1f13d, 0x1f13d},
1424 {0x1f13f, 0x1f13f},
1425 {0x1f142, 0x1f142},
1426 {0x1f146, 0x1f146},
1427 {0x1f14a, 0x1f14e},
1428 {0x1f157, 0x1f157},
1429 {0x1f15f, 0x1f15f},
1430 {0x1f179, 0x1f179},
1431 {0x1f17b, 0x1f17c},
1432 {0x1f17f, 0x1f17f},
1433 {0x1f18a, 0x1f18d},
1434 {0x1f190, 0x1f190},
1435 {0xf0000, 0xffffd},
1436 {0x100000, 0x10fffd}
1439 #ifdef USE_AMBIWIDTH_AUTO
1440 if (gui.in_use && *p_ambw == 'a')
1442 int cell;
1444 /* This is required by screen.c implicitly. */
1445 if (c == 0)
1446 return 1;
1447 if ((cell = gui_mch_get_charwidth(c)) > 0)
1448 return cell;
1450 #endif
1452 if (c >= 0x100)
1454 #ifdef USE_WCHAR_FUNCTIONS
1456 * Assume the library function wcwidth() works better than our own
1457 * stuff. It should return 1 for ambiguous width chars!
1459 int n = wcwidth(c);
1461 if (n < 0)
1462 return 6; /* unprintable, displays <xxxx> */
1463 if (n > 1)
1464 return n;
1465 #else
1466 if (!utf_printable(c))
1467 return 6; /* unprintable, displays <xxxx> */
1468 if (intable(doublewidth, sizeof(doublewidth), c))
1469 return 2;
1470 #endif
1473 /* Characters below 0x100 are influenced by 'isprint' option */
1474 else if (c >= 0x80 && !vim_isprintc(c))
1475 return 4; /* unprintable, displays <xx> */
1477 if (c >= 0x80 && *p_ambw == 'd' && intable(ambiguous, sizeof(ambiguous), c))
1478 return 2;
1480 return 1;
1484 * mb_ptr2cells() function pointer.
1485 * Return the number of display cells character at "*p" occupies.
1486 * This doesn't take care of unprintable characters, use ptr2cells() for that.
1489 latin_ptr2cells(p)
1490 char_u *p UNUSED;
1492 return 1;
1496 utf_ptr2cells(p)
1497 char_u *p;
1499 int c;
1501 /* Need to convert to a wide character. */
1502 if (*p >= 0x80)
1504 c = utf_ptr2char(p);
1505 /* An illegal byte is displayed as <xx>. */
1506 if (utf_ptr2len(p) == 1 || c == NUL)
1507 return 4;
1508 /* If the char is ASCII it must be an overlong sequence. */
1509 if (c < 0x80)
1510 return char2cells(c);
1511 return utf_char2cells(c);
1513 return 1;
1517 dbcs_ptr2cells(p)
1518 char_u *p;
1520 /* Number of cells is equal to number of bytes, except for euc-jp when
1521 * the first byte is 0x8e. */
1522 if (enc_dbcs == DBCS_JPNU && *p == 0x8e)
1523 return 1;
1524 return MB_BYTE2LEN(*p);
1528 * mb_ptr2cells_len() function pointer.
1529 * Like mb_ptr2cells(), but limit string length to "size".
1530 * For an empty string or truncated character returns 1.
1533 latin_ptr2cells_len(p, size)
1534 char_u *p UNUSED;
1535 int size UNUSED;
1537 return 1;
1540 static int
1541 utf_ptr2cells_len(p, size)
1542 char_u *p;
1543 int size;
1545 int c;
1547 /* Need to convert to a wide character. */
1548 if (size > 0 && *p >= 0x80)
1550 if (utf_ptr2len_len(p, size) < utf8len_tab[*p])
1551 return 1; /* truncated */
1552 c = utf_ptr2char(p);
1553 /* An illegal byte is displayed as <xx>. */
1554 if (utf_ptr2len(p) == 1 || c == NUL)
1555 return 4;
1556 /* If the char is ASCII it must be an overlong sequence. */
1557 if (c < 0x80)
1558 return char2cells(c);
1559 return utf_char2cells(c);
1561 return 1;
1564 static int
1565 dbcs_ptr2cells_len(p, size)
1566 char_u *p;
1567 int size;
1569 /* Number of cells is equal to number of bytes, except for euc-jp when
1570 * the first byte is 0x8e. */
1571 if (size <= 1 || (enc_dbcs == DBCS_JPNU && *p == 0x8e))
1572 return 1;
1573 return MB_BYTE2LEN(*p);
1577 * mb_char2cells() function pointer.
1578 * Return the number of display cells character "c" occupies.
1579 * Only takes care of multi-byte chars, not "^C" and such.
1582 latin_char2cells(c)
1583 int c UNUSED;
1585 return 1;
1588 static int
1589 dbcs_char2cells(c)
1590 int c;
1592 /* Number of cells is equal to number of bytes, except for euc-jp when
1593 * the first byte is 0x8e. */
1594 if (enc_dbcs == DBCS_JPNU && ((unsigned)c >> 8) == 0x8e)
1595 return 1;
1596 /* use the first byte */
1597 return MB_BYTE2LEN((unsigned)c >> 8);
1601 * mb_off2cells() function pointer.
1602 * Return number of display cells for char at ScreenLines[off].
1603 * We make sure that the offset used is less than "max_off".
1606 latin_off2cells(off, max_off)
1607 unsigned off UNUSED;
1608 unsigned max_off UNUSED;
1610 return 1;
1614 dbcs_off2cells(off, max_off)
1615 unsigned off;
1616 unsigned max_off;
1618 /* never check beyond end of the line */
1619 if (off >= max_off)
1620 return 1;
1622 /* Number of cells is equal to number of bytes, except for euc-jp when
1623 * the first byte is 0x8e. */
1624 if (enc_dbcs == DBCS_JPNU && ScreenLines[off] == 0x8e)
1625 return 1;
1626 return MB_BYTE2LEN(ScreenLines[off]);
1630 utf_off2cells(off, max_off)
1631 unsigned off;
1632 unsigned max_off;
1634 return (off + 1 < max_off && ScreenLines[off + 1] == 0) ? 2 : 1;
1638 * mb_ptr2char() function pointer.
1639 * Convert a byte sequence into a character.
1642 latin_ptr2char(p)
1643 char_u *p;
1645 return *p;
1648 static int
1649 dbcs_ptr2char(p)
1650 char_u *p;
1652 if (MB_BYTE2LEN(*p) > 1 && p[1] != NUL)
1653 return (p[0] << 8) + p[1];
1654 return *p;
1658 * Convert a UTF-8 byte sequence to a wide character.
1659 * If the sequence is illegal or truncated by a NUL the first byte is
1660 * returned.
1661 * Does not include composing characters, of course.
1664 utf_ptr2char(p)
1665 char_u *p;
1667 int len;
1669 if (p[0] < 0x80) /* be quick for ASCII */
1670 return p[0];
1672 len = utf8len_tab_zero[p[0]];
1673 if (len > 1 && (p[1] & 0xc0) == 0x80)
1675 if (len == 2)
1676 return ((p[0] & 0x1f) << 6) + (p[1] & 0x3f);
1677 if ((p[2] & 0xc0) == 0x80)
1679 if (len == 3)
1680 return ((p[0] & 0x0f) << 12) + ((p[1] & 0x3f) << 6)
1681 + (p[2] & 0x3f);
1682 if ((p[3] & 0xc0) == 0x80)
1684 if (len == 4)
1685 return ((p[0] & 0x07) << 18) + ((p[1] & 0x3f) << 12)
1686 + ((p[2] & 0x3f) << 6) + (p[3] & 0x3f);
1687 if ((p[4] & 0xc0) == 0x80)
1689 if (len == 5)
1690 return ((p[0] & 0x03) << 24) + ((p[1] & 0x3f) << 18)
1691 + ((p[2] & 0x3f) << 12) + ((p[3] & 0x3f) << 6)
1692 + (p[4] & 0x3f);
1693 if ((p[5] & 0xc0) == 0x80 && len == 6)
1694 return ((p[0] & 0x01) << 30) + ((p[1] & 0x3f) << 24)
1695 + ((p[2] & 0x3f) << 18) + ((p[3] & 0x3f) << 12)
1696 + ((p[4] & 0x3f) << 6) + (p[5] & 0x3f);
1701 /* Illegal value, just return the first byte */
1702 return p[0];
1706 * Get character at **pp and advance *pp to the next character.
1707 * Note: composing characters are skipped!
1710 mb_ptr2char_adv(pp)
1711 char_u **pp;
1713 int c;
1715 c = (*mb_ptr2char)(*pp);
1716 *pp += (*mb_ptr2len)(*pp);
1717 return c;
1721 * Get character at **pp and advance *pp to the next character.
1722 * Note: composing characters are returned as separate characters.
1725 mb_cptr2char_adv(pp)
1726 char_u **pp;
1728 int c;
1730 c = (*mb_ptr2char)(*pp);
1731 if (enc_utf8)
1732 *pp += utf_ptr2len(*pp);
1733 else
1734 *pp += (*mb_ptr2len)(*pp);
1735 return c;
1738 #if defined(FEAT_ARABIC) || defined(PROTO)
1740 * Check whether we are dealing with Arabic combining characters.
1741 * Note: these are NOT really composing characters!
1744 arabic_combine(one, two)
1745 int one; /* first character */
1746 int two; /* character just after "one" */
1748 if (one == a_LAM)
1749 return arabic_maycombine(two);
1750 return FALSE;
1754 * Check whether we are dealing with a character that could be regarded as an
1755 * Arabic combining character, need to check the character before this.
1758 arabic_maycombine(two)
1759 int two;
1761 if (p_arshape && !p_tbidi)
1762 return (two == a_ALEF_MADDA
1763 || two == a_ALEF_HAMZA_ABOVE
1764 || two == a_ALEF_HAMZA_BELOW
1765 || two == a_ALEF);
1766 return FALSE;
1770 * Check if the character pointed to by "p2" is a composing character when it
1771 * comes after "p1". For Arabic sometimes "ab" is replaced with "c", which
1772 * behaves like a composing character.
1775 utf_composinglike(p1, p2)
1776 char_u *p1;
1777 char_u *p2;
1779 int c2;
1781 c2 = utf_ptr2char(p2);
1782 if (utf_iscomposing(c2))
1783 return TRUE;
1784 if (!arabic_maycombine(c2))
1785 return FALSE;
1786 return arabic_combine(utf_ptr2char(p1), c2);
1788 #endif
1791 * Convert a UTF-8 byte string to a wide character. Also get up to MAX_MCO
1792 * composing characters.
1795 utfc_ptr2char(p, pcc)
1796 char_u *p;
1797 int *pcc; /* return: composing chars, last one is 0 */
1799 int len;
1800 int c;
1801 int cc;
1802 int i = 0;
1804 c = utf_ptr2char(p);
1805 len = utf_ptr2len(p);
1807 /* Only accept a composing char when the first char isn't illegal. */
1808 if ((len > 1 || *p < 0x80)
1809 && p[len] >= 0x80
1810 && UTF_COMPOSINGLIKE(p, p + len))
1812 cc = utf_ptr2char(p + len);
1813 for (;;)
1815 pcc[i++] = cc;
1816 if (i == MAX_MCO)
1817 break;
1818 len += utf_ptr2len(p + len);
1819 if (p[len] < 0x80 || !utf_iscomposing(cc = utf_ptr2char(p + len)))
1820 break;
1824 if (i < MAX_MCO) /* last composing char must be 0 */
1825 pcc[i] = 0;
1827 return c;
1831 * Convert a UTF-8 byte string to a wide character. Also get up to MAX_MCO
1832 * composing characters. Use no more than p[maxlen].
1835 utfc_ptr2char_len(p, pcc, maxlen)
1836 char_u *p;
1837 int *pcc; /* return: composing chars, last one is 0 */
1838 int maxlen;
1840 int len;
1841 int c;
1842 int cc;
1843 int i = 0;
1845 c = utf_ptr2char(p);
1846 len = utf_ptr2len_len(p, maxlen);
1847 /* Only accept a composing char when the first char isn't illegal. */
1848 if ((len > 1 || *p < 0x80)
1849 && len < maxlen
1850 && p[len] >= 0x80
1851 && UTF_COMPOSINGLIKE(p, p + len))
1853 cc = utf_ptr2char(p + len);
1854 for (;;)
1856 pcc[i++] = cc;
1857 if (i == MAX_MCO)
1858 break;
1859 len += utf_ptr2len_len(p + len, maxlen - len);
1860 if (len >= maxlen
1861 || p[len] < 0x80
1862 || !utf_iscomposing(cc = utf_ptr2char(p + len)))
1863 break;
1867 if (i < MAX_MCO) /* last composing char must be 0 */
1868 pcc[i] = 0;
1870 return c;
1874 * Convert the character at screen position "off" to a sequence of bytes.
1875 * Includes the composing characters.
1876 * "buf" must at least have the length MB_MAXBYTES.
1877 * Returns the produced number of bytes.
1880 utfc_char2bytes(off, buf)
1881 int off;
1882 char_u *buf;
1884 int len;
1885 int i;
1887 len = utf_char2bytes(ScreenLinesUC[off], buf);
1888 for (i = 0; i < Screen_mco; ++i)
1890 if (ScreenLinesC[i][off] == 0)
1891 break;
1892 len += utf_char2bytes(ScreenLinesC[i][off], buf + len);
1894 return len;
1898 * Get the length of a UTF-8 byte sequence, not including any following
1899 * composing characters.
1900 * Returns 0 for "".
1901 * Returns 1 for an illegal byte sequence.
1904 utf_ptr2len(p)
1905 char_u *p;
1907 int len;
1908 int i;
1910 if (*p == NUL)
1911 return 0;
1912 len = utf8len_tab[*p];
1913 for (i = 1; i < len; ++i)
1914 if ((p[i] & 0xc0) != 0x80)
1915 return 1;
1916 return len;
1920 * Return length of UTF-8 character, obtained from the first byte.
1921 * "b" must be between 0 and 255!
1922 * Returns 1 for an invalid first byte value.
1925 utf_byte2len(b)
1926 int b;
1928 return utf8len_tab[b];
1932 * Get the length of UTF-8 byte sequence "p[size]". Does not include any
1933 * following composing characters.
1934 * Returns 1 for "".
1935 * Returns 1 for an illegal byte sequence (also in incomplete byte seq.).
1936 * Returns number > "size" for an incomplete byte sequence.
1937 * Never returns zero.
1940 utf_ptr2len_len(p, size)
1941 char_u *p;
1942 int size;
1944 int len;
1945 int i;
1946 int m;
1948 len = utf8len_tab[*p];
1949 if (len == 1)
1950 return 1; /* NUL, ascii or illegal lead byte */
1951 if (len > size)
1952 m = size; /* incomplete byte sequence. */
1953 else
1954 m = len;
1955 for (i = 1; i < m; ++i)
1956 if ((p[i] & 0xc0) != 0x80)
1957 return 1;
1958 return len;
1962 * Return the number of bytes the UTF-8 encoding of the character at "p" takes.
1963 * This includes following composing characters.
1966 utfc_ptr2len(p)
1967 char_u *p;
1969 int len;
1970 int b0 = *p;
1971 #ifdef FEAT_ARABIC
1972 int prevlen;
1973 #endif
1975 if (b0 == NUL)
1976 return 0;
1977 if (b0 < 0x80 && p[1] < 0x80) /* be quick for ASCII */
1978 return 1;
1980 /* Skip over first UTF-8 char, stopping at a NUL byte. */
1981 len = utf_ptr2len(p);
1983 /* Check for illegal byte. */
1984 if (len == 1 && b0 >= 0x80)
1985 return 1;
1988 * Check for composing characters. We can handle only the first six, but
1989 * skip all of them (otherwise the cursor would get stuck).
1991 #ifdef FEAT_ARABIC
1992 prevlen = 0;
1993 #endif
1994 for (;;)
1996 if (p[len] < 0x80 || !UTF_COMPOSINGLIKE(p + prevlen, p + len))
1997 return len;
1999 /* Skip over composing char */
2000 #ifdef FEAT_ARABIC
2001 prevlen = len;
2002 #endif
2003 len += utf_ptr2len(p + len);
2008 * Return the number of bytes the UTF-8 encoding of the character at "p[size]"
2009 * takes. This includes following composing characters.
2010 * Returns 0 for an empty string.
2011 * Returns 1 for an illegal char or an incomplete byte sequence.
2014 utfc_ptr2len_len(p, size)
2015 char_u *p;
2016 int size;
2018 int len;
2019 #ifdef FEAT_ARABIC
2020 int prevlen;
2021 #endif
2023 if (size < 1 || *p == NUL)
2024 return 0;
2025 if (p[0] < 0x80 && (size == 1 || p[1] < 0x80)) /* be quick for ASCII */
2026 return 1;
2028 /* Skip over first UTF-8 char, stopping at a NUL byte. */
2029 len = utf_ptr2len_len(p, size);
2031 /* Check for illegal byte and incomplete byte sequence. */
2032 if ((len == 1 && p[0] >= 0x80) || len > size)
2033 return 1;
2036 * Check for composing characters. We can handle only the first six, but
2037 * skip all of them (otherwise the cursor would get stuck).
2039 #ifdef FEAT_ARABIC
2040 prevlen = 0;
2041 #endif
2042 while (len < size)
2044 int len_next_char;
2046 if (p[len] < 0x80)
2047 break;
2050 * Next character length should not go beyond size to ensure that
2051 * UTF_COMPOSINGLIKE(...) does not read beyond size.
2053 len_next_char = utf_ptr2len_len(p + len, size - len);
2054 if (len_next_char > size - len)
2055 break;
2057 if (!UTF_COMPOSINGLIKE(p + prevlen, p + len))
2058 break;
2060 /* Skip over composing char */
2061 #ifdef FEAT_ARABIC
2062 prevlen = len;
2063 #endif
2064 len += len_next_char;
2066 return len;
2070 * Return the number of bytes the UTF-8 encoding of character "c" takes.
2071 * This does not include composing characters.
2074 utf_char2len(c)
2075 int c;
2077 if (c < 0x80)
2078 return 1;
2079 if (c < 0x800)
2080 return 2;
2081 if (c < 0x10000)
2082 return 3;
2083 if (c < 0x200000)
2084 return 4;
2085 if (c < 0x4000000)
2086 return 5;
2087 return 6;
2091 * Convert Unicode character "c" to UTF-8 string in "buf[]".
2092 * Returns the number of bytes.
2093 * This does not include composing characters.
2096 utf_char2bytes(c, buf)
2097 int c;
2098 char_u *buf;
2100 if (c < 0x80) /* 7 bits */
2102 buf[0] = c;
2103 return 1;
2105 if (c < 0x800) /* 11 bits */
2107 buf[0] = 0xc0 + ((unsigned)c >> 6);
2108 buf[1] = 0x80 + (c & 0x3f);
2109 return 2;
2111 if (c < 0x10000) /* 16 bits */
2113 buf[0] = 0xe0 + ((unsigned)c >> 12);
2114 buf[1] = 0x80 + (((unsigned)c >> 6) & 0x3f);
2115 buf[2] = 0x80 + (c & 0x3f);
2116 return 3;
2118 if (c < 0x200000) /* 21 bits */
2120 buf[0] = 0xf0 + ((unsigned)c >> 18);
2121 buf[1] = 0x80 + (((unsigned)c >> 12) & 0x3f);
2122 buf[2] = 0x80 + (((unsigned)c >> 6) & 0x3f);
2123 buf[3] = 0x80 + (c & 0x3f);
2124 return 4;
2126 if (c < 0x4000000) /* 26 bits */
2128 buf[0] = 0xf8 + ((unsigned)c >> 24);
2129 buf[1] = 0x80 + (((unsigned)c >> 18) & 0x3f);
2130 buf[2] = 0x80 + (((unsigned)c >> 12) & 0x3f);
2131 buf[3] = 0x80 + (((unsigned)c >> 6) & 0x3f);
2132 buf[4] = 0x80 + (c & 0x3f);
2133 return 5;
2135 /* 31 bits */
2136 buf[0] = 0xfc + ((unsigned)c >> 30);
2137 buf[1] = 0x80 + (((unsigned)c >> 24) & 0x3f);
2138 buf[2] = 0x80 + (((unsigned)c >> 18) & 0x3f);
2139 buf[3] = 0x80 + (((unsigned)c >> 12) & 0x3f);
2140 buf[4] = 0x80 + (((unsigned)c >> 6) & 0x3f);
2141 buf[5] = 0x80 + (c & 0x3f);
2142 return 6;
2146 * Return TRUE if "c" is a composing UTF-8 character. This means it will be
2147 * drawn on top of the preceding character.
2148 * Based on code from Markus Kuhn.
2151 utf_iscomposing(c)
2152 int c;
2154 /* Sorted list of non-overlapping intervals.
2155 * Generated by ../runtime/tools/unicode.vim. */
2156 static struct interval combining[] =
2158 {0x0300, 0x036f},
2159 {0x0483, 0x0489},
2160 {0x0591, 0x05bd},
2161 {0x05bf, 0x05bf},
2162 {0x05c1, 0x05c2},
2163 {0x05c4, 0x05c5},
2164 {0x05c7, 0x05c7},
2165 {0x0610, 0x061a},
2166 {0x064b, 0x065e},
2167 {0x0670, 0x0670},
2168 {0x06d6, 0x06dc},
2169 {0x06de, 0x06e4},
2170 {0x06e7, 0x06e8},
2171 {0x06ea, 0x06ed},
2172 {0x0711, 0x0711},
2173 {0x0730, 0x074a},
2174 {0x07a6, 0x07b0},
2175 {0x07eb, 0x07f3},
2176 {0x0816, 0x0819},
2177 {0x081b, 0x0823},
2178 {0x0825, 0x0827},
2179 {0x0829, 0x082d},
2180 {0x0900, 0x0903},
2181 {0x093c, 0x093c},
2182 {0x093e, 0x094e},
2183 {0x0951, 0x0955},
2184 {0x0962, 0x0963},
2185 {0x0981, 0x0983},
2186 {0x09bc, 0x09bc},
2187 {0x09be, 0x09c4},
2188 {0x09c7, 0x09c8},
2189 {0x09cb, 0x09cd},
2190 {0x09d7, 0x09d7},
2191 {0x09e2, 0x09e3},
2192 {0x0a01, 0x0a03},
2193 {0x0a3c, 0x0a3c},
2194 {0x0a3e, 0x0a42},
2195 {0x0a47, 0x0a48},
2196 {0x0a4b, 0x0a4d},
2197 {0x0a51, 0x0a51},
2198 {0x0a70, 0x0a71},
2199 {0x0a75, 0x0a75},
2200 {0x0a81, 0x0a83},
2201 {0x0abc, 0x0abc},
2202 {0x0abe, 0x0ac5},
2203 {0x0ac7, 0x0ac9},
2204 {0x0acb, 0x0acd},
2205 {0x0ae2, 0x0ae3},
2206 {0x0b01, 0x0b03},
2207 {0x0b3c, 0x0b3c},
2208 {0x0b3e, 0x0b44},
2209 {0x0b47, 0x0b48},
2210 {0x0b4b, 0x0b4d},
2211 {0x0b56, 0x0b57},
2212 {0x0b62, 0x0b63},
2213 {0x0b82, 0x0b82},
2214 {0x0bbe, 0x0bc2},
2215 {0x0bc6, 0x0bc8},
2216 {0x0bca, 0x0bcd},
2217 {0x0bd7, 0x0bd7},
2218 {0x0c01, 0x0c03},
2219 {0x0c3e, 0x0c44},
2220 {0x0c46, 0x0c48},
2221 {0x0c4a, 0x0c4d},
2222 {0x0c55, 0x0c56},
2223 {0x0c62, 0x0c63},
2224 {0x0c82, 0x0c83},
2225 {0x0cbc, 0x0cbc},
2226 {0x0cbe, 0x0cc4},
2227 {0x0cc6, 0x0cc8},
2228 {0x0cca, 0x0ccd},
2229 {0x0cd5, 0x0cd6},
2230 {0x0ce2, 0x0ce3},
2231 {0x0d02, 0x0d03},
2232 {0x0d3e, 0x0d44},
2233 {0x0d46, 0x0d48},
2234 {0x0d4a, 0x0d4d},
2235 {0x0d57, 0x0d57},
2236 {0x0d62, 0x0d63},
2237 {0x0d82, 0x0d83},
2238 {0x0dca, 0x0dca},
2239 {0x0dcf, 0x0dd4},
2240 {0x0dd6, 0x0dd6},
2241 {0x0dd8, 0x0ddf},
2242 {0x0df2, 0x0df3},
2243 {0x0e31, 0x0e31},
2244 {0x0e34, 0x0e3a},
2245 {0x0e47, 0x0e4e},
2246 {0x0eb1, 0x0eb1},
2247 {0x0eb4, 0x0eb9},
2248 {0x0ebb, 0x0ebc},
2249 {0x0ec8, 0x0ecd},
2250 {0x0f18, 0x0f19},
2251 {0x0f35, 0x0f35},
2252 {0x0f37, 0x0f37},
2253 {0x0f39, 0x0f39},
2254 {0x0f3e, 0x0f3f},
2255 {0x0f71, 0x0f84},
2256 {0x0f86, 0x0f87},
2257 {0x0f90, 0x0f97},
2258 {0x0f99, 0x0fbc},
2259 {0x0fc6, 0x0fc6},
2260 {0x102b, 0x103e},
2261 {0x1056, 0x1059},
2262 {0x105e, 0x1060},
2263 {0x1062, 0x1064},
2264 {0x1067, 0x106d},
2265 {0x1071, 0x1074},
2266 {0x1082, 0x108d},
2267 {0x108f, 0x108f},
2268 {0x109a, 0x109d},
2269 {0x135f, 0x135f},
2270 {0x1712, 0x1714},
2271 {0x1732, 0x1734},
2272 {0x1752, 0x1753},
2273 {0x1772, 0x1773},
2274 {0x17b6, 0x17d3},
2275 {0x17dd, 0x17dd},
2276 {0x180b, 0x180d},
2277 {0x18a9, 0x18a9},
2278 {0x1920, 0x192b},
2279 {0x1930, 0x193b},
2280 {0x19b0, 0x19c0},
2281 {0x19c8, 0x19c9},
2282 {0x1a17, 0x1a1b},
2283 {0x1a55, 0x1a5e},
2284 {0x1a60, 0x1a7c},
2285 {0x1a7f, 0x1a7f},
2286 {0x1b00, 0x1b04},
2287 {0x1b34, 0x1b44},
2288 {0x1b6b, 0x1b73},
2289 {0x1b80, 0x1b82},
2290 {0x1ba1, 0x1baa},
2291 {0x1c24, 0x1c37},
2292 {0x1cd0, 0x1cd2},
2293 {0x1cd4, 0x1ce8},
2294 {0x1ced, 0x1ced},
2295 {0x1cf2, 0x1cf2},
2296 {0x1dc0, 0x1de6},
2297 {0x1dfd, 0x1dff},
2298 {0x20d0, 0x20f0},
2299 {0x2cef, 0x2cf1},
2300 {0x2de0, 0x2dff},
2301 {0x302a, 0x302f},
2302 {0x3099, 0x309a},
2303 {0xa66f, 0xa672},
2304 {0xa67c, 0xa67d},
2305 {0xa6f0, 0xa6f1},
2306 {0xa802, 0xa802},
2307 {0xa806, 0xa806},
2308 {0xa80b, 0xa80b},
2309 {0xa823, 0xa827},
2310 {0xa880, 0xa881},
2311 {0xa8b4, 0xa8c4},
2312 {0xa8e0, 0xa8f1},
2313 {0xa926, 0xa92d},
2314 {0xa947, 0xa953},
2315 {0xa980, 0xa983},
2316 {0xa9b3, 0xa9c0},
2317 {0xaa29, 0xaa36},
2318 {0xaa43, 0xaa43},
2319 {0xaa4c, 0xaa4d},
2320 {0xaa7b, 0xaa7b},
2321 {0xaab0, 0xaab0},
2322 {0xaab2, 0xaab4},
2323 {0xaab7, 0xaab8},
2324 {0xaabe, 0xaabf},
2325 {0xaac1, 0xaac1},
2326 {0xabe3, 0xabea},
2327 {0xabec, 0xabed},
2328 {0xfb1e, 0xfb1e},
2329 {0xfe00, 0xfe0f},
2330 {0xfe20, 0xfe26},
2331 {0x101fd, 0x101fd},
2332 {0x10a01, 0x10a03},
2333 {0x10a05, 0x10a06},
2334 {0x10a0c, 0x10a0f},
2335 {0x10a38, 0x10a3a},
2336 {0x10a3f, 0x10a3f},
2337 {0x11080, 0x11082},
2338 {0x110b0, 0x110ba},
2339 {0x1d165, 0x1d169},
2340 {0x1d16d, 0x1d172},
2341 {0x1d17b, 0x1d182},
2342 {0x1d185, 0x1d18b},
2343 {0x1d1aa, 0x1d1ad},
2344 {0x1d242, 0x1d244},
2345 {0xe0100, 0xe01ef}
2348 return intable(combining, sizeof(combining), c);
2352 * Return TRUE for characters that can be displayed in a normal way.
2353 * Only for characters of 0x100 and above!
2356 utf_printable(c)
2357 int c;
2359 #ifdef USE_WCHAR_FUNCTIONS
2361 * Assume the iswprint() library function works better than our own stuff.
2363 return iswprint(c);
2364 #else
2365 /* Sorted list of non-overlapping intervals.
2366 * 0xd800-0xdfff is reserved for UTF-16, actually illegal. */
2367 static struct interval nonprint[] =
2369 {0x070f, 0x070f}, {0x180b, 0x180e}, {0x200b, 0x200f}, {0x202a, 0x202e},
2370 {0x206a, 0x206f}, {0xd800, 0xdfff}, {0xfeff, 0xfeff}, {0xfff9, 0xfffb},
2371 {0xfffe, 0xffff}
2374 return !intable(nonprint, sizeof(nonprint), c);
2375 #endif
2379 * Get class of a Unicode character.
2380 * 0: white space
2381 * 1: punctuation
2382 * 2 or bigger: some class of word character.
2385 utf_class(c)
2386 int c;
2388 /* sorted list of non-overlapping intervals */
2389 static struct clinterval
2391 unsigned short first;
2392 unsigned short last;
2393 unsigned short class;
2394 } classes[] =
2396 {0x037e, 0x037e, 1}, /* Greek question mark */
2397 {0x0387, 0x0387, 1}, /* Greek ano teleia */
2398 {0x055a, 0x055f, 1}, /* Armenian punctuation */
2399 {0x0589, 0x0589, 1}, /* Armenian full stop */
2400 {0x05be, 0x05be, 1},
2401 {0x05c0, 0x05c0, 1},
2402 {0x05c3, 0x05c3, 1},
2403 {0x05f3, 0x05f4, 1},
2404 {0x060c, 0x060c, 1},
2405 {0x061b, 0x061b, 1},
2406 {0x061f, 0x061f, 1},
2407 {0x066a, 0x066d, 1},
2408 {0x06d4, 0x06d4, 1},
2409 {0x0700, 0x070d, 1}, /* Syriac punctuation */
2410 {0x0964, 0x0965, 1},
2411 {0x0970, 0x0970, 1},
2412 {0x0df4, 0x0df4, 1},
2413 {0x0e4f, 0x0e4f, 1},
2414 {0x0e5a, 0x0e5b, 1},
2415 {0x0f04, 0x0f12, 1},
2416 {0x0f3a, 0x0f3d, 1},
2417 {0x0f85, 0x0f85, 1},
2418 {0x104a, 0x104f, 1}, /* Myanmar punctuation */
2419 {0x10fb, 0x10fb, 1}, /* Georgian punctuation */
2420 {0x1361, 0x1368, 1}, /* Ethiopic punctuation */
2421 {0x166d, 0x166e, 1}, /* Canadian Syl. punctuation */
2422 {0x1680, 0x1680, 0},
2423 {0x169b, 0x169c, 1},
2424 {0x16eb, 0x16ed, 1},
2425 {0x1735, 0x1736, 1},
2426 {0x17d4, 0x17dc, 1}, /* Khmer punctuation */
2427 {0x1800, 0x180a, 1}, /* Mongolian punctuation */
2428 {0x2000, 0x200b, 0}, /* spaces */
2429 {0x200c, 0x2027, 1}, /* punctuation and symbols */
2430 {0x2028, 0x2029, 0},
2431 {0x202a, 0x202e, 1}, /* punctuation and symbols */
2432 {0x202f, 0x202f, 0},
2433 {0x2030, 0x205e, 1}, /* punctuation and symbols */
2434 {0x205f, 0x205f, 0},
2435 {0x2060, 0x27ff, 1}, /* punctuation and symbols */
2436 {0x2070, 0x207f, 0x2070}, /* superscript */
2437 {0x2080, 0x2094, 0x2080}, /* subscript */
2438 {0x20a0, 0x27ff, 1}, /* all kinds of symbols */
2439 {0x2800, 0x28ff, 0x2800}, /* braille */
2440 {0x2900, 0x2998, 1}, /* arrows, brackets, etc. */
2441 {0x29d8, 0x29db, 1},
2442 {0x29fc, 0x29fd, 1},
2443 {0x3000, 0x3000, 0}, /* ideographic space */
2444 {0x3001, 0x3020, 1}, /* ideographic punctuation */
2445 {0x3030, 0x3030, 1},
2446 {0x303d, 0x303d, 1},
2447 {0x3040, 0x309f, 0x3040}, /* Hiragana */
2448 {0x30a0, 0x30ff, 0x30a0}, /* Katakana */
2449 {0x3300, 0x9fff, 0x4e00}, /* CJK Ideographs */
2450 {0xac00, 0xd7a3, 0xac00}, /* Hangul Syllables */
2451 {0xf900, 0xfaff, 0x4e00}, /* CJK Ideographs */
2452 {0xfd3e, 0xfd3f, 1},
2453 {0xfe30, 0xfe6b, 1}, /* punctuation forms */
2454 {0xff00, 0xff0f, 1}, /* half/fullwidth ASCII */
2455 {0xff1a, 0xff20, 1}, /* half/fullwidth ASCII */
2456 {0xff3b, 0xff40, 1}, /* half/fullwidth ASCII */
2457 {0xff5b, 0xff65, 1}, /* half/fullwidth ASCII */
2459 int bot = 0;
2460 int top = sizeof(classes) / sizeof(struct clinterval) - 1;
2461 int mid;
2463 /* First quick check for Latin1 characters, use 'iskeyword'. */
2464 if (c < 0x100)
2466 if (c == ' ' || c == '\t' || c == NUL || c == 0xa0)
2467 return 0; /* blank */
2468 if (vim_iswordc(c))
2469 return 2; /* word character */
2470 return 1; /* punctuation */
2473 /* binary search in table */
2474 while (top >= bot)
2476 mid = (bot + top) / 2;
2477 if (classes[mid].last < c)
2478 bot = mid + 1;
2479 else if (classes[mid].first > c)
2480 top = mid - 1;
2481 else
2482 return (int)classes[mid].class;
2485 /* most other characters are "word" characters */
2486 return 2;
2490 * Code for Unicode case-dependent operations. Based on notes in
2491 * http://www.unicode.org/Public/UNIDATA/CaseFolding.txt
2492 * This code uses simple case folding, not full case folding.
2493 * Last updated for Unicode 5.2.
2497 * The following tables are built by ../runtime/tools/unicode.vim.
2498 * They must be in numeric order, because we use binary search.
2499 * An entry such as {0x41,0x5a,1,32} means that Unicode characters in the
2500 * range from 0x41 to 0x5a inclusive, stepping by 1, are changed to
2501 * folded/upper/lower by adding 32.
2503 typedef struct
2505 int rangeStart;
2506 int rangeEnd;
2507 int step;
2508 int offset;
2509 } convertStruct;
2511 static convertStruct foldCase[] =
2513 {0x41,0x5a,1,32},
2514 {0xb5,0xb5,-1,775},
2515 {0xc0,0xd6,1,32},
2516 {0xd8,0xde,1,32},
2517 {0x100,0x12e,2,1},
2518 {0x132,0x136,2,1},
2519 {0x139,0x147,2,1},
2520 {0x14a,0x176,2,1},
2521 {0x178,0x178,-1,-121},
2522 {0x179,0x17d,2,1},
2523 {0x17f,0x17f,-1,-268},
2524 {0x181,0x181,-1,210},
2525 {0x182,0x184,2,1},
2526 {0x186,0x186,-1,206},
2527 {0x187,0x187,-1,1},
2528 {0x189,0x18a,1,205},
2529 {0x18b,0x18b,-1,1},
2530 {0x18e,0x18e,-1,79},
2531 {0x18f,0x18f,-1,202},
2532 {0x190,0x190,-1,203},
2533 {0x191,0x191,-1,1},
2534 {0x193,0x193,-1,205},
2535 {0x194,0x194,-1,207},
2536 {0x196,0x196,-1,211},
2537 {0x197,0x197,-1,209},
2538 {0x198,0x198,-1,1},
2539 {0x19c,0x19c,-1,211},
2540 {0x19d,0x19d,-1,213},
2541 {0x19f,0x19f,-1,214},
2542 {0x1a0,0x1a4,2,1},
2543 {0x1a6,0x1a6,-1,218},
2544 {0x1a7,0x1a7,-1,1},
2545 {0x1a9,0x1a9,-1,218},
2546 {0x1ac,0x1ac,-1,1},
2547 {0x1ae,0x1ae,-1,218},
2548 {0x1af,0x1af,-1,1},
2549 {0x1b1,0x1b2,1,217},
2550 {0x1b3,0x1b5,2,1},
2551 {0x1b7,0x1b7,-1,219},
2552 {0x1b8,0x1bc,4,1},
2553 {0x1c4,0x1c4,-1,2},
2554 {0x1c5,0x1c5,-1,1},
2555 {0x1c7,0x1c7,-1,2},
2556 {0x1c8,0x1c8,-1,1},
2557 {0x1ca,0x1ca,-1,2},
2558 {0x1cb,0x1db,2,1},
2559 {0x1de,0x1ee,2,1},
2560 {0x1f1,0x1f1,-1,2},
2561 {0x1f2,0x1f4,2,1},
2562 {0x1f6,0x1f6,-1,-97},
2563 {0x1f7,0x1f7,-1,-56},
2564 {0x1f8,0x21e,2,1},
2565 {0x220,0x220,-1,-130},
2566 {0x222,0x232,2,1},
2567 {0x23a,0x23a,-1,10795},
2568 {0x23b,0x23b,-1,1},
2569 {0x23d,0x23d,-1,-163},
2570 {0x23e,0x23e,-1,10792},
2571 {0x241,0x241,-1,1},
2572 {0x243,0x243,-1,-195},
2573 {0x244,0x244,-1,69},
2574 {0x245,0x245,-1,71},
2575 {0x246,0x24e,2,1},
2576 {0x345,0x345,-1,116},
2577 {0x370,0x372,2,1},
2578 {0x376,0x376,-1,1},
2579 {0x386,0x386,-1,38},
2580 {0x388,0x38a,1,37},
2581 {0x38c,0x38c,-1,64},
2582 {0x38e,0x38f,1,63},
2583 {0x391,0x3a1,1,32},
2584 {0x3a3,0x3ab,1,32},
2585 {0x3c2,0x3c2,-1,1},
2586 {0x3cf,0x3cf,-1,8},
2587 {0x3d0,0x3d0,-1,-30},
2588 {0x3d1,0x3d1,-1,-25},
2589 {0x3d5,0x3d5,-1,-15},
2590 {0x3d6,0x3d6,-1,-22},
2591 {0x3d8,0x3ee,2,1},
2592 {0x3f0,0x3f0,-1,-54},
2593 {0x3f1,0x3f1,-1,-48},
2594 {0x3f4,0x3f4,-1,-60},
2595 {0x3f5,0x3f5,-1,-64},
2596 {0x3f7,0x3f7,-1,1},
2597 {0x3f9,0x3f9,-1,-7},
2598 {0x3fa,0x3fa,-1,1},
2599 {0x3fd,0x3ff,1,-130},
2600 {0x400,0x40f,1,80},
2601 {0x410,0x42f,1,32},
2602 {0x460,0x480,2,1},
2603 {0x48a,0x4be,2,1},
2604 {0x4c0,0x4c0,-1,15},
2605 {0x4c1,0x4cd,2,1},
2606 {0x4d0,0x524,2,1},
2607 {0x531,0x556,1,48},
2608 {0x10a0,0x10c5,1,7264},
2609 {0x1e00,0x1e94,2,1},
2610 {0x1e9b,0x1e9b,-1,-58},
2611 {0x1e9e,0x1e9e,-1,-7615},
2612 {0x1ea0,0x1efe,2,1},
2613 {0x1f08,0x1f0f,1,-8},
2614 {0x1f18,0x1f1d,1,-8},
2615 {0x1f28,0x1f2f,1,-8},
2616 {0x1f38,0x1f3f,1,-8},
2617 {0x1f48,0x1f4d,1,-8},
2618 {0x1f59,0x1f5f,2,-8},
2619 {0x1f68,0x1f6f,1,-8},
2620 {0x1f88,0x1f8f,1,-8},
2621 {0x1f98,0x1f9f,1,-8},
2622 {0x1fa8,0x1faf,1,-8},
2623 {0x1fb8,0x1fb9,1,-8},
2624 {0x1fba,0x1fbb,1,-74},
2625 {0x1fbc,0x1fbc,-1,-9},
2626 {0x1fbe,0x1fbe,-1,-7173},
2627 {0x1fc8,0x1fcb,1,-86},
2628 {0x1fcc,0x1fcc,-1,-9},
2629 {0x1fd8,0x1fd9,1,-8},
2630 {0x1fda,0x1fdb,1,-100},
2631 {0x1fe8,0x1fe9,1,-8},
2632 {0x1fea,0x1feb,1,-112},
2633 {0x1fec,0x1fec,-1,-7},
2634 {0x1ff8,0x1ff9,1,-128},
2635 {0x1ffa,0x1ffb,1,-126},
2636 {0x1ffc,0x1ffc,-1,-9},
2637 {0x2126,0x2126,-1,-7517},
2638 {0x212a,0x212a,-1,-8383},
2639 {0x212b,0x212b,-1,-8262},
2640 {0x2132,0x2132,-1,28},
2641 {0x2160,0x216f,1,16},
2642 {0x2183,0x2183,-1,1},
2643 {0x24b6,0x24cf,1,26},
2644 {0x2c00,0x2c2e,1,48},
2645 {0x2c60,0x2c60,-1,1},
2646 {0x2c62,0x2c62,-1,-10743},
2647 {0x2c63,0x2c63,-1,-3814},
2648 {0x2c64,0x2c64,-1,-10727},
2649 {0x2c67,0x2c6b,2,1},
2650 {0x2c6d,0x2c6d,-1,-10780},
2651 {0x2c6e,0x2c6e,-1,-10749},
2652 {0x2c6f,0x2c6f,-1,-10783},
2653 {0x2c70,0x2c70,-1,-10782},
2654 {0x2c72,0x2c75,3,1},
2655 {0x2c7e,0x2c7f,1,-10815},
2656 {0x2c80,0x2ce2,2,1},
2657 {0x2ceb,0x2ced,2,1},
2658 {0xa640,0xa65e,2,1},
2659 {0xa662,0xa66c,2,1},
2660 {0xa680,0xa696,2,1},
2661 {0xa722,0xa72e,2,1},
2662 {0xa732,0xa76e,2,1},
2663 {0xa779,0xa77b,2,1},
2664 {0xa77d,0xa77d,-1,-35332},
2665 {0xa77e,0xa786,2,1},
2666 {0xa78b,0xa78b,-1,1},
2667 {0xff21,0xff3a,1,32},
2668 {0x10400,0x10427,1,40}
2671 static int utf_convert(int a, convertStruct table[], int tableSize);
2674 * Generic conversion function for case operations.
2675 * Return the converted equivalent of "a", which is a UCS-4 character. Use
2676 * the given conversion "table". Uses binary search on "table".
2678 static int
2679 utf_convert(a, table, tableSize)
2680 int a;
2681 convertStruct table[];
2682 int tableSize;
2684 int start, mid, end; /* indices into table */
2686 start = 0;
2687 end = tableSize / sizeof(convertStruct);
2688 while (start < end)
2690 /* need to search further */
2691 mid = (end + start) /2;
2692 if (table[mid].rangeEnd < a)
2693 start = mid + 1;
2694 else
2695 end = mid;
2697 if (table[start].rangeStart <= a && a <= table[start].rangeEnd
2698 && (a - table[start].rangeStart) % table[start].step == 0)
2699 return (a + table[start].offset);
2700 else
2701 return a;
2705 * Return the folded-case equivalent of "a", which is a UCS-4 character. Uses
2706 * simple case folding.
2709 utf_fold(a)
2710 int a;
2712 return utf_convert(a, foldCase, sizeof(foldCase));
2715 static convertStruct toLower[] =
2717 {0x41,0x5a,1,32},
2718 {0xc0,0xd6,1,32},
2719 {0xd8,0xde,1,32},
2720 {0x100,0x12e,2,1},
2721 {0x130,0x130,-1,-199},
2722 {0x132,0x136,2,1},
2723 {0x139,0x147,2,1},
2724 {0x14a,0x176,2,1},
2725 {0x178,0x178,-1,-121},
2726 {0x179,0x17d,2,1},
2727 {0x181,0x181,-1,210},
2728 {0x182,0x184,2,1},
2729 {0x186,0x186,-1,206},
2730 {0x187,0x187,-1,1},
2731 {0x189,0x18a,1,205},
2732 {0x18b,0x18b,-1,1},
2733 {0x18e,0x18e,-1,79},
2734 {0x18f,0x18f,-1,202},
2735 {0x190,0x190,-1,203},
2736 {0x191,0x191,-1,1},
2737 {0x193,0x193,-1,205},
2738 {0x194,0x194,-1,207},
2739 {0x196,0x196,-1,211},
2740 {0x197,0x197,-1,209},
2741 {0x198,0x198,-1,1},
2742 {0x19c,0x19c,-1,211},
2743 {0x19d,0x19d,-1,213},
2744 {0x19f,0x19f,-1,214},
2745 {0x1a0,0x1a4,2,1},
2746 {0x1a6,0x1a6,-1,218},
2747 {0x1a7,0x1a7,-1,1},
2748 {0x1a9,0x1a9,-1,218},
2749 {0x1ac,0x1ac,-1,1},
2750 {0x1ae,0x1ae,-1,218},
2751 {0x1af,0x1af,-1,1},
2752 {0x1b1,0x1b2,1,217},
2753 {0x1b3,0x1b5,2,1},
2754 {0x1b7,0x1b7,-1,219},
2755 {0x1b8,0x1bc,4,1},
2756 {0x1c4,0x1c4,-1,2},
2757 {0x1c5,0x1c5,-1,1},
2758 {0x1c7,0x1c7,-1,2},
2759 {0x1c8,0x1c8,-1,1},
2760 {0x1ca,0x1ca,-1,2},
2761 {0x1cb,0x1db,2,1},
2762 {0x1de,0x1ee,2,1},
2763 {0x1f1,0x1f1,-1,2},
2764 {0x1f2,0x1f4,2,1},
2765 {0x1f6,0x1f6,-1,-97},
2766 {0x1f7,0x1f7,-1,-56},
2767 {0x1f8,0x21e,2,1},
2768 {0x220,0x220,-1,-130},
2769 {0x222,0x232,2,1},
2770 {0x23a,0x23a,-1,10795},
2771 {0x23b,0x23b,-1,1},
2772 {0x23d,0x23d,-1,-163},
2773 {0x23e,0x23e,-1,10792},
2774 {0x241,0x241,-1,1},
2775 {0x243,0x243,-1,-195},
2776 {0x244,0x244,-1,69},
2777 {0x245,0x245,-1,71},
2778 {0x246,0x24e,2,1},
2779 {0x370,0x372,2,1},
2780 {0x376,0x376,-1,1},
2781 {0x386,0x386,-1,38},
2782 {0x388,0x38a,1,37},
2783 {0x38c,0x38c,-1,64},
2784 {0x38e,0x38f,1,63},
2785 {0x391,0x3a1,1,32},
2786 {0x3a3,0x3ab,1,32},
2787 {0x3cf,0x3cf,-1,8},
2788 {0x3d8,0x3ee,2,1},
2789 {0x3f4,0x3f4,-1,-60},
2790 {0x3f7,0x3f7,-1,1},
2791 {0x3f9,0x3f9,-1,-7},
2792 {0x3fa,0x3fa,-1,1},
2793 {0x3fd,0x3ff,1,-130},
2794 {0x400,0x40f,1,80},
2795 {0x410,0x42f,1,32},
2796 {0x460,0x480,2,1},
2797 {0x48a,0x4be,2,1},
2798 {0x4c0,0x4c0,-1,15},
2799 {0x4c1,0x4cd,2,1},
2800 {0x4d0,0x524,2,1},
2801 {0x531,0x556,1,48},
2802 {0x10a0,0x10c5,1,7264},
2803 {0x1e00,0x1e94,2,1},
2804 {0x1e9e,0x1e9e,-1,-7615},
2805 {0x1ea0,0x1efe,2,1},
2806 {0x1f08,0x1f0f,1,-8},
2807 {0x1f18,0x1f1d,1,-8},
2808 {0x1f28,0x1f2f,1,-8},
2809 {0x1f38,0x1f3f,1,-8},
2810 {0x1f48,0x1f4d,1,-8},
2811 {0x1f59,0x1f5f,2,-8},
2812 {0x1f68,0x1f6f,1,-8},
2813 {0x1f88,0x1f8f,1,-8},
2814 {0x1f98,0x1f9f,1,-8},
2815 {0x1fa8,0x1faf,1,-8},
2816 {0x1fb8,0x1fb9,1,-8},
2817 {0x1fba,0x1fbb,1,-74},
2818 {0x1fbc,0x1fbc,-1,-9},
2819 {0x1fc8,0x1fcb,1,-86},
2820 {0x1fcc,0x1fcc,-1,-9},
2821 {0x1fd8,0x1fd9,1,-8},
2822 {0x1fda,0x1fdb,1,-100},
2823 {0x1fe8,0x1fe9,1,-8},
2824 {0x1fea,0x1feb,1,-112},
2825 {0x1fec,0x1fec,-1,-7},
2826 {0x1ff8,0x1ff9,1,-128},
2827 {0x1ffa,0x1ffb,1,-126},
2828 {0x1ffc,0x1ffc,-1,-9},
2829 {0x2126,0x2126,-1,-7517},
2830 {0x212a,0x212a,-1,-8383},
2831 {0x212b,0x212b,-1,-8262},
2832 {0x2132,0x2132,-1,28},
2833 {0x2160,0x216f,1,16},
2834 {0x2183,0x2183,-1,1},
2835 {0x24b6,0x24cf,1,26},
2836 {0x2c00,0x2c2e,1,48},
2837 {0x2c60,0x2c60,-1,1},
2838 {0x2c62,0x2c62,-1,-10743},
2839 {0x2c63,0x2c63,-1,-3814},
2840 {0x2c64,0x2c64,-1,-10727},
2841 {0x2c67,0x2c6b,2,1},
2842 {0x2c6d,0x2c6d,-1,-10780},
2843 {0x2c6e,0x2c6e,-1,-10749},
2844 {0x2c6f,0x2c6f,-1,-10783},
2845 {0x2c70,0x2c70,-1,-10782},
2846 {0x2c72,0x2c75,3,1},
2847 {0x2c7e,0x2c7f,1,-10815},
2848 {0x2c80,0x2ce2,2,1},
2849 {0x2ceb,0x2ced,2,1},
2850 {0xa640,0xa65e,2,1},
2851 {0xa662,0xa66c,2,1},
2852 {0xa680,0xa696,2,1},
2853 {0xa722,0xa72e,2,1},
2854 {0xa732,0xa76e,2,1},
2855 {0xa779,0xa77b,2,1},
2856 {0xa77d,0xa77d,-1,-35332},
2857 {0xa77e,0xa786,2,1},
2858 {0xa78b,0xa78b,-1,1},
2859 {0xff21,0xff3a,1,32},
2860 {0x10400,0x10427,1,40}
2863 static convertStruct toUpper[] =
2865 {0x61,0x7a,1,-32},
2866 {0xb5,0xb5,-1,743},
2867 {0xe0,0xf6,1,-32},
2868 {0xf8,0xfe,1,-32},
2869 {0xff,0xff,-1,121},
2870 {0x101,0x12f,2,-1},
2871 {0x131,0x131,-1,-232},
2872 {0x133,0x137,2,-1},
2873 {0x13a,0x148,2,-1},
2874 {0x14b,0x177,2,-1},
2875 {0x17a,0x17e,2,-1},
2876 {0x17f,0x17f,-1,-300},
2877 {0x180,0x180,-1,195},
2878 {0x183,0x185,2,-1},
2879 {0x188,0x18c,4,-1},
2880 {0x192,0x192,-1,-1},
2881 {0x195,0x195,-1,97},
2882 {0x199,0x199,-1,-1},
2883 {0x19a,0x19a,-1,163},
2884 {0x19e,0x19e,-1,130},
2885 {0x1a1,0x1a5,2,-1},
2886 {0x1a8,0x1ad,5,-1},
2887 {0x1b0,0x1b4,4,-1},
2888 {0x1b6,0x1b9,3,-1},
2889 {0x1bd,0x1bd,-1,-1},
2890 {0x1bf,0x1bf,-1,56},
2891 {0x1c5,0x1c5,-1,-1},
2892 {0x1c6,0x1c6,-1,-2},
2893 {0x1c8,0x1c8,-1,-1},
2894 {0x1c9,0x1c9,-1,-2},
2895 {0x1cb,0x1cb,-1,-1},
2896 {0x1cc,0x1cc,-1,-2},
2897 {0x1ce,0x1dc,2,-1},
2898 {0x1dd,0x1dd,-1,-79},
2899 {0x1df,0x1ef,2,-1},
2900 {0x1f2,0x1f2,-1,-1},
2901 {0x1f3,0x1f3,-1,-2},
2902 {0x1f5,0x1f9,4,-1},
2903 {0x1fb,0x21f,2,-1},
2904 {0x223,0x233,2,-1},
2905 {0x23c,0x23c,-1,-1},
2906 {0x23f,0x240,1,10815},
2907 {0x242,0x247,5,-1},
2908 {0x249,0x24f,2,-1},
2909 {0x250,0x250,-1,10783},
2910 {0x251,0x251,-1,10780},
2911 {0x252,0x252,-1,10782},
2912 {0x253,0x253,-1,-210},
2913 {0x254,0x254,-1,-206},
2914 {0x256,0x257,1,-205},
2915 {0x259,0x259,-1,-202},
2916 {0x25b,0x25b,-1,-203},
2917 {0x260,0x260,-1,-205},
2918 {0x263,0x263,-1,-207},
2919 {0x268,0x268,-1,-209},
2920 {0x269,0x269,-1,-211},
2921 {0x26b,0x26b,-1,10743},
2922 {0x26f,0x26f,-1,-211},
2923 {0x271,0x271,-1,10749},
2924 {0x272,0x272,-1,-213},
2925 {0x275,0x275,-1,-214},
2926 {0x27d,0x27d,-1,10727},
2927 {0x280,0x283,3,-218},
2928 {0x288,0x288,-1,-218},
2929 {0x289,0x289,-1,-69},
2930 {0x28a,0x28b,1,-217},
2931 {0x28c,0x28c,-1,-71},
2932 {0x292,0x292,-1,-219},
2933 {0x345,0x345,-1,84},
2934 {0x371,0x373,2,-1},
2935 {0x377,0x377,-1,-1},
2936 {0x37b,0x37d,1,130},
2937 {0x3ac,0x3ac,-1,-38},
2938 {0x3ad,0x3af,1,-37},
2939 {0x3b1,0x3c1,1,-32},
2940 {0x3c2,0x3c2,-1,-31},
2941 {0x3c3,0x3cb,1,-32},
2942 {0x3cc,0x3cc,-1,-64},
2943 {0x3cd,0x3ce,1,-63},
2944 {0x3d0,0x3d0,-1,-62},
2945 {0x3d1,0x3d1,-1,-57},
2946 {0x3d5,0x3d5,-1,-47},
2947 {0x3d6,0x3d6,-1,-54},
2948 {0x3d7,0x3d7,-1,-8},
2949 {0x3d9,0x3ef,2,-1},
2950 {0x3f0,0x3f0,-1,-86},
2951 {0x3f1,0x3f1,-1,-80},
2952 {0x3f2,0x3f2,-1,7},
2953 {0x3f5,0x3f5,-1,-96},
2954 {0x3f8,0x3fb,3,-1},
2955 {0x430,0x44f,1,-32},
2956 {0x450,0x45f,1,-80},
2957 {0x461,0x481,2,-1},
2958 {0x48b,0x4bf,2,-1},
2959 {0x4c2,0x4ce,2,-1},
2960 {0x4cf,0x4cf,-1,-15},
2961 {0x4d1,0x525,2,-1},
2962 {0x561,0x586,1,-48},
2963 {0x1d79,0x1d79,-1,35332},
2964 {0x1d7d,0x1d7d,-1,3814},
2965 {0x1e01,0x1e95,2,-1},
2966 {0x1e9b,0x1e9b,-1,-59},
2967 {0x1ea1,0x1eff,2,-1},
2968 {0x1f00,0x1f07,1,8},
2969 {0x1f10,0x1f15,1,8},
2970 {0x1f20,0x1f27,1,8},
2971 {0x1f30,0x1f37,1,8},
2972 {0x1f40,0x1f45,1,8},
2973 {0x1f51,0x1f57,2,8},
2974 {0x1f60,0x1f67,1,8},
2975 {0x1f70,0x1f71,1,74},
2976 {0x1f72,0x1f75,1,86},
2977 {0x1f76,0x1f77,1,100},
2978 {0x1f78,0x1f79,1,128},
2979 {0x1f7a,0x1f7b,1,112},
2980 {0x1f7c,0x1f7d,1,126},
2981 {0x1f80,0x1f87,1,8},
2982 {0x1f90,0x1f97,1,8},
2983 {0x1fa0,0x1fa7,1,8},
2984 {0x1fb0,0x1fb1,1,8},
2985 {0x1fb3,0x1fb3,-1,9},
2986 {0x1fbe,0x1fbe,-1,-7205},
2987 {0x1fc3,0x1fc3,-1,9},
2988 {0x1fd0,0x1fd1,1,8},
2989 {0x1fe0,0x1fe1,1,8},
2990 {0x1fe5,0x1fe5,-1,7},
2991 {0x1ff3,0x1ff3,-1,9},
2992 {0x214e,0x214e,-1,-28},
2993 {0x2170,0x217f,1,-16},
2994 {0x2184,0x2184,-1,-1},
2995 {0x24d0,0x24e9,1,-26},
2996 {0x2c30,0x2c5e,1,-48},
2997 {0x2c61,0x2c61,-1,-1},
2998 {0x2c65,0x2c65,-1,-10795},
2999 {0x2c66,0x2c66,-1,-10792},
3000 {0x2c68,0x2c6c,2,-1},
3001 {0x2c73,0x2c76,3,-1},
3002 {0x2c81,0x2ce3,2,-1},
3003 {0x2cec,0x2cee,2,-1},
3004 {0x2d00,0x2d25,1,-7264},
3005 {0xa641,0xa65f,2,-1},
3006 {0xa663,0xa66d,2,-1},
3007 {0xa681,0xa697,2,-1},
3008 {0xa723,0xa72f,2,-1},
3009 {0xa733,0xa76f,2,-1},
3010 {0xa77a,0xa77c,2,-1},
3011 {0xa77f,0xa787,2,-1},
3012 {0xa78c,0xa78c,-1,-1},
3013 {0xff41,0xff5a,1,-32},
3014 {0x10428,0x1044f,1,-40}
3018 * Return the upper-case equivalent of "a", which is a UCS-4 character. Use
3019 * simple case folding.
3022 utf_toupper(a)
3023 int a;
3025 /* If 'casemap' contains "keepascii" use ASCII style toupper(). */
3026 if (a < 128 && (cmp_flags & CMP_KEEPASCII))
3027 return TOUPPER_ASC(a);
3029 #if defined(HAVE_TOWUPPER) && defined(__STDC_ISO_10646__)
3030 /* If towupper() is available and handles Unicode, use it. */
3031 if (!(cmp_flags & CMP_INTERNAL))
3032 return towupper(a);
3033 #endif
3035 /* For characters below 128 use locale sensitive toupper(). */
3036 if (a < 128)
3037 return TOUPPER_LOC(a);
3039 /* For any other characters use the above mapping table. */
3040 return utf_convert(a, toUpper, sizeof(toUpper));
3044 utf_islower(a)
3045 int a;
3047 return (utf_toupper(a) != a);
3051 * Return the lower-case equivalent of "a", which is a UCS-4 character. Use
3052 * simple case folding.
3055 utf_tolower(a)
3056 int a;
3058 /* If 'casemap' contains "keepascii" use ASCII style tolower(). */
3059 if (a < 128 && (cmp_flags & CMP_KEEPASCII))
3060 return TOLOWER_ASC(a);
3062 #if defined(HAVE_TOWLOWER) && defined(__STDC_ISO_10646__)
3063 /* If towlower() is available and handles Unicode, use it. */
3064 if (!(cmp_flags & CMP_INTERNAL))
3065 return towlower(a);
3066 #endif
3068 /* For characters below 128 use locale sensitive tolower(). */
3069 if (a < 128)
3070 return TOLOWER_LOC(a);
3072 /* For any other characters use the above mapping table. */
3073 return utf_convert(a, toLower, sizeof(toLower));
3077 utf_isupper(a)
3078 int a;
3080 return (utf_tolower(a) != a);
3084 * Version of strnicmp() that handles multi-byte characters.
3085 * Needed for Big5, Sjift-JIS and UTF-8 encoding. Other DBCS encodings can
3086 * probably use strnicmp(), because there are no ASCII characters in the
3087 * second byte.
3088 * Returns zero if s1 and s2 are equal (ignoring case), the difference between
3089 * two characters otherwise.
3092 mb_strnicmp(s1, s2, nn)
3093 char_u *s1, *s2;
3094 size_t nn;
3096 int i, j, l;
3097 int cdiff;
3098 int incomplete = FALSE;
3099 int n = (int)nn;
3101 for (i = 0; i < n; i += l)
3103 if (s1[i] == NUL && s2[i] == NUL) /* both strings end */
3104 return 0;
3105 if (enc_utf8)
3107 l = utf_byte2len(s1[i]);
3108 if (l > n - i)
3110 l = n - i; /* incomplete character */
3111 incomplete = TRUE;
3113 /* Check directly first, it's faster. */
3114 for (j = 0; j < l; ++j)
3116 if (s1[i + j] != s2[i + j])
3117 break;
3118 if (s1[i + j] == 0)
3119 /* Both stings have the same bytes but are incomplete or
3120 * have illegal bytes, accept them as equal. */
3121 l = j;
3123 if (j < l)
3125 /* If one of the two characters is incomplete return -1. */
3126 if (incomplete || i + utf_byte2len(s2[i]) > n)
3127 return -1;
3128 cdiff = utf_fold(utf_ptr2char(s1 + i))
3129 - utf_fold(utf_ptr2char(s2 + i));
3130 if (cdiff != 0)
3131 return cdiff;
3134 else
3136 l = (*mb_ptr2len)(s1 + i);
3137 if (l <= 1)
3139 /* Single byte: first check normally, then with ignore case. */
3140 if (s1[i] != s2[i])
3142 cdiff = MB_TOLOWER(s1[i]) - MB_TOLOWER(s2[i]);
3143 if (cdiff != 0)
3144 return cdiff;
3147 else
3149 /* For non-Unicode multi-byte don't ignore case. */
3150 if (l > n - i)
3151 l = n - i;
3152 cdiff = STRNCMP(s1 + i, s2 + i, l);
3153 if (cdiff != 0)
3154 return cdiff;
3158 return 0;
3162 * "g8": show bytes of the UTF-8 char under the cursor. Doesn't matter what
3163 * 'encoding' has been set to.
3165 void
3166 show_utf8()
3168 int len;
3169 int rlen = 0;
3170 char_u *line;
3171 int clen;
3172 int i;
3174 /* Get the byte length of the char under the cursor, including composing
3175 * characters. */
3176 line = ml_get_cursor();
3177 len = utfc_ptr2len(line);
3178 if (len == 0)
3180 MSG("NUL");
3181 return;
3184 clen = 0;
3185 for (i = 0; i < len; ++i)
3187 if (clen == 0)
3189 /* start of (composing) character, get its length */
3190 if (i > 0)
3192 STRCPY(IObuff + rlen, "+ ");
3193 rlen += 2;
3195 clen = utf_ptr2len(line + i);
3197 sprintf((char *)IObuff + rlen, "%02x ", line[i]);
3198 --clen;
3199 rlen += (int)STRLEN(IObuff + rlen);
3200 if (rlen > IOSIZE - 20)
3201 break;
3204 msg(IObuff);
3208 * mb_head_off() function pointer.
3209 * Return offset from "p" to the first byte of the character it points into.
3210 * If "p" points to the NUL at the end of the string return 0.
3211 * Returns 0 when already at the first byte of a character.
3214 latin_head_off(base, p)
3215 char_u *base UNUSED;
3216 char_u *p UNUSED;
3218 return 0;
3222 dbcs_head_off(base, p)
3223 char_u *base;
3224 char_u *p;
3226 char_u *q;
3228 /* It can't be a trailing byte when not using DBCS, at the start of the
3229 * string or the previous byte can't start a double-byte. */
3230 if (p <= base || MB_BYTE2LEN(p[-1]) == 1 || *p == NUL)
3231 return 0;
3233 /* This is slow: need to start at the base and go forward until the
3234 * byte we are looking for. Return 1 when we went past it, 0 otherwise. */
3235 q = base;
3236 while (q < p)
3237 q += dbcs_ptr2len(q);
3238 return (q == p) ? 0 : 1;
3242 * Special version of dbcs_head_off() that works for ScreenLines[], where
3243 * single-width DBCS_JPNU characters are stored separately.
3246 dbcs_screen_head_off(base, p)
3247 char_u *base;
3248 char_u *p;
3250 char_u *q;
3252 /* It can't be a trailing byte when not using DBCS, at the start of the
3253 * string or the previous byte can't start a double-byte.
3254 * For euc-jp an 0x8e byte in the previous cell always means we have a
3255 * lead byte in the current cell. */
3256 if (p <= base
3257 || (enc_dbcs == DBCS_JPNU && p[-1] == 0x8e)
3258 || MB_BYTE2LEN(p[-1]) == 1
3259 || *p == NUL)
3260 return 0;
3262 /* This is slow: need to start at the base and go forward until the
3263 * byte we are looking for. Return 1 when we went past it, 0 otherwise.
3264 * For DBCS_JPNU look out for 0x8e, which means the second byte is not
3265 * stored as the next byte. */
3266 q = base;
3267 while (q < p)
3269 if (enc_dbcs == DBCS_JPNU && *q == 0x8e)
3270 ++q;
3271 else
3272 q += dbcs_ptr2len(q);
3274 return (q == p) ? 0 : 1;
3278 utf_head_off(base, p)
3279 char_u *base;
3280 char_u *p;
3282 char_u *q;
3283 char_u *s;
3284 int c;
3285 int len;
3286 #ifdef FEAT_ARABIC
3287 char_u *j;
3288 #endif
3290 if (*p < 0x80) /* be quick for ASCII */
3291 return 0;
3293 /* Skip backwards over trailing bytes: 10xx.xxxx
3294 * Skip backwards again if on a composing char. */
3295 for (q = p; ; --q)
3297 /* Move s to the last byte of this char. */
3298 for (s = q; (s[1] & 0xc0) == 0x80; ++s)
3300 /* Move q to the first byte of this char. */
3301 while (q > base && (*q & 0xc0) == 0x80)
3302 --q;
3303 /* Check for illegal sequence. Do allow an illegal byte after where we
3304 * started. */
3305 len = utf8len_tab[*q];
3306 if (len != (int)(s - q + 1) && len != (int)(p - q + 1))
3307 return 0;
3309 if (q <= base)
3310 break;
3312 c = utf_ptr2char(q);
3313 if (utf_iscomposing(c))
3314 continue;
3316 #ifdef FEAT_ARABIC
3317 if (arabic_maycombine(c))
3319 /* Advance to get a sneak-peak at the next char */
3320 j = q;
3321 --j;
3322 /* Move j to the first byte of this char. */
3323 while (j > base && (*j & 0xc0) == 0x80)
3324 --j;
3325 if (arabic_combine(utf_ptr2char(j), c))
3326 continue;
3328 #endif
3329 break;
3332 return (int)(p - q);
3336 * Copy a character from "*fp" to "*tp" and advance the pointers.
3338 void
3339 mb_copy_char(fp, tp)
3340 char_u **fp;
3341 char_u **tp;
3343 int l = (*mb_ptr2len)(*fp);
3345 mch_memmove(*tp, *fp, (size_t)l);
3346 *tp += l;
3347 *fp += l;
3351 * Return the offset from "p" to the first byte of a character. When "p" is
3352 * at the start of a character 0 is returned, otherwise the offset to the next
3353 * character. Can start anywhere in a stream of bytes.
3356 mb_off_next(base, p)
3357 char_u *base;
3358 char_u *p;
3360 int i;
3361 int j;
3363 if (enc_utf8)
3365 if (*p < 0x80) /* be quick for ASCII */
3366 return 0;
3368 /* Find the next character that isn't 10xx.xxxx */
3369 for (i = 0; (p[i] & 0xc0) == 0x80; ++i)
3371 if (i > 0)
3373 /* Check for illegal sequence. */
3374 for (j = 0; p - j > base; ++j)
3375 if ((p[-j] & 0xc0) != 0x80)
3376 break;
3377 if (utf8len_tab[p[-j]] != i + j)
3378 return 0;
3380 return i;
3383 /* Only need to check if we're on a trail byte, it doesn't matter if we
3384 * want the offset to the next or current character. */
3385 return (*mb_head_off)(base, p);
3389 * Return the offset from "p" to the last byte of the character it points
3390 * into. Can start anywhere in a stream of bytes.
3393 mb_tail_off(base, p)
3394 char_u *base;
3395 char_u *p;
3397 int i;
3398 int j;
3400 if (*p == NUL)
3401 return 0;
3403 if (enc_utf8)
3405 /* Find the last character that is 10xx.xxxx */
3406 for (i = 0; (p[i + 1] & 0xc0) == 0x80; ++i)
3408 /* Check for illegal sequence. */
3409 for (j = 0; p - j > base; ++j)
3410 if ((p[-j] & 0xc0) != 0x80)
3411 break;
3412 if (utf8len_tab[p[-j]] != i + j + 1)
3413 return 0;
3414 return i;
3417 /* It can't be the first byte if a double-byte when not using DBCS, at the
3418 * end of the string or the byte can't start a double-byte. */
3419 if (enc_dbcs == 0 || p[1] == NUL || MB_BYTE2LEN(*p) == 1)
3420 return 0;
3422 /* Return 1 when on the lead byte, 0 when on the tail byte. */
3423 return 1 - dbcs_head_off(base, p);
3427 * Find the next illegal byte sequence.
3429 void
3430 utf_find_illegal()
3432 pos_T pos = curwin->w_cursor;
3433 char_u *p;
3434 int len;
3435 vimconv_T vimconv;
3436 char_u *tofree = NULL;
3438 vimconv.vc_type = CONV_NONE;
3439 if (enc_utf8 && (enc_canon_props(curbuf->b_p_fenc) & ENC_8BIT))
3441 /* 'encoding' is "utf-8" but we are editing a 8-bit encoded file,
3442 * possibly a utf-8 file with illegal bytes. Setup for conversion
3443 * from utf-8 to 'fileencoding'. */
3444 convert_setup(&vimconv, p_enc, curbuf->b_p_fenc);
3447 #ifdef FEAT_VIRTUALEDIT
3448 curwin->w_cursor.coladd = 0;
3449 #endif
3450 for (;;)
3452 p = ml_get_cursor();
3453 if (vimconv.vc_type != CONV_NONE)
3455 vim_free(tofree);
3456 tofree = string_convert(&vimconv, p, NULL);
3457 if (tofree == NULL)
3458 break;
3459 p = tofree;
3462 while (*p != NUL)
3464 /* Illegal means that there are not enough trail bytes (checked by
3465 * utf_ptr2len()) or too many of them (overlong sequence). */
3466 len = utf_ptr2len(p);
3467 if (*p >= 0x80 && (len == 1
3468 || utf_char2len(utf_ptr2char(p)) != len))
3470 if (vimconv.vc_type == CONV_NONE)
3471 curwin->w_cursor.col += (colnr_T)(p - ml_get_cursor());
3472 else
3474 int l;
3476 len = (int)(p - tofree);
3477 for (p = ml_get_cursor(); *p != NUL && len-- > 0; p += l)
3479 l = utf_ptr2len(p);
3480 curwin->w_cursor.col += l;
3483 goto theend;
3485 p += len;
3487 if (curwin->w_cursor.lnum == curbuf->b_ml.ml_line_count)
3488 break;
3489 ++curwin->w_cursor.lnum;
3490 curwin->w_cursor.col = 0;
3493 /* didn't find it: don't move and beep */
3494 curwin->w_cursor = pos;
3495 beep_flush();
3497 theend:
3498 vim_free(tofree);
3499 convert_setup(&vimconv, NULL, NULL);
3502 #if defined(HAVE_GTK2) || defined(PROTO)
3504 * Return TRUE if string "s" is a valid utf-8 string.
3505 * When "end" is NULL stop at the first NUL.
3506 * When "end" is positive stop there.
3509 utf_valid_string(s, end)
3510 char_u *s;
3511 char_u *end;
3513 int l;
3514 char_u *p = s;
3516 while (end == NULL ? *p != NUL : p < end)
3518 l = utf8len_tab_zero[*p];
3519 if (l == 0)
3520 return FALSE; /* invalid lead byte */
3521 if (end != NULL && p + l > end)
3522 return FALSE; /* incomplete byte sequence */
3523 ++p;
3524 while (--l > 0)
3525 if ((*p++ & 0xc0) != 0x80)
3526 return FALSE; /* invalid trail byte */
3528 return TRUE;
3530 #endif
3532 #if defined(FEAT_GUI) || defined(PROTO)
3534 * Special version of mb_tail_off() for use in ScreenLines[].
3537 dbcs_screen_tail_off(base, p)
3538 char_u *base;
3539 char_u *p;
3541 /* It can't be the first byte if a double-byte when not using DBCS, at the
3542 * end of the string or the byte can't start a double-byte.
3543 * For euc-jp an 0x8e byte always means we have a lead byte in the current
3544 * cell. */
3545 if (*p == NUL || p[1] == NUL
3546 || (enc_dbcs == DBCS_JPNU && *p == 0x8e)
3547 || MB_BYTE2LEN(*p) == 1)
3548 return 0;
3550 /* Return 1 when on the lead byte, 0 when on the tail byte. */
3551 return 1 - dbcs_screen_head_off(base, p);
3553 #endif
3556 * If the cursor moves on an trail byte, set the cursor on the lead byte.
3557 * Thus it moves left if necessary.
3558 * Return TRUE when the cursor was adjusted.
3560 void
3561 mb_adjust_cursor()
3563 mb_adjustpos(&curwin->w_cursor);
3567 * Adjust position "*lp" to point to the first byte of a multi-byte character.
3568 * If it points to a tail byte it's moved backwards to the head byte.
3570 void
3571 mb_adjustpos(lp)
3572 pos_T *lp;
3574 char_u *p;
3576 if (lp->col > 0
3577 #ifdef FEAT_VIRTUALEDIT
3578 || lp->coladd > 1
3579 #endif
3582 p = ml_get(lp->lnum);
3583 lp->col -= (*mb_head_off)(p, p + lp->col);
3584 #ifdef FEAT_VIRTUALEDIT
3585 /* Reset "coladd" when the cursor would be on the right half of a
3586 * double-wide character. */
3587 if (lp->coladd == 1
3588 && p[lp->col] != TAB
3589 && vim_isprintc((*mb_ptr2char)(p + lp->col))
3590 && ptr2cells(p + lp->col) > 1)
3591 lp->coladd = 0;
3592 #endif
3597 * Return a pointer to the character before "*p", if there is one.
3599 char_u *
3600 mb_prevptr(line, p)
3601 char_u *line; /* start of the string */
3602 char_u *p;
3604 if (p > line)
3605 mb_ptr_back(line, p);
3606 return p;
3610 * Return the character length of "str". Each multi-byte character (with
3611 * following composing characters) counts as one.
3614 mb_charlen(str)
3615 char_u *str;
3617 char_u *p = str;
3618 int count;
3620 if (p == NULL)
3621 return 0;
3623 for (count = 0; *p != NUL; count++)
3624 p += (*mb_ptr2len)(p);
3626 return count;
3629 #if defined(FEAT_SPELL) || defined(PROTO)
3631 * Like mb_charlen() but for a string with specified length.
3634 mb_charlen_len(str, len)
3635 char_u *str;
3636 int len;
3638 char_u *p = str;
3639 int count;
3641 for (count = 0; *p != NUL && p < str + len; count++)
3642 p += (*mb_ptr2len)(p);
3644 return count;
3646 #endif
3649 * Try to un-escape a multi-byte character.
3650 * Used for the "to" and "from" part of a mapping.
3651 * Return the un-escaped string if it is a multi-byte character, and advance
3652 * "pp" to just after the bytes that formed it.
3653 * Return NULL if no multi-byte char was found.
3655 char_u *
3656 mb_unescape(pp)
3657 char_u **pp;
3659 static char_u buf[MB_MAXBYTES + 1];
3660 int n, m = 0;
3661 char_u *str = *pp;
3663 /* Must translate K_SPECIAL KS_SPECIAL KE_FILLER to K_SPECIAL and CSI
3664 * KS_EXTRA KE_CSI to CSI. */
3665 for (n = 0; str[n] != NUL && m <= MB_MAXBYTES; ++n)
3667 if (str[n] == K_SPECIAL
3668 && str[n + 1] == KS_SPECIAL
3669 && str[n + 2] == KE_FILLER)
3671 buf[m++] = K_SPECIAL;
3672 n += 2;
3674 else if ((str[n] == K_SPECIAL
3675 # ifdef FEAT_GUI
3676 || str[n] == CSI
3677 # endif
3679 && str[n + 1] == KS_EXTRA
3680 && str[n + 2] == (int)KE_CSI)
3682 buf[m++] = CSI;
3683 n += 2;
3685 else if (str[n] == K_SPECIAL
3686 # ifdef FEAT_GUI
3687 || str[n] == CSI
3688 # endif
3690 break; /* a special key can't be a multibyte char */
3691 else
3692 buf[m++] = str[n];
3693 buf[m] = NUL;
3695 /* Return a multi-byte character if it's found. An illegal sequence
3696 * will result in a 1 here. */
3697 if ((*mb_ptr2len)(buf) > 1)
3699 *pp = str + n + 1;
3700 return buf;
3703 return NULL;
3707 * Return TRUE if the character at "row"/"col" on the screen is the left side
3708 * of a double-width character.
3709 * Caller must make sure "row" and "col" are not invalid!
3712 mb_lefthalve(row, col)
3713 int row;
3714 int col;
3716 #ifdef FEAT_HANGULIN
3717 if (composing_hangul)
3718 return TRUE;
3719 #endif
3720 return (*mb_off2cells)(LineOffset[row] + col,
3721 LineOffset[row] + screen_Columns) > 1;
3725 * Correct a position on the screen, if it's the right half of a double-wide
3726 * char move it to the left half. Returns the corrected column.
3729 mb_fix_col(col, row)
3730 int col;
3731 int row;
3733 col = check_col(col);
3734 row = check_row(row);
3735 if (has_mbyte && ScreenLines != NULL && col > 0
3736 && ((enc_dbcs
3737 && ScreenLines[LineOffset[row] + col] != NUL
3738 && dbcs_screen_head_off(ScreenLines + LineOffset[row],
3739 ScreenLines + LineOffset[row] + col))
3740 || (enc_utf8 && ScreenLines[LineOffset[row] + col] == 0)))
3741 return col - 1;
3742 return col;
3744 #endif
3746 #if defined(FEAT_MBYTE) || defined(FEAT_POSTSCRIPT) || defined(PROTO)
3747 static int enc_alias_search __ARGS((char_u *name));
3750 * Skip the Vim specific head of a 'encoding' name.
3752 char_u *
3753 enc_skip(p)
3754 char_u *p;
3756 if (STRNCMP(p, "2byte-", 6) == 0)
3757 return p + 6;
3758 if (STRNCMP(p, "8bit-", 5) == 0)
3759 return p + 5;
3760 return p;
3764 * Find the canonical name for encoding "enc".
3765 * When the name isn't recognized, returns "enc" itself, but with all lower
3766 * case characters and '_' replaced with '-'.
3767 * Returns an allocated string. NULL for out-of-memory.
3769 char_u *
3770 enc_canonize(enc)
3771 char_u *enc;
3773 char_u *r;
3774 char_u *p, *s;
3775 int i;
3777 # ifdef FEAT_MBYTE
3778 if (STRCMP(enc, "default") == 0)
3780 /* Use the default encoding as it's found by set_init_1(). */
3781 r = get_encoding_default();
3782 if (r == NULL)
3783 r = (char_u *)"latin1";
3784 return vim_strsave(r);
3786 # endif
3788 /* copy "enc" to allocated memory, with room for two '-' */
3789 r = alloc((unsigned)(STRLEN(enc) + 3));
3790 if (r != NULL)
3792 /* Make it all lower case and replace '_' with '-'. */
3793 p = r;
3794 for (s = enc; *s != NUL; ++s)
3796 if (*s == '_')
3797 *p++ = '-';
3798 else
3799 *p++ = TOLOWER_ASC(*s);
3801 *p = NUL;
3803 /* Skip "2byte-" and "8bit-". */
3804 p = enc_skip(r);
3806 /* Change "microsoft-cp" to "cp". Used in some spell files. */
3807 if (STRNCMP(p, "microsoft-cp", 12) == 0)
3808 STRMOVE(p, p + 10);
3810 /* "iso8859" -> "iso-8859" */
3811 if (STRNCMP(p, "iso8859", 7) == 0)
3813 STRMOVE(p + 4, p + 3);
3814 p[3] = '-';
3817 /* "iso-8859n" -> "iso-8859-n" */
3818 if (STRNCMP(p, "iso-8859", 8) == 0 && p[8] != '-')
3820 STRMOVE(p + 9, p + 8);
3821 p[8] = '-';
3824 /* "latin-N" -> "latinN" */
3825 if (STRNCMP(p, "latin-", 6) == 0)
3826 STRMOVE(p + 5, p + 6);
3828 if (enc_canon_search(p) >= 0)
3830 /* canonical name can be used unmodified */
3831 if (p != r)
3832 STRMOVE(r, p);
3834 else if ((i = enc_alias_search(p)) >= 0)
3836 /* alias recognized, get canonical name */
3837 vim_free(r);
3838 r = vim_strsave((char_u *)enc_canon_table[i].name);
3841 return r;
3845 * Search for an encoding alias of "name".
3846 * Returns -1 when not found.
3848 static int
3849 enc_alias_search(name)
3850 char_u *name;
3852 int i;
3854 for (i = 0; enc_alias_table[i].name != NULL; ++i)
3855 if (STRCMP(name, enc_alias_table[i].name) == 0)
3856 return enc_alias_table[i].canon;
3857 return -1;
3859 #endif
3861 #if defined(FEAT_MBYTE) || defined(PROTO)
3863 #ifdef HAVE_LANGINFO_H
3864 # include <langinfo.h>
3865 #endif
3868 * Get the canonicalized encoding of the current locale.
3869 * Returns an allocated string when successful, NULL when not.
3871 char_u *
3872 enc_locale()
3874 #ifndef WIN3264
3875 char *s;
3876 char *p;
3877 int i;
3878 #endif
3879 char buf[50];
3880 #ifdef WIN3264
3881 long acp = GetACP();
3883 if (acp == 1200)
3884 STRCPY(buf, "ucs-2le");
3885 else if (acp == 1252) /* cp1252 is used as latin1 */
3886 STRCPY(buf, "latin1");
3887 else
3888 sprintf(buf, "cp%ld", acp);
3889 #else
3890 # ifdef HAVE_NL_LANGINFO_CODESET
3891 if ((s = nl_langinfo(CODESET)) == NULL || *s == NUL)
3892 # endif
3893 # if defined(HAVE_LOCALE_H) || defined(X_LOCALE)
3894 if ((s = setlocale(LC_CTYPE, NULL)) == NULL || *s == NUL)
3895 # endif
3896 if ((s = getenv("LC_ALL")) == NULL || *s == NUL)
3897 if ((s = getenv("LC_CTYPE")) == NULL || *s == NUL)
3898 s = getenv("LANG");
3900 if (s == NULL || *s == NUL)
3901 return FAIL;
3903 /* The most generic locale format is:
3904 * language[_territory][.codeset][@modifier][+special][,[sponsor][_revision]]
3905 * If there is a '.' remove the part before it.
3906 * if there is something after the codeset, remove it.
3907 * Make the name lowercase and replace '_' with '-'.
3908 * Exception: "ja_JP.EUC" == "euc-jp", "zh_CN.EUC" = "euc-cn",
3909 * "ko_KR.EUC" == "euc-kr"
3911 if ((p = (char *)vim_strchr((char_u *)s, '.')) != NULL)
3913 if (p > s + 2 && STRNICMP(p + 1, "EUC", 3) == 0
3914 && !isalnum((int)p[4]) && p[4] != '-' && p[-3] == '_')
3916 /* copy "XY.EUC" to "euc-XY" to buf[10] */
3917 STRCPY(buf + 10, "euc-");
3918 buf[14] = p[-2];
3919 buf[15] = p[-1];
3920 buf[16] = 0;
3921 s = buf + 10;
3923 else
3924 s = p + 1;
3926 for (i = 0; s[i] != NUL && i < (int)sizeof(buf) - 1; ++i)
3928 if (s[i] == '_' || s[i] == '-')
3929 buf[i] = '-';
3930 else if (isalnum((int)s[i]))
3931 buf[i] = TOLOWER_ASC(s[i]);
3932 else
3933 break;
3935 buf[i] = NUL;
3936 #endif
3938 return enc_canonize((char_u *)buf);
3941 #if defined(WIN3264) || defined(PROTO)
3943 * Convert an encoding name to an MS-Windows codepage.
3944 * Returns zero if no codepage can be figured out.
3947 encname2codepage(name)
3948 char_u *name;
3950 int cp;
3951 char_u *p = name;
3952 int idx;
3954 if (STRNCMP(p, "8bit-", 5) == 0)
3955 p += 5;
3956 else if (STRNCMP(p_enc, "2byte-", 6) == 0)
3957 p += 6;
3959 if (p[0] == 'c' && p[1] == 'p')
3960 cp = atoi(p + 2);
3961 else if ((idx = enc_canon_search(p)) >= 0)
3962 cp = enc_canon_table[idx].codepage;
3963 else
3964 return 0;
3965 if (IsValidCodePage(cp))
3966 return cp;
3967 return 0;
3969 #endif
3971 # if defined(USE_ICONV) || defined(PROTO)
3973 static char_u *iconv_string __ARGS((vimconv_T *vcp, char_u *str, int slen, int *unconvlenp, int *resultlenp));
3976 * Call iconv_open() with a check if iconv() works properly (there are broken
3977 * versions).
3978 * Returns (void *)-1 if failed.
3979 * (should return iconv_t, but that causes problems with prototypes).
3981 void *
3982 my_iconv_open(to, from)
3983 char_u *to;
3984 char_u *from;
3986 iconv_t fd;
3987 #define ICONV_TESTLEN 400
3988 char_u tobuf[ICONV_TESTLEN];
3989 char *p;
3990 size_t tolen;
3991 static int iconv_ok = -1;
3993 if (iconv_ok == FALSE)
3994 return (void *)-1; /* detected a broken iconv() previously */
3996 #ifdef DYNAMIC_ICONV
3997 /* Check if the iconv.dll can be found. */
3998 if (!iconv_enabled(TRUE))
3999 return (void *)-1;
4000 #endif
4002 fd = iconv_open((char *)enc_skip(to), (char *)enc_skip(from));
4004 if (fd != (iconv_t)-1 && iconv_ok == -1)
4007 * Do a dummy iconv() call to check if it actually works. There is a
4008 * version of iconv() on Linux that is broken. We can't ignore it,
4009 * because it's wide-spread. The symptoms are that after outputting
4010 * the initial shift state the "to" pointer is NULL and conversion
4011 * stops for no apparent reason after about 8160 characters.
4013 p = (char *)tobuf;
4014 tolen = ICONV_TESTLEN;
4015 (void)iconv(fd, NULL, NULL, &p, &tolen);
4016 if (p == NULL)
4018 iconv_ok = FALSE;
4019 iconv_close(fd);
4020 fd = (iconv_t)-1;
4022 else
4023 iconv_ok = TRUE;
4026 return (void *)fd;
4030 * Convert the string "str[slen]" with iconv().
4031 * If "unconvlenp" is not NULL handle the string ending in an incomplete
4032 * sequence and set "*unconvlenp" to the length of it.
4033 * Returns the converted string in allocated memory. NULL for an error.
4034 * If resultlenp is not NULL, sets it to the result length in bytes.
4036 static char_u *
4037 iconv_string(vcp, str, slen, unconvlenp, resultlenp)
4038 vimconv_T *vcp;
4039 char_u *str;
4040 int slen;
4041 int *unconvlenp;
4042 int *resultlenp;
4044 const char *from;
4045 size_t fromlen;
4046 char *to;
4047 size_t tolen;
4048 size_t len = 0;
4049 size_t done = 0;
4050 char_u *result = NULL;
4051 char_u *p;
4052 int l;
4054 from = (char *)str;
4055 fromlen = slen;
4056 for (;;)
4058 if (len == 0 || ICONV_ERRNO == ICONV_E2BIG)
4060 /* Allocate enough room for most conversions. When re-allocating
4061 * increase the buffer size. */
4062 len = len + fromlen * 2 + 40;
4063 p = alloc((unsigned)len);
4064 if (p != NULL && done > 0)
4065 mch_memmove(p, result, done);
4066 vim_free(result);
4067 result = p;
4068 if (result == NULL) /* out of memory */
4069 break;
4072 to = (char *)result + done;
4073 tolen = len - done - 2;
4074 /* Avoid a warning for systems with a wrong iconv() prototype by
4075 * casting the second argument to void *. */
4076 if (iconv(vcp->vc_fd, (void *)&from, &fromlen, &to, &tolen)
4077 != (size_t)-1)
4079 /* Finished, append a NUL. */
4080 *to = NUL;
4081 break;
4084 /* Check both ICONV_EINVAL and EINVAL, because the dynamically loaded
4085 * iconv library may use one of them. */
4086 if (!vcp->vc_fail && unconvlenp != NULL
4087 && (ICONV_ERRNO == ICONV_EINVAL || ICONV_ERRNO == EINVAL))
4089 /* Handle an incomplete sequence at the end. */
4090 *to = NUL;
4091 *unconvlenp = (int)fromlen;
4092 break;
4095 /* Check both ICONV_EILSEQ and EILSEQ, because the dynamically loaded
4096 * iconv library may use one of them. */
4097 else if (!vcp->vc_fail
4098 && (ICONV_ERRNO == ICONV_EILSEQ || ICONV_ERRNO == EILSEQ
4099 || ICONV_ERRNO == ICONV_EINVAL || ICONV_ERRNO == EINVAL))
4101 /* Can't convert: insert a '?' and skip a character. This assumes
4102 * conversion from 'encoding' to something else. In other
4103 * situations we don't know what to skip anyway. */
4104 *to++ = '?';
4105 if ((*mb_ptr2cells)((char_u *)from) > 1)
4106 *to++ = '?';
4107 if (enc_utf8)
4108 l = utfc_ptr2len_len((char_u *)from, (int)fromlen);
4109 else
4111 l = (*mb_ptr2len)((char_u *)from);
4112 if (l > (int)fromlen)
4113 l = (int)fromlen;
4115 from += l;
4116 fromlen -= l;
4118 else if (ICONV_ERRNO != ICONV_E2BIG)
4120 /* conversion failed */
4121 vim_free(result);
4122 result = NULL;
4123 break;
4125 /* Not enough room or skipping illegal sequence. */
4126 done = to - (char *)result;
4129 if (resultlenp != NULL)
4130 *resultlenp = (int)(to - (char *)result);
4131 return result;
4134 # if defined(DYNAMIC_ICONV) || defined(PROTO)
4136 * Dynamically load the "iconv.dll" on Win32.
4139 #ifndef DYNAMIC_ICONV /* just generating prototypes */
4140 # define HINSTANCE int
4141 #endif
4142 static HINSTANCE hIconvDLL = 0;
4143 static HINSTANCE hMsvcrtDLL = 0;
4145 # ifndef DYNAMIC_ICONV_DLL
4146 # define DYNAMIC_ICONV_DLL "iconv.dll"
4147 # define DYNAMIC_ICONV_DLL_ALT "libiconv.dll"
4148 # endif
4149 # ifndef DYNAMIC_MSVCRT_DLL
4150 # define DYNAMIC_MSVCRT_DLL "msvcrt.dll"
4151 # endif
4154 * Try opening the iconv.dll and return TRUE if iconv() can be used.
4157 iconv_enabled(verbose)
4158 int verbose;
4160 if (hIconvDLL != 0 && hMsvcrtDLL != 0)
4161 return TRUE;
4162 hIconvDLL = LoadLibrary(DYNAMIC_ICONV_DLL);
4163 if (hIconvDLL == 0) /* sometimes it's called libiconv.dll */
4164 hIconvDLL = LoadLibrary(DYNAMIC_ICONV_DLL_ALT);
4165 if (hIconvDLL != 0)
4166 hMsvcrtDLL = LoadLibrary(DYNAMIC_MSVCRT_DLL);
4167 if (hIconvDLL == 0 || hMsvcrtDLL == 0)
4169 /* Only give the message when 'verbose' is set, otherwise it might be
4170 * done whenever a conversion is attempted. */
4171 if (verbose && p_verbose > 0)
4173 verbose_enter();
4174 EMSG2(_(e_loadlib),
4175 hIconvDLL == 0 ? DYNAMIC_ICONV_DLL : DYNAMIC_MSVCRT_DLL);
4176 verbose_leave();
4178 iconv_end();
4179 return FALSE;
4182 iconv = (void *)GetProcAddress(hIconvDLL, "libiconv");
4183 iconv_open = (void *)GetProcAddress(hIconvDLL, "libiconv_open");
4184 iconv_close = (void *)GetProcAddress(hIconvDLL, "libiconv_close");
4185 iconvctl = (void *)GetProcAddress(hIconvDLL, "libiconvctl");
4186 iconv_errno = (void *)GetProcAddress(hMsvcrtDLL, "_errno");
4187 if (iconv == NULL || iconv_open == NULL || iconv_close == NULL
4188 || iconvctl == NULL || iconv_errno == NULL)
4190 iconv_end();
4191 if (verbose && p_verbose > 0)
4193 verbose_enter();
4194 EMSG2(_(e_loadfunc), "for libiconv");
4195 verbose_leave();
4197 return FALSE;
4199 return TRUE;
4202 void
4203 iconv_end()
4205 /* Don't use iconv() when inputting or outputting characters. */
4206 if (input_conv.vc_type == CONV_ICONV)
4207 convert_setup(&input_conv, NULL, NULL);
4208 if (output_conv.vc_type == CONV_ICONV)
4209 convert_setup(&output_conv, NULL, NULL);
4211 if (hIconvDLL != 0)
4212 FreeLibrary(hIconvDLL);
4213 if (hMsvcrtDLL != 0)
4214 FreeLibrary(hMsvcrtDLL);
4215 hIconvDLL = 0;
4216 hMsvcrtDLL = 0;
4218 # endif /* DYNAMIC_ICONV */
4219 # endif /* USE_ICONV */
4221 #endif /* FEAT_MBYTE */
4223 #if defined(FEAT_XIM) || defined(PROTO)
4225 # ifdef FEAT_GUI_GTK
4226 static int xim_has_preediting INIT(= FALSE); /* IM current status */
4229 * Set preedit_start_col to the current cursor position.
4231 static void
4232 init_preedit_start_col(void)
4234 if (State & CMDLINE)
4235 preedit_start_col = cmdline_getvcol_cursor();
4236 else if (curwin != NULL)
4237 getvcol(curwin, &curwin->w_cursor, &preedit_start_col, NULL, NULL);
4238 /* Prevent that preediting marks the buffer as changed. */
4239 xim_changed_while_preediting = curbuf->b_changed;
4241 # endif
4243 # if defined(HAVE_GTK2) && !defined(PROTO)
4245 static int im_is_active = FALSE; /* IM is enabled for current mode */
4246 static int preedit_is_active = FALSE;
4247 static int im_preedit_cursor = 0; /* cursor offset in characters */
4248 static int im_preedit_trailing = 0; /* number of characters after cursor */
4250 static unsigned long im_commit_handler_id = 0;
4251 static unsigned int im_activatekey_keyval = GDK_VoidSymbol;
4252 static unsigned int im_activatekey_state = 0;
4254 void
4255 im_set_active(int active)
4257 int was_active;
4259 #ifdef FEAT_UIMFEP
4260 if (!gui.in_use)
4262 uimfep_set_active(active);
4263 return;
4265 #endif
4267 was_active = !!im_is_active;
4268 im_is_active = (active && !p_imdisable);
4270 if (im_is_active != was_active)
4271 xim_reset();
4274 void
4275 xim_set_focus(int focus)
4277 if (xic != NULL)
4279 if (focus)
4280 gtk_im_context_focus_in(xic);
4281 else
4282 gtk_im_context_focus_out(xic);
4286 void
4287 im_set_position(int row, int col)
4289 if (xic != NULL)
4291 GdkRectangle area;
4293 area.x = FILL_X(col);
4294 area.y = FILL_Y(row);
4295 area.width = gui.char_width * (mb_lefthalve(row, col) ? 2 : 1);
4296 area.height = gui.char_height;
4298 gtk_im_context_set_cursor_location(xic, &area);
4302 # if 0 || defined(PROTO) /* apparently only used in gui_x11.c */
4303 void
4304 xim_set_preedit(void)
4306 im_set_position(gui.row, gui.col);
4308 # endif
4310 static void
4311 im_add_to_input(char_u *str, int len)
4313 /* Convert from 'termencoding' (always "utf-8") to 'encoding' */
4314 if (input_conv.vc_type != CONV_NONE)
4316 str = string_convert(&input_conv, str, &len);
4317 g_return_if_fail(str != NULL);
4320 add_to_input_buf_csi(str, len);
4322 if (input_conv.vc_type != CONV_NONE)
4323 vim_free(str);
4325 if (p_mh) /* blank out the pointer if necessary */
4326 gui_mch_mousehide(TRUE);
4329 static void
4330 im_delete_preedit(void)
4332 char_u bskey[] = {CSI, 'k', 'b'};
4333 char_u delkey[] = {CSI, 'k', 'D'};
4335 if (State & NORMAL)
4337 im_preedit_cursor = 0;
4338 return;
4340 for (; im_preedit_cursor > 0; --im_preedit_cursor)
4341 add_to_input_buf(bskey, (int)sizeof(bskey));
4343 for (; im_preedit_trailing > 0; --im_preedit_trailing)
4344 add_to_input_buf(delkey, (int)sizeof(delkey));
4348 * Move the cursor left by "num_move_back" characters.
4349 * Note that ins_left() checks im_is_preediting() to avoid breaking undo for
4350 * these K_LEFT keys.
4352 static void
4353 im_correct_cursor(int num_move_back)
4355 char_u backkey[] = {CSI, 'k', 'l'};
4357 if (State & NORMAL)
4358 return;
4359 # ifdef FEAT_RIGHTLEFT
4360 if ((State & CMDLINE) == 0 && curwin != NULL && curwin->w_p_rl)
4361 backkey[2] = 'r';
4362 # endif
4363 for (; num_move_back > 0; --num_move_back)
4364 add_to_input_buf(backkey, (int)sizeof(backkey));
4367 static int xim_expected_char = NUL;
4368 static int xim_ignored_char = FALSE;
4371 * Update the mode and cursor while in an IM callback.
4373 static void
4374 im_show_info(void)
4376 int old_vgetc_busy;
4378 old_vgetc_busy = vgetc_busy;
4379 vgetc_busy = TRUE;
4380 showmode();
4381 vgetc_busy = old_vgetc_busy;
4382 setcursor();
4383 out_flush();
4387 * Callback invoked when the user finished preediting.
4388 * Put the final string into the input buffer.
4390 static void
4391 im_commit_cb(GtkIMContext *context UNUSED,
4392 const gchar *str,
4393 gpointer data UNUSED)
4395 int slen = (int)STRLEN(str);
4396 int add_to_input = TRUE;
4397 int clen;
4398 int len = slen;
4399 int commit_with_preedit = TRUE;
4400 char_u *im_str, *p;
4402 #ifdef XIM_DEBUG
4403 xim_log("im_commit_cb(): %s\n", str);
4404 #endif
4406 /* The imhangul module doesn't reset the preedit string before
4407 * committing. Call im_delete_preedit() to work around that. */
4408 im_delete_preedit();
4410 /* Indicate that preediting has finished. */
4411 if (preedit_start_col == MAXCOL)
4413 init_preedit_start_col();
4414 commit_with_preedit = FALSE;
4417 /* The thing which setting "preedit_start_col" to MAXCOL means that
4418 * "preedit_start_col" will be set forcely when calling
4419 * preedit_changed_cb() next time.
4420 * "preedit_start_col" should not reset with MAXCOL on this part. Vim
4421 * is simulating the preediting by using add_to_input_str(). when
4422 * preedit begin immediately before committed, the typebuf is not
4423 * flushed to screen, then it can't get correct "preedit_start_col".
4424 * Thus, it should calculate the cells by adding cells of the committed
4425 * string. */
4426 if (input_conv.vc_type != CONV_NONE)
4428 im_str = string_convert(&input_conv, (char_u *)str, &len);
4429 g_return_if_fail(im_str != NULL);
4431 else
4432 im_str = (char_u *)str;
4433 clen = 0;
4434 for (p = im_str; p < im_str + len; p += (*mb_ptr2len)(p))
4435 clen += (*mb_ptr2cells)(p);
4436 if (input_conv.vc_type != CONV_NONE)
4437 vim_free(im_str);
4438 preedit_start_col += clen;
4440 /* Is this a single character that matches a keypad key that's just
4441 * been pressed? If so, we don't want it to be entered as such - let
4442 * us carry on processing the raw keycode so that it may be used in
4443 * mappings as <kSomething>. */
4444 if (xim_expected_char != NUL)
4446 /* We're currently processing a keypad or other special key */
4447 if (slen == 1 && str[0] == xim_expected_char)
4449 /* It's a match - don't do it here */
4450 xim_ignored_char = TRUE;
4451 add_to_input = FALSE;
4453 else
4455 /* Not a match */
4456 xim_ignored_char = FALSE;
4460 if (add_to_input)
4461 im_add_to_input((char_u *)str, slen);
4463 /* Inserting chars while "im_is_active" is set does not cause a change of
4464 * buffer. When the chars are committed the buffer must be marked as
4465 * changed. */
4466 if (!commit_with_preedit)
4467 preedit_start_col = MAXCOL;
4469 /* This flag is used in changed() at next call. */
4470 xim_changed_while_preediting = TRUE;
4472 if (gtk_main_level() > 0)
4473 gtk_main_quit();
4477 * Callback invoked after start to the preedit.
4479 static void
4480 im_preedit_start_cb(GtkIMContext *context UNUSED, gpointer data UNUSED)
4482 #ifdef XIM_DEBUG
4483 xim_log("im_preedit_start_cb()\n");
4484 #endif
4486 im_is_active = TRUE;
4487 preedit_is_active = TRUE;
4488 gui_update_cursor(TRUE, FALSE);
4489 im_show_info();
4493 * Callback invoked after end to the preedit.
4495 static void
4496 im_preedit_end_cb(GtkIMContext *context UNUSED, gpointer data UNUSED)
4498 #ifdef XIM_DEBUG
4499 xim_log("im_preedit_end_cb()\n");
4500 #endif
4501 im_delete_preedit();
4503 /* Indicate that preediting has finished */
4504 preedit_start_col = MAXCOL;
4505 xim_has_preediting = FALSE;
4507 #if 0
4508 /* Removal of this line suggested by Takuhiro Nishioka. Fixes that IM was
4509 * switched off unintentionally. We now use preedit_is_active (added by
4510 * SungHyun Nam). */
4511 im_is_active = FALSE;
4512 #endif
4513 preedit_is_active = FALSE;
4514 gui_update_cursor(TRUE, FALSE);
4515 im_show_info();
4519 * Callback invoked after changes to the preedit string. If the preedit
4520 * string was empty before, remember the preedit start column so we know
4521 * where to apply feedback attributes. Delete the previous preedit string
4522 * if there was one, save the new preedit cursor offset, and put the new
4523 * string into the input buffer.
4525 * TODO: The pragmatic "put into input buffer" approach used here has
4526 * several fundamental problems:
4528 * - The characters in the preedit string are subject to remapping.
4529 * That's broken, only the finally committed string should be remapped.
4531 * - There is a race condition involved: The retrieved value for the
4532 * current cursor position will be wrong if any unprocessed characters
4533 * are still queued in the input buffer.
4535 * - Due to the lack of synchronization between the file buffer in memory
4536 * and any typed characters, it's practically impossible to implement the
4537 * "retrieve_surrounding" and "delete_surrounding" signals reliably. IM
4538 * modules for languages such as Thai are likely to rely on this feature
4539 * for proper operation.
4541 * Conclusions: I think support for preediting needs to be moved to the
4542 * core parts of Vim. Ideally, until it has been committed, the preediting
4543 * string should only be displayed and not affect the buffer content at all.
4544 * The question how to deal with the synchronization issue still remains.
4545 * Circumventing the input buffer is probably not desirable. Anyway, I think
4546 * implementing "retrieve_surrounding" is the only hard problem.
4548 * One way to solve all of this in a clean manner would be to queue all key
4549 * press/release events "as is" in the input buffer, and apply the IM filtering
4550 * at the receiving end of the queue. This, however, would have a rather large
4551 * impact on the code base. If there is an easy way to force processing of all
4552 * remaining input from within the "retrieve_surrounding" signal handler, this
4553 * might not be necessary. Gotta ask on vim-dev for opinions.
4555 static void
4556 im_preedit_changed_cb(GtkIMContext *context, gpointer data UNUSED)
4558 char *preedit_string = NULL;
4559 int cursor_index = 0;
4560 int num_move_back = 0;
4561 char_u *str;
4562 char_u *p;
4563 int i;
4565 gtk_im_context_get_preedit_string(context,
4566 &preedit_string, NULL,
4567 &cursor_index);
4569 #ifdef XIM_DEBUG
4570 xim_log("im_preedit_changed_cb(): %s\n", preedit_string);
4571 #endif
4573 g_return_if_fail(preedit_string != NULL); /* just in case */
4575 /* If preedit_start_col is MAXCOL set it to the current cursor position. */
4576 if (preedit_start_col == MAXCOL && preedit_string[0] != '\0')
4578 xim_has_preediting = TRUE;
4580 /* Urgh, this breaks if the input buffer isn't empty now */
4581 init_preedit_start_col();
4583 else if (cursor_index == 0 && preedit_string[0] == '\0')
4585 xim_has_preediting = FALSE;
4587 /* If at the start position (after typing backspace)
4588 * preedit_start_col must be reset. */
4589 preedit_start_col = MAXCOL;
4592 im_delete_preedit();
4595 * Compute the end of the preediting area: "preedit_end_col".
4596 * According to the documentation of gtk_im_context_get_preedit_string(),
4597 * the cursor_pos output argument returns the offset in bytes. This is
4598 * unfortunately not true -- real life shows the offset is in characters,
4599 * and the GTK+ source code agrees with me. Will file a bug later.
4601 if (preedit_start_col != MAXCOL)
4602 preedit_end_col = preedit_start_col;
4603 str = (char_u *)preedit_string;
4604 for (p = str, i = 0; *p != NUL; p += utf_byte2len(*p), ++i)
4606 int is_composing;
4608 is_composing = ((*p & 0x80) != 0 && utf_iscomposing(utf_ptr2char(p)));
4610 * These offsets are used as counters when generating <BS> and <Del>
4611 * to delete the preedit string. So don't count composing characters
4612 * unless 'delcombine' is enabled.
4614 if (!is_composing || p_deco)
4616 if (i < cursor_index)
4617 ++im_preedit_cursor;
4618 else
4619 ++im_preedit_trailing;
4621 if (!is_composing && i >= cursor_index)
4623 /* This is essentially the same as im_preedit_trailing, except
4624 * composing characters are not counted even if p_deco is set. */
4625 ++num_move_back;
4627 if (preedit_start_col != MAXCOL)
4628 preedit_end_col += utf_ptr2cells(p);
4631 if (p > str)
4633 im_add_to_input(str, (int)(p - str));
4634 im_correct_cursor(num_move_back);
4637 g_free(preedit_string);
4639 if (gtk_main_level() > 0)
4640 gtk_main_quit();
4644 * Translate the Pango attributes at iter to Vim highlighting attributes.
4645 * Ignore attributes not supported by Vim highlighting. This shouldn't have
4646 * too much impact -- right now we handle even more attributes than necessary
4647 * for the IM modules I tested with.
4649 static int
4650 translate_pango_attributes(PangoAttrIterator *iter)
4652 PangoAttribute *attr;
4653 int char_attr = HL_NORMAL;
4655 attr = pango_attr_iterator_get(iter, PANGO_ATTR_UNDERLINE);
4656 if (attr != NULL && ((PangoAttrInt *)attr)->value
4657 != (int)PANGO_UNDERLINE_NONE)
4658 char_attr |= HL_UNDERLINE;
4660 attr = pango_attr_iterator_get(iter, PANGO_ATTR_WEIGHT);
4661 if (attr != NULL && ((PangoAttrInt *)attr)->value >= (int)PANGO_WEIGHT_BOLD)
4662 char_attr |= HL_BOLD;
4664 attr = pango_attr_iterator_get(iter, PANGO_ATTR_STYLE);
4665 if (attr != NULL && ((PangoAttrInt *)attr)->value
4666 != (int)PANGO_STYLE_NORMAL)
4667 char_attr |= HL_ITALIC;
4669 attr = pango_attr_iterator_get(iter, PANGO_ATTR_BACKGROUND);
4670 if (attr != NULL)
4672 const PangoColor *color = &((PangoAttrColor *)attr)->color;
4674 /* Assume inverse if black background is requested */
4675 if ((color->red | color->green | color->blue) == 0)
4676 char_attr |= HL_INVERSE;
4679 return char_attr;
4683 * Retrieve the highlighting attributes at column col in the preedit string.
4684 * Return -1 if not in preediting mode or if col is out of range.
4687 im_get_feedback_attr(int col)
4689 char *preedit_string = NULL;
4690 PangoAttrList *attr_list = NULL;
4691 int char_attr = -1;
4693 if (xic == NULL)
4694 return char_attr;
4696 gtk_im_context_get_preedit_string(xic, &preedit_string, &attr_list, NULL);
4698 if (preedit_string != NULL && attr_list != NULL)
4700 int idx;
4702 /* Get the byte index as used by PangoAttrIterator */
4703 for (idx = 0; col > 0 && preedit_string[idx] != '\0'; --col)
4704 idx += utfc_ptr2len((char_u *)preedit_string + idx);
4706 if (preedit_string[idx] != '\0')
4708 PangoAttrIterator *iter;
4709 int start, end;
4711 char_attr = HL_NORMAL;
4712 iter = pango_attr_list_get_iterator(attr_list);
4714 /* Extract all relevant attributes from the list. */
4717 pango_attr_iterator_range(iter, &start, &end);
4719 if (idx >= start && idx < end)
4720 char_attr |= translate_pango_attributes(iter);
4722 while (pango_attr_iterator_next(iter));
4724 pango_attr_iterator_destroy(iter);
4728 if (attr_list != NULL)
4729 pango_attr_list_unref(attr_list);
4730 g_free(preedit_string);
4732 return char_attr;
4735 void
4736 xim_init(void)
4738 #ifdef XIM_DEBUG
4739 xim_log("xim_init()\n");
4740 #endif
4742 g_return_if_fail(gui.drawarea != NULL);
4743 g_return_if_fail(gui.drawarea->window != NULL);
4745 xic = gtk_im_multicontext_new();
4746 g_object_ref(xic);
4748 im_commit_handler_id = g_signal_connect(G_OBJECT(xic), "commit",
4749 G_CALLBACK(&im_commit_cb), NULL);
4750 g_signal_connect(G_OBJECT(xic), "preedit_changed",
4751 G_CALLBACK(&im_preedit_changed_cb), NULL);
4752 g_signal_connect(G_OBJECT(xic), "preedit_start",
4753 G_CALLBACK(&im_preedit_start_cb), NULL);
4754 g_signal_connect(G_OBJECT(xic), "preedit_end",
4755 G_CALLBACK(&im_preedit_end_cb), NULL);
4757 gtk_im_context_set_client_window(xic, gui.drawarea->window);
4760 void
4761 im_shutdown(void)
4763 #ifdef XIM_DEBUG
4764 xim_log("im_shutdown()\n");
4765 #endif
4767 if (xic != NULL)
4769 gtk_im_context_focus_out(xic);
4770 g_object_unref(xic);
4771 xic = NULL;
4773 im_is_active = FALSE;
4774 im_commit_handler_id = 0;
4775 preedit_start_col = MAXCOL;
4776 xim_has_preediting = FALSE;
4780 * Convert the string argument to keyval and state for GdkEventKey.
4781 * If str is valid return TRUE, otherwise FALSE.
4783 * See 'imactivatekey' for documentation of the format.
4785 static int
4786 im_string_to_keyval(const char *str, unsigned int *keyval, unsigned int *state)
4788 const char *mods_end;
4789 unsigned tmp_keyval;
4790 unsigned tmp_state = 0;
4792 mods_end = strrchr(str, '-');
4793 mods_end = (mods_end != NULL) ? mods_end + 1 : str;
4795 /* Parse modifier keys */
4796 while (str < mods_end)
4797 switch (*str++)
4799 case '-': break;
4800 case 'S': case 's': tmp_state |= (unsigned)GDK_SHIFT_MASK; break;
4801 case 'L': case 'l': tmp_state |= (unsigned)GDK_LOCK_MASK; break;
4802 case 'C': case 'c': tmp_state |= (unsigned)GDK_CONTROL_MASK;break;
4803 case '1': tmp_state |= (unsigned)GDK_MOD1_MASK; break;
4804 case '2': tmp_state |= (unsigned)GDK_MOD2_MASK; break;
4805 case '3': tmp_state |= (unsigned)GDK_MOD3_MASK; break;
4806 case '4': tmp_state |= (unsigned)GDK_MOD4_MASK; break;
4807 case '5': tmp_state |= (unsigned)GDK_MOD5_MASK; break;
4808 default:
4809 return FALSE;
4812 tmp_keyval = gdk_keyval_from_name(str);
4814 if (tmp_keyval == 0 || tmp_keyval == GDK_VoidSymbol)
4815 return FALSE;
4817 if (keyval != NULL)
4818 *keyval = tmp_keyval;
4819 if (state != NULL)
4820 *state = tmp_state;
4822 return TRUE;
4826 * Return TRUE if p_imak is valid, otherwise FALSE. As a special case, an
4827 * empty string is also regarded as valid.
4829 * Note: The numerical key value of p_imak is cached if it was valid; thus
4830 * boldly assuming im_xim_isvalid_imactivate() will always be called whenever
4831 * 'imak' changes. This is currently the case but not obvious -- should
4832 * probably rename the function for clarity.
4835 im_xim_isvalid_imactivate(void)
4837 if (p_imak[0] == NUL)
4839 im_activatekey_keyval = GDK_VoidSymbol;
4840 im_activatekey_state = 0;
4841 return TRUE;
4844 return im_string_to_keyval((const char *)p_imak,
4845 &im_activatekey_keyval,
4846 &im_activatekey_state);
4849 static void
4850 im_synthesize_keypress(unsigned int keyval, unsigned int state)
4852 GdkEventKey *event;
4854 # ifdef HAVE_GTK_MULTIHEAD
4855 event = (GdkEventKey *)gdk_event_new(GDK_KEY_PRESS);
4856 g_object_ref(gui.drawarea->window); /* unreffed by gdk_event_free() */
4857 # else
4858 event = (GdkEventKey *)g_malloc0((gulong)sizeof(GdkEvent));
4859 event->type = GDK_KEY_PRESS;
4860 # endif
4861 event->window = gui.drawarea->window;
4862 event->send_event = TRUE;
4863 event->time = GDK_CURRENT_TIME;
4864 event->state = state;
4865 event->keyval = keyval;
4866 event->hardware_keycode = /* needed for XIM */
4867 XKeysymToKeycode(GDK_WINDOW_XDISPLAY(event->window), (KeySym)keyval);
4868 event->length = 0;
4869 event->string = NULL;
4871 gtk_im_context_filter_keypress(xic, event);
4873 /* For consistency, also send the corresponding release event. */
4874 event->type = GDK_KEY_RELEASE;
4875 event->send_event = FALSE;
4876 gtk_im_context_filter_keypress(xic, event);
4878 # ifdef HAVE_GTK_MULTIHEAD
4879 gdk_event_free((GdkEvent *)event);
4880 # else
4881 g_free(event);
4882 # endif
4885 void
4886 xim_reset(void)
4888 if (xic != NULL)
4891 * The third-party imhangul module (and maybe others too) ignores
4892 * gtk_im_context_reset() or at least doesn't reset the active state.
4893 * Thus sending imactivatekey would turn it off if it was on before,
4894 * which is clearly not what we want. Fortunately we can work around
4895 * that for imhangul by sending GDK_Escape, but I don't know if it
4896 * works with all IM modules that support an activation key :/
4898 * An alternative approach would be to destroy the IM context and
4899 * recreate it. But that means loading/unloading the IM module on
4900 * every mode switch, which causes a quite noticable delay even on
4901 * my rather fast box...
4903 * Moreover, there are some XIM which cannot respond to
4904 * im_synthesize_keypress(). we hope that they reset by
4905 * xim_shutdown().
4907 if (im_activatekey_keyval != GDK_VoidSymbol && im_is_active)
4908 im_synthesize_keypress(GDK_Escape, 0U);
4910 gtk_im_context_reset(xic);
4913 * HACK for Ami: This sequence of function calls makes Ami handle
4914 * the IM reset graciously, without breaking loads of other stuff.
4915 * It seems to force English mode as well, which is exactly what we
4916 * want because it makes the Ami status display work reliably.
4918 gtk_im_context_set_use_preedit(xic, FALSE);
4920 if (p_imdisable)
4921 im_shutdown();
4922 else
4924 gtk_im_context_set_use_preedit(xic, TRUE);
4925 xim_set_focus(gui.in_focus);
4927 if (im_activatekey_keyval != GDK_VoidSymbol)
4929 if (im_is_active)
4931 g_signal_handler_block(xic, im_commit_handler_id);
4932 im_synthesize_keypress(im_activatekey_keyval,
4933 im_activatekey_state);
4934 g_signal_handler_unblock(xic, im_commit_handler_id);
4937 else
4939 im_shutdown();
4940 xim_init();
4941 xim_set_focus(gui.in_focus);
4946 preedit_start_col = MAXCOL;
4947 xim_has_preediting = FALSE;
4951 xim_queue_key_press_event(GdkEventKey *event, int down)
4953 if (down)
4956 * Workaround GTK2 XIM 'feature' that always converts keypad keys to
4957 * chars., even when not part of an IM sequence (ref. feature of
4958 * gdk/gdkkeyuni.c).
4959 * Flag any keypad keys that might represent a single char.
4960 * If this (on its own - i.e., not part of an IM sequence) is
4961 * committed while we're processing one of these keys, we can ignore
4962 * that commit and go ahead & process it ourselves. That way we can
4963 * still distinguish keypad keys for use in mappings.
4964 * Also add GDK_space to make <S-Space> work.
4966 switch (event->keyval)
4968 case GDK_KP_Add: xim_expected_char = '+'; break;
4969 case GDK_KP_Subtract: xim_expected_char = '-'; break;
4970 case GDK_KP_Divide: xim_expected_char = '/'; break;
4971 case GDK_KP_Multiply: xim_expected_char = '*'; break;
4972 case GDK_KP_Decimal: xim_expected_char = '.'; break;
4973 case GDK_KP_Equal: xim_expected_char = '='; break;
4974 case GDK_KP_0: xim_expected_char = '0'; break;
4975 case GDK_KP_1: xim_expected_char = '1'; break;
4976 case GDK_KP_2: xim_expected_char = '2'; break;
4977 case GDK_KP_3: xim_expected_char = '3'; break;
4978 case GDK_KP_4: xim_expected_char = '4'; break;
4979 case GDK_KP_5: xim_expected_char = '5'; break;
4980 case GDK_KP_6: xim_expected_char = '6'; break;
4981 case GDK_KP_7: xim_expected_char = '7'; break;
4982 case GDK_KP_8: xim_expected_char = '8'; break;
4983 case GDK_KP_9: xim_expected_char = '9'; break;
4984 case GDK_space: xim_expected_char = ' '; break;
4985 default: xim_expected_char = NUL;
4987 xim_ignored_char = FALSE;
4991 * When typing fFtT, XIM may be activated. Thus it must pass
4992 * gtk_im_context_filter_keypress() in Normal mode.
4993 * And while doing :sh too.
4995 if (xic != NULL && !p_imdisable
4996 && (State & (INSERT | CMDLINE | NORMAL | EXTERNCMD)) != 0)
4999 * Filter 'imactivatekey' and map it to CTRL-^. This way, Vim is
5000 * always aware of the current status of IM, and can even emulate
5001 * the activation key for modules that don't support one.
5003 if (event->keyval == im_activatekey_keyval
5004 && (event->state & im_activatekey_state) == im_activatekey_state)
5006 unsigned int state_mask;
5008 /* Require the state of the 3 most used modifiers to match exactly.
5009 * Otherwise e.g. <S-C-space> would be unusable for other purposes
5010 * if the IM activate key is <S-space>. */
5011 state_mask = im_activatekey_state;
5012 state_mask |= ((int)GDK_SHIFT_MASK | (int)GDK_CONTROL_MASK
5013 | (int)GDK_MOD1_MASK);
5015 if ((event->state & state_mask) != im_activatekey_state)
5016 return FALSE;
5018 /* Don't send it a second time on GDK_KEY_RELEASE. */
5019 if (event->type != GDK_KEY_PRESS)
5020 return TRUE;
5022 if (map_to_exists_mode((char_u *)"", LANGMAP, FALSE))
5024 im_set_active(FALSE);
5026 /* ":lmap" mappings exists, toggle use of mappings. */
5027 State ^= LANGMAP;
5028 if (State & LANGMAP)
5030 curbuf->b_p_iminsert = B_IMODE_NONE;
5031 State &= ~LANGMAP;
5033 else
5035 curbuf->b_p_iminsert = B_IMODE_LMAP;
5036 State |= LANGMAP;
5038 return TRUE;
5041 return gtk_im_context_filter_keypress(xic, event);
5044 /* Don't filter events through the IM context if IM isn't active
5045 * right now. Unlike with GTK+ 1.2 we cannot rely on the IM module
5046 * not doing anything before the activation key was sent. */
5047 if (im_activatekey_keyval == GDK_VoidSymbol || im_is_active)
5049 int imresult = gtk_im_context_filter_keypress(xic, event);
5051 /* Some XIM send following sequence:
5052 * 1. preedited string.
5053 * 2. committed string.
5054 * 3. line changed key.
5055 * 4. preedited string.
5056 * 5. remove preedited string.
5057 * if 3, Vim can't move back the above line for 5.
5058 * thus, this part should not parse the key. */
5059 if (!imresult && preedit_start_col != MAXCOL
5060 && event->keyval == GDK_Return)
5062 im_synthesize_keypress(GDK_Return, 0U);
5063 return FALSE;
5066 /* If XIM tried to commit a keypad key as a single char.,
5067 * ignore it so we can use the keypad key 'raw', for mappings. */
5068 if (xim_expected_char != NUL && xim_ignored_char)
5069 /* We had a keypad key, and XIM tried to thieve it */
5070 return FALSE;
5072 /* Normal processing */
5073 return imresult;
5077 return FALSE;
5081 im_get_status(void)
5083 #ifdef FEAT_UIMFEP
5084 if (!gui.in_use)
5085 return uimfep_get_status();
5086 #endif
5087 return im_is_active;
5090 # else /* !HAVE_GTK2 */
5092 static int xim_is_active = FALSE; /* XIM should be active in the current
5093 mode */
5094 static int xim_has_focus = FALSE; /* XIM is really being used for Vim */
5095 #ifdef FEAT_GUI_X11
5096 static XIMStyle input_style;
5097 static int status_area_enabled = TRUE;
5098 #endif
5100 #ifdef FEAT_GUI_GTK
5101 # ifdef WIN3264
5102 # include <gdk/gdkwin32.h>
5103 # else
5104 # include <gdk/gdkx.h>
5105 # endif
5106 #else
5107 # ifdef PROTO
5108 /* Define a few things to be able to generate prototypes while not configured
5109 * for GTK. */
5110 # define GSList int
5111 # define gboolean int
5112 typedef int GdkEvent;
5113 typedef int GdkEventKey;
5114 # define GdkIC int
5115 # endif
5116 #endif
5118 #if defined(FEAT_GUI_GTK) || defined(PROTO)
5119 static int preedit_buf_len = 0;
5120 static int xim_can_preediting INIT(= FALSE); /* XIM in showmode() */
5121 static int xim_input_style;
5122 #ifndef FEAT_GUI_GTK
5123 # define gboolean int
5124 #endif
5125 static gboolean use_status_area = 0;
5127 static int im_xim_str2keycode __ARGS((unsigned int *code, unsigned int *state));
5128 static void im_xim_send_event_imactivate __ARGS((void));
5131 * Convert string to keycode and state for XKeyEvent.
5132 * When string is valid return OK, when invalid return FAIL.
5134 * See 'imactivatekey' documentation for the format.
5136 static int
5137 im_xim_str2keycode(code, state)
5138 unsigned int *code;
5139 unsigned int *state;
5141 int retval = OK;
5142 int len;
5143 unsigned keycode = 0, keystate = 0;
5144 Window window;
5145 Display *display;
5146 char_u *flag_end;
5147 char_u *str;
5149 if (*p_imak != NUL)
5151 len = STRLEN(p_imak);
5152 for (flag_end = p_imak + len - 1;
5153 flag_end > p_imak && *flag_end != '-'; --flag_end)
5156 /* Parse modifier keys */
5157 for (str = p_imak; str < flag_end; ++str)
5159 switch (*str)
5161 case 's': case 'S':
5162 keystate |= ShiftMask;
5163 break;
5164 case 'l': case 'L':
5165 keystate |= LockMask;
5166 break;
5167 case 'c': case 'C':
5168 keystate |= ControlMask;
5169 break;
5170 case '1':
5171 keystate |= Mod1Mask;
5172 break;
5173 case '2':
5174 keystate |= Mod2Mask;
5175 break;
5176 case '3':
5177 keystate |= Mod3Mask;
5178 break;
5179 case '4':
5180 keystate |= Mod4Mask;
5181 break;
5182 case '5':
5183 keystate |= Mod5Mask;
5184 break;
5185 case '-':
5186 break;
5187 default:
5188 retval = FAIL;
5191 if (*str == '-')
5192 ++str;
5194 /* Get keycode from string. */
5195 gui_get_x11_windis(&window, &display);
5196 if (display)
5197 keycode = XKeysymToKeycode(display, XStringToKeysym((char *)str));
5198 if (keycode == 0)
5199 retval = FAIL;
5201 if (code != NULL)
5202 *code = keycode;
5203 if (state != NULL)
5204 *state = keystate;
5206 return retval;
5209 static void
5210 im_xim_send_event_imactivate()
5212 /* Force turn on preedit state by symulate keypress event.
5213 * Keycode and state is specified by 'imactivatekey'.
5215 XKeyEvent ev;
5217 gui_get_x11_windis(&ev.window, &ev.display);
5218 ev.root = RootWindow(ev.display, DefaultScreen(ev.display));
5219 ev.subwindow = None;
5220 ev.time = CurrentTime;
5221 ev.x = 1;
5222 ev.y = 1;
5223 ev.x_root = 1;
5224 ev.y_root = 1;
5225 ev.same_screen = 1;
5226 ev.type = KeyPress;
5227 if (im_xim_str2keycode(&ev.keycode, &ev.state) == OK)
5228 XSendEvent(ev.display, ev.window, 1, KeyPressMask, (XEvent*)&ev);
5232 * Return TRUE if 'imactivatekey' has a valid value.
5235 im_xim_isvalid_imactivate()
5237 return im_xim_str2keycode(NULL, NULL) == OK;
5239 #endif /* FEAT_GUI_GTK */
5242 * Switch using XIM on/off. This is used by the code that changes "State".
5244 void
5245 im_set_active(active)
5246 int active;
5248 if (xic == NULL)
5250 #ifdef FEAT_UIMFEP
5251 if (!gui.in_use)
5252 uimfep_set_active(active);
5253 #endif
5254 return;
5257 /* If 'imdisable' is set, XIM is never active. */
5258 if (p_imdisable)
5259 active = FALSE;
5260 #if !defined (FEAT_GUI_GTK)
5261 else if (input_style & XIMPreeditPosition)
5262 /* There is a problem in switching XIM off when preediting is used,
5263 * and it is not clear how this can be solved. For now, keep XIM on
5264 * all the time, like it was done in Vim 5.8. */
5265 active = TRUE;
5266 #endif
5268 /* Remember the active state, it is needed when Vim gets keyboard focus. */
5269 xim_is_active = active;
5271 #ifdef FEAT_GUI_GTK
5272 /* When 'imactivatekey' has valid key-string, try to control XIM preedit
5273 * state. When 'imactivatekey' has no or invalid string, try old XIM
5274 * focus control.
5276 if (*p_imak != NUL)
5278 /* BASIC STRATEGY:
5279 * Destroy old Input Context (XIC), and create new one. New XIC
5280 * would have a state of preedit that is off. When argument:active
5281 * is false, that's all. Else argument:active is true, send a key
5282 * event specified by 'imactivatekey' to activate XIM preedit state.
5285 xim_is_active = TRUE; /* Disable old XIM focus control */
5286 /* If we can monitor preedit state with preedit callback functions,
5287 * try least creation of new XIC.
5289 if (xim_input_style & (int)GDK_IM_PREEDIT_CALLBACKS)
5291 if (xim_can_preediting && !active)
5293 /* Force turn off preedit state. With some IM
5294 * implementations, we cannot turn off preedit state by
5295 * symulate keypress event. It is why using such a method
5296 * that destroy old IC (input context), and create new one.
5297 * When create new IC, its preedit state is usually off.
5299 xim_reset();
5300 xim_set_focus(FALSE);
5301 gdk_ic_destroy(xic);
5302 xim_init();
5303 xim_can_preediting = FALSE;
5305 else if (!xim_can_preediting && active)
5306 im_xim_send_event_imactivate();
5308 else
5310 /* First, force destroy old IC, and create new one. It
5311 * symulates "turning off preedit state".
5313 xim_set_focus(FALSE);
5314 gdk_ic_destroy(xic);
5315 xim_init();
5316 xim_can_preediting = FALSE;
5318 /* 2nd, when requested to activate IM, symulate this by sending
5319 * the event.
5321 if (active)
5323 im_xim_send_event_imactivate();
5324 xim_can_preediting = TRUE;
5328 else
5330 # ifndef XIMPreeditUnKnown
5331 /* X11R5 doesn't have these, it looks safe enough to define here. */
5332 typedef unsigned long XIMPreeditState;
5333 # define XIMPreeditUnKnown 0L
5334 # define XIMPreeditEnable 1L
5335 # define XIMPreeditDisable (1L<<1)
5336 # define XNPreeditState "preeditState"
5337 # endif
5338 XIMPreeditState preedit_state = XIMPreeditUnKnown;
5339 XVaNestedList preedit_attr;
5340 XIC pxic;
5342 preedit_attr = XVaCreateNestedList(0,
5343 XNPreeditState, &preedit_state,
5344 NULL);
5345 pxic = ((GdkICPrivate *)xic)->xic;
5347 if (!XGetICValues(pxic, XNPreeditAttributes, preedit_attr, NULL))
5349 XFree(preedit_attr);
5350 preedit_attr = XVaCreateNestedList(0,
5351 XNPreeditState,
5352 active ? XIMPreeditEnable : XIMPreeditDisable,
5353 NULL);
5354 XSetICValues(pxic, XNPreeditAttributes, preedit_attr, NULL);
5355 xim_can_preediting = active;
5356 xim_is_active = active;
5358 XFree(preedit_attr);
5360 if (xim_input_style & XIMPreeditCallbacks)
5362 preedit_buf_len = 0;
5363 init_preedit_start_col();
5365 #else
5366 # if 0
5367 /* When had tested kinput2 + canna + Athena GUI version with
5368 * 'imactivatekey' is "s-space", im_xim_send_event_imactivate() did not
5369 * work correctly. It just inserted one space. I don't know why we
5370 * couldn't switch state of XIM preediting. This is reason why these
5371 * codes are commented out.
5373 /* First, force destroy old IC, and create new one. It symulates
5374 * "turning off preedit state".
5376 xim_set_focus(FALSE);
5377 XDestroyIC(xic);
5378 xic = NULL;
5379 xim_init();
5381 /* 2nd, when requested to activate IM, symulate this by sending the
5382 * event.
5384 if (active)
5385 im_xim_send_event_imactivate();
5386 # endif
5387 #endif
5388 xim_set_preedit();
5392 * Adjust using XIM for gaining or losing keyboard focus. Also called when
5393 * "xim_is_active" changes.
5395 void
5396 xim_set_focus(focus)
5397 int focus;
5399 if (xic == NULL)
5400 return;
5403 * XIM only gets focus when the Vim window has keyboard focus and XIM has
5404 * been set active for the current mode.
5406 if (focus && xim_is_active)
5408 if (!xim_has_focus)
5410 xim_has_focus = TRUE;
5411 #ifdef FEAT_GUI_GTK
5412 gdk_im_begin(xic, gui.drawarea->window);
5413 #else
5414 XSetICFocus(xic);
5415 #endif
5418 else
5420 if (xim_has_focus)
5422 xim_has_focus = FALSE;
5423 #ifdef FEAT_GUI_GTK
5424 gdk_im_end();
5425 #else
5426 XUnsetICFocus(xic);
5427 #endif
5432 void
5433 im_set_position(row, col)
5434 int row UNUSED;
5435 int col UNUSED;
5437 xim_set_preedit();
5441 * Set the XIM to the current cursor position.
5443 void
5444 xim_set_preedit()
5446 if (xic == NULL)
5447 return;
5449 xim_set_focus(TRUE);
5451 #ifdef FEAT_GUI_GTK
5452 if (gdk_im_ready())
5454 int attrmask;
5455 GdkICAttr *attr;
5457 if (!xic_attr)
5458 return;
5460 attr = xic_attr;
5461 attrmask = 0;
5463 # ifdef FEAT_XFONTSET
5464 if ((xim_input_style & (int)GDK_IM_PREEDIT_POSITION)
5465 && gui.fontset != NOFONTSET
5466 && gui.fontset->type == GDK_FONT_FONTSET)
5468 if (!xim_has_focus)
5470 if (attr->spot_location.y >= 0)
5472 attr->spot_location.x = 0;
5473 attr->spot_location.y = -100;
5474 attrmask |= (int)GDK_IC_SPOT_LOCATION;
5477 else
5479 gint width, height;
5481 if (attr->spot_location.x != TEXT_X(gui.col)
5482 || attr->spot_location.y != TEXT_Y(gui.row))
5484 attr->spot_location.x = TEXT_X(gui.col);
5485 attr->spot_location.y = TEXT_Y(gui.row);
5486 attrmask |= (int)GDK_IC_SPOT_LOCATION;
5489 gdk_window_get_size(gui.drawarea->window, &width, &height);
5490 width -= 2 * gui.border_offset;
5491 height -= 2 * gui.border_offset;
5492 if (xim_input_style & (int)GDK_IM_STATUS_AREA)
5493 height -= gui.char_height;
5494 if (attr->preedit_area.width != width
5495 || attr->preedit_area.height != height)
5497 attr->preedit_area.x = gui.border_offset;
5498 attr->preedit_area.y = gui.border_offset;
5499 attr->preedit_area.width = width;
5500 attr->preedit_area.height = height;
5501 attrmask |= (int)GDK_IC_PREEDIT_AREA;
5504 if (attr->preedit_fontset != gui.current_font)
5506 attr->preedit_fontset = gui.current_font;
5507 attrmask |= (int)GDK_IC_PREEDIT_FONTSET;
5511 # endif /* FEAT_XFONTSET */
5513 if (xim_fg_color == INVALCOLOR)
5515 xim_fg_color = gui.def_norm_pixel;
5516 xim_bg_color = gui.def_back_pixel;
5518 if (attr->preedit_foreground.pixel != xim_fg_color)
5520 attr->preedit_foreground.pixel = xim_fg_color;
5521 attrmask |= (int)GDK_IC_PREEDIT_FOREGROUND;
5523 if (attr->preedit_background.pixel != xim_bg_color)
5525 attr->preedit_background.pixel = xim_bg_color;
5526 attrmask |= (int)GDK_IC_PREEDIT_BACKGROUND;
5529 if (attrmask != 0)
5530 gdk_ic_set_attr(xic, attr, (GdkICAttributesType)attrmask);
5532 #else /* FEAT_GUI_GTK */
5534 XVaNestedList attr_list;
5535 XRectangle spot_area;
5536 XPoint over_spot;
5537 int line_space;
5539 if (!xim_has_focus)
5541 /* hide XIM cursor */
5542 over_spot.x = 0;
5543 over_spot.y = -100; /* arbitrary invisible position */
5544 attr_list = (XVaNestedList) XVaCreateNestedList(0,
5545 XNSpotLocation,
5546 &over_spot,
5547 NULL);
5548 XSetICValues(xic, XNPreeditAttributes, attr_list, NULL);
5549 XFree(attr_list);
5550 return;
5553 if (input_style & XIMPreeditPosition)
5555 if (xim_fg_color == INVALCOLOR)
5557 xim_fg_color = gui.def_norm_pixel;
5558 xim_bg_color = gui.def_back_pixel;
5560 over_spot.x = TEXT_X(gui.col);
5561 over_spot.y = TEXT_Y(gui.row);
5562 spot_area.x = 0;
5563 spot_area.y = 0;
5564 spot_area.height = gui.char_height * Rows;
5565 spot_area.width = gui.char_width * Columns;
5566 line_space = gui.char_height;
5567 attr_list = (XVaNestedList) XVaCreateNestedList(0,
5568 XNSpotLocation, &over_spot,
5569 XNForeground, (Pixel) xim_fg_color,
5570 XNBackground, (Pixel) xim_bg_color,
5571 XNArea, &spot_area,
5572 XNLineSpace, line_space,
5573 NULL);
5574 if (XSetICValues(xic, XNPreeditAttributes, attr_list, NULL))
5575 EMSG(_("E284: Cannot set IC values"));
5576 XFree(attr_list);
5579 #endif /* FEAT_GUI_GTK */
5583 * Set up the status area.
5585 * This should use a separate Widget, but that seems not possible, because
5586 * preedit_area and status_area should be set to the same window as for the
5587 * text input. Unfortunately this means the status area pollutes the text
5588 * window...
5590 void
5591 xim_set_status_area()
5593 if (xic == NULL)
5594 return;
5596 #ifdef FEAT_GUI_GTK
5597 # if defined(FEAT_XFONTSET)
5598 if (use_status_area)
5600 GdkICAttr *attr;
5601 int style;
5602 gint width, height;
5603 GtkWidget *widget;
5604 int attrmask;
5606 if (!xic_attr)
5607 return;
5609 attr = xic_attr;
5610 attrmask = 0;
5611 style = (int)gdk_ic_get_style(xic);
5612 if ((style & (int)GDK_IM_STATUS_MASK) == (int)GDK_IM_STATUS_AREA)
5614 if (gui.fontset != NOFONTSET
5615 && gui.fontset->type == GDK_FONT_FONTSET)
5617 widget = gui.mainwin;
5618 gdk_window_get_size(widget->window, &width, &height);
5620 attrmask |= (int)GDK_IC_STATUS_AREA;
5621 attr->status_area.x = 0;
5622 attr->status_area.y = height - gui.char_height - 1;
5623 attr->status_area.width = width;
5624 attr->status_area.height = gui.char_height;
5627 if (attrmask != 0)
5628 gdk_ic_set_attr(xic, attr, (GdkICAttributesType)attrmask);
5630 # endif
5631 #else
5633 XVaNestedList preedit_list = 0, status_list = 0, list = 0;
5634 XRectangle pre_area, status_area;
5636 if (input_style & XIMStatusArea)
5638 if (input_style & XIMPreeditArea)
5640 XRectangle *needed_rect;
5642 /* to get status_area width */
5643 status_list = XVaCreateNestedList(0, XNAreaNeeded,
5644 &needed_rect, NULL);
5645 XGetICValues(xic, XNStatusAttributes, status_list, NULL);
5646 XFree(status_list);
5648 status_area.width = needed_rect->width;
5650 else
5651 status_area.width = gui.char_width * Columns;
5653 status_area.x = 0;
5654 status_area.y = gui.char_height * Rows + gui.border_offset;
5655 if (gui.which_scrollbars[SBAR_BOTTOM])
5656 status_area.y += gui.scrollbar_height;
5657 #ifdef FEAT_MENU
5658 if (gui.menu_is_active)
5659 status_area.y += gui.menu_height;
5660 #endif
5661 status_area.height = gui.char_height;
5662 status_list = XVaCreateNestedList(0, XNArea, &status_area, NULL);
5664 else
5666 status_area.x = 0;
5667 status_area.y = gui.char_height * Rows + gui.border_offset;
5668 if (gui.which_scrollbars[SBAR_BOTTOM])
5669 status_area.y += gui.scrollbar_height;
5670 #ifdef FEAT_MENU
5671 if (gui.menu_is_active)
5672 status_area.y += gui.menu_height;
5673 #endif
5674 status_area.width = 0;
5675 status_area.height = gui.char_height;
5678 if (input_style & XIMPreeditArea) /* off-the-spot */
5680 pre_area.x = status_area.x + status_area.width;
5681 pre_area.y = gui.char_height * Rows + gui.border_offset;
5682 pre_area.width = gui.char_width * Columns - pre_area.x;
5683 if (gui.which_scrollbars[SBAR_BOTTOM])
5684 pre_area.y += gui.scrollbar_height;
5685 #ifdef FEAT_MENU
5686 if (gui.menu_is_active)
5687 pre_area.y += gui.menu_height;
5688 #endif
5689 pre_area.height = gui.char_height;
5690 preedit_list = XVaCreateNestedList(0, XNArea, &pre_area, NULL);
5692 else if (input_style & XIMPreeditPosition) /* over-the-spot */
5694 pre_area.x = 0;
5695 pre_area.y = 0;
5696 pre_area.height = gui.char_height * Rows;
5697 pre_area.width = gui.char_width * Columns;
5698 preedit_list = XVaCreateNestedList(0, XNArea, &pre_area, NULL);
5701 if (preedit_list && status_list)
5702 list = XVaCreateNestedList(0, XNPreeditAttributes, preedit_list,
5703 XNStatusAttributes, status_list, NULL);
5704 else if (preedit_list)
5705 list = XVaCreateNestedList(0, XNPreeditAttributes, preedit_list,
5706 NULL);
5707 else if (status_list)
5708 list = XVaCreateNestedList(0, XNStatusAttributes, status_list,
5709 NULL);
5710 else
5711 list = NULL;
5713 if (list)
5715 XSetICValues(xic, XNVaNestedList, list, NULL);
5716 XFree(list);
5718 if (status_list)
5719 XFree(status_list);
5720 if (preedit_list)
5721 XFree(preedit_list);
5723 #endif
5726 #if defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK)
5727 static char e_xim[] = N_("E285: Failed to create input context");
5728 #endif
5730 #if defined(FEAT_GUI_X11) || defined(PROTO)
5731 # if defined(XtSpecificationRelease) && XtSpecificationRelease >= 6 && !defined(sun)
5732 # define USE_X11R6_XIM
5733 # endif
5735 static int xim_real_init __ARGS((Window x11_window, Display *x11_display));
5738 #ifdef USE_X11R6_XIM
5739 static void xim_instantiate_cb __ARGS((Display *display, XPointer client_data, XPointer call_data));
5740 static void xim_destroy_cb __ARGS((XIM im, XPointer client_data, XPointer call_data));
5742 static void
5743 xim_instantiate_cb(display, client_data, call_data)
5744 Display *display;
5745 XPointer client_data UNUSED;
5746 XPointer call_data UNUSED;
5748 Window x11_window;
5749 Display *x11_display;
5751 #ifdef XIM_DEBUG
5752 xim_log("xim_instantiate_cb()\n");
5753 #endif
5755 gui_get_x11_windis(&x11_window, &x11_display);
5756 if (display != x11_display)
5757 return;
5759 xim_real_init(x11_window, x11_display);
5760 gui_set_shellsize(FALSE, FALSE, RESIZE_BOTH);
5761 if (xic != NULL)
5762 XUnregisterIMInstantiateCallback(x11_display, NULL, NULL, NULL,
5763 xim_instantiate_cb, NULL);
5766 static void
5767 xim_destroy_cb(im, client_data, call_data)
5768 XIM im UNUSED;
5769 XPointer client_data UNUSED;
5770 XPointer call_data UNUSED;
5772 Window x11_window;
5773 Display *x11_display;
5775 #ifdef XIM_DEBUG
5776 xim_log("xim_destroy_cb()\n");
5777 #endif
5778 gui_get_x11_windis(&x11_window, &x11_display);
5780 xic = NULL;
5781 status_area_enabled = FALSE;
5783 gui_set_shellsize(FALSE, FALSE, RESIZE_BOTH);
5785 XRegisterIMInstantiateCallback(x11_display, NULL, NULL, NULL,
5786 xim_instantiate_cb, NULL);
5788 #endif
5790 void
5791 xim_init()
5793 Window x11_window;
5794 Display *x11_display;
5796 #ifdef XIM_DEBUG
5797 xim_log("xim_init()\n");
5798 #endif
5800 gui_get_x11_windis(&x11_window, &x11_display);
5802 xic = NULL;
5804 if (xim_real_init(x11_window, x11_display))
5805 return;
5807 gui_set_shellsize(FALSE, FALSE, RESIZE_BOTH);
5809 #ifdef USE_X11R6_XIM
5810 XRegisterIMInstantiateCallback(x11_display, NULL, NULL, NULL,
5811 xim_instantiate_cb, NULL);
5812 #endif
5815 static int
5816 xim_real_init(x11_window, x11_display)
5817 Window x11_window;
5818 Display *x11_display;
5820 int i;
5821 char *p,
5823 *ns,
5824 *end,
5825 tmp[1024];
5826 #define IMLEN_MAX 40
5827 char buf[IMLEN_MAX + 7];
5828 XIM xim = NULL;
5829 XIMStyles *xim_styles;
5830 XIMStyle this_input_style = 0;
5831 Boolean found;
5832 XPoint over_spot;
5833 XVaNestedList preedit_list, status_list;
5835 input_style = 0;
5836 status_area_enabled = FALSE;
5838 if (xic != NULL)
5839 return FALSE;
5841 if (gui.rsrc_input_method != NULL && *gui.rsrc_input_method != NUL)
5843 strcpy(tmp, gui.rsrc_input_method);
5844 for (ns = s = tmp; ns != NULL && *s != NUL;)
5846 s = (char *)skipwhite((char_u *)s);
5847 if (*s == NUL)
5848 break;
5849 if ((ns = end = strchr(s, ',')) == NULL)
5850 end = s + strlen(s);
5851 while (isspace(((char_u *)end)[-1]))
5852 end--;
5853 *end = NUL;
5855 if (strlen(s) <= IMLEN_MAX)
5857 strcpy(buf, "@im=");
5858 strcat(buf, s);
5859 if ((p = XSetLocaleModifiers(buf)) != NULL && *p != NUL
5860 && (xim = XOpenIM(x11_display, NULL, NULL, NULL))
5861 != NULL)
5862 break;
5865 s = ns + 1;
5869 if (xim == NULL && (p = XSetLocaleModifiers("")) != NULL && *p != NUL)
5870 xim = XOpenIM(x11_display, NULL, NULL, NULL);
5872 /* This is supposed to be useful to obtain characters through
5873 * XmbLookupString() without really using a XIM. */
5874 if (xim == NULL && (p = XSetLocaleModifiers("@im=none")) != NULL
5875 && *p != NUL)
5876 xim = XOpenIM(x11_display, NULL, NULL, NULL);
5878 if (xim == NULL)
5880 /* Only give this message when verbose is set, because too many people
5881 * got this message when they didn't want to use a XIM. */
5882 if (p_verbose > 0)
5884 verbose_enter();
5885 EMSG(_("E286: Failed to open input method"));
5886 verbose_leave();
5888 return FALSE;
5891 #ifdef USE_X11R6_XIM
5893 XIMCallback destroy_cb;
5895 destroy_cb.callback = xim_destroy_cb;
5896 destroy_cb.client_data = NULL;
5897 if (XSetIMValues(xim, XNDestroyCallback, &destroy_cb, NULL))
5898 EMSG(_("E287: Warning: Could not set destroy callback to IM"));
5900 #endif
5902 if (XGetIMValues(xim, XNQueryInputStyle, &xim_styles, NULL) || !xim_styles)
5904 EMSG(_("E288: input method doesn't support any style"));
5905 XCloseIM(xim);
5906 return FALSE;
5909 found = False;
5910 strcpy(tmp, gui.rsrc_preedit_type_name);
5911 for (s = tmp; s && !found; )
5913 while (*s && isspace((unsigned char)*s))
5914 s++;
5915 if (!*s)
5916 break;
5917 if ((ns = end = strchr(s, ',')) != 0)
5918 ns++;
5919 else
5920 end = s + strlen(s);
5921 while (isspace((unsigned char)*end))
5922 end--;
5923 *end = '\0';
5925 if (!strcmp(s, "OverTheSpot"))
5926 this_input_style = (XIMPreeditPosition | XIMStatusArea);
5927 else if (!strcmp(s, "OffTheSpot"))
5928 this_input_style = (XIMPreeditArea | XIMStatusArea);
5929 else if (!strcmp(s, "Root"))
5930 this_input_style = (XIMPreeditNothing | XIMStatusNothing);
5932 for (i = 0; (unsigned short)i < xim_styles->count_styles; i++)
5934 if (this_input_style == xim_styles->supported_styles[i])
5936 found = True;
5937 break;
5940 if (!found)
5941 for (i = 0; (unsigned short)i < xim_styles->count_styles; i++)
5943 if ((xim_styles->supported_styles[i] & this_input_style)
5944 == (this_input_style & ~XIMStatusArea))
5946 this_input_style &= ~XIMStatusArea;
5947 found = True;
5948 break;
5952 s = ns;
5954 XFree(xim_styles);
5956 if (!found)
5958 /* Only give this message when verbose is set, because too many people
5959 * got this message when they didn't want to use a XIM. */
5960 if (p_verbose > 0)
5962 verbose_enter();
5963 EMSG(_("E289: input method doesn't support my preedit type"));
5964 verbose_leave();
5966 XCloseIM(xim);
5967 return FALSE;
5970 over_spot.x = TEXT_X(gui.col);
5971 over_spot.y = TEXT_Y(gui.row);
5972 input_style = this_input_style;
5974 /* A crash was reported when trying to pass gui.norm_font as XNFontSet,
5975 * thus that has been removed. Hopefully the default works... */
5976 #ifdef FEAT_XFONTSET
5977 if (gui.fontset != NOFONTSET)
5979 preedit_list = XVaCreateNestedList(0,
5980 XNSpotLocation, &over_spot,
5981 XNForeground, (Pixel)gui.def_norm_pixel,
5982 XNBackground, (Pixel)gui.def_back_pixel,
5983 XNFontSet, (XFontSet)gui.fontset,
5984 NULL);
5985 status_list = XVaCreateNestedList(0,
5986 XNForeground, (Pixel)gui.def_norm_pixel,
5987 XNBackground, (Pixel)gui.def_back_pixel,
5988 XNFontSet, (XFontSet)gui.fontset,
5989 NULL);
5991 else
5992 #endif
5994 preedit_list = XVaCreateNestedList(0,
5995 XNSpotLocation, &over_spot,
5996 XNForeground, (Pixel)gui.def_norm_pixel,
5997 XNBackground, (Pixel)gui.def_back_pixel,
5998 NULL);
5999 status_list = XVaCreateNestedList(0,
6000 XNForeground, (Pixel)gui.def_norm_pixel,
6001 XNBackground, (Pixel)gui.def_back_pixel,
6002 NULL);
6005 xic = XCreateIC(xim,
6006 XNInputStyle, input_style,
6007 XNClientWindow, x11_window,
6008 XNFocusWindow, gui.wid,
6009 XNPreeditAttributes, preedit_list,
6010 XNStatusAttributes, status_list,
6011 NULL);
6012 XFree(status_list);
6013 XFree(preedit_list);
6014 if (xic != NULL)
6016 if (input_style & XIMStatusArea)
6018 xim_set_status_area();
6019 status_area_enabled = TRUE;
6021 else
6022 gui_set_shellsize(FALSE, FALSE, RESIZE_BOTH);
6024 else
6026 EMSG(_(e_xim));
6027 XCloseIM(xim);
6028 return FALSE;
6031 return TRUE;
6034 #endif /* FEAT_GUI_X11 */
6036 #if defined(FEAT_GUI_GTK) || defined(PROTO)
6038 # ifdef FEAT_XFONTSET
6039 static char e_overthespot[] = N_("E290: over-the-spot style requires fontset");
6040 # endif
6042 # ifdef PROTO
6043 typedef int GdkIC;
6044 # endif
6046 void
6047 xim_decide_input_style()
6049 /* GDK_IM_STATUS_CALLBACKS was disabled, enabled it to allow Japanese
6050 * OverTheSpot. */
6051 int supported_style = (int)GDK_IM_PREEDIT_NONE |
6052 (int)GDK_IM_PREEDIT_NOTHING |
6053 (int)GDK_IM_PREEDIT_POSITION |
6054 (int)GDK_IM_PREEDIT_CALLBACKS |
6055 (int)GDK_IM_STATUS_CALLBACKS |
6056 (int)GDK_IM_STATUS_AREA |
6057 (int)GDK_IM_STATUS_NONE |
6058 (int)GDK_IM_STATUS_NOTHING;
6060 #ifdef XIM_DEBUG
6061 xim_log("xim_decide_input_style()\n");
6062 #endif
6064 if (!gdk_im_ready())
6065 xim_input_style = 0;
6066 else
6068 if (gtk_major_version > 1
6069 || (gtk_major_version == 1
6070 && (gtk_minor_version > 2
6071 || (gtk_minor_version == 2 && gtk_micro_version >= 3))))
6072 use_status_area = TRUE;
6073 else
6075 EMSG(_("E291: Your GTK+ is older than 1.2.3. Status area disabled"));
6076 use_status_area = FALSE;
6078 #ifdef FEAT_XFONTSET
6079 if (gui.fontset == NOFONTSET || gui.fontset->type != GDK_FONT_FONTSET)
6080 #endif
6081 supported_style &= ~((int)GDK_IM_PREEDIT_POSITION
6082 | (int)GDK_IM_STATUS_AREA);
6083 if (!use_status_area)
6084 supported_style &= ~(int)GDK_IM_STATUS_AREA;
6085 xim_input_style = (int)gdk_im_decide_style((GdkIMStyle)supported_style);
6089 static void
6090 preedit_start_cbproc(XIC thexic UNUSED,
6091 XPointer client_data UNUSED,
6092 XPointer call_data UNUSED)
6094 #ifdef XIM_DEBUG
6095 xim_log("xim_decide_input_style()\n");
6096 #endif
6098 draw_feedback = NULL;
6099 xim_can_preediting = TRUE;
6100 xim_has_preediting = TRUE;
6101 gui_update_cursor(TRUE, FALSE);
6102 if (showmode() > 0)
6104 setcursor();
6105 out_flush();
6109 static void
6110 xim_back_delete(int n)
6112 char_u str[3];
6114 str[0] = CSI;
6115 str[1] = 'k';
6116 str[2] = 'b';
6117 while (n-- > 0)
6118 add_to_input_buf(str, 3);
6121 static GSList *key_press_event_queue = NULL;
6122 static gboolean processing_queued_event = FALSE;
6124 static void
6125 preedit_draw_cbproc(XIC thexic UNUSED,
6126 XPointer client_data UNUSED,
6127 XPointer call_data)
6129 XIMPreeditDrawCallbackStruct *draw_data;
6130 XIMText *text;
6131 char *src;
6132 GSList *event_queue;
6134 #ifdef XIM_DEBUG
6135 xim_log("preedit_draw_cbproc()\n");
6136 #endif
6138 draw_data = (XIMPreeditDrawCallbackStruct *) call_data;
6139 text = (XIMText *) draw_data->text;
6141 if ((text == NULL && draw_data->chg_length == preedit_buf_len)
6142 || preedit_buf_len == 0)
6144 init_preedit_start_col();
6145 vim_free(draw_feedback);
6146 draw_feedback = NULL;
6148 if (draw_data->chg_length > 0)
6150 int bs_cnt;
6152 if (draw_data->chg_length > preedit_buf_len)
6153 bs_cnt = preedit_buf_len;
6154 else
6155 bs_cnt = draw_data->chg_length;
6156 xim_back_delete(bs_cnt);
6157 preedit_buf_len -= bs_cnt;
6159 if (text != NULL)
6161 int len;
6162 #ifdef FEAT_MBYTE
6163 char_u *buf = NULL;
6164 unsigned int nfeedback = 0;
6165 #endif
6166 char_u *ptr;
6168 src = text->string.multi_byte;
6169 if (src != NULL && !text->encoding_is_wchar)
6171 len = strlen(src);
6172 ptr = (char_u *)src;
6173 /* Avoid the enter for decision */
6174 if (*ptr == '\n')
6175 return;
6177 #ifdef FEAT_MBYTE
6178 if (input_conv.vc_type != CONV_NONE
6179 && (buf = string_convert(&input_conv,
6180 (char_u *)src, &len)) != NULL)
6182 /* Converted from 'termencoding' to 'encoding'. */
6183 add_to_input_buf_csi(buf, len);
6184 ptr = buf;
6186 else
6187 #endif
6188 add_to_input_buf_csi((char_u *)src, len);
6189 /* Add count of character to preedit_buf_len */
6190 while (*ptr != NUL)
6192 #ifdef FEAT_MBYTE
6193 if (draw_data->text->feedback != NULL)
6195 if (draw_feedback == NULL)
6196 draw_feedback = (char *)alloc(draw_data->chg_first
6197 + text->length);
6198 else
6199 draw_feedback = vim_realloc(draw_feedback,
6200 draw_data->chg_first + text->length);
6201 if (draw_feedback != NULL)
6203 draw_feedback[nfeedback + draw_data->chg_first]
6204 = draw_data->text->feedback[nfeedback];
6205 nfeedback++;
6208 if (has_mbyte)
6209 ptr += (*mb_ptr2len)(ptr);
6210 else
6211 #endif
6212 ptr++;
6213 preedit_buf_len++;
6215 #ifdef FEAT_MBYTE
6216 vim_free(buf);
6217 #endif
6218 preedit_end_col = MAXCOL;
6221 if (text != NULL || draw_data->chg_length > 0)
6223 event_queue = key_press_event_queue;
6224 processing_queued_event = TRUE;
6225 while (event_queue != NULL && processing_queued_event)
6227 GdkEvent *ev = event_queue->data;
6229 gboolean *ret;
6230 gtk_signal_emit_by_name((GtkObject*)gui.mainwin, "key_press_event",
6231 ev, &ret);
6232 gdk_event_free(ev);
6233 event_queue = event_queue->next;
6235 processing_queued_event = FALSE;
6236 if (key_press_event_queue)
6238 g_slist_free(key_press_event_queue);
6239 key_press_event_queue = NULL;
6242 if (gtk_main_level() > 0)
6243 gtk_main_quit();
6247 * Retrieve the highlighting attributes at column col in the preedit string.
6248 * Return -1 if not in preediting mode or if col is out of range.
6251 im_get_feedback_attr(int col)
6253 if (draw_feedback != NULL && col < preedit_buf_len)
6255 if (draw_feedback[col] & XIMReverse)
6256 return HL_INVERSE;
6257 else if (draw_feedback[col] & XIMUnderline)
6258 return HL_UNDERLINE;
6259 else
6260 return hl_attr(HLF_V);
6263 return -1;
6266 static void
6267 preedit_caret_cbproc(XIC thexic UNUSED,
6268 XPointer client_data UNUSED,
6269 XPointer call_data UNUSED)
6271 #ifdef XIM_DEBUG
6272 xim_log("preedit_caret_cbproc()\n");
6273 #endif
6276 static void
6277 preedit_done_cbproc(XIC thexic UNUSED,
6278 XPointer client_data UNUSED,
6279 XPointer call_data UNUSED)
6281 #ifdef XIM_DEBUG
6282 xim_log("preedit_done_cbproc()\n");
6283 #endif
6285 vim_free(draw_feedback);
6286 draw_feedback = NULL;
6287 xim_can_preediting = FALSE;
6288 xim_has_preediting = FALSE;
6289 gui_update_cursor(TRUE, FALSE);
6290 if (showmode() > 0)
6292 setcursor();
6293 out_flush();
6297 void
6298 xim_reset(void)
6300 char *text;
6302 #ifdef XIM_DEBUG
6303 xim_log("xim_reset()\n");
6304 #endif
6306 if (xic != NULL)
6308 text = XmbResetIC(((GdkICPrivate *)xic)->xic);
6309 if (text != NULL && !(xim_input_style & (int)GDK_IM_PREEDIT_CALLBACKS))
6310 add_to_input_buf_csi((char_u *)text, strlen(text));
6311 else
6312 preedit_buf_len = 0;
6313 if (text != NULL)
6314 XFree(text);
6319 xim_queue_key_press_event(GdkEventKey *event, int down UNUSED)
6321 #ifdef XIM_DEBUG
6322 xim_log("xim_queue_key_press_event()\n");
6323 #endif
6325 if (preedit_buf_len <= 0)
6326 return FALSE;
6327 if (processing_queued_event)
6328 processing_queued_event = FALSE;
6330 key_press_event_queue = g_slist_append(key_press_event_queue,
6331 gdk_event_copy((GdkEvent *)event));
6332 return TRUE;
6335 static void
6336 preedit_callback_setup(GdkIC *ic UNUSED)
6338 XIC xxic;
6339 XVaNestedList preedit_attr;
6340 XIMCallback preedit_start_cb;
6341 XIMCallback preedit_draw_cb;
6342 XIMCallback preedit_caret_cb;
6343 XIMCallback preedit_done_cb;
6345 xxic = ((GdkICPrivate*)xic)->xic;
6346 preedit_start_cb.callback = (XIMProc)preedit_start_cbproc;
6347 preedit_draw_cb.callback = (XIMProc)preedit_draw_cbproc;
6348 preedit_caret_cb.callback = (XIMProc)preedit_caret_cbproc;
6349 preedit_done_cb.callback = (XIMProc)preedit_done_cbproc;
6350 preedit_attr
6351 = XVaCreateNestedList(0,
6352 XNPreeditStartCallback, &preedit_start_cb,
6353 XNPreeditDrawCallback, &preedit_draw_cb,
6354 XNPreeditCaretCallback, &preedit_caret_cb,
6355 XNPreeditDoneCallback, &preedit_done_cb,
6356 NULL);
6357 XSetICValues(xxic, XNPreeditAttributes, preedit_attr, NULL);
6358 XFree(preedit_attr);
6361 static void
6362 reset_state_setup(GdkIC *ic UNUSED)
6364 #ifdef USE_X11R6_XIM
6365 /* don't change the input context when we call reset */
6366 XSetICValues(((GdkICPrivate *)ic)->xic, XNResetState, XIMPreserveState,
6367 NULL);
6368 #endif
6371 void
6372 xim_init(void)
6374 #ifdef XIM_DEBUG
6375 xim_log("xim_init()\n");
6376 #endif
6378 xic = NULL;
6379 xic_attr = NULL;
6381 if (!gdk_im_ready())
6383 if (p_verbose > 0)
6385 verbose_enter();
6386 EMSG(_("E292: Input Method Server is not running"));
6387 verbose_leave();
6389 return;
6391 if ((xic_attr = gdk_ic_attr_new()) != NULL)
6393 #ifdef FEAT_XFONTSET
6394 gint width, height;
6395 #endif
6396 int mask;
6397 GdkColormap *colormap;
6398 GdkICAttr *attr = xic_attr;
6399 int attrmask = (int)GDK_IC_ALL_REQ;
6400 GtkWidget *widget = gui.drawarea;
6402 attr->style = (GdkIMStyle)xim_input_style;
6403 attr->client_window = gui.mainwin->window;
6405 if ((colormap = gtk_widget_get_colormap(widget)) !=
6406 gtk_widget_get_default_colormap())
6408 attrmask |= (int)GDK_IC_PREEDIT_COLORMAP;
6409 attr->preedit_colormap = colormap;
6411 attrmask |= (int)GDK_IC_PREEDIT_FOREGROUND;
6412 attrmask |= (int)GDK_IC_PREEDIT_BACKGROUND;
6413 attr->preedit_foreground = widget->style->fg[GTK_STATE_NORMAL];
6414 attr->preedit_background = widget->style->base[GTK_STATE_NORMAL];
6416 #ifdef FEAT_XFONTSET
6417 if ((xim_input_style & (int)GDK_IM_PREEDIT_MASK)
6418 == (int)GDK_IM_PREEDIT_POSITION)
6420 if (gui.fontset == NOFONTSET
6421 || gui.fontset->type != GDK_FONT_FONTSET)
6423 EMSG(_(e_overthespot));
6425 else
6427 gdk_window_get_size(widget->window, &width, &height);
6429 attrmask |= (int)GDK_IC_PREEDIT_POSITION_REQ;
6430 attr->spot_location.x = TEXT_X(0);
6431 attr->spot_location.y = TEXT_Y(0);
6432 attr->preedit_area.x = gui.border_offset;
6433 attr->preedit_area.y = gui.border_offset;
6434 attr->preedit_area.width = width - 2*gui.border_offset;
6435 attr->preedit_area.height = height - 2*gui.border_offset;
6436 attr->preedit_fontset = gui.fontset;
6440 if ((xim_input_style & (int)GDK_IM_STATUS_MASK)
6441 == (int)GDK_IM_STATUS_AREA)
6443 if (gui.fontset == NOFONTSET
6444 || gui.fontset->type != GDK_FONT_FONTSET)
6446 EMSG(_(e_overthespot));
6448 else
6450 gdk_window_get_size(gui.mainwin->window, &width, &height);
6451 attrmask |= (int)GDK_IC_STATUS_AREA_REQ;
6452 attr->status_area.x = 0;
6453 attr->status_area.y = height - gui.char_height - 1;
6454 attr->status_area.width = width;
6455 attr->status_area.height = gui.char_height;
6456 attr->status_fontset = gui.fontset;
6459 else if ((xim_input_style & (int)GDK_IM_STATUS_MASK)
6460 == (int)GDK_IM_STATUS_CALLBACKS)
6462 /* FIXME */
6464 #endif
6466 xic = gdk_ic_new(attr, (GdkICAttributesType)attrmask);
6468 if (xic == NULL)
6469 EMSG(_(e_xim));
6470 else
6472 mask = (int)gdk_window_get_events(widget->window);
6473 mask |= (int)gdk_ic_get_events(xic);
6474 gdk_window_set_events(widget->window, (GdkEventMask)mask);
6475 if (xim_input_style & (int)GDK_IM_PREEDIT_CALLBACKS)
6476 preedit_callback_setup(xic);
6477 reset_state_setup(xic);
6482 void
6483 im_shutdown(void)
6485 #ifdef XIM_DEBUG
6486 xim_log("im_shutdown()\n");
6487 #endif
6489 if (xic != NULL)
6491 gdk_im_end();
6492 gdk_ic_destroy(xic);
6493 xic = NULL;
6495 xim_is_active = FALSE;
6496 xim_can_preediting = FALSE;
6497 preedit_start_col = MAXCOL;
6498 xim_has_preediting = FALSE;
6501 #endif /* FEAT_GUI_GTK */
6504 xim_get_status_area_height()
6506 #ifdef FEAT_GUI_GTK
6507 if (xim_input_style & (int)GDK_IM_STATUS_AREA)
6508 return gui.char_height;
6509 #else
6510 if (status_area_enabled)
6511 return gui.char_height;
6512 #endif
6513 return 0;
6517 * Get IM status. When IM is on, return TRUE. Else return FALSE.
6518 * FIXME: This doesn't work correctly: Having focus doesn't always mean XIM is
6519 * active, when not having focus XIM may still be active (e.g., when using a
6520 * tear-off menu item).
6523 im_get_status()
6525 #ifdef FEAT_UIMFEP
6526 if (!gui.in_use)
6527 return uimfep_get_status();
6528 #endif
6529 # ifdef FEAT_GUI_GTK
6530 if (xim_input_style & (int)GDK_IM_PREEDIT_CALLBACKS)
6531 return xim_can_preediting;
6532 # endif
6533 return xim_has_focus;
6536 # endif /* !HAVE_GTK2 */
6538 # if defined(HAVE_GTK2) || defined(PROTO)
6540 preedit_get_status(void)
6542 return preedit_is_active;
6544 # endif
6546 # if defined(FEAT_GUI_GTK) || defined(PROTO)
6548 im_is_preediting()
6550 return xim_has_preediting;
6552 # endif
6553 #endif /* FEAT_XIM */
6555 #if defined(FEAT_MBYTE) || defined(PROTO)
6558 * Setup "vcp" for conversion from "from" to "to".
6559 * The names must have been made canonical with enc_canonize().
6560 * vcp->vc_type must have been initialized to CONV_NONE.
6561 * Note: cannot be used for conversion from/to ucs-2 and ucs-4 (will use utf-8
6562 * instead).
6563 * Afterwards invoke with "from" and "to" equal to NULL to cleanup.
6564 * Return FAIL when conversion is not supported, OK otherwise.
6567 convert_setup(vcp, from, to)
6568 vimconv_T *vcp;
6569 char_u *from;
6570 char_u *to;
6572 return convert_setup_ext(vcp, from, TRUE, to, TRUE);
6576 * As convert_setup(), but only when from_unicode_is_utf8 is TRUE will all
6577 * "from" unicode charsets be considered utf-8. Same for "to".
6580 convert_setup_ext(vcp, from, from_unicode_is_utf8, to, to_unicode_is_utf8)
6581 vimconv_T *vcp;
6582 char_u *from;
6583 int from_unicode_is_utf8;
6584 char_u *to;
6585 int to_unicode_is_utf8;
6587 int from_prop;
6588 int to_prop;
6589 int from_is_utf8;
6590 int to_is_utf8;
6592 /* Reset to no conversion. */
6593 # ifdef USE_ICONV
6594 if (vcp->vc_type == CONV_ICONV && vcp->vc_fd != (iconv_t)-1)
6595 iconv_close(vcp->vc_fd);
6596 # endif
6597 vcp->vc_type = CONV_NONE;
6598 vcp->vc_factor = 1;
6599 vcp->vc_fail = FALSE;
6601 /* No conversion when one of the names is empty or they are equal. */
6602 if (from == NULL || *from == NUL || to == NULL || *to == NUL
6603 || STRCMP(from, to) == 0)
6604 return OK;
6606 from_prop = enc_canon_props(from);
6607 to_prop = enc_canon_props(to);
6608 if (from_unicode_is_utf8)
6609 from_is_utf8 = from_prop & ENC_UNICODE;
6610 else
6611 from_is_utf8 = from_prop == ENC_UNICODE;
6612 if (to_unicode_is_utf8)
6613 to_is_utf8 = to_prop & ENC_UNICODE;
6614 else
6615 to_is_utf8 = to_prop == ENC_UNICODE;
6617 if ((from_prop & ENC_LATIN1) && to_is_utf8)
6619 /* Internal latin1 -> utf-8 conversion. */
6620 vcp->vc_type = CONV_TO_UTF8;
6621 vcp->vc_factor = 2; /* up to twice as long */
6623 else if ((from_prop & ENC_LATIN9) && to_is_utf8)
6625 /* Internal latin9 -> utf-8 conversion. */
6626 vcp->vc_type = CONV_9_TO_UTF8;
6627 vcp->vc_factor = 3; /* up to three as long (euro sign) */
6629 else if (from_is_utf8 && (to_prop & ENC_LATIN1))
6631 /* Internal utf-8 -> latin1 conversion. */
6632 vcp->vc_type = CONV_TO_LATIN1;
6634 else if (from_is_utf8 && (to_prop & ENC_LATIN9))
6636 /* Internal utf-8 -> latin9 conversion. */
6637 vcp->vc_type = CONV_TO_LATIN9;
6639 #ifdef WIN3264
6640 /* Win32-specific codepage <-> codepage conversion without iconv. */
6641 else if ((from_is_utf8 || encname2codepage(from) > 0)
6642 && (to_is_utf8 || encname2codepage(to) > 0))
6644 vcp->vc_type = CONV_CODEPAGE;
6645 vcp->vc_factor = 2; /* up to twice as long */
6646 vcp->vc_cpfrom = from_is_utf8 ? 0 : encname2codepage(from);
6647 vcp->vc_cpto = to_is_utf8 ? 0 : encname2codepage(to);
6649 #endif
6650 #ifdef MACOS_X
6651 else if ((from_prop & ENC_MACROMAN) && (to_prop & ENC_LATIN1))
6653 vcp->vc_type = CONV_MAC_LATIN1;
6655 else if ((from_prop & ENC_MACROMAN) && to_is_utf8)
6657 vcp->vc_type = CONV_MAC_UTF8;
6658 vcp->vc_factor = 2; /* up to twice as long */
6660 else if ((from_prop & ENC_LATIN1) && (to_prop & ENC_MACROMAN))
6662 vcp->vc_type = CONV_LATIN1_MAC;
6664 else if (from_is_utf8 && (to_prop & ENC_MACROMAN))
6666 vcp->vc_type = CONV_UTF8_MAC;
6668 #endif
6669 # ifdef USE_ICONV
6670 else
6672 /* Use iconv() for conversion. */
6673 vcp->vc_fd = (iconv_t)my_iconv_open(
6674 to_is_utf8 ? (char_u *)"utf-8" : to,
6675 from_is_utf8 ? (char_u *)"utf-8" : from);
6676 if (vcp->vc_fd != (iconv_t)-1)
6678 vcp->vc_type = CONV_ICONV;
6679 vcp->vc_factor = 4; /* could be longer too... */
6682 # endif
6683 if (vcp->vc_type == CONV_NONE)
6684 return FAIL;
6686 return OK;
6689 #if defined(FEAT_GUI) || defined(AMIGA) || defined(WIN3264) \
6690 || defined(MSDOS) || defined(PROTO)
6692 * Do conversion on typed input characters in-place.
6693 * The input and output are not NUL terminated!
6694 * Returns the length after conversion.
6697 convert_input(ptr, len, maxlen)
6698 char_u *ptr;
6699 int len;
6700 int maxlen;
6702 return convert_input_safe(ptr, len, maxlen, NULL, NULL);
6704 #endif
6707 * Like convert_input(), but when there is an incomplete byte sequence at the
6708 * end return that as an allocated string in "restp" and set "*restlenp" to
6709 * the length. If "restp" is NULL it is not used.
6712 convert_input_safe(ptr, len, maxlen, restp, restlenp)
6713 char_u *ptr;
6714 int len;
6715 int maxlen;
6716 char_u **restp;
6717 int *restlenp;
6719 char_u *d;
6720 int dlen = len;
6721 int unconvertlen = 0;
6723 d = string_convert_ext(&input_conv, ptr, &dlen,
6724 restp == NULL ? NULL : &unconvertlen);
6725 if (d != NULL)
6727 if (dlen <= maxlen)
6729 if (unconvertlen > 0)
6731 /* Move the unconverted characters to allocated memory. */
6732 *restp = alloc(unconvertlen);
6733 if (*restp != NULL)
6734 mch_memmove(*restp, ptr + len - unconvertlen, unconvertlen);
6735 *restlenp = unconvertlen;
6737 mch_memmove(ptr, d, dlen);
6739 else
6740 /* result is too long, keep the unconverted text (the caller must
6741 * have done something wrong!) */
6742 dlen = len;
6743 vim_free(d);
6745 return dlen;
6749 * Convert text "ptr[*lenp]" according to "vcp".
6750 * Returns the result in allocated memory and sets "*lenp".
6751 * When "lenp" is NULL, use NUL terminated strings.
6752 * Illegal chars are often changed to "?", unless vcp->vc_fail is set.
6753 * When something goes wrong, NULL is returned and "*lenp" is unchanged.
6755 char_u *
6756 string_convert(vcp, ptr, lenp)
6757 vimconv_T *vcp;
6758 char_u *ptr;
6759 int *lenp;
6761 return string_convert_ext(vcp, ptr, lenp, NULL);
6765 * Like string_convert(), but when "unconvlenp" is not NULL and there are is
6766 * an incomplete sequence at the end it is not converted and "*unconvlenp" is
6767 * set to the number of remaining bytes.
6769 char_u *
6770 string_convert_ext(vcp, ptr, lenp, unconvlenp)
6771 vimconv_T *vcp;
6772 char_u *ptr;
6773 int *lenp;
6774 int *unconvlenp;
6776 char_u *retval = NULL;
6777 char_u *d;
6778 int len;
6779 int i;
6780 int l;
6781 int c;
6783 if (lenp == NULL)
6784 len = (int)STRLEN(ptr);
6785 else
6786 len = *lenp;
6787 if (len == 0)
6788 return vim_strsave((char_u *)"");
6790 switch (vcp->vc_type)
6792 case CONV_TO_UTF8: /* latin1 to utf-8 conversion */
6793 retval = alloc(len * 2 + 1);
6794 if (retval == NULL)
6795 break;
6796 d = retval;
6797 for (i = 0; i < len; ++i)
6799 c = ptr[i];
6800 if (c < 0x80)
6801 *d++ = c;
6802 else
6804 *d++ = 0xc0 + ((unsigned)c >> 6);
6805 *d++ = 0x80 + (c & 0x3f);
6808 *d = NUL;
6809 if (lenp != NULL)
6810 *lenp = (int)(d - retval);
6811 break;
6813 case CONV_9_TO_UTF8: /* latin9 to utf-8 conversion */
6814 retval = alloc(len * 3 + 1);
6815 if (retval == NULL)
6816 break;
6817 d = retval;
6818 for (i = 0; i < len; ++i)
6820 c = ptr[i];
6821 switch (c)
6823 case 0xa4: c = 0x20ac; break; /* euro */
6824 case 0xa6: c = 0x0160; break; /* S hat */
6825 case 0xa8: c = 0x0161; break; /* S -hat */
6826 case 0xb4: c = 0x017d; break; /* Z hat */
6827 case 0xb8: c = 0x017e; break; /* Z -hat */
6828 case 0xbc: c = 0x0152; break; /* OE */
6829 case 0xbd: c = 0x0153; break; /* oe */
6830 case 0xbe: c = 0x0178; break; /* Y */
6832 d += utf_char2bytes(c, d);
6834 *d = NUL;
6835 if (lenp != NULL)
6836 *lenp = (int)(d - retval);
6837 break;
6839 case CONV_TO_LATIN1: /* utf-8 to latin1 conversion */
6840 case CONV_TO_LATIN9: /* utf-8 to latin9 conversion */
6841 retval = alloc(len + 1);
6842 if (retval == NULL)
6843 break;
6844 d = retval;
6845 for (i = 0; i < len; ++i)
6847 l = utf_ptr2len_len(ptr + i, len - i);
6848 if (l == 0)
6849 *d++ = NUL;
6850 else if (l == 1)
6852 int l_w = utf8len_tab_zero[ptr[i]];
6854 if (l_w == 0)
6856 /* Illegal utf-8 byte cannot be converted */
6857 vim_free(retval);
6858 return NULL;
6860 if (unconvlenp != NULL && l_w > len - i)
6862 /* Incomplete sequence at the end. */
6863 *unconvlenp = len - i;
6864 break;
6866 *d++ = ptr[i];
6868 else
6870 c = utf_ptr2char(ptr + i);
6871 if (vcp->vc_type == CONV_TO_LATIN9)
6872 switch (c)
6874 case 0x20ac: c = 0xa4; break; /* euro */
6875 case 0x0160: c = 0xa6; break; /* S hat */
6876 case 0x0161: c = 0xa8; break; /* S -hat */
6877 case 0x017d: c = 0xb4; break; /* Z hat */
6878 case 0x017e: c = 0xb8; break; /* Z -hat */
6879 case 0x0152: c = 0xbc; break; /* OE */
6880 case 0x0153: c = 0xbd; break; /* oe */
6881 case 0x0178: c = 0xbe; break; /* Y */
6882 case 0xa4:
6883 case 0xa6:
6884 case 0xa8:
6885 case 0xb4:
6886 case 0xb8:
6887 case 0xbc:
6888 case 0xbd:
6889 case 0xbe: c = 0x100; break; /* not in latin9 */
6891 if (!utf_iscomposing(c)) /* skip composing chars */
6893 if (c < 0x100)
6894 *d++ = c;
6895 else if (vcp->vc_fail)
6897 vim_free(retval);
6898 return NULL;
6900 else
6902 *d++ = 0xbf;
6903 if (utf_char2cells(c) > 1)
6904 *d++ = '?';
6907 i += l - 1;
6910 *d = NUL;
6911 if (lenp != NULL)
6912 *lenp = (int)(d - retval);
6913 break;
6915 # ifdef MACOS_CONVERT
6916 case CONV_MAC_LATIN1:
6917 retval = mac_string_convert(ptr, len, lenp, vcp->vc_fail,
6918 'm', 'l', unconvlenp);
6919 break;
6921 case CONV_LATIN1_MAC:
6922 retval = mac_string_convert(ptr, len, lenp, vcp->vc_fail,
6923 'l', 'm', unconvlenp);
6924 break;
6926 case CONV_MAC_UTF8:
6927 retval = mac_string_convert(ptr, len, lenp, vcp->vc_fail,
6928 'm', 'u', unconvlenp);
6929 break;
6931 case CONV_UTF8_MAC:
6932 retval = mac_string_convert(ptr, len, lenp, vcp->vc_fail,
6933 'u', 'm', unconvlenp);
6934 break;
6935 # endif
6937 # ifdef USE_ICONV
6938 case CONV_ICONV: /* conversion with output_conv.vc_fd */
6939 retval = iconv_string(vcp, ptr, len, unconvlenp, lenp);
6940 break;
6941 # endif
6942 # ifdef WIN3264
6943 case CONV_CODEPAGE: /* codepage -> codepage */
6945 int retlen;
6946 int tmp_len;
6947 short_u *tmp;
6949 /* 1. codepage/UTF-8 -> ucs-2. */
6950 if (vcp->vc_cpfrom == 0)
6951 tmp_len = utf8_to_utf16(ptr, len, NULL, NULL);
6952 else
6953 tmp_len = MultiByteToWideChar(vcp->vc_cpfrom, 0,
6954 ptr, len, 0, 0);
6955 tmp = (short_u *)alloc(sizeof(short_u) * tmp_len);
6956 if (tmp == NULL)
6957 break;
6958 if (vcp->vc_cpfrom == 0)
6959 utf8_to_utf16(ptr, len, tmp, unconvlenp);
6960 else
6961 MultiByteToWideChar(vcp->vc_cpfrom, 0, ptr, len, tmp, tmp_len);
6963 /* 2. ucs-2 -> codepage/UTF-8. */
6964 if (vcp->vc_cpto == 0)
6965 retlen = utf16_to_utf8(tmp, tmp_len, NULL);
6966 else
6967 retlen = WideCharToMultiByte(vcp->vc_cpto, 0,
6968 tmp, tmp_len, 0, 0, 0, 0);
6969 retval = alloc(retlen + 1);
6970 if (retval != NULL)
6972 if (vcp->vc_cpto == 0)
6973 utf16_to_utf8(tmp, tmp_len, retval);
6974 else
6975 WideCharToMultiByte(vcp->vc_cpto, 0,
6976 tmp, tmp_len, retval, retlen, 0, 0);
6977 retval[retlen] = NUL;
6978 if (lenp != NULL)
6979 *lenp = retlen;
6981 vim_free(tmp);
6982 break;
6984 # endif
6987 return retval;
6989 #endif
6991 #if defined(FEAT_UIMFEP)
6992 static void
6993 uimfep_set_active(int active)
6995 int mustfree = 0;
6996 char_u *setmode;
6997 setmode = vim_getenv("UIM_FEP_SETMODE", &mustfree);
6998 if (setmode != NULL)
7000 FILE *fp = fopen(setmode, "w");
7001 if (fp)
7003 fprintf(fp, "%d\n", active ? uimfep_lastmode : 0);
7004 fflush(fp);
7005 fclose(fp);
7008 if (mustfree)
7009 vim_free(setmode);
7012 static int
7013 uimfep_get_status(void)
7015 int mustfree = 0;
7016 int mode = 0;
7017 char_u *getmode;
7018 getmode = vim_getenv("UIM_FEP_GETMODE", &mustfree);
7019 if (getmode != NULL)
7021 FILE *fp = fopen(getmode, "r");
7022 if (fp)
7024 char_u buf[99];
7025 if (fgets(buf, sizeof(buf), fp))
7026 mode = atoi(buf);
7027 fclose(fp);
7030 if (mustfree)
7031 vim_free(getmode);
7032 if (mode != 0)
7033 uimfep_lastmode = mode;
7034 return mode != 0;
7037 # if defined(USE_IM_CONTROL) && (!defined(FEAT_XIM) \
7038 && !defined(FEAT_MBYTE_IME) && !defined(GLOBAL_IME))
7039 void
7040 im_set_active(int active)
7042 uimfep_set_active(active);
7046 im_get_status(void)
7048 return uimfep_get_status();
7050 # endif
7052 #endif /* defined(FEAT_UIMFEP) */