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