robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1#include <assert.h> 2#include <inttypes.h> 3#include <math.h> 4#include <stdarg.h> 5#include <stdbool.h> 6#include <stddef.h> 7#include <stdio.h> 8#include <stdlib.h> 9#include <string.h> 10 11#include "auto/config.h" 12#include "nvim/api/private/defs.h" 13#include "nvim/api/private/helpers.h" 14#include "nvim/ascii_defs.h" 15#include "nvim/assert_defs.h" 16#include "nvim/charset.h" 17#include "nvim/errors.h" 18#include "nvim/eval/encode.h" 19#include "nvim/eval/typval.h" 20#include "nvim/eval/typval_defs.h" 21#include "nvim/ex_docmd.h" 22#include "nvim/garray.h" 23#include "nvim/garray_defs.h" 24#include "nvim/gettext_defs.h" 25#include "nvim/macros_defs.h" 26#include "nvim/math.h" 27#include "nvim/mbyte.h" 28#include "nvim/mbyte_defs.h" 29#include "nvim/memory.h" 30#include "nvim/memory_defs.h" 31#include "nvim/message.h" 32#include "nvim/option.h" 33#include "nvim/plines.h" 34#include "nvim/strings.h" 35#include "nvim/types_defs.h" 36#include "nvim/vim_defs.h" 37 38#include "strings.c.generated.h" 39 40static const char e_cannot_mix_positional_and_non_positional_str [] 41= N_ ("E1500: Cannot mix positional and non-positional arguments: %s" ); 42static const char e_fmt_arg_nr_unused_str [] 43= N_ ("E1501: format argument %d unused in $-style format: %s" ); 44static const char e_positional_num_field_spec_reused_str_str [] 45= N_ ("E1502: Positional argument %d used as field width reused as different type: %s/%s" ); 46static const char e_positional_nr_out_of_bounds_str [] 47= N_ ("E1503: Positional argument %d out of bounds: %s" ); 48static const char e_positional_arg_num_type_inconsistent_str_str [] 49= N_ ("E1504: Positional argument %d type used inconsistently: %s/%s" ); 50static const char e_invalid_format_specifier_str [] 51= N_ ("E1505: Invalid format specifier: %s" ); 52static const char e_aptypes_is_null_nr_str [] 53= "E1507: Internal error: ap_types or ap_types[idx] is NULL: %d: %s" ; 54 55static const char typename_unknown []= N_ ("unknown" ); 56static const char typename_int []= "int" ; 57static const char typename_longint []= "long int" ; 58static const char typename_longlongint []= "long long int" ; 59static const char typename_signedsizet []= "signed size_t" ; 60static const char typename_unsignedint []= "unsigned int" ; 61static const char typename_unsignedlongint []= "unsigned long int" ; 62static const char typename_unsignedlonglongint []= "unsigned long long int" ; 63static const char typename_sizet []= "size_t" ; 64static const char typename_pointer []= N_ ("pointer" ); 65static const char typename_percent []= N_ ("percent" ); 66static const char typename_char []= "char" ; 67static const char typename_string []= N_ ("string" ); 68static const char typename_float []= "float" ; 69 70/// Copy up to `len` bytes of `string` into newly allocated memory and 71/// terminate with a NUL. The allocated memory always has size `len + 1`, even 72/// when `string` is shorter. 73char * xstrnsave (const char * string ,size_t len ) 74FUNC_ATTR_NONNULL_RET FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_ALL 75{ 76return strncpy (xmallocz (len ),string ,len );// NOLINT(runtime/printf) 77} 78 79// Same as vim_strsave(), but any characters found in esc_chars are preceded 80// by a backslash. 81char * vim_strsave_escaped (const char * string ,const char * esc_chars ) 82FUNC_ATTR_NONNULL_RET FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_ALL 83{ 84return vim_strsave_escaped_ext (string ,esc_chars ,'\\' , false); 85} 86 87// Same as vim_strsave_escaped(), but when "bsl" is true also escape 88// characters where rem_backslash() would remove the backslash. 89// Escape the characters with "cc". 90char * vim_strsave_escaped_ext (const char * string ,const char * esc_chars ,char cc ,bool bsl ) 91FUNC_ATTR_NONNULL_RET FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_ALL 92{ 93// First count the number of backslashes required. 94// Then allocate the memory and insert them. 95size_t length = 1 ;// count the trailing NUL 96for (const char * p = string ;* p ;p ++ ) { 97const size_t l = (size_t )(utfc_ptr2len (p )); 98if (l > 1 ) { 99length += l ;// count a multibyte char 100p += l - 1 ; 101continue ; 102 } 103if (vim_strchr (esc_chars , (uint8_t )(* p ))!= NULL || (bsl && rem_backslash (p ))) { 104length ++ ;// count a backslash 105 } 106length ++ ;// count an ordinary char 107 } 108 109char * escaped_string = xmalloc (length ); 110char * p2 = escaped_string ; 111for (const char * p = string ;* p ;p ++ ) { 112const size_t l = (size_t )(utfc_ptr2len (p )); 113if (l > 1 ) { 114memcpy (p2 ,p ,l ); 115p2 += l ; 116p += l - 1 ;// skip multibyte char 117continue ; 118 } 119if (vim_strchr (esc_chars , (uint8_t )(* p ))!= NULL || (bsl && rem_backslash (p ))) { 120* p2 ++ = cc ; 121 } 122* p2 ++ = * p ; 123 } 124* p2 = NUL ; 125 126return escaped_string ; 127} 128 129/// Save a copy of an unquoted string 130/// 131/// Turns string like `a\bc"def\"ghi\\\n"jkl` into `a\bcdef"ghi\\njkl`, for use 132/// in shell_build_argv: the only purpose of backslash is making next character 133/// be treated literally inside the double quotes, if this character is 134/// backslash or quote. 135/// 136/// @param[in] string String to copy. 137/// @param[in] length Length of the string to copy. 138/// 139/// @return [allocated] Copy of the string. 140char * vim_strnsave_unquoted (const char * const string ,const size_t length ) 141FUNC_ATTR_MALLOC FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL 142FUNC_ATTR_NONNULL_RET 143{ 144#define ESCAPE_COND (p ,inquote ,string_end ) \ 145 (*(p) == '\\' && (inquote) && (p) + 1 < (string_end) && ((p)[1] == '\\' || (p)[1] == '"')) 146size_t ret_length = 0 ; 147bool inquote = false; 148const char * const string_end = string + length ; 149for (const char * p = string ;p < string_end ;p ++ ) { 150if (* p == '"' ) { 151inquote = !inquote ; 152 }else if (ESCAPE_COND (p ,inquote ,string_end )) { 153ret_length ++ ; 154p ++ ; 155 }else { 156ret_length ++ ; 157 } 158 } 159 160char * const ret = xmallocz (ret_length ); 161char * rp = ret ; 162inquote = false; 163for (const char * p = string ;p < string_end ;p ++ ) { 164if (* p == '"' ) { 165inquote = !inquote ; 166 }else if (ESCAPE_COND (p ,inquote ,string_end )) { 167* rp ++ = * (++ p ); 168 }else { 169* rp ++ = * p ; 170 } 171 } 172#undef ESCAPE_COND 173 174return ret ; 175} 176 177/// Escape "string" for use as a shell argument with system(). 178/// This uses single quotes, except when we know we need to use double quotes 179/// (MS-Windows without 'shellslash' set). 180/// Escape a newline, depending on the 'shell' option. 181/// When "do_special" is true also replace "!", "%", "#" and things starting 182/// with "<" like "<cfile>". 183/// When "do_newline" is false do not escape newline unless it is csh shell. 184/// 185/// @return the result in allocated memory. 186char * vim_strsave_shellescape (const char * string ,bool do_special ,bool do_newline ) 187FUNC_ATTR_NONNULL_RET FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_ALL 188{ 189size_t l ; 190 191// Only csh and similar shells expand '!' within single quotes. For sh and 192// the like we must not put a backslash before it, it will be taken 193// literally. If do_special is set the '!' will be escaped twice. 194// Csh also needs to have "\n" escaped twice when do_special is set. 195int csh_like = csh_like_shell (); 196 197// Fish shell uses '\' as an escape character within single quotes, so '\' 198// itself must be escaped to get a literal '\'. 199bool fish_like = fish_like_shell (); 200 201// First count the number of extra bytes required. 202size_t length = strlen (string )+ 3 ;// two quotes and a trailing NUL 203for (const char * p = string ;* p != NUL ;MB_PTR_ADV (p )) { 204#ifdef MSWIN 205if (!p_ssl ) { 206if (* p == '"' ) { 207length ++ ;// " -> "" 208 } 209 }else 210#endif 211if (* p == '\'' ) { 212length += 3 ;// ' => '\'' 213 } 214if ((* p == '\n' && (csh_like || do_newline )) 215|| (* p == '!' && (csh_like || do_special ))) { 216length ++ ;// insert backslash 217if (csh_like && do_special ) { 218length ++ ;// insert backslash 219 } 220 } 221if (do_special && find_cmdline_var (p ,& l ) >=0 ) { 222length ++ ;// insert backslash 223p += l - 1 ; 224 } 225if (* p == '\\' && fish_like ) { 226length ++ ;// insert backslash 227 } 228 } 229 230// Allocate memory for the result and fill it. 231char * escaped_string = xmalloc (length ); 232char * d = escaped_string ; 233 234// add opening quote 235#ifdef MSWIN 236if (!p_ssl ) { 237* d ++ = '"' ; 238 }else 239#endif 240* d ++ = '\'' ; 241 242for (const char * p = string ;* p != NUL ;) { 243#ifdef MSWIN 244if (!p_ssl ) { 245if (* p == '"' ) { 246* d ++ = '"' ; 247* d ++ = '"' ; 248p ++ ; 249continue ; 250 } 251 }else 252#endif 253if (* p == '\'' ) { 254* d ++ = '\'' ; 255* d ++ = '\\' ; 256* d ++ = '\'' ; 257* d ++ = '\'' ; 258p ++ ; 259continue ; 260 } 261if ((* p == '\n' && (csh_like || do_newline )) 262|| (* p == '!' && (csh_like || do_special ))) { 263* d ++ = '\\' ; 264if (csh_like && do_special ) { 265* d ++ = '\\' ; 266 } 267* d ++ = * p ++ ; 268continue ; 269 } 270if (do_special && find_cmdline_var (p ,& l ) >=0 ) { 271* d ++ = '\\' ;// insert backslash 272memcpy (d ,p ,l );// copy the var 273d += l ; 274p += l ; 275continue ; 276 } 277if (* p == '\\' && fish_like ) { 278* d ++ = '\\' ; 279* d ++ = * p ++ ; 280continue ; 281 } 282 283mb_copy_char (& p ,& d ); 284 } 285 286// add terminating quote and finish with a NUL 287#ifdef MSWIN 288if (!p_ssl ) { 289* d ++ = '"' ; 290 }else 291#endif 292* d ++ = '\'' ; 293* d = NUL ; 294 295return escaped_string ; 296} 297 298// Like vim_strsave(), but make all characters uppercase. 299// This uses ASCII lower-to-upper case translation, language independent. 300char * vim_strsave_up (const char * string ) 301FUNC_ATTR_NONNULL_RET FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_ALL 302{ 303char * p1 = xmalloc (strlen (string )+ 1 ); 304vim_strcpy_up (p1 ,string ); 305return p1 ; 306} 307 308/// Like xstrnsave(), but make all characters uppercase. 309/// This uses ASCII lower-to-upper case translation, language independent. 310char * vim_strnsave_up (const char * string ,size_t len ) 311FUNC_ATTR_NONNULL_RET FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_ALL 312{ 313char * p1 = xmalloc (len + 1 ); 314vim_strncpy_up (p1 ,string ,len ); 315return p1 ; 316} 317 318// ASCII lower-to-upper case translation, language independent. 319void vim_strup (char * p ) 320FUNC_ATTR_NONNULL_ALL 321{ 322uint8_t c ; 323while ((c = (uint8_t )(* p ))!= NUL ) { 324* p ++ = (char )(uint8_t )(c < 'a' || c > 'z' ?c :c - 0x20 ); 325 } 326} 327 328// strcpy plus vim_strup. 329void vim_strcpy_up (char * restrictdst ,const char * restrictsrc ) 330FUNC_ATTR_NONNULL_ALL 331{ 332uint8_t c ; 333while ((c = (uint8_t )(* src ++ ))!= NUL ) { 334* dst ++ = (char )(uint8_t )(c < 'a' || c > 'z' ?c :c - 0x20 ); 335 } 336* dst = NUL ; 337} 338 339// strncpy (NUL-terminated) plus vim_strup. 340void vim_strncpy_up (char * restrictdst ,const char * restrictsrc ,size_t n ) 341FUNC_ATTR_NONNULL_ALL 342{ 343uint8_t c ; 344while (n -- && (c = (uint8_t )(* src ++ ))!= NUL ) { 345* dst ++ = (char )(uint8_t )(c < 'a' || c > 'z' ?c :c - 0x20 ); 346 } 347* dst = NUL ; 348} 349 350// memcpy (does not NUL-terminate) plus vim_strup. 351void vim_memcpy_up (char * restrictdst ,const char * restrictsrc ,size_t n ) 352FUNC_ATTR_NONNULL_ALL 353{ 354uint8_t c ; 355while (n -- ) { 356c = (uint8_t )(* src ++ ); 357* dst ++ = (char )(uint8_t )(c < 'a' || c > 'z' ?c :c - 0x20 ); 358 } 359} 360 361/// Multi-byte uppercase `src` into `dst`. `dst` must have room for the result. 362/// In the worst case, the uppercased form needs `strlen(src) * MB_MAXBYTES` bytes plus NUL. 363/// 364/// @return number of bytes written to `dst`, not including the NUL terminator. 365size_t mb_strup_buf (const char * src ,char * dst ) 366FUNC_ATTR_NONNULL_ALL 367{ 368size_t i = 0 ; 369for (const char * p = src ;* p != NUL ;) { 370CharInfo ci = utf_ptr2CharInfo (p ); 371int c = ci .value < 0 ? (uint8_t )(* p ) :ci .value ; 372i += (size_t )utf_char2bytes (mb_toupper (c ),dst + i ); 373p += ci .len ; 374 } 375dst [i ]= NUL ; 376return i ; 377} 378 379/// Make given string all upper-case or all lower-case 380/// 381/// Handles multi-byte characters as good as possible. 382/// 383/// @param[in] orig Input string. 384/// @param[in] upper If true make uppercase, otherwise lowercase 385/// 386/// @return [allocated] upper-cased string. 387char * strcase_save (const char * const orig ,bool upper ) 388FUNC_ATTR_NONNULL_RET FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_ALL 389{ 390// Calculate the initial length and allocate memory for the result 391size_t orig_len = strlen (orig ); 392// +1 for the null terminator 393char * res = xmalloc (orig_len + 1 ); 394// Index in the result string 395size_t res_index = 0 ; 396// Current position in the original string 397const char * p = orig ; 398 399while (* p != NUL ) { 400CharInfo char_info = utf_ptr2CharInfo (p ); 401int c = char_info .value < 0 ? (uint8_t )(* p ) :char_info .value ; 402int newc = upper ?mb_toupper (c ) :mb_tolower (c ); 403// Cast to size_t to avoid mixing types in arithmetic 404size_t newl = (size_t )utf_char2len (newc ); 405 406// Check if there's enough space in the allocated memory 407if (res_index + newl > orig_len ) { 408// Need more space: allocate extra space for the new character and the null terminator 409size_t new_size = res_index + newl + 1 ; 410res = xrealloc (res ,new_size ); 411// Adjust the original length to the new size, minus the null terminator 412orig_len = new_size - 1 ; 413 } 414 415// Write the possibly new character into the result string 416utf_char2bytes (newc ,res + res_index ); 417// Move the index in the result string 418res_index += newl ; 419// Move to the next character in the original string 420p += char_info .len ; 421 } 422 423// Null-terminate the result string 424res [res_index ]= NUL ; 425return res ; 426} 427 428// delete spaces at the end of a string 429void del_trailing_spaces (char * ptr ) 430FUNC_ATTR_NONNULL_ALL 431{ 432char * q = ptr + strlen (ptr ); 433while (-- q > ptr && ascii_iswhite (q [0 ])&& q [-1 ]!= '\\' && q [-1 ]!= Ctrl_V ) { 434* q = NUL ; 435 } 436} 437 438#if (!defined(HAVE_STRCASECMP )&& !defined(HAVE_STRICMP )) 439// Compare two strings, ignoring case, using current locale. 440// Doesn't work for multi-byte characters. 441// return 0 for match, < 0 for smaller, > 0 for bigger 442int vim_stricmp (const char * s1 ,const char * s2 ) 443FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE 444{ 445int i ; 446 447while (true) { 448i = (int )TOLOWER_LOC ((uint8_t )(* s1 ))- (int )TOLOWER_LOC ((uint8_t )(* s2 )); 449if (i != 0 ) { 450return i ;// this character different 451 } 452if (* s1 == NUL ) { 453break ;// strings match until NUL 454 } 455s1 ++ ; 456s2 ++ ; 457 } 458return 0 ;// strings match 459} 460#endif 461 462#if (!defined(HAVE_STRNCASECMP )&& !defined(HAVE_STRNICMP )) 463// Compare two strings, for length "len", ignoring case, using current locale. 464// Doesn't work for multi-byte characters. 465// return 0 for match, < 0 for smaller, > 0 for bigger 466int vim_strnicmp (const char * s1 ,const char * s2 ,size_t len ) 467FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE 468{ 469int i ; 470 471while (len > 0 ) { 472i = (int )TOLOWER_LOC ((uint8_t )(* s1 ))- (int )TOLOWER_LOC ((uint8_t )(* s2 )); 473if (i != 0 ) { 474return i ;// this character different 475 } 476if (* s1 == NUL ) { 477break ;// strings match until NUL 478 } 479s1 ++ ; 480s2 ++ ; 481len -- ; 482 } 483return 0 ;// strings match 484} 485#endif 486 487/// Case-insensitive `strequal`. 488bool striequal (const char * a ,const char * b ) 489FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT 490{ 491return (a == NULL && b == NULL )|| (a && b && STRICMP (a ,b )== 0 ); 492} 493 494/// Compare two ASCII strings, for length "len", ignoring case, ignoring locale. 495/// 496/// @return 0 for match, < 0 for smaller, > 0 for bigger 497int vim_strnicmp_asc (const char * s1 ,const char * s2 ,size_t len ) 498FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT 499{ 500int i = 0 ; 501while (len > 0 ) { 502i = TOLOWER_ASC (* s1 )- TOLOWER_ASC (* s2 ); 503if (i != 0 ) { 504break ;// this character is different 505 } 506if (* s1 == NUL ) { 507break ;// strings match until NUL 508 } 509s1 ++ ; 510s2 ++ ; 511len -- ; 512 } 513return i ; 514} 515 516/// strchr() version which handles multibyte strings 517/// 518/// @param[in] string String to search in. 519/// @param[in] c Character to search for. 520/// 521/// @return Pointer to the first byte of the found character in string or NULL 522/// if it was not found or character is invalid. NUL character is never 523/// found, use `strlen()` instead. 524char * vim_strchr (const char * const string ,const int c ) 525FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT 526{ 527if (c <=0 ) { 528return NULL ; 529 }else if (c < 0x80 ) { 530// NOLINTNEXTLINE(*-casting): remove once CI uses glibc 2.43 531return (char * )strchr (string ,c ); 532 }else { 533char u8char [MB_MAXBYTES + 1 ]; 534const int len = utf_char2bytes (c ,u8char ); 535u8char [len ]= NUL ; 536// NOLINTNEXTLINE(*-casting): remove once CI uses glibc 2.43 537return (char * )strstr (string ,u8char ); 538 } 539} 540 541// Sort an array of strings. 542 543static int sort_compare (const void * s1 ,const void * s2 ) 544FUNC_ATTR_NONNULL_ALL 545{ 546return strcmp (* (char ** )s1 ,* (char ** )s2 ); 547} 548 549void sort_strings (char ** files ,int count ) 550{ 551qsort ((void * )files , (size_t )count ,sizeof (char * ),sort_compare ); 552} 553 554// Return true if string "s" contains a non-ASCII character (128 or higher). 555// When "s" is NULL false is returned. 556bool has_non_ascii (const char * s ) 557FUNC_ATTR_PURE 558{ 559if (s != NULL ) { 560for (const char * p = s ;* p != NUL ;p ++ ) { 561if ((uint8_t )(* p ) >=128 ) { 562return true; 563 } 564 } 565 } 566return false; 567} 568 569/// Return true if string "s" contains a non-ASCII character (128 or higher). 570/// When "s" is NULL false is returned. 571bool has_non_ascii_len (const char * const s ,const size_t len ) 572FUNC_ATTR_PURE 573{ 574if (s != NULL ) { 575for (size_t i = 0 ;i < len ;i ++ ) { 576if ((uint8_t )s [i ] >=128 ) { 577return true; 578 } 579 } 580 } 581return false; 582} 583 584/// Concatenate two strings and return the result in allocated memory. 585char * concat_str (const char * restrictstr1 ,const char * restrictstr2 ) 586FUNC_ATTR_NONNULL_RET FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_ALL 587{ 588size_t l = strlen (str1 ); 589char * dest = xmalloc (l + strlen (str2 )+ 1 ); 590STRCPY (dest ,str1 ); 591STRCPY (dest + l ,str2 ); 592return dest ; 593} 594 595static const char * const e_printf = 596N_ ("E766: Insufficient arguments for printf()" ); 597 598/// Get number argument from idxp entry in tvs 599/// 600/// Will give an error message for Vimscript entry with invalid type or for insufficient entries. 601/// 602/// @param[in] tvs List of Vimscript values. List is terminated by VAR_UNKNOWN value. 603/// @param[in,out] idxp Index in a list. Will be incremented. Indexing starts at 1. 604/// 605/// @return Number value or 0 in case of error. 606static varnumber_T tv_nr (typval_T * tvs ,int * idxp ) 607FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT 608{ 609int idx = * idxp - 1 ; 610varnumber_T n = 0 ; 611 612if (tvs [idx ].v_type == VAR_UNKNOWN ) { 613emsg (_ (e_printf )); 614 }else { 615 (* idxp )++ ; 616bool err = false; 617n = tv_get_number_chk (& tvs [idx ],& err ); 618if (err ) { 619n = 0 ; 620 } 621 } 622return n ; 623} 624 625/// Get string argument from idxp entry in tvs 626/// 627/// Will give an error message for Vimscript entry with invalid type or for 628/// insufficient entries. 629/// 630/// @param[in] tvs List of Vimscript values. List is terminated by VAR_UNKNOWN 631/// value. 632/// @param[in,out] idxp Index in a list. Will be incremented. 633/// @param[out] tofree If the idxp entry in tvs is not a String or a Number, 634/// it will be converted to String in the same format 635/// as ":echo" and stored in "*tofree". The caller must 636/// free "*tofree". 637/// 638/// @return String value or NULL in case of error. 639static const char * tv_str (typval_T * tvs ,int * idxp ,char ** const tofree ) 640FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT 641{ 642int idx = * idxp - 1 ; 643const char * s = NULL ; 644 645if (tvs [idx ].v_type == VAR_UNKNOWN ) { 646emsg (_ (e_printf )); 647 }else { 648 (* idxp )++ ; 649if (tvs [idx ].v_type == VAR_STRING || tvs [idx ].v_type == VAR_NUMBER ) { 650s = tv_get_string_chk (& tvs [idx ]); 651* tofree = NULL ; 652 }else { 653s = * tofree = encode_tv2echo (& tvs [idx ],NULL ); 654 } 655 } 656return s ; 657} 658 659/// Get pointer argument from the next entry in tvs 660/// 661/// Will give an error message for Vimscript entry with invalid type or for 662/// insufficient entries. 663/// 664/// @param[in] tvs List of typval_T values. 665/// @param[in,out] idxp Pointer to the index of the current value. 666/// 667/// @return Pointer stored in typval_T or NULL. 668static const void * tv_ptr (const typval_T * const tvs ,int * const idxp ) 669FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT 670{ 671#define OFF (attr ) offsetof(union typval_vval_union, attr) 672STATIC_ASSERT (OFF (v_string )== OFF (v_list ) 673&& OFF (v_string )== OFF (v_dict ) 674&& OFF (v_string )== OFF (v_blob ) 675&& OFF (v_string )== OFF (v_partial ) 676&& sizeof (tvs [0 ].vval .v_string )== sizeof (tvs [0 ].vval .v_list ) 677&& sizeof (tvs [0 ].vval .v_string )== sizeof (tvs [0 ].vval .v_dict ) 678&& sizeof (tvs [0 ].vval .v_string )== sizeof (tvs [0 ].vval .v_blob ) 679&& sizeof (tvs [0 ].vval .v_string )== sizeof (tvs [0 ].vval .v_partial ), 680"Strings, Dictionaries, Lists, Blobs and Partials are expected to be pointers, " 681"so that all of them can be accessed via v_string" ); 682#undef OFF 683const int idx = * idxp - 1 ; 684if (tvs [idx ].v_type == VAR_UNKNOWN ) { 685emsg (_ (e_printf )); 686return NULL ; 687 } 688 (* idxp )++ ; 689return tvs [idx ].vval .v_string ; 690} 691 692/// Get float argument from idxp entry in tvs 693/// 694/// Will give an error message for Vimscript entry with invalid type or for 695/// insufficient entries. 696/// 697/// @param[in] tvs List of Vimscript values. List is terminated by VAR_UNKNOWN value. 698/// @param[in,out] idxp Index in a list. Will be incremented. 699/// 700/// @return Floating-point value or zero in case of error. 701static float_T tv_float (typval_T * const tvs ,int * const idxp ) 702FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT 703{ 704int idx = * idxp - 1 ; 705float_T f = 0 ; 706 707if (tvs [idx ].v_type == VAR_UNKNOWN ) { 708emsg (_ (e_printf )); 709 }else { 710 (* idxp )++ ; 711if (tvs [idx ].v_type == VAR_FLOAT ) { 712f = tvs [idx ].vval .v_float ; 713 }else if (tvs [idx ].v_type == VAR_NUMBER ) { 714f = (float_T )tvs [idx ].vval .v_number ; 715 }else { 716emsg (_ ("E807: Expected Float argument for printf()" )); 717 } 718 } 719return f ; 720} 721 722// This code was included to provide a portable vsnprintf() and snprintf(). 723// Some systems may provide their own, but we always use this one for 724// consistency. 725// 726// This code is based on snprintf.c - a portable implementation of snprintf 727// by Mark Martinec <mark.martinec@ijs.si>, Version 2.2, 2000-10-06. 728// Included with permission. It was heavily modified to fit in Vim. 729// The original code, including useful comments, can be found here: 730// 731// http://www.ijs.si/software/snprintf/ 732// 733// This snprintf() only supports the following conversion specifiers: 734// s, c, b, B, d, u, o, x, X, p (and synonyms: i, D, U, O - see below) 735// with flags: '-', '+', ' ', '0' and '#'. 736// An asterisk is supported for field width as well as precision. 737// 738// Limited support for floating point was added: 'f', 'e', 'E', 'g', 'G'. 739// 740// Length modifiers 'h' (short int), 'l' (long int) and "ll" (long long int) are 741// supported. 742// 743// The locale is not used, the string is used as a byte string. This is only 744// relevant for double-byte encodings where the second byte may be '%'. 745// 746// It is permitted for "str_m" to be zero, and it is permitted to specify NULL 747// pointer for resulting string argument if "str_m" is zero (as per ISO C99). 748// 749// The return value is the number of characters which would be generated 750// for the given input, excluding the trailing NUL. If this value 751// is greater or equal to "str_m", not all characters from the result 752// have been stored in str, output bytes beyond the ("str_m"-1) -th character 753// are discarded. If "str_m" is greater than zero it is guaranteed 754// the resulting string will be NUL-terminated. 755 756// vim_vsnprintf_typval() can be invoked with either "va_list" or a list of 757// "typval_T". When the latter is not used it must be NULL. 758 759/// Append a formatted value to the string 760/// 761/// @see vim_vsnprintf_typval(). 762int vim_snprintf_add (char * str ,size_t str_m ,const char * fmt , ...) 763FUNC_ATTR_PRINTF (3 ,4 ) 764{ 765const size_t len = strlen (str ); 766size_t space ; 767 768if (str_m <=len ) { 769space = 0 ; 770 }else { 771space = str_m - len ; 772 } 773va_list ap ; 774va_start (ap ,fmt ); 775const int str_l = vim_vsnprintf (str + len ,space ,fmt ,ap ); 776va_end (ap ); 777return str_l ; 778} 779 780/// Write formatted value to the string 781/// 782/// @param[out] str String to write to. 783/// @param[in] str_m String length. 784/// @param[in] fmt String format. 785/// 786/// @return Number of bytes excluding NUL byte that would be written to the 787/// string if str_m was greater or equal to the return value. 788int vim_snprintf (char * str ,size_t str_m ,const char * fmt , ...) 789FUNC_ATTR_PRINTF (3 ,4 ) 790{ 791va_list ap ; 792va_start (ap ,fmt ); 793const int str_l = vim_vsnprintf (str ,str_m ,fmt ,ap ); 794va_end (ap ); 795return str_l ; 796} 797 798// Return the representation of infinity for printf() function: 799// "-inf", "inf", "+inf", " inf", "-INF", "INF", "+INF" or " INF". 800static const char * infinity_str (bool positive ,char fmt_spec ,int force_sign , 801int space_for_positive ) 802{ 803static const char * table []= { 804"-inf" ,"inf" ,"+inf" ," inf" , 805"-INF" ,"INF" ,"+INF" ," INF" 806 }; 807int idx = positive * (1 + force_sign + force_sign * space_for_positive ); 808if (ASCII_ISUPPER (fmt_spec )) { 809idx += 4 ; 810 } 811return table [idx ]; 812} 813 814/// Like vim_snprintf() except the return value can be safely used to increment a 815/// buffer length. 816/// Normal `snprintf()` (and `vim_snprintf()`) returns the number of bytes that 817/// would have been copied if the destination buffer was large enough. 818/// This means that you cannot rely on it's return value for the destination 819/// length because the destination may be shorter than the source. This function 820/// guarantees the returned length will never be greater than the destination length. 821size_t vim_snprintf_safelen (char * str ,size_t str_m ,const char * fmt , ...) 822{ 823va_list ap ; 824int str_l ; 825 826if (str_m == 0 ) { 827return 0 ; 828 } 829 830va_start (ap ,fmt ); 831str_l = vim_vsnprintf_typval (str ,str_m ,fmt ,ap ,NULL ); 832va_end (ap ); 833 834if (str_l < 0 ) { 835* str = NUL ; 836return 0 ; 837 } 838return ((size_t )str_l >=str_m ) ?str_m - 1 : (size_t )str_l ; 839} 840 841int vim_vsnprintf (char * str ,size_t str_m ,const char * fmt ,va_list ap ) 842{ 843return vim_vsnprintf_typval (str ,str_m ,fmt ,ap ,NULL ); 844} 845 846enum { 847TYPE_UNKNOWN = -1 , 848TYPE_INT , 849TYPE_LONGINT , 850TYPE_LONGLONGINT , 851TYPE_SIGNEDSIZET , 852TYPE_UNSIGNEDINT , 853TYPE_UNSIGNEDLONGINT , 854TYPE_UNSIGNEDLONGLONGINT , 855TYPE_SIZET , 856TYPE_POINTER , 857TYPE_PERCENT , 858TYPE_CHAR , 859TYPE_STRING , 860TYPE_FLOAT , 861}; 862 863/// Types that can be used in a format string 864static int format_typeof (const char * type ) 865FUNC_ATTR_NONNULL_ALL 866{ 867// allowed values: \0, h, l, L 868char length_modifier = NUL ; 869 870// current conversion specifier character 871char fmt_spec = NUL ; 872 873// parse 'h', 'l', 'll' and 'z' length modifiers 874if (* type == 'h' || * type == 'l' || * type == 'z' ) { 875length_modifier = * type ; 876type ++ ; 877if (length_modifier == 'l' && * type == 'l' ) { 878// double l = long long 879length_modifier = 'L' ; 880type ++ ; 881 } 882 } 883fmt_spec = * type ; 884 885// common synonyms: 886switch (fmt_spec ) { 887case 'i' : 888fmt_spec = 'd' ;break ; 889case '*' : 890fmt_spec = 'd' ;length_modifier = 'h' ;break ; 891case 'D' : 892fmt_spec = 'd' ;length_modifier = 'l' ;break ; 893case 'U' : 894fmt_spec = 'u' ;length_modifier = 'l' ;break ; 895case 'O' : 896fmt_spec = 'o' ;length_modifier = 'l' ;break ; 897default : 898break ; 899 } 900 901// get parameter value, do initial processing 902switch (fmt_spec ) { 903// '%' and 'c' behave similar to 's' regarding flags and field 904// widths 905case '%' : 906return TYPE_PERCENT ; 907 908case 'c' : 909return TYPE_CHAR ; 910 911case 's' : 912case 'S' : 913return TYPE_STRING ; 914 915case 'd' : 916case 'u' : 917case 'b' : 918case 'B' : 919case 'o' : 920case 'x' : 921case 'X' : 922case 'p' : 923// NOTE: the u, b, o, x, X and p conversion specifiers 924// imply the value is unsigned; d implies a signed 925// value 926 927// 0 if numeric argument is zero (or if pointer is 928// NULL for 'p'), +1 if greater than zero (or nonzero 929// for unsigned arguments), -1 if negative (unsigned 930// argument is never negative) 931 932if (fmt_spec == 'p' ) { 933return TYPE_POINTER ; 934 }else if (fmt_spec == 'b' || fmt_spec == 'B' ) { 935return TYPE_UNSIGNEDLONGLONGINT ; 936 }else if (fmt_spec == 'd' ) { 937// signed 938switch (length_modifier ) { 939case NUL : 940case 'h' : 941// char and short arguments are passed as int. 942return TYPE_INT ; 943case 'l' : 944return TYPE_LONGINT ; 945case 'L' : 946return TYPE_LONGLONGINT ; 947case 'z' : 948return TYPE_SIGNEDSIZET ; 949 } 950 }else { 951// unsigned 952switch (length_modifier ) { 953case NUL : 954case 'h' : 955return TYPE_UNSIGNEDINT ; 956case 'l' : 957return TYPE_UNSIGNEDLONGINT ; 958case 'L' : 959return TYPE_UNSIGNEDLONGLONGINT ; 960case 'z' : 961return TYPE_SIZET ; 962 } 963 } 964break ; 965 966case 'f' : 967case 'F' : 968case 'e' : 969case 'E' : 970case 'g' : 971case 'G' : 972return TYPE_FLOAT ; 973 } 974 975return TYPE_UNKNOWN ; 976} 977 978static const char * format_typename (const char * type ) 979FUNC_ATTR_NONNULL_ALL 980{ 981switch (format_typeof (type )) { 982case TYPE_INT : 983return typename_int ; 984case TYPE_LONGINT : 985return typename_longint ; 986case TYPE_LONGLONGINT : 987return typename_longlongint ; 988case TYPE_UNSIGNEDINT : 989return typename_unsignedint ; 990case TYPE_SIGNEDSIZET : 991return typename_signedsizet ; 992case TYPE_UNSIGNEDLONGINT : 993return typename_unsignedlongint ; 994case TYPE_UNSIGNEDLONGLONGINT : 995return typename_unsignedlonglongint ; 996case TYPE_SIZET : 997return typename_sizet ; 998case TYPE_POINTER : 999return _ (typename_pointer ); 1000case TYPE_PERCENT : 1001return _ (typename_percent ); 1002case TYPE_CHAR : 1003return typename_char ; 1004case TYPE_STRING : 1005return _ (typename_string ); 1006case TYPE_FLOAT : 1007return typename_float ; 1008 } 1009 1010return _ (typename_unknown ); 1011} 1012 1013static int adjust_types (const char *** ap_types ,int arg ,int * num_posarg ,const char * type ) 1014FUNC_ATTR_NONNULL_ALL 1015{ 1016if (arg <=0 ) { 1017semsg (_ (e_invalid_format_specifier_str ),type ); 1018return FAIL ; 1019 } 1020 1021if (* ap_types == NULL || * num_posarg < arg ) { 1022const char ** new_types = * ap_types == NULL 1023 ?xcalloc ((size_t )arg ,sizeof (const char * )) 1024 :xrealloc (* ap_types , (size_t )arg * sizeof (const char * )); 1025 1026for (int idx = * num_posarg ;idx < arg ;idx ++ ) { 1027new_types [idx ]= NULL ; 1028 } 1029 1030* ap_types = new_types ; 1031* num_posarg = arg ; 1032 } 1033 1034if ((* ap_types )[arg - 1 ]!= NULL ) { 1035if ((* ap_types )[arg - 1 ][0 ]== '*' || type [0 ]== '*' ) { 1036const char * pt = type ; 1037if (pt [0 ]== '*' ) { 1038pt = (* ap_types )[arg - 1 ]; 1039 } 1040 1041if (pt [0 ]!= '*' ) { 1042switch (pt [0 ]) { 1043case 'd' : 1044case 'i' : 1045break ; 1046default : 1047semsg (_ (e_positional_num_field_spec_reused_str_str ),arg , 1048format_typename ((* ap_types )[arg - 1 ]),format_typename (type )); 1049return FAIL ; 1050 } 1051 } 1052 }else { 1053if (format_typeof (type )!= format_typeof ((* ap_types )[arg - 1 ])) { 1054semsg (_ (e_positional_arg_num_type_inconsistent_str_str ),arg , 1055format_typename (type ),format_typename ((* ap_types )[arg - 1 ])); 1056return FAIL ; 1057 } 1058 } 1059 } 1060 1061 (* ap_types )[arg - 1 ]= type ; 1062 1063return OK ; 1064} 1065 1066static void format_overflow_error (const char * pstart ) 1067{ 1068const char * p = pstart ; 1069 1070while (ascii_isdigit ((int )(* p ))) { 1071p ++ ; 1072 } 1073 1074semsg (_ (e_val_too_large_len ), (int )(p - pstart ),pstart ); 1075} 1076 1077enum {MAX_ALLOWED_STRING_WIDTH = 1048576 , };// 1MiB 1078 1079static int get_unsigned_int (const char * pstart ,const char ** p ,unsigned * uj ,bool overflow_err ) 1080{ 1081* uj = (unsigned )(** p - '0' ); 1082 (* p )++ ; 1083 1084while (ascii_isdigit ((int )(** p ))&& * uj < MAX_ALLOWED_STRING_WIDTH ) { 1085* uj = 10 * * uj + (unsigned )(** p - '0' ); 1086 (* p )++ ; 1087 } 1088 1089if (* uj > MAX_ALLOWED_STRING_WIDTH ) { 1090if (overflow_err ) { 1091format_overflow_error (pstart ); 1092return FAIL ; 1093 }else { 1094* uj = MAX_ALLOWED_STRING_WIDTH ; 1095 } 1096 } 1097 1098return OK ; 1099} 1100 1101static int parse_fmt_types (const char *** ap_types ,int * num_posarg ,const char * fmt ,typval_T * tvs ) 1102FUNC_ATTR_NONNULL_ARG (1 ,2 ) 1103{ 1104const char * p = fmt ; 1105const char * arg = NULL ; 1106 1107int any_pos = 0 ; 1108int any_arg = 0 ; 1109 1110#define CHECK_POS_ARG \ 1111 do { \ 1112 if (any_pos && any_arg) { \ 1113 semsg(_(e_cannot_mix_positional_and_non_positional_str), fmt); \ 1114 goto error; \ 1115 } \ 1116 } while (0); 1117 1118if (p == NULL ) { 1119return OK ; 1120 } 1121 1122while (* p != NUL ) { 1123if (* p != '%' ) { 1124size_t n = (size_t )(xstrchrnul (p + 1 ,'%' )- p ); 1125p += n ; 1126 }else { 1127// allowed values: \0, h, l, L 1128char length_modifier = NUL ; 1129 1130// variable for positional arg 1131int pos_arg = -1 ; 1132const char * pstart = p + 1 ; 1133 1134p ++ ;// skip '%' 1135 1136// First check to see if we find a positional 1137// argument specifier 1138const char * ptype = p ; 1139 1140while (ascii_isdigit (* ptype )) { 1141ptype ++ ; 1142 } 1143 1144if (* ptype == '$' ) { 1145if (* p == '0' ) { 1146// 0 flag at the wrong place 1147semsg (_ (e_invalid_format_specifier_str ),fmt ); 1148 gotoerror ; 1149 } 1150 1151// Positional argument 1152unsigned uj ; 1153 1154if (get_unsigned_int (pstart ,& p ,& uj ,tvs != NULL )== FAIL ) { 1155 gotoerror ; 1156 } 1157 1158pos_arg = (int )uj ; 1159 1160any_pos = 1 ; 1161CHECK_POS_ARG ; 1162 1163p ++ ; 1164 } 1165 1166// parse flags 1167while (* p == '0' || * p == '-' || * p == '+' || * p == ' ' 1168|| * p == '#' || * p == '\'' ) { 1169switch (* p ) { 1170case '0' : 1171break ; 1172case '-' : 1173break ; 1174case '+' : 1175break ; 1176case ' ' :// If both the ' ' and '+' flags appear, the ' ' 1177// flag should be ignored 1178break ; 1179case '#' : 1180break ; 1181case '\'' : 1182break ; 1183 } 1184p ++ ; 1185 } 1186// If the '0' and '-' flags both appear, the '0' flag should be 1187// ignored. 1188 1189// parse field width 1190if (* (arg = p )== '*' ) { 1191p ++ ; 1192 1193if (ascii_isdigit ((int )(* p ))) { 1194// Positional argument field width 1195unsigned uj ; 1196 1197if (get_unsigned_int (arg + 1 ,& p ,& uj ,tvs != NULL )== FAIL ) { 1198 gotoerror ; 1199 } 1200 1201if (* p != '$' ) { 1202semsg (_ (e_invalid_format_specifier_str ),fmt ); 1203 gotoerror ; 1204 }else { 1205p ++ ; 1206any_pos = 1 ; 1207CHECK_POS_ARG ; 1208 1209if (adjust_types (ap_types , (int )uj ,num_posarg ,arg )== FAIL ) { 1210 gotoerror ; 1211 } 1212 } 1213 }else { 1214any_arg = 1 ; 1215CHECK_POS_ARG ; 1216 } 1217 }else if (ascii_isdigit ((int )(* p ))) { 1218// size_t could be wider than unsigned int; make sure we treat 1219// argument like common implementations do 1220const char * digstart = p ; 1221unsigned uj ; 1222 1223if (get_unsigned_int (digstart ,& p ,& uj ,tvs != NULL )== FAIL ) { 1224 gotoerror ; 1225 } 1226 1227if (* p == '$' ) { 1228semsg (_ (e_invalid_format_specifier_str ),fmt ); 1229 gotoerror ; 1230 } 1231 } 1232 1233// parse precision 1234if (* p == '.' ) { 1235p ++ ; 1236 1237if (* (arg = p )== '*' ) { 1238p ++ ; 1239 1240if (ascii_isdigit ((int )(* p ))) { 1241// Parse precision 1242unsigned uj ; 1243 1244if (get_unsigned_int (arg + 1 ,& p ,& uj ,tvs != NULL )== FAIL ) { 1245 gotoerror ; 1246 } 1247 1248if (* p == '$' ) { 1249any_pos = 1 ; 1250CHECK_POS_ARG ; 1251 1252p ++ ; 1253 1254if (adjust_types (ap_types , (int )uj ,num_posarg ,arg )== FAIL ) { 1255 gotoerror ; 1256 } 1257 }else { 1258semsg (_ (e_invalid_format_specifier_str ),fmt ); 1259 gotoerror ; 1260 } 1261 }else { 1262any_arg = 1 ; 1263CHECK_POS_ARG ; 1264 } 1265 }else if (ascii_isdigit ((int )(* p ))) { 1266// size_t could be wider than unsigned int; make sure we 1267// treat argument like common implementations do 1268const char * digstart = p ; 1269unsigned uj ; 1270 1271if (get_unsigned_int (digstart ,& p ,& uj ,tvs != NULL )== FAIL ) { 1272 gotoerror ; 1273 } 1274 1275if (* p == '$' ) { 1276semsg (_ (e_invalid_format_specifier_str ),fmt ); 1277 gotoerror ; 1278 } 1279 } 1280 } 1281 1282if (pos_arg != -1 ) { 1283any_pos = 1 ; 1284CHECK_POS_ARG ; 1285 1286ptype = p ; 1287 } 1288 1289// parse 'h', 'l', 'll' and 'z' length modifiers 1290if (* p == 'h' || * p == 'l' || * p == 'z' ) { 1291length_modifier = * p ; 1292p ++ ; 1293if (length_modifier == 'l' && * p == 'l' ) { 1294// double l = long long 1295// length_modifier = 'L'; 1296p ++ ; 1297 } 1298 } 1299 1300switch (* p ) { 1301// Check for known format specifiers. % is special! 1302case 'i' : 1303case '*' : 1304case 'd' : 1305case 'u' : 1306case 'o' : 1307case 'D' : 1308case 'U' : 1309case 'O' : 1310case 'x' : 1311case 'X' : 1312case 'b' : 1313case 'B' : 1314case 'c' : 1315case 's' : 1316case 'S' : 1317case 'p' : 1318case 'f' : 1319case 'F' : 1320case 'e' : 1321case 'E' : 1322case 'g' : 1323case 'G' : 1324if (pos_arg != -1 ) { 1325if (adjust_types (ap_types ,pos_arg ,num_posarg ,ptype )== FAIL ) { 1326 gotoerror ; 1327 } 1328 }else { 1329any_arg = 1 ; 1330CHECK_POS_ARG ; 1331 } 1332break ; 1333 1334default : 1335if (pos_arg != -1 ) { 1336semsg (_ (e_cannot_mix_positional_and_non_positional_str ),fmt ); 1337 gotoerror ; 1338 } 1339 } 1340 1341if (* p != NUL ) { 1342p ++ ;// step over the just processed conversion specifier 1343 } 1344 } 1345 } 1346 1347for (int arg_idx = 0 ;arg_idx < * num_posarg ;arg_idx ++ ) { 1348if ((* ap_types )[arg_idx ]== NULL ) { 1349semsg (_ (e_fmt_arg_nr_unused_str ),arg_idx + 1 ,fmt ); 1350 gotoerror ; 1351 } 1352 1353if (tvs != NULL && tvs [arg_idx ].v_type == VAR_UNKNOWN ) { 1354semsg (_ (e_positional_nr_out_of_bounds_str ),arg_idx + 1 ,fmt ); 1355 gotoerror ; 1356 } 1357 } 1358 1359return OK ; 1360 1361error : 1362xfree (* ap_types ); 1363* ap_types = NULL ; 1364* num_posarg = 0 ; 1365return FAIL ; 1366} 1367 1368static void skip_to_arg (const char ** ap_types ,va_list ap_start ,va_list * ap ,int * arg_idx , 1369int * arg_cur ,const char * fmt ) 1370FUNC_ATTR_NONNULL_ARG (3 ,4 ,5 ) 1371{ 1372int arg_min = 0 ; 1373 1374if (* arg_cur + 1 == * arg_idx ) { 1375 (* arg_cur )++ ; 1376 (* arg_idx )++ ; 1377return ; 1378 } 1379 1380if (* arg_cur >=* arg_idx ) { 1381// Reset ap to ap_start and skip arg_idx - 1 types 1382va_end (* ap ); 1383va_copy (* ap ,ap_start ); 1384 }else { 1385// Skip over any we should skip 1386arg_min = * arg_cur ; 1387 } 1388 1389for (* arg_cur = arg_min ;* arg_cur < * arg_idx - 1 ; (* arg_cur )++ ) { 1390if (ap_types == NULL || ap_types [* arg_cur ]== NULL ) { 1391siemsg (e_aptypes_is_null_nr_str ,fmt ,* arg_cur ); 1392return ; 1393 } 1394 1395const char * p = ap_types [* arg_cur ]; 1396 1397int fmt_type = format_typeof (p ); 1398 1399// get parameter value, do initial processing 1400switch (fmt_type ) { 1401case TYPE_PERCENT : 1402case TYPE_UNKNOWN : 1403break ; 1404 1405case TYPE_CHAR : 1406va_arg (* ap ,int ); 1407break ; 1408 1409case TYPE_STRING : 1410va_arg (* ap ,const char * ); 1411break ; 1412 1413case TYPE_POINTER : 1414va_arg (* ap ,void * ); 1415break ; 1416 1417case TYPE_INT : 1418va_arg (* ap ,int ); 1419break ; 1420 1421case TYPE_LONGINT : 1422va_arg (* ap ,long ); 1423break ; 1424 1425case TYPE_LONGLONGINT : 1426va_arg (* ap ,long long );// NOLINT(runtime/int) 1427break ; 1428 1429case TYPE_SIGNEDSIZET :// implementation-defined, usually ptrdiff_t 1430va_arg (* ap ,ptrdiff_t ); 1431break ; 1432 1433case TYPE_UNSIGNEDINT : 1434va_arg (* ap ,unsigned ); 1435break ; 1436 1437case TYPE_UNSIGNEDLONGINT : 1438va_arg (* ap ,unsigned long ); 1439break ; 1440 1441case TYPE_UNSIGNEDLONGLONGINT : 1442va_arg (* ap ,unsigned long long);// NOLINT(runtime/int) 1443break ; 1444 1445case TYPE_SIZET : 1446va_arg (* ap ,size_t ); 1447break ; 1448 1449case TYPE_FLOAT : 1450va_arg (* ap ,double ); 1451break ; 1452 } 1453 } 1454 1455// Because we know that after we return from this call, 1456// a va_arg() call is made, we can pre-emptively 1457// increment the current argument index. 1458 (* arg_cur )++ ; 1459 (* arg_idx )++ ; 1460} 1461 1462/// Write formatted value to the string 1463/// 1464/// @param[out] str String to write to. 1465/// @param[in] str_m String length. 1466/// @param[in] fmt String format. 1467/// @param[in] ap Values that should be formatted. Ignored if tvs is not NULL. 1468/// @param[in] tvs Values that should be formatted, for printf() Vimscript 1469/// function. Must be NULL in other cases. 1470/// 1471/// @return Number of bytes excluding NUL byte that would be written to the 1472/// string if str_m was greater or equal to the return value. 1473int vim_vsnprintf_typval (char * str ,size_t str_m ,const char * fmt ,va_list ap_start , 1474typval_T * const tvs ) 1475{ 1476size_t str_l = 0 ; 1477bool str_avail = str_l < str_m ; 1478const char * p = fmt ; 1479int arg_cur = 0 ; 1480int num_posarg = 0 ; 1481int arg_idx = 1 ; 1482va_list ap ; 1483const char ** ap_types = NULL ; 1484 1485if (parse_fmt_types (& ap_types ,& num_posarg ,fmt ,tvs )== FAIL ) { 1486return 0 ; 1487 } 1488 1489va_copy (ap ,ap_start ); 1490 1491if (!p ) { 1492p = "" ; 1493 } 1494while (* p ) { 1495if (* p != '%' ) { 1496// copy up to the next '%' or NUL without any changes 1497size_t n = (size_t )(xstrchrnul (p + 1 ,'%' )- p ); 1498if (str_avail ) { 1499size_t avail = str_m - str_l ; 1500memmove (str + str_l ,p ,MIN (n ,avail )); 1501str_avail = n < avail ; 1502 } 1503p += n ; 1504assert (n <=SIZE_MAX - str_l ); 1505str_l += n ; 1506 }else { 1507size_t min_field_width = 0 ; 1508size_t precision = 0 ; 1509bool zero_padding = false; 1510bool precision_specified = false; 1511bool justify_left = false; 1512bool alternate_form = false; 1513bool force_sign = false; 1514 1515// if both ' ' and '+' flags appear, ' ' flag should be ignored 1516int space_for_positive = 1 ; 1517 1518// allowed values: \0, h, l, 2 (for ll), z, L 1519char length_modifier = NUL ; 1520 1521// temporary buffer for simple numeric->string conversion 1522#define TMP_LEN 350 // 1e308 seems reasonable as the maximum printable 1523char tmp [TMP_LEN ]; 1524 1525// string address in case of string argument 1526const char * str_arg = NULL ; 1527 1528// natural field width of arg without padding and sign 1529size_t str_arg_l ; 1530 1531// unsigned char argument value (only defined for c conversion); 1532// standard explicitly states the char argument for the c 1533// conversion is unsigned 1534unsigned char uchar_arg ; 1535 1536// number of zeros to be inserted for numeric conversions as 1537// required by the precision or minimal field width 1538size_t number_of_zeros_to_pad = 0 ; 1539 1540// index into tmp where zero padding is to be inserted 1541size_t zero_padding_insertion_ind = 0 ; 1542 1543// current conversion specifier character 1544char fmt_spec = NUL ; 1545 1546// buffer for 's' and 'S' specs 1547char * tofree = NULL ; 1548 1549// variable for positional arg 1550int pos_arg = -1 ; 1551 1552p ++ ;// skip '%' 1553 1554// First check to see if we find a positional 1555// argument specifier 1556const char * ptype = p ; 1557 1558while (ascii_isdigit (* ptype )) { 1559ptype ++ ; 1560 } 1561 1562if (* ptype == '$' ) { 1563// Positional argument 1564const char * digstart = p ; 1565unsigned uj ; 1566 1567if (get_unsigned_int (digstart ,& p ,& uj ,tvs != NULL )== FAIL ) { 1568 gotoerror ; 1569 } 1570 1571pos_arg = (int )uj ; 1572 1573p ++ ; 1574 } 1575 1576// parse flags 1577while (true) { 1578switch (* p ) { 1579case '0' : 1580zero_padding = true;p ++ ;continue ; 1581case '-' : 1582justify_left = true;p ++ ;continue ; 1583// if both '0' and '-' flags appear, '0' should be ignored 1584case '+' : 1585force_sign = true;space_for_positive = 0 ;p ++ ;continue ; 1586case ' ' : 1587force_sign = true;p ++ ;continue ; 1588// if both ' ' and '+' flags appear, ' ' should be ignored 1589case '#' : 1590alternate_form = true;p ++ ;continue ; 1591case '\'' : 1592p ++ ;continue ; 1593default : 1594break ; 1595 } 1596break ; 1597 } 1598 1599// parse field width 1600if (* p == '*' ) { 1601const char * digstart = p + 1 ; 1602 1603p ++ ; 1604 1605if (ascii_isdigit ((int )(* p ))) { 1606// Positional argument field width 1607unsigned uj ; 1608 1609if (get_unsigned_int (digstart ,& p ,& uj ,tvs != NULL )== FAIL ) { 1610 gotoerror ; 1611 } 1612 1613arg_idx = (int )uj ; 1614 1615p ++ ; 1616 } 1617 1618int j = (tvs 1619 ? (int )tv_nr (tvs ,& arg_idx ) 1620 : (skip_to_arg (ap_types ,ap_start ,& ap ,& arg_idx , 1621& arg_cur ,fmt ), 1622va_arg (ap ,int ))); 1623 1624if (j > MAX_ALLOWED_STRING_WIDTH ) { 1625if (tvs != NULL ) { 1626format_overflow_error (digstart ); 1627 gotoerror ; 1628 }else { 1629j = MAX_ALLOWED_STRING_WIDTH ; 1630 } 1631 } 1632 1633if (j >=0 ) { 1634min_field_width = (size_t )j ; 1635 }else { 1636min_field_width = (size_t )- j ; 1637justify_left = true; 1638 } 1639 }else if (ascii_isdigit ((int )(* p ))) { 1640// size_t could be wider than unsigned int; make sure we treat 1641// argument like common implementations do 1642const char * digstart = p ; 1643unsigned uj ; 1644 1645if (get_unsigned_int (digstart ,& p ,& uj ,tvs != NULL )== FAIL ) { 1646 gotoerror ; 1647 } 1648 1649min_field_width = uj ; 1650 } 1651 1652// parse precision 1653if (* p == '.' ) { 1654p ++ ; 1655precision_specified = true; 1656 1657if (ascii_isdigit ((int )(* p ))) { 1658// size_t could be wider than unsigned int; make sure we 1659// treat argument like common implementations do 1660const char * digstart = p ; 1661unsigned uj ; 1662 1663if (get_unsigned_int (digstart ,& p ,& uj ,tvs != NULL )== FAIL ) { 1664 gotoerror ; 1665 } 1666 1667precision = uj ; 1668 }else if (* p == '*' ) { 1669const char * digstart = p ; 1670 1671p ++ ; 1672 1673if (ascii_isdigit ((int )(* p ))) { 1674// positional argument 1675unsigned uj ; 1676 1677if (get_unsigned_int (digstart ,& p ,& uj ,tvs != NULL )== FAIL ) { 1678 gotoerror ; 1679 } 1680 1681arg_idx = (int )uj ; 1682 1683p ++ ; 1684 } 1685 1686int j = (tvs 1687 ? (int )tv_nr (tvs ,& arg_idx ) 1688 : (skip_to_arg (ap_types ,ap_start ,& ap ,& arg_idx , 1689& arg_cur ,fmt ), 1690va_arg (ap ,int ))); 1691 1692if (j > MAX_ALLOWED_STRING_WIDTH ) { 1693if (tvs != NULL ) { 1694format_overflow_error (digstart ); 1695 gotoerror ; 1696 }else { 1697j = MAX_ALLOWED_STRING_WIDTH ; 1698 } 1699 } 1700 1701if (j >=0 ) { 1702precision = (size_t )j ; 1703 }else { 1704precision_specified = false; 1705precision = 0 ; 1706 } 1707 } 1708 } 1709 1710// parse 'h', 'l', 'll' and 'z' length modifiers 1711if (* p == 'h' || * p == 'l' || * p == 'z' ) { 1712length_modifier = * p ; 1713p ++ ; 1714if (length_modifier == 'l' && * p == 'l' ) { 1715// double l = long long 1716length_modifier = 'L' ; 1717p ++ ; 1718 } 1719 } 1720 1721fmt_spec = * p ; 1722 1723// common synonyms 1724switch (fmt_spec ) { 1725case 'i' : 1726fmt_spec = 'd' ;break ; 1727case 'D' : 1728fmt_spec = 'd' ;length_modifier = 'l' ;break ; 1729case 'U' : 1730fmt_spec = 'u' ;length_modifier = 'l' ;break ; 1731case 'O' : 1732fmt_spec = 'o' ;length_modifier = 'l' ;break ; 1733default : 1734break ; 1735 } 1736 1737switch (fmt_spec ) { 1738case 'd' : 1739case 'u' : 1740case 'o' : 1741case 'x' : 1742case 'X' : 1743if (tvs && length_modifier == NUL ) { 1744length_modifier = 'L' ; 1745 } 1746 } 1747 1748if (pos_arg != -1 ) { 1749arg_idx = pos_arg ; 1750 } 1751 1752// get parameter value, do initial processing 1753switch (fmt_spec ) { 1754// '%' and 'c' behave similar to 's' regarding flags and field widths 1755case '%' : 1756case 'c' : 1757case 's' : 1758case 'S' : 1759str_arg_l = 1 ; 1760switch (fmt_spec ) { 1761case '%' : 1762str_arg = p ; 1763break ; 1764 1765case 'c' : { 1766const int j = (tvs 1767 ? (int )tv_nr (tvs ,& arg_idx ) 1768 : (skip_to_arg (ap_types ,ap_start ,& ap ,& arg_idx , 1769& arg_cur ,fmt ), 1770va_arg (ap ,int ))); 1771 1772// standard demands unsigned char 1773uchar_arg = (unsigned char )j ; 1774str_arg = (char * )& uchar_arg ; 1775break ; 1776 } 1777 1778case 's' : 1779case 'S' : 1780str_arg = (tvs 1781 ?tv_str (tvs ,& arg_idx ,& tofree ) 1782 : (skip_to_arg (ap_types ,ap_start ,& ap ,& arg_idx , 1783& arg_cur ,fmt ), 1784va_arg (ap ,const char * ))); 1785 1786if (!str_arg ) { 1787#ifdef ENABLE_ASAN_UBSAN 1788// this is only for vsnprintf() emulation, v:_null_string handled in tv_str() 1789if (!tvs ) { 1790__sanitizer_print_stack_trace (); 1791__sanitizer_report_error_summary ("SUMMARY: NULL argument passed to %s" ); 1792 } 1793#endif 1794str_arg = "[NULL]" ; 1795str_arg_l = 6 ; 1796 }else if (!precision_specified ) { 1797// make sure not to address string beyond the specified 1798// precision 1799str_arg_l = strlen (str_arg ); 1800 }else if (precision == 0 ) { 1801// truncate string if necessary as requested by precision 1802str_arg_l = 0 ; 1803 }else { 1804// memchr on HP does not like n > 2^31 1805// TODO(elmart): check if this still holds / is relevant 1806str_arg_l = (size_t )((char * )xmemscan (str_arg , 1807NUL , 1808MIN (precision , 18090x7fffffff )) 1810- str_arg ); 1811 } 1812if (fmt_spec == 'S' ) { 1813const char * p1 ; 1814size_t i ; 1815 1816for (i = 0 ,p1 = str_arg ;* p1 ;p1 += utfc_ptr2len (p1 )) { 1817size_t cell = (size_t )utf_ptr2cells (p1 ); 1818if (precision_specified && i + cell > precision ) { 1819break ; 1820 } 1821i += cell ; 1822 } 1823 1824str_arg_l = (size_t )(p1 - str_arg ); 1825if (min_field_width != 0 ) { 1826min_field_width += str_arg_l - i ; 1827 } 1828 } 1829break ; 1830 1831default : 1832break ; 1833 } 1834break ; 1835 1836case 'd' : 1837case 'u' : 1838case 'b' : 1839case 'B' : 1840case 'o' : 1841case 'x' : 1842case 'X' : 1843case 'p' : { 1844// u, b, B, o, x, X and p conversion specifiers imply 1845// the value is unsigned; d implies a signed value 1846 1847// 0 if numeric argument is zero (or if pointer is NULL for 'p'), 1848// +1 if greater than zero (or non NULL for 'p'), 1849// -1 if negative (unsigned argument is never negative) 1850int arg_sign = 0 ; 1851 1852intmax_t arg = 0 ; 1853uintmax_t uarg = 0 ; 1854 1855// only defined for p conversion 1856const void * ptr_arg = NULL ; 1857 1858if (fmt_spec == 'p' ) { 1859ptr_arg = (tvs 1860 ?tv_ptr (tvs ,& arg_idx ) 1861 : (skip_to_arg (ap_types ,ap_start ,& ap ,& arg_idx , 1862& arg_cur ,fmt ), 1863va_arg (ap ,void * ))); 1864 1865if (ptr_arg ) { 1866arg_sign = 1 ; 1867 } 1868 }else if (fmt_spec == 'b' || fmt_spec == 'B' ) { 1869uarg = (tvs 1870 ? (unsigned long long )tv_nr (tvs ,& arg_idx )// NOLINT(runtime/int) 1871 : (skip_to_arg (ap_types ,ap_start ,& ap ,& arg_idx , 1872& arg_cur ,fmt ), 1873va_arg (ap ,unsigned long long)));// NOLINT(runtime/int) 1874arg_sign = (uarg != 0 ); 1875 }else if (fmt_spec == 'd' ) { 1876// signed 1877switch (length_modifier ) { 1878case NUL : 1879arg = (tvs 1880 ? (int )tv_nr (tvs ,& arg_idx ) 1881 : (skip_to_arg (ap_types ,ap_start ,& ap ,& arg_idx , 1882& arg_cur ,fmt ), 1883va_arg (ap ,int ))); 1884break ; 1885case 'h' : 1886// char and short arguments are passed as int16_t 1887arg = (int16_t ) 1888 (tvs 1889 ? (int )tv_nr (tvs ,& arg_idx ) 1890 : (skip_to_arg (ap_types ,ap_start ,& ap ,& arg_idx , 1891& arg_cur ,fmt ), 1892va_arg (ap ,int ))); 1893break ; 1894case 'l' : 1895arg = (tvs 1896 ? (long )tv_nr (tvs ,& arg_idx ) 1897 : (skip_to_arg (ap_types ,ap_start ,& ap ,& arg_idx , 1898& arg_cur ,fmt ), 1899va_arg (ap ,long ))); 1900break ; 1901case 'L' : 1902arg = (tvs 1903 ? (long long )tv_nr (tvs ,& arg_idx )// NOLINT(runtime/int) 1904 : (skip_to_arg (ap_types ,ap_start ,& ap ,& arg_idx , 1905& arg_cur ,fmt ), 1906va_arg (ap ,long long )));// NOLINT(runtime/int) 1907break ; 1908case 'z' :// implementation-defined, usually ptrdiff_t 1909arg = (tvs 1910 ? (ptrdiff_t )tv_nr (tvs ,& arg_idx ) 1911 : (skip_to_arg (ap_types ,ap_start ,& ap ,& arg_idx , 1912& arg_cur ,fmt ), 1913va_arg (ap ,ptrdiff_t ))); 1914break ; 1915 } 1916if (arg > 0 ) { 1917arg_sign = 1 ; 1918 }else if (arg < 0 ) { 1919arg_sign = -1 ; 1920 } 1921 }else { 1922// unsigned 1923switch (length_modifier ) { 1924case NUL : 1925uarg = (tvs 1926 ? (unsigned )tv_nr (tvs ,& arg_idx ) 1927 : (skip_to_arg (ap_types ,ap_start ,& ap ,& arg_idx , 1928& arg_cur ,fmt ), 1929va_arg (ap ,unsigned ))); 1930break ; 1931case 'h' : 1932uarg = (uint16_t ) 1933 (tvs 1934 ? (unsigned )tv_nr (tvs ,& arg_idx ) 1935 : (skip_to_arg (ap_types ,ap_start ,& ap ,& arg_idx , 1936& arg_cur ,fmt ), 1937va_arg (ap ,unsigned ))); 1938break ; 1939case 'l' : 1940uarg = (tvs 1941 ? (unsigned long )tv_nr (tvs ,& arg_idx ) 1942 : (skip_to_arg (ap_types ,ap_start ,& ap ,& arg_idx , 1943& arg_cur ,fmt ), 1944va_arg (ap ,unsigned long ))); 1945break ; 1946case 'L' : 1947uarg = (tvs 1948 ? (unsigned long long )tv_nr (tvs ,& arg_idx )// NOLINT(runtime/int) 1949 : (skip_to_arg (ap_types ,ap_start ,& ap ,& arg_idx , 1950& arg_cur ,fmt ), 1951va_arg (ap ,unsigned long long)));// NOLINT(runtime/int) 1952break ; 1953case 'z' : 1954uarg = (tvs 1955 ? (size_t )tv_nr (tvs ,& arg_idx ) 1956 : (skip_to_arg (ap_types ,ap_start ,& ap ,& arg_idx , 1957& arg_cur ,fmt ), 1958va_arg (ap ,size_t ))); 1959break ; 1960 } 1961arg_sign = (uarg != 0 ); 1962 } 1963 1964str_arg = tmp ; 1965str_arg_l = 0 ; 1966 1967// For d, i, u, o, x, and X conversions, if precision is specified, 1968// '0' flag should be ignored. This is so with Solaris 2.6, Digital 1969// UNIX 4.0, HPUX 10, Linux, FreeBSD, NetBSD; but not with Perl. 1970if (precision_specified ) { 1971zero_padding = false; 1972 } 1973 1974if (fmt_spec == 'd' ) { 1975if (force_sign && arg_sign >=0 ) { 1976tmp [str_arg_l ++ ]= space_for_positive ?' ' :'+' ; 1977 } 1978// leave negative numbers for snprintf to handle, to 1979// avoid handling tricky cases like (short int)-32768 1980 }else if (alternate_form ) { 1981if (arg_sign != 0 && (fmt_spec == 'x' || fmt_spec == 'X' 1982|| fmt_spec == 'b' || fmt_spec == 'B' )) { 1983tmp [str_arg_l ++ ]= '0' ; 1984tmp [str_arg_l ++ ]= fmt_spec ; 1985 } 1986// alternate form should have no effect for p * conversion, but ... 1987 } 1988 1989zero_padding_insertion_ind = str_arg_l ; 1990if (!precision_specified ) { 1991precision = 1 ;// default precision is 1 1992 } 1993if (precision == 0 && arg_sign == 0 ) { 1994// when zero value is formatted with an explicit precision 0, 1995// resulting formatted string is empty (d, i, u, b, B, o, x, X, p) 1996 }else { 1997switch (fmt_spec ) { 1998case 'p' :// pointer 1999str_arg_l += (size_t )snprintf (tmp + str_arg_l , 2000sizeof (tmp )- str_arg_l , 2001"%p" ,ptr_arg ); 2002break ; 2003case 'd' :// signed 2004str_arg_l += (size_t )snprintf (tmp + str_arg_l , 2005sizeof (tmp )- str_arg_l , 2006"%" PRIdMAX ,arg ); 2007break ; 2008case 'b' : 2009case 'B' : {// binary 2010size_t bits = 0 ; 2011for (bits = sizeof (uintmax_t )* 8 ;bits > 0 ;bits -- ) { 2012if ((uarg >> (bits - 1 ))& 0x1 ) { 2013break ; 2014 } 2015 } 2016 2017while (bits > 0 ) { 2018tmp [str_arg_l ++ ]= ((uarg >>-- bits )& 0x1 ) ?'1' :'0' ; 2019 } 2020break ; 2021 } 2022default : {// unsigned 2023// construct a simple format string for snprintf 2024char f []= "%" PRIuMAX ; 2025f [sizeof ("%" PRIuMAX )- 1 - 1 ]= fmt_spec ; 2026assert (PRIuMAX [sizeof (PRIuMAX )- 1 - 1 ]== 'u' ); 2027str_arg_l += (size_t )snprintf (tmp + str_arg_l , 2028sizeof (tmp )- str_arg_l , 2029f ,uarg ); 2030break ; 2031 } 2032 } 2033assert (str_arg_l < sizeof (tmp )); 2034 2035// include the optional minus sign and possible "0x" in the region 2036// before the zero padding insertion point 2037if (zero_padding_insertion_ind < str_arg_l 2038&& tmp [zero_padding_insertion_ind ]== '-' ) { 2039zero_padding_insertion_ind ++ ; 2040 } 2041if (zero_padding_insertion_ind + 1 < str_arg_l 2042&& tmp [zero_padding_insertion_ind ]== '0' 2043&& (tmp [zero_padding_insertion_ind + 1 ]== 'x' 2044|| tmp [zero_padding_insertion_ind + 1 ]== 'X' 2045|| tmp [zero_padding_insertion_ind + 1 ]== 'b' 2046|| tmp [zero_padding_insertion_ind + 1 ]== 'B' )) { 2047zero_padding_insertion_ind += 2 ; 2048 } 2049 } 2050 2051 { 2052size_t num_of_digits = str_arg_l - zero_padding_insertion_ind ; 2053 2054if (alternate_form && fmt_spec == 'o' 2055// unless zero is already the first character 2056&& !(zero_padding_insertion_ind < str_arg_l 2057&& tmp [zero_padding_insertion_ind ]== '0' )) { 2058// assure leading zero for alternate-form octal numbers 2059if (!precision_specified || precision < num_of_digits + 1 ) { 2060// precision is increased to force the first character to be 2061// zero, except if a zero value is formatted with an explicit 2062// precision of zero 2063precision = num_of_digits + 1 ; 2064 } 2065 } 2066// zero padding to specified precision? 2067if (num_of_digits < precision ) { 2068number_of_zeros_to_pad = precision - num_of_digits ; 2069 } 2070 } 2071// zero padding to specified minimal field width? 2072if (!justify_left && zero_padding ) { 2073const int n = (int )(min_field_width - (str_arg_l 2074+ number_of_zeros_to_pad )); 2075if (n > 0 ) { 2076number_of_zeros_to_pad += (size_t )n ; 2077 } 2078 } 2079break ; 2080 } 2081 2082case 'f' : 2083case 'F' : 2084case 'e' : 2085case 'E' : 2086case 'g' : 2087case 'G' : { 2088// floating point 2089char format [40 ]; 2090bool remove_trailing_zeroes = false; 2091 2092double f = (tvs 2093 ?tv_float (tvs ,& arg_idx ) 2094 : (skip_to_arg (ap_types ,ap_start ,& ap ,& arg_idx , 2095& arg_cur ,fmt ), 2096va_arg (ap ,double ))); 2097 2098double abs_f = f < 0 ?- f :f ; 2099 2100if (fmt_spec == 'g' || fmt_spec == 'G' ) { 2101// can't use %g directly, cause it prints "1.0" as "1" 2102if ((abs_f >=0.001 && abs_f < 10000000.0 )|| abs_f == 0.0 ) { 2103fmt_spec = ASCII_ISUPPER (fmt_spec ) ?'F' :'f' ; 2104 }else { 2105fmt_spec = fmt_spec == 'g' ?'e' :'E' ; 2106 } 2107remove_trailing_zeroes = true; 2108 } 2109 2110if (xisinf (f ) 2111|| (strchr ("fF" ,fmt_spec )!= NULL && abs_f > 1.0e307 )) { 2112xstrlcpy (tmp ,infinity_str (f > 0.0 ,fmt_spec , 2113force_sign ,space_for_positive ), 2114sizeof (tmp )); 2115str_arg_l = strlen (tmp ); 2116zero_padding = false; 2117 }else if (xisnan (f )) { 2118// Not a number: nan or NAN 2119memmove (tmp ,ASCII_ISUPPER (fmt_spec ) ?"NAN" :"nan" ,4 ); 2120str_arg_l = 3 ; 2121zero_padding = false; 2122 }else { 2123// Regular float number 2124format [0 ]= '%' ; 2125size_t l = 1 ; 2126if (force_sign ) { 2127format [l ++ ]= space_for_positive ?' ' :'+' ; 2128 } 2129if (precision_specified ) { 2130size_t max_prec = TMP_LEN - 10 ; 2131 2132// make sure we don't get more digits than we have room for 2133if ((fmt_spec == 'f' || fmt_spec == 'F' )&& abs_f > 1.0 ) { 2134max_prec -= (size_t )log10 (abs_f ); 2135 } 2136if (precision > max_prec ) { 2137precision = max_prec ; 2138 } 2139l += (size_t )snprintf (format + l ,sizeof (format )- l ,".%d" , 2140 (int )precision ); 2141 } 2142 2143// Cast to char to avoid a conversion warning on Ubuntu 12.04. 2144assert (l + 1 < sizeof (format )); 2145format [l ]= (char )(fmt_spec == 'F' ?'f' :fmt_spec ); 2146format [l + 1 ]= NUL ; 2147 2148str_arg_l = (size_t )snprintf (tmp ,sizeof (tmp ),format ,f ); 2149assert (str_arg_l < sizeof (tmp )); 2150 2151if (remove_trailing_zeroes ) { 2152char * tp ; 2153 2154// using %g or %G: remove superfluous zeroes 2155if (fmt_spec == 'f' || fmt_spec == 'F' ) { 2156tp = tmp + str_arg_l - 1 ; 2157 }else { 2158tp = vim_strchr (tmp ,fmt_spec == 'e' ?'e' :'E' ); 2159if (tp ) { 2160// remove superfluous '+' and leading zeroes from exponent 2161if (tp [1 ]== '+' ) { 2162// change "1.0e+07" to "1.0e07" 2163STRMOVE (tp + 1 ,tp + 2 ); 2164str_arg_l -- ; 2165 } 2166int i = (tp [1 ]== '-' ) ?2 :1 ; 2167while (tp [i ]== '0' ) { 2168// change "1.0e07" to "1.0e7" 2169STRMOVE (tp + i ,tp + i + 1 ); 2170str_arg_l -- ; 2171 } 2172tp -- ; 2173 } 2174 } 2175 2176if (tp != NULL && !precision_specified ) { 2177// remove trailing zeroes, but keep the one just after a dot 2178while (tp > tmp + 2 && * tp == '0' && tp [-1 ]!= '.' ) { 2179STRMOVE (tp ,tp + 1 ); 2180tp -- ; 2181str_arg_l -- ; 2182 } 2183 } 2184 }else { 2185// Be consistent: some printf("%e") use 1.0e+12 and some 2186// 1.0e+012; remove one zero in the last case. 2187char * tp = vim_strchr (tmp ,fmt_spec == 'e' ?'e' :'E' ); 2188if (tp && (tp [1 ]== '+' || tp [1 ]== '-' )&& tp [2 ]== '0' 2189&& ascii_isdigit (tp [3 ])&& ascii_isdigit (tp [4 ])) { 2190STRMOVE (tp + 2 ,tp + 3 ); 2191str_arg_l -- ; 2192 } 2193 } 2194 } 2195if (zero_padding && min_field_width > str_arg_l 2196&& (tmp [0 ]== '-' || force_sign )) { 2197// Padding 0's should be inserted after the sign. 2198number_of_zeros_to_pad = min_field_width - str_arg_l ; 2199zero_padding_insertion_ind = 1 ; 2200 } 2201str_arg = tmp ; 2202break ; 2203 } 2204 2205default : 2206// unrecognized conversion specifier, keep format string as-is 2207zero_padding = false;// turn zero padding off for non-numeric conversion 2208justify_left = true; 2209min_field_width = 0 ;// reset flags 2210 2211// discard the unrecognized conversion, just keep 2212// the unrecognized conversion character 2213str_arg = p ; 2214str_arg_l = 0 ; 2215if (* p ) { 2216str_arg_l ++ ;// include invalid conversion specifier 2217 } 2218// unchanged if not at end-of-string 2219break ; 2220 } 2221 2222if (* p ) { 2223p ++ ;// step over the just processed conversion specifier 2224 } 2225 2226// insert padding to the left as requested by min_field_width; 2227// this does not include the zero padding in case of numerical conversions 2228if (!justify_left ) { 2229assert (str_arg_l <=SIZE_MAX - number_of_zeros_to_pad ); 2230if (min_field_width > str_arg_l + number_of_zeros_to_pad ) { 2231// left padding with blank or zero 2232size_t pn = min_field_width - (str_arg_l + number_of_zeros_to_pad ); 2233if (str_avail ) { 2234size_t avail = str_m - str_l ; 2235memset (str + str_l ,zero_padding ?'0' :' ' ,MIN (pn ,avail )); 2236str_avail = pn < avail ; 2237 } 2238assert (pn <=SIZE_MAX - str_l ); 2239str_l += pn ; 2240 } 2241 } 2242 2243// zero padding as requested by the precision or by the minimal 2244// field width for numeric conversions required? 2245if (number_of_zeros_to_pad == 0 ) { 2246// will not copy first part of numeric right now, 2247// force it to be copied later in its entirety 2248zero_padding_insertion_ind = 0 ; 2249 }else { 2250// insert first part of numerics (sign or '0x') before zero padding 2251if (zero_padding_insertion_ind > 0 ) { 2252size_t zn = zero_padding_insertion_ind ; 2253if (str_avail ) { 2254size_t avail = str_m - str_l ; 2255memmove (str + str_l ,str_arg ,MIN (zn ,avail )); 2256str_avail = zn < avail ; 2257 } 2258assert (zn <=SIZE_MAX - str_l ); 2259str_l += zn ; 2260 } 2261 2262// insert zero padding as requested by precision or min field width 2263size_t zn = number_of_zeros_to_pad ; 2264if (str_avail ) { 2265size_t avail = str_m - str_l ; 2266memset (str + str_l ,'0' ,MIN (zn ,avail )); 2267str_avail = zn < avail ; 2268 } 2269assert (zn <=SIZE_MAX - str_l ); 2270str_l += zn ; 2271 } 2272 2273// insert formatted string 2274// (or as-is conversion specifier for unknown conversions) 2275if (str_arg_l > zero_padding_insertion_ind ) { 2276size_t sn = str_arg_l - zero_padding_insertion_ind ; 2277if (str_avail ) { 2278size_t avail = str_m - str_l ; 2279memmove (str + str_l , 2280str_arg + zero_padding_insertion_ind , 2281MIN (sn ,avail )); 2282str_avail = sn < avail ; 2283 } 2284assert (sn <=SIZE_MAX - str_l ); 2285str_l += sn ; 2286 } 2287 2288// insert right padding 2289if (justify_left ) { 2290assert (str_arg_l <=SIZE_MAX - number_of_zeros_to_pad ); 2291if (min_field_width > str_arg_l + number_of_zeros_to_pad ) { 2292// right blank padding to the field width 2293size_t pn = min_field_width - (str_arg_l + number_of_zeros_to_pad ); 2294if (str_avail ) { 2295size_t avail = str_m - str_l ; 2296memset (str + str_l ,' ' ,MIN (pn ,avail )); 2297str_avail = pn < avail ; 2298 } 2299assert (pn <=SIZE_MAX - str_l ); 2300str_l += pn ; 2301 } 2302 } 2303 2304xfree (tofree ); 2305 } 2306 } 2307 2308if (str_m > 0 ) { 2309// make sure the string is nul-terminated even at the expense of 2310// overwriting the last character (shouldn't happen, but just in case) 2311str [str_l <=str_m - 1 ?str_l :str_m - 1 ]= NUL ; 2312 } 2313 2314if (tvs != NULL 2315&& tvs [num_posarg != 0 ?num_posarg :arg_idx - 1 ].v_type != VAR_UNKNOWN ) { 2316emsg (_ ("E767: Too many arguments to printf()" )); 2317 } 2318 2319error : 2320xfree (ap_types ); 2321va_end (ap ); 2322 2323// return the number of characters formatted (excluding trailing nul 2324// character); that is, the number of characters that would have been 2325// written to the buffer if it were large enough. 2326return (int )str_l ; 2327} 2328 2329int kv_do_printf (StringBuilder * str ,const char * fmt , ...) 2330FUNC_ATTR_PRINTF (2 ,3 ) 2331{ 2332size_t remaining = str -> capacity - str -> size ; 2333 2334va_list ap ; 2335va_start (ap ,fmt ); 2336int printed = vsnprintf (str -> items ?str -> items + str -> size :NULL ,remaining ,fmt ,ap ); 2337va_end (ap ); 2338 2339if (printed < 0 ) { 2340return -1 ; 2341 } 2342 2343// printed string didn't fit, resize and try again 2344if ((size_t )printed >=remaining ) { 2345kv_ensure_space (* str , (size_t )printed + 1 );// include space for NUL terminator at the end 2346assert (str -> items != NULL ); 2347va_start (ap ,fmt ); 2348printed = vsnprintf (str -> items + str -> size ,str -> capacity - str -> size ,fmt ,ap ); 2349va_end (ap ); 2350if (printed < 0 ) { 2351return -1 ; 2352 } 2353 } 2354 2355str -> size += (size_t )printed ; 2356return printed ; 2357} 2358 2359String arena_printf (Arena * arena ,const char * fmt , ...) 2360FUNC_ATTR_PRINTF (2 ,3 ) 2361{ 2362size_t remaining = 0 ; 2363char * buf = NULL ; 2364if (arena ) { 2365if (!arena -> cur_blk ) { 2366arena_alloc_block (arena ); 2367 } 2368 2369// happy case, we can fit the printed string in the rest of the current 2370// block (one pass): 2371remaining = arena -> size - arena -> pos ; 2372buf = arena -> cur_blk + arena -> pos ; 2373 } 2374 2375va_list ap ; 2376va_start (ap ,fmt ); 2377int printed = vsnprintf (buf ,remaining ,fmt ,ap ); 2378va_end (ap ); 2379 2380if (printed < 0 ) { 2381return (String )STRING_INIT ; 2382 } 2383 2384// printed string didn't fit, allocate and try again 2385if ((size_t )printed >=remaining ) { 2386buf = arena_alloc (arena , (size_t )printed + 1 , false); 2387va_start (ap ,fmt ); 2388printed = vsnprintf (buf , (size_t )printed + 1 ,fmt ,ap ); 2389va_end (ap ); 2390if (printed < 0 ) { 2391return (String )STRING_INIT ; 2392 } 2393 }else { 2394arena -> pos += (size_t )printed + 1 ; 2395 } 2396 2397return cbuf_as_string (buf , (size_t )printed ); 2398} 2399 2400/// Reverse text into allocated memory. 2401/// 2402/// @return the allocated string. 2403char * reverse_text (char * s ) 2404FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET 2405{ 2406size_t len = strlen (s ); 2407char * rev = xmalloc (len + 1 ); 2408for (size_t s_i = 0 ,rev_i = len ;s_i < len ;s_i ++ ) { 2409const int mb_len = utfc_ptr2len (s + s_i ); 2410rev_i -= (size_t )mb_len ; 2411memmove (rev + rev_i ,s + s_i , (size_t )mb_len ); 2412s_i += (size_t )mb_len - 1 ; 2413 } 2414rev [len ]= NUL ; 2415return rev ; 2416} 2417 2418/// Replace all occurrences of "what" with "rep" in "src". If no replacement happens then NULL is 2419/// returned otherwise return a newly allocated string. 2420/// 2421/// @param[in] src Source text 2422/// @param[in] what Substring to replace 2423/// @param[in] rep Substring to replace with 2424/// 2425/// @return [allocated] Copy of the string. 2426char * strrep (const char * src ,const char * what ,const char * rep ) 2427{ 2428const char * pos = src ; 2429size_t whatlen = strlen (what ); 2430 2431// Count occurrences 2432size_t count = 0 ; 2433while ((pos = strstr (pos ,what ))!= NULL ) { 2434count ++ ; 2435pos += whatlen ; 2436 } 2437 2438if (count == 0 ) { 2439return NULL ; 2440 } 2441 2442size_t replen = strlen (rep ); 2443char * ret = xmalloc (strlen (src )+ count * (replen - whatlen )+ 1 ); 2444char * ptr = ret ; 2445while ((pos = strstr (src ,what ))!= NULL ) { 2446size_t idx = (size_t )(pos - src ); 2447memcpy (ptr ,src ,idx ); 2448ptr += idx ; 2449STRCPY (ptr ,rep ); 2450ptr += replen ; 2451src = pos + whatlen ; 2452 } 2453 2454// Copy remaining 2455STRCPY (ptr ,src ); 2456 2457return ret ; 2458} 2459 2460/// Implementation of "byteidx()" and "byteidxcomp()" functions 2461static void byteidx_common (typval_T * argvars ,typval_T * rettv ,bool comp ) 2462{ 2463rettv -> vval .v_number = -1 ; 2464 2465const char * const str = tv_get_string_chk (& argvars [0 ]); 2466varnumber_T idx = tv_get_number_chk (& argvars [1 ],NULL ); 2467if (str == NULL || idx < 0 ) { 2468return ; 2469 } 2470 2471varnumber_T utf16idx = false; 2472if (argvars [2 ].v_type != VAR_UNKNOWN ) { 2473bool error = false; 2474utf16idx = tv_get_bool_chk (& argvars [2 ],& error ); 2475if (error ) { 2476return ; 2477 } 2478if (utf16idx < 0 || utf16idx > 1 ) { 2479semsg (_ (e_using_number_as_bool_nr ),utf16idx ); 2480return ; 2481 } 2482 } 2483 2484int (* ptr2len )(const char * ); 2485if (comp ) { 2486ptr2len = utf_ptr2len ; 2487 }else { 2488ptr2len = utfc_ptr2len ; 2489 } 2490 2491const char * t = str ; 2492for (;idx > 0 ;idx -- ) { 2493if (* t == NUL ) {// EOL reached. 2494return ; 2495 } 2496if (utf16idx ) { 2497const int clen = ptr2len (t ); 2498const int c = (clen > 1 ) ?utf_ptr2char (t ) :* t ; 2499if (c > 0xFFFF ) { 2500idx -- ; 2501 } 2502if (idx > 0 ) { 2503t += clen ; 2504 } 2505 }else if (idx > 0 ) { 2506t += ptr2len (t ); 2507 } 2508 } 2509rettv -> vval .v_number = (varnumber_T )(t - str ); 2510} 2511 2512/// "byteidx()" function 2513void f_byteidx (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 2514{ 2515byteidx_common (argvars ,rettv , false); 2516} 2517 2518/// "byteidxcomp()" function 2519void f_byteidxcomp (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 2520{ 2521byteidx_common (argvars ,rettv , true); 2522} 2523 2524/// "charidx()" function 2525void f_charidx (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 2526{ 2527rettv -> vval .v_number = -1 ; 2528 2529if (tv_check_for_string_arg (argvars ,0 )== FAIL 2530|| tv_check_for_number_arg (argvars ,1 )== FAIL 2531|| tv_check_for_opt_bool_arg (argvars ,2 )== FAIL 2532|| (argvars [2 ].v_type != VAR_UNKNOWN 2533&& tv_check_for_opt_bool_arg (argvars ,3 )== FAIL )) { 2534return ; 2535 } 2536 2537const char * const str = tv_get_string_chk (& argvars [0 ]); 2538varnumber_T idx = tv_get_number_chk (& argvars [1 ],NULL ); 2539if (str == NULL || idx < 0 ) { 2540return ; 2541 } 2542 2543varnumber_T countcc = false; 2544varnumber_T utf16idx = false; 2545if (argvars [2 ].v_type != VAR_UNKNOWN ) { 2546countcc = tv_get_bool (& argvars [2 ]); 2547if (argvars [3 ].v_type != VAR_UNKNOWN ) { 2548utf16idx = tv_get_bool (& argvars [3 ]); 2549 } 2550 } 2551 2552int (* ptr2len )(const char * ); 2553if (countcc ) { 2554ptr2len = utf_ptr2len ; 2555 }else { 2556ptr2len = utfc_ptr2len ; 2557 } 2558 2559const char * p ; 2560int len ; 2561for (p = str ,len = 0 ;utf16idx ?idx >=0 :p <=str + idx ;len ++ ) { 2562if (* p == NUL ) { 2563// If the index is exactly the number of bytes or utf-16 code units 2564// in the string then return the length of the string in characters. 2565if (utf16idx ? (idx == 0 ) : (p == (str + idx ))) { 2566rettv -> vval .v_number = len ; 2567 } 2568return ; 2569 } 2570if (utf16idx ) { 2571idx -- ; 2572const int clen = ptr2len (p ); 2573const int c = (clen > 1 ) ?utf_ptr2char (p ) :* p ; 2574if (c > 0xFFFF ) { 2575idx -- ; 2576 } 2577 } 2578p += ptr2len (p ); 2579 } 2580 2581rettv -> vval .v_number = len > 0 ?len - 1 :0 ; 2582} 2583 2584/// "str2list()" function 2585void f_str2list (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 2586{ 2587tv_list_alloc_ret (rettv ,kListLenUnknown ); 2588const char * p = tv_get_string (& argvars [0 ]); 2589 2590for (;* p != NUL ;p += utf_ptr2len (p )) { 2591tv_list_append_number (rettv -> vval .v_list ,utf_ptr2char (p )); 2592 } 2593} 2594 2595/// "str2nr()" function 2596void f_str2nr (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 2597{ 2598int base = 10 ; 2599int what = 0 ; 2600 2601if (argvars [1 ].v_type != VAR_UNKNOWN ) { 2602base = (int )tv_get_number (& argvars [1 ]); 2603if (base != 2 && base != 8 && base != 10 && base != 16 ) { 2604emsg (_ (e_invarg )); 2605return ; 2606 } 2607if (argvars [2 ].v_type != VAR_UNKNOWN && tv_get_bool (& argvars [2 ])) { 2608what |=STR2NR_QUOTE ; 2609 } 2610 } 2611 2612char * p = skipwhite (tv_get_string (& argvars [0 ])); 2613bool isneg = (* p == '-' ); 2614if (* p == '+' || * p == '-' ) { 2615p = skipwhite (p + 1 ); 2616 } 2617switch (base ) { 2618case 2 : 2619what |=STR2NR_BIN |STR2NR_FORCE ; 2620break ; 2621case 8 : 2622what |=STR2NR_OCT |STR2NR_OOCT |STR2NR_FORCE ; 2623break ; 2624case 16 : 2625what |=STR2NR_HEX |STR2NR_FORCE ; 2626break ; 2627 } 2628varnumber_T n ; 2629vim_str2nr (p ,NULL ,NULL ,what ,& n ,NULL ,0 , false,NULL ); 2630// Text after the number is silently ignored. 2631if (isneg ) { 2632rettv -> vval .v_number = - n ; 2633 }else { 2634rettv -> vval .v_number = n ; 2635 } 2636} 2637 2638/// "strgetchar()" function 2639void f_strgetchar (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 2640{ 2641rettv -> vval .v_number = -1 ; 2642 2643const char * const str = tv_get_string_chk (& argvars [0 ]); 2644if (str == NULL ) { 2645return ; 2646 } 2647bool error = false; 2648varnumber_T charidx = tv_get_number_chk (& argvars [1 ],& error ); 2649if (error ) { 2650return ; 2651 } 2652 2653const size_t len = strlen (str ); 2654size_t byteidx = 0 ; 2655 2656while (charidx >=0 && byteidx < len ) { 2657if (charidx == 0 ) { 2658rettv -> vval .v_number = utf_ptr2char (str + byteidx ); 2659break ; 2660 } 2661charidx -- ; 2662byteidx += (size_t )utf_ptr2len (str + byteidx ); 2663 } 2664} 2665 2666/// "stridx()" function 2667void f_stridx (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 2668{ 2669rettv -> vval .v_number = -1 ; 2670 2671char buf [NUMBUFLEN ]; 2672const char * const needle = tv_get_string_chk (& argvars [1 ]); 2673const char * haystack = tv_get_string_buf_chk (& argvars [0 ],buf ); 2674const char * const haystack_start = haystack ; 2675if (needle == NULL || haystack == NULL ) { 2676return ;// Type error; errmsg already given. 2677 } 2678 2679if (argvars [2 ].v_type != VAR_UNKNOWN ) { 2680bool error = false; 2681 2682const ptrdiff_t start_idx = (ptrdiff_t )tv_get_number_chk (& argvars [2 ], 2683& error ); 2684if (error || start_idx >= (ptrdiff_t )strlen (haystack )) { 2685return ; 2686 } 2687if (start_idx >=0 ) { 2688haystack += start_idx ; 2689 } 2690 } 2691 2692const char * pos = strstr (haystack ,needle ); 2693if (pos != NULL ) { 2694rettv -> vval .v_number = (varnumber_T )(pos - haystack_start ); 2695 } 2696} 2697 2698/// "string()" function 2699void f_string (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 2700{ 2701rettv -> v_type = VAR_STRING ; 2702rettv -> vval .v_string = encode_tv2string (& argvars [0 ],NULL ); 2703} 2704 2705/// "strlen()" function 2706void f_strlen (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 2707{ 2708rettv -> vval .v_number = (varnumber_T )strlen (tv_get_string (& argvars [0 ])); 2709} 2710 2711static void strchar_common (typval_T * argvars ,typval_T * rettv ,bool skipcc ) 2712{ 2713const char * s = tv_get_string (& argvars [0 ]); 2714varnumber_T len = 0 ; 2715int (* func_mb_ptr2char_adv )(const char ** pp ); 2716 2717func_mb_ptr2char_adv = skipcc ?mb_ptr2char_adv :mb_cptr2char_adv ; 2718while (* s != NUL ) { 2719func_mb_ptr2char_adv (& s ); 2720len ++ ; 2721 } 2722rettv -> vval .v_number = len ; 2723} 2724 2725/// "strcharlen()" function 2726void f_strcharlen (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 2727{ 2728strchar_common (argvars ,rettv , true); 2729} 2730 2731/// "strchars()" function 2732void f_strchars (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 2733{ 2734varnumber_T skipcc = false; 2735 2736if (argvars [1 ].v_type != VAR_UNKNOWN ) { 2737bool error = false; 2738skipcc = tv_get_bool_chk (& argvars [1 ],& error ); 2739if (error ) { 2740return ; 2741 } 2742if (skipcc < 0 || skipcc > 1 ) { 2743semsg (_ (e_using_number_as_bool_nr ),skipcc ); 2744return ; 2745 } 2746 } 2747 2748strchar_common (argvars ,rettv ,skipcc ); 2749} 2750 2751/// "strutf16len()" function 2752void f_strutf16len (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 2753{ 2754rettv -> vval .v_number = -1 ; 2755 2756if (tv_check_for_string_arg (argvars ,0 )== FAIL 2757|| tv_check_for_opt_bool_arg (argvars ,1 )== FAIL ) { 2758return ; 2759 } 2760 2761varnumber_T countcc = false; 2762if (argvars [1 ].v_type != VAR_UNKNOWN ) { 2763countcc = tv_get_bool (& argvars [1 ]); 2764 } 2765 2766const char * s = tv_get_string (& argvars [0 ]); 2767varnumber_T len = 0 ; 2768int (* func_mb_ptr2char_adv )(const char ** pp ); 2769 2770func_mb_ptr2char_adv = countcc ?mb_cptr2char_adv :mb_ptr2char_adv ; 2771while (* s != NUL ) { 2772const int ch = func_mb_ptr2char_adv (& s ); 2773if (ch > 0xFFFF ) { 2774len ++ ; 2775 } 2776len ++ ; 2777 } 2778rettv -> vval .v_number = len ; 2779} 2780 2781/// "strdisplaywidth()" function 2782void f_strdisplaywidth (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 2783{ 2784const char * const s = tv_get_string (& argvars [0 ]); 2785int col = 0 ; 2786 2787if (argvars [1 ].v_type != VAR_UNKNOWN ) { 2788col = (int )tv_get_number (& argvars [1 ]); 2789 } 2790 2791rettv -> vval .v_number = (varnumber_T )(linetabsize_col (col , (char * )s )- col ); 2792} 2793 2794/// "strwidth()" function 2795void f_strwidth (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 2796{ 2797const char * const s = tv_get_string (& argvars [0 ]); 2798 2799rettv -> vval .v_number = (varnumber_T )mb_string2cells (s ); 2800} 2801 2802/// "strcharpart()" function 2803void f_strcharpart (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 2804{ 2805const char * const p = tv_get_string (& argvars [0 ]); 2806const size_t slen = strlen (p ); 2807 2808int nbyte = 0 ; 2809varnumber_T skipcc = false; 2810bool error = false; 2811varnumber_T nchar = tv_get_number_chk (& argvars [1 ],& error ); 2812if (!error ) { 2813if (argvars [2 ].v_type != VAR_UNKNOWN 2814&& argvars [3 ].v_type != VAR_UNKNOWN ) { 2815skipcc = tv_get_bool_chk (& argvars [3 ],& error ); 2816if (error ) { 2817return ; 2818 } 2819if (skipcc < 0 || skipcc > 1 ) { 2820semsg (_ (e_using_number_as_bool_nr ),skipcc ); 2821return ; 2822 } 2823 } 2824 2825if (nchar > 0 ) { 2826while (nchar > 0 && (size_t )nbyte < slen ) { 2827if (skipcc ) { 2828nbyte += utfc_ptr2len (p + nbyte ); 2829 }else { 2830nbyte += utf_ptr2len (p + nbyte ); 2831 } 2832nchar -- ; 2833 } 2834 }else { 2835nbyte = (int )nchar ; 2836 } 2837 } 2838int len = 0 ; 2839if (argvars [2 ].v_type != VAR_UNKNOWN ) { 2840int charlen = (int )tv_get_number (& argvars [2 ]); 2841while (charlen > 0 && nbyte + len < (int )slen ) { 2842int off = nbyte + len ; 2843 2844if (off < 0 ) { 2845len += 1 ; 2846 }else { 2847if (skipcc ) { 2848len += utfc_ptr2len (p + off ); 2849 }else { 2850len += utf_ptr2len (p + off ); 2851 } 2852 } 2853charlen -- ; 2854 } 2855 }else { 2856len = (int )slen - nbyte ;// default: all bytes that are available. 2857 } 2858 2859// Only return the overlap between the specified part and the actual 2860// string. 2861if (nbyte < 0 ) { 2862len += nbyte ; 2863nbyte = 0 ; 2864 }else if ((size_t )nbyte > slen ) { 2865nbyte = (int )slen ; 2866 } 2867if (len < 0 ) { 2868len = 0 ; 2869 }else if (nbyte + len > (int )slen ) { 2870len = (int )slen - nbyte ; 2871 } 2872 2873rettv -> v_type = VAR_STRING ; 2874rettv -> vval .v_string = xmemdupz (p + nbyte , (size_t )len ); 2875} 2876 2877/// "strpart()" function 2878void f_strpart (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 2879{ 2880bool error = false; 2881 2882const char * const p = tv_get_string (& argvars [0 ]); 2883const size_t slen = strlen (p ); 2884 2885varnumber_T n = tv_get_number_chk (& argvars [1 ],& error ); 2886varnumber_T len ; 2887if (error ) { 2888len = 0 ; 2889 }else if (argvars [2 ].v_type != VAR_UNKNOWN ) { 2890len = tv_get_number (& argvars [2 ]); 2891 }else { 2892len = (varnumber_T )slen - n ;// Default len: all bytes that are available. 2893 } 2894 2895// Only return the overlap between the specified part and the actual 2896// string. 2897if (n < 0 ) { 2898len += n ; 2899n = 0 ; 2900 }else if (n > (varnumber_T )slen ) { 2901n = (varnumber_T )slen ; 2902 } 2903if (len < 0 ) { 2904len = 0 ; 2905 }else if (n + len > (varnumber_T )slen ) { 2906len = (varnumber_T )slen - n ; 2907 } 2908 2909if (argvars [2 ].v_type != VAR_UNKNOWN && argvars [3 ].v_type != VAR_UNKNOWN ) { 2910int64_t off ; 2911 2912// length in characters 2913for (off = n ;off < (int64_t )slen && len > 0 ;len -- ) { 2914off += utfc_ptr2len (p + off ); 2915 } 2916len = off - n ; 2917 } 2918 2919rettv -> v_type = VAR_STRING ; 2920rettv -> vval .v_string = xmemdupz (p + n , (size_t )len ); 2921} 2922 2923/// "strridx()" function 2924void f_strridx (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 2925{ 2926char buf [NUMBUFLEN ]; 2927const char * const needle = tv_get_string_chk (& argvars [1 ]); 2928const char * const haystack = tv_get_string_buf_chk (& argvars [0 ],buf ); 2929 2930rettv -> vval .v_number = -1 ; 2931if (needle == NULL || haystack == NULL ) { 2932return ;// Type error; errmsg already given. 2933 } 2934 2935const size_t haystack_len = strlen (haystack ); 2936ptrdiff_t end_idx ; 2937if (argvars [2 ].v_type != VAR_UNKNOWN ) { 2938// Third argument: upper limit for index. 2939end_idx = (ptrdiff_t )tv_get_number_chk (& argvars [2 ],NULL ); 2940if (end_idx < 0 ) { 2941return ;// Can never find a match. 2942 } 2943 }else { 2944end_idx = (ptrdiff_t )haystack_len ; 2945 } 2946 2947const char * lastmatch = NULL ; 2948if (* needle == NUL ) { 2949// Empty string matches past the end. 2950lastmatch = haystack + end_idx ; 2951 }else { 2952for (const char * rest = haystack ;* rest != NUL ;rest ++ ) { 2953rest = strstr (rest ,needle ); 2954if (rest == NULL || rest > haystack + end_idx ) { 2955break ; 2956 } 2957lastmatch = rest ; 2958 } 2959 } 2960 2961if (lastmatch != NULL ) { 2962rettv -> vval .v_number = (varnumber_T )(lastmatch - haystack ); 2963 } 2964} 2965 2966/// "strtrans()" function 2967void f_strtrans (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 2968{ 2969rettv -> v_type = VAR_STRING ; 2970rettv -> vval .v_string = transstr (tv_get_string (& argvars [0 ]), true); 2971} 2972 2973/// "utf16idx()" function 2974/// 2975/// Converts a byte or character offset in a string to the corresponding UTF-16 2976/// code unit offset. 2977void f_utf16idx (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 2978{ 2979rettv -> vval .v_number = -1 ; 2980 2981if (tv_check_for_string_arg (argvars ,0 )== FAIL 2982|| tv_check_for_opt_number_arg (argvars ,1 )== FAIL 2983|| tv_check_for_opt_bool_arg (argvars ,2 )== FAIL 2984|| (argvars [2 ].v_type != VAR_UNKNOWN 2985&& tv_check_for_opt_bool_arg (argvars ,3 )== FAIL )) { 2986return ; 2987 } 2988 2989const char * const str = tv_get_string_chk (& argvars [0 ]); 2990varnumber_T idx = tv_get_number_chk (& argvars [1 ],NULL ); 2991if (str == NULL || idx < 0 ) { 2992return ; 2993 } 2994 2995varnumber_T countcc = false; 2996varnumber_T charidx = false; 2997if (argvars [2 ].v_type != VAR_UNKNOWN ) { 2998countcc = tv_get_bool (& argvars [2 ]); 2999if (argvars [3 ].v_type != VAR_UNKNOWN ) { 3000charidx = tv_get_bool (& argvars [3 ]); 3001 } 3002 } 3003 3004int (* ptr2len )(const char * ); 3005if (countcc ) { 3006ptr2len = utf_ptr2len ; 3007 }else { 3008ptr2len = utfc_ptr2len ; 3009 } 3010 3011const char * p ; 3012int len ; 3013int utf16idx = 0 ; 3014for (p = str ,len = 0 ;charidx ?idx >=0 :p <=str + idx ;len ++ ) { 3015if (* p == NUL ) { 3016// If the index is exactly the number of bytes or characters in the 3017// string then return the length of the string in utf-16 code units. 3018if (charidx ? (idx == 0 ) : (p == (str + idx ))) { 3019rettv -> vval .v_number = len ; 3020 } 3021return ; 3022 } 3023utf16idx = len ; 3024const int clen = ptr2len (p ); 3025const int c = (clen > 1 ) ?utf_ptr2char (p ) :* p ; 3026if (c > 0xFFFF ) { 3027len ++ ; 3028 } 3029p += clen ; 3030if (charidx ) { 3031idx -- ; 3032 } 3033 } 3034 3035rettv -> vval .v_number = utf16idx ; 3036} 3037 3038/// "tolower(string)" function 3039void f_tolower (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 3040{ 3041rettv -> v_type = VAR_STRING ; 3042rettv -> vval .v_string = strcase_save (tv_get_string (& argvars [0 ]), false); 3043} 3044 3045/// "toupper(string)" function 3046void f_toupper (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 3047{ 3048rettv -> v_type = VAR_STRING ; 3049rettv -> vval .v_string = strcase_save (tv_get_string (& argvars [0 ]), true); 3050} 3051 3052/// "tr(string, fromstr, tostr)" function 3053void f_tr (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 3054{ 3055char buf [NUMBUFLEN ]; 3056char buf2 [NUMBUFLEN ]; 3057 3058const char * in_str = tv_get_string (& argvars [0 ]); 3059const char * fromstr = tv_get_string_buf_chk (& argvars [1 ],buf ); 3060const char * tostr = tv_get_string_buf_chk (& argvars [2 ],buf2 ); 3061 3062// Default return value: empty string. 3063rettv -> v_type = VAR_STRING ; 3064rettv -> vval .v_string = NULL ; 3065if (fromstr == NULL || tostr == NULL ) { 3066return ;// Type error; errmsg already given. 3067 } 3068garray_T ga ; 3069ga_init (& ga , (int )sizeof (char ),80 ); 3070 3071// fromstr and tostr have to contain the same number of chars. 3072bool first = true; 3073while (* in_str != NUL ) { 3074const char * cpstr = in_str ; 3075const int inlen = utfc_ptr2len (in_str ); 3076int cplen = inlen ; 3077int idx = 0 ; 3078int fromlen ; 3079for (const char * p = fromstr ;* p != NUL ;p += fromlen ) { 3080fromlen = utfc_ptr2len (p ); 3081if (fromlen == inlen && strncmp (in_str ,p , (size_t )inlen )== 0 ) { 3082int tolen ; 3083for (p = tostr ;* p != NUL ;p += tolen ) { 3084tolen = utfc_ptr2len (p ); 3085if (idx -- == 0 ) { 3086cplen = tolen ; 3087cpstr = p ; 3088break ; 3089 } 3090 } 3091if (* p == NUL ) {// tostr is shorter than fromstr. 3092 gotoerror ; 3093 } 3094break ; 3095 } 3096idx ++ ; 3097 } 3098 3099if (first && cpstr == in_str ) { 3100// Check that fromstr and tostr have the same number of 3101// (multi-byte) characters. Done only once when a character 3102// of in_str doesn't appear in fromstr. 3103first = false; 3104int tolen ; 3105for (const char * p = tostr ;* p != NUL ;p += tolen ) { 3106tolen = utfc_ptr2len (p ); 3107idx -- ; 3108 } 3109if (idx != 0 ) { 3110 gotoerror ; 3111 } 3112 } 3113 3114ga_grow (& ga ,cplen ); 3115memmove ((char * )ga .ga_data + ga .ga_len ,cpstr , (size_t )cplen ); 3116ga .ga_len += cplen ; 3117 3118in_str += inlen ; 3119 } 3120 3121// add a terminating NUL 3122ga_append (& ga ,NUL ); 3123 3124rettv -> vval .v_string = ga .ga_data ; 3125return ; 3126error : 3127semsg (_ (e_invarg2 ),fromstr ); 3128ga_clear (& ga ); 3129} 3130 3131/// "trim({expr})" function 3132void f_trim (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 3133{ 3134char buf1 [NUMBUFLEN ]; 3135char buf2 [NUMBUFLEN ]; 3136const char * head = tv_get_string_buf_chk (& argvars [0 ],buf1 ); 3137const char * mask = NULL ; 3138const char * prev ; 3139const char * p ; 3140int dir = 0 ; 3141 3142rettv -> v_type = VAR_STRING ; 3143rettv -> vval .v_string = NULL ; 3144if (head == NULL ) { 3145return ; 3146 } 3147 3148if (tv_check_for_opt_string_arg (argvars ,1 )== FAIL ) { 3149return ; 3150 } 3151 3152if (argvars [1 ].v_type == VAR_STRING ) { 3153mask = tv_get_string_buf_chk (& argvars [1 ],buf2 ); 3154if (* mask == NUL ) { 3155mask = NULL ; 3156 } 3157 3158if (argvars [2 ].v_type != VAR_UNKNOWN ) { 3159bool error = false; 3160// leading or trailing characters to trim 3161dir = (int )tv_get_number_chk (& argvars [2 ],& error ); 3162if (error ) { 3163return ; 3164 } 3165if (dir < 0 || dir > 2 ) { 3166semsg (_ (e_invarg2 ),tv_get_string (& argvars [2 ])); 3167return ; 3168 } 3169 } 3170 } 3171 3172if (dir == 0 || dir == 1 ) { 3173// Trim leading characters 3174while (* head != NUL ) { 3175int c1 = utf_ptr2char (head ); 3176if (mask == NULL ) { 3177if (c1 > ' ' && c1 != 0xa0 ) { 3178break ; 3179 } 3180 }else { 3181for (p = mask ;* p != NUL ;MB_PTR_ADV (p )) { 3182if (c1 == utf_ptr2char (p )) { 3183break ; 3184 } 3185 } 3186if (* p == NUL ) { 3187break ; 3188 } 3189 } 3190MB_PTR_ADV (head ); 3191 } 3192 } 3193 3194const char * tail = head + strlen (head ); 3195if (dir == 0 || dir == 2 ) { 3196// Trim trailing characters 3197for (;tail > head ;tail = prev ) { 3198prev = tail ; 3199MB_PTR_BACK (head ,prev ); 3200int c1 = utf_ptr2char (prev ); 3201if (mask == NULL ) { 3202if (c1 > ' ' && c1 != 0xa0 ) { 3203break ; 3204 } 3205 }else { 3206for (p = mask ;* p != NUL ;MB_PTR_ADV (p )) { 3207if (c1 == utf_ptr2char (p )) { 3208break ; 3209 } 3210 } 3211if (* p == NUL ) { 3212break ; 3213 } 3214 } 3215 } 3216 } 3217rettv -> vval .v_string = xstrnsave (head , (size_t )(tail - head )); 3218} 3219 3220/// compare two keyvalue_T structs by case sensitive value 3221int cmp_keyvalue_value (const void * a ,const void * b ) 3222{ 3223keyvalue_T * kv1 = (keyvalue_T * )a ; 3224keyvalue_T * kv2 = (keyvalue_T * )b ; 3225 3226return strcmp (kv1 -> value ,kv2 -> value ); 3227} 3228 3229/// compare two keyvalue_T structs by value with length 3230int cmp_keyvalue_value_n (const void * a ,const void * b ) 3231{ 3232keyvalue_T * kv1 = (keyvalue_T * )a ; 3233keyvalue_T * kv2 = (keyvalue_T * )b ; 3234 3235return strncmp (kv1 -> value ,kv2 -> value ,MAX (kv1 -> length ,kv2 -> length )); 3236} 3237 3238/// compare two keyvalue_T structs by case insensitive value 3239int cmp_keyvalue_value_i (const void * a ,const void * b ) 3240{ 3241keyvalue_T * kv1 = (keyvalue_T * )a ; 3242keyvalue_T * kv2 = (keyvalue_T * )b ; 3243 3244return STRICMP (kv1 -> value ,kv2 -> value ); 3245} 3246 3247/// compare two keyvalue_T structs by case insensitive value with length 3248int cmp_keyvalue_value_ni (const void * a ,const void * b ) 3249{ 3250keyvalue_T * kv1 = (keyvalue_T * )a ; 3251keyvalue_T * kv2 = (keyvalue_T * )b ; 3252 3253return STRNICMP (kv1 -> value ,kv2 -> value ,MAX (kv1 -> length ,kv2 -> length )); 3254}