robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
90.1 KiB3254 linesraw
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)
74  FUNC_ATTR_NONNULL_RET FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_ALL
75{
76  return 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)
82  FUNC_ATTR_NONNULL_RET FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_ALL
83{
84  return 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)
91  FUNC_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.
95  size_t length = 1;                    // count the trailing NUL
96  for (const char *p = string; *p; p++) {
97    const size_t l = (size_t)(utfc_ptr2len(p));
98    if (l > 1) {
99      length += l;                      // count a multibyte char
100      p += l - 1;
101      continue;
102    }
103    if (vim_strchr(esc_chars, (uint8_t)(*p)) != NULL || (bsl && rem_backslash(p))) {
104      length++;                         // count a backslash
105    }
106    length++;                           // count an ordinary char
107  }
108
109  char *escaped_string = xmalloc(length);
110  char *p2 = escaped_string;
111  for (const char *p = string; *p; p++) {
112    const size_t l = (size_t)(utfc_ptr2len(p));
113    if (l > 1) {
114      memcpy(p2, p, l);
115      p2 += l;
116      p += l - 1;                     // skip multibyte char
117      continue;
118    }
119    if (vim_strchr(esc_chars, (uint8_t)(*p)) != NULL || (bsl && rem_backslash(p))) {
120      *p2++ = cc;
121    }
122    *p2++ = *p;
123  }
124  *p2 = NUL;
125
126  return 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)
141  FUNC_ATTR_MALLOC FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
142  FUNC_ATTR_NONNULL_RET
143{
144#define ESCAPE_COND(p, inquote, string_end) \
145  (*(p) == '\\' && (inquote) && (p) + 1 < (string_end) && ((p)[1] == '\\' || (p)[1] == '"'))
146  size_t ret_length = 0;
147  bool inquote = false;
148  const char *const string_end = string + length;
149  for (const char *p = string; p < string_end; p++) {
150    if (*p == '"') {
151      inquote = !inquote;
152    } else if (ESCAPE_COND(p, inquote, string_end)) {
153      ret_length++;
154      p++;
155    } else {
156      ret_length++;
157    }
158  }
159
160  char *const ret = xmallocz(ret_length);
161  char *rp = ret;
162  inquote = false;
163  for (const char *p = string; p < string_end; p++) {
164    if (*p == '"') {
165      inquote = !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
174  return 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)
187  FUNC_ATTR_NONNULL_RET FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_ALL
188{
189  size_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.
195  int 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 '\'.
199  bool fish_like = fish_like_shell();
200
201  // First count the number of extra bytes required.
202  size_t length = strlen(string) + 3;       // two quotes and a trailing NUL
203  for (const char *p = string; *p != NUL; MB_PTR_ADV(p)) {
204#ifdef MSWIN
205    if (!p_ssl) {
206      if (*p == '"') {
207        length++;                       // " -> ""
208      }
209    } else
210#endif
211    if (*p == '\'') {
212      length += 3;                      // ' => '\''
213    }
214    if ((*p == '\n' && (csh_like || do_newline))
215        || (*p == '!' && (csh_like || do_special))) {
216      length++;                         // insert backslash
217      if (csh_like && do_special) {
218        length++;                       // insert backslash
219      }
220    }
221    if (do_special && find_cmdline_var(p, &l) >= 0) {
222      length++;                         // insert backslash
223      p += l - 1;
224    }
225    if (*p == '\\' && fish_like) {
226      length++;  // insert backslash
227    }
228  }
229
230  // Allocate memory for the result and fill it.
231  char *escaped_string = xmalloc(length);
232  char *d = escaped_string;
233
234  // add opening quote
235#ifdef MSWIN
236  if (!p_ssl) {
237    *d++ = '"';
238  } else
239#endif
240  *d++ = '\'';
241
242  for (const char *p = string; *p != NUL;) {
243#ifdef MSWIN
244    if (!p_ssl) {
245      if (*p == '"') {
246        *d++ = '"';
247        *d++ = '"';
248        p++;
249        continue;
250      }
251    } else
252#endif
253    if (*p == '\'') {
254      *d++ = '\'';
255      *d++ = '\\';
256      *d++ = '\'';
257      *d++ = '\'';
258      p++;
259      continue;
260    }
261    if ((*p == '\n' && (csh_like || do_newline))
262        || (*p == '!' && (csh_like || do_special))) {
263      *d++ = '\\';
264      if (csh_like && do_special) {
265        *d++ = '\\';
266      }
267      *d++ = *p++;
268      continue;
269    }
270    if (do_special && find_cmdline_var(p, &l) >= 0) {
271      *d++ = '\\';                    // insert backslash
272      memcpy(d, p, l);                // copy the var
273      d += l;
274      p += l;
275      continue;
276    }
277    if (*p == '\\' && fish_like) {
278      *d++ = '\\';
279      *d++ = *p++;
280      continue;
281    }
282
283    mb_copy_char(&p, &d);
284  }
285
286  // add terminating quote and finish with a NUL
287#ifdef MSWIN
288  if (!p_ssl) {
289    *d++ = '"';
290  } else
291#endif
292  *d++ = '\'';
293  *d = NUL;
294
295  return 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)
301  FUNC_ATTR_NONNULL_RET FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_ALL
302{
303  char *p1 = xmalloc(strlen(string) + 1);
304  vim_strcpy_up(p1, string);
305  return 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)
311  FUNC_ATTR_NONNULL_RET FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_ALL
312{
313  char *p1 = xmalloc(len + 1);
314  vim_strncpy_up(p1, string, len);
315  return p1;
316}
317
318// ASCII lower-to-upper case translation, language independent.
319void vim_strup(char *p)
320  FUNC_ATTR_NONNULL_ALL
321{
322  uint8_t c;
323  while ((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 *restrict dst, const char *restrict src)
330  FUNC_ATTR_NONNULL_ALL
331{
332  uint8_t c;
333  while ((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 *restrict dst, const char *restrict src, size_t n)
341  FUNC_ATTR_NONNULL_ALL
342{
343  uint8_t c;
344  while (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 *restrict dst, const char *restrict src, size_t n)
352  FUNC_ATTR_NONNULL_ALL
353{
354  uint8_t c;
355  while (n--) {
356    c = (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)
366  FUNC_ATTR_NONNULL_ALL
367{
368  size_t i = 0;
369  for (const char *p = src; *p != NUL;) {
370    CharInfo ci = utf_ptr2CharInfo(p);
371    int c = ci.value < 0 ? (uint8_t)(*p) : ci.value;
372    i += (size_t)utf_char2bytes(mb_toupper(c), dst + i);
373    p += ci.len;
374  }
375  dst[i] = NUL;
376  return 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)
388  FUNC_ATTR_NONNULL_RET FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_ALL
389{
390  // Calculate the initial length and allocate memory for the result
391  size_t orig_len = strlen(orig);
392  // +1 for the null terminator
393  char *res = xmalloc(orig_len + 1);
394  // Index in the result string
395  size_t res_index = 0;
396  // Current position in the original string
397  const char *p = orig;
398
399  while (*p != NUL) {
400    CharInfo char_info = utf_ptr2CharInfo(p);
401    int c = char_info.value < 0 ? (uint8_t)(*p) : char_info.value;
402    int newc = upper ? mb_toupper(c) : mb_tolower(c);
403    // Cast to size_t to avoid mixing types in arithmetic
404    size_t newl = (size_t)utf_char2len(newc);
405
406    // Check if there's enough space in the allocated memory
407    if (res_index + newl > orig_len) {
408      // Need more space: allocate extra space for the new character and the null terminator
409      size_t new_size = res_index + newl + 1;
410      res = xrealloc(res, new_size);
411      // Adjust the original length to the new size, minus the null terminator
412      orig_len = new_size - 1;
413    }
414
415    // Write the possibly new character into the result string
416    utf_char2bytes(newc, res + res_index);
417    // Move the index in the result string
418    res_index += newl;
419    // Move to the next character in the original string
420    p += char_info.len;
421  }
422
423  // Null-terminate the result string
424  res[res_index] = NUL;
425  return res;
426}
427
428// delete spaces at the end of a string
429void del_trailing_spaces(char *ptr)
430  FUNC_ATTR_NONNULL_ALL
431{
432  char *q = ptr + strlen(ptr);
433  while (--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)
443  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE
444{
445  int i;
446
447  while (true) {
448    i = (int)TOLOWER_LOC((uint8_t)(*s1)) - (int)TOLOWER_LOC((uint8_t)(*s2));
449    if (i != 0) {
450      return i;                             // this character different
451    }
452    if (*s1 == NUL) {
453      break;                                // strings match until NUL
454    }
455    s1++;
456    s2++;
457  }
458  return 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)
467  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE
468{
469  int i;
470
471  while (len > 0) {
472    i = (int)TOLOWER_LOC((uint8_t)(*s1)) - (int)TOLOWER_LOC((uint8_t)(*s2));
473    if (i != 0) {
474      return i;                             // this character different
475    }
476    if (*s1 == NUL) {
477      break;                                // strings match until NUL
478    }
479    s1++;
480    s2++;
481    len--;
482  }
483  return 0;                                 // strings match
484}
485#endif
486
487/// Case-insensitive `strequal`.
488bool striequal(const char *a, const char *b)
489  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
490{
491  return (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)
498  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
499{
500  int i = 0;
501  while (len > 0) {
502    i = TOLOWER_ASC(*s1) - TOLOWER_ASC(*s2);
503    if (i != 0) {
504      break;                       // this character is different
505    }
506    if (*s1 == NUL) {
507      break;                       // strings match until NUL
508    }
509    s1++;
510    s2++;
511    len--;
512  }
513  return 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)
525  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
526{
527  if (c <= 0) {
528    return NULL;
529  } else if (c < 0x80) {
530    // NOLINTNEXTLINE(*-casting): remove once CI uses glibc 2.43
531    return (char *)strchr(string, c);
532  } else {
533    char u8char[MB_MAXBYTES + 1];
534    const int len = utf_char2bytes(c, u8char);
535    u8char[len] = NUL;
536    // NOLINTNEXTLINE(*-casting): remove once CI uses glibc 2.43
537    return (char *)strstr(string, u8char);
538  }
539}
540
541// Sort an array of strings.
542
543static int sort_compare(const void *s1, const void *s2)
544  FUNC_ATTR_NONNULL_ALL
545{
546  return strcmp(*(char **)s1, *(char **)s2);
547}
548
549void sort_strings(char **files, int count)
550{
551  qsort((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)
557  FUNC_ATTR_PURE
558{
559  if (s != NULL) {
560    for (const char *p = s; *p != NUL; p++) {
561      if ((uint8_t)(*p) >= 128) {
562        return true;
563      }
564    }
565  }
566  return 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)
572  FUNC_ATTR_PURE
573{
574  if (s != NULL) {
575    for (size_t i = 0; i < len; i++) {
576      if ((uint8_t)s[i] >= 128) {
577        return true;
578      }
579    }
580  }
581  return false;
582}
583
584/// Concatenate two strings and return the result in allocated memory.
585char *concat_str(const char *restrict str1, const char *restrict str2)
586  FUNC_ATTR_NONNULL_RET FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_ALL
587{
588  size_t l = strlen(str1);
589  char *dest = xmalloc(l + strlen(str2) + 1);
590  STRCPY(dest, str1);
591  STRCPY(dest + l, str2);
592  return dest;
593}
594
595static const char *const e_printf =
596  N_("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)
607  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
608{
609  int idx = *idxp - 1;
610  varnumber_T n = 0;
611
612  if (tvs[idx].v_type == VAR_UNKNOWN) {
613    emsg(_(e_printf));
614  } else {
615    (*idxp)++;
616    bool err = false;
617    n = tv_get_number_chk(&tvs[idx], &err);
618    if (err) {
619      n = 0;
620    }
621  }
622  return 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)
640  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
641{
642  int idx = *idxp - 1;
643  const char *s = NULL;
644
645  if (tvs[idx].v_type == VAR_UNKNOWN) {
646    emsg(_(e_printf));
647  } else {
648    (*idxp)++;
649    if (tvs[idx].v_type == VAR_STRING || tvs[idx].v_type == VAR_NUMBER) {
650      s = tv_get_string_chk(&tvs[idx]);
651      *tofree = NULL;
652    } else {
653      s = *tofree = encode_tv2echo(&tvs[idx], NULL);
654    }
655  }
656  return 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)
669  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
670{
671#define OFF(attr) offsetof(union typval_vval_union, attr)
672  STATIC_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
683  const int idx = *idxp - 1;
684  if (tvs[idx].v_type == VAR_UNKNOWN) {
685    emsg(_(e_printf));
686    return NULL;
687  }
688  (*idxp)++;
689  return 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)
702  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
703{
704  int idx = *idxp - 1;
705  float_T f = 0;
706
707  if (tvs[idx].v_type == VAR_UNKNOWN) {
708    emsg(_(e_printf));
709  } else {
710    (*idxp)++;
711    if (tvs[idx].v_type == VAR_FLOAT) {
712      f = tvs[idx].vval.v_float;
713    } else if (tvs[idx].v_type == VAR_NUMBER) {
714      f = (float_T)tvs[idx].vval.v_number;
715    } else {
716      emsg(_("E807: Expected Float argument for printf()"));
717    }
718  }
719  return 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, ...)
763  FUNC_ATTR_PRINTF(3, 4)
764{
765  const size_t len = strlen(str);
766  size_t space;
767
768  if (str_m <= len) {
769    space = 0;
770  } else {
771    space = str_m - len;
772  }
773  va_list ap;
774  va_start(ap, fmt);
775  const int str_l = vim_vsnprintf(str + len, space, fmt, ap);
776  va_end(ap);
777  return 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, ...)
789  FUNC_ATTR_PRINTF(3, 4)
790{
791  va_list ap;
792  va_start(ap, fmt);
793  const int str_l = vim_vsnprintf(str, str_m, fmt, ap);
794  va_end(ap);
795  return 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,
801                                int space_for_positive)
802{
803  static const char *table[] = {
804    "-inf", "inf", "+inf", " inf",
805    "-INF", "INF", "+INF", " INF"
806  };
807  int idx = positive * (1 + force_sign + force_sign * space_for_positive);
808  if (ASCII_ISUPPER(fmt_spec)) {
809    idx += 4;
810  }
811  return 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{
823  va_list ap;
824  int str_l;
825
826  if (str_m == 0) {
827    return 0;
828  }
829
830  va_start(ap, fmt);
831  str_l = vim_vsnprintf_typval(str, str_m, fmt, ap, NULL);
832  va_end(ap);
833
834  if (str_l < 0) {
835    *str = NUL;
836    return 0;
837  }
838  return ((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{
843  return vim_vsnprintf_typval(str, str_m, fmt, ap, NULL);
844}
845
846enum {
847  TYPE_UNKNOWN = -1,
848  TYPE_INT,
849  TYPE_LONGINT,
850  TYPE_LONGLONGINT,
851  TYPE_SIGNEDSIZET,
852  TYPE_UNSIGNEDINT,
853  TYPE_UNSIGNEDLONGINT,
854  TYPE_UNSIGNEDLONGLONGINT,
855  TYPE_SIZET,
856  TYPE_POINTER,
857  TYPE_PERCENT,
858  TYPE_CHAR,
859  TYPE_STRING,
860  TYPE_FLOAT,
861};
862
863/// Types that can be used in a format string
864static int format_typeof(const char *type)
865  FUNC_ATTR_NONNULL_ALL
866{
867  // allowed values: \0, h, l, L
868  char length_modifier = NUL;
869
870  // current conversion specifier character
871  char fmt_spec = NUL;
872
873  // parse 'h', 'l', 'll' and 'z' length modifiers
874  if (*type == 'h' || *type == 'l' || *type == 'z') {
875    length_modifier = *type;
876    type++;
877    if (length_modifier == 'l' && *type == 'l') {
878      // double l = long long
879      length_modifier = 'L';
880      type++;
881    }
882  }
883  fmt_spec = *type;
884
885  // common synonyms:
886  switch (fmt_spec) {
887  case 'i':
888    fmt_spec = 'd'; break;
889  case '*':
890    fmt_spec = 'd'; length_modifier = 'h'; break;
891  case 'D':
892    fmt_spec = 'd'; length_modifier = 'l'; break;
893  case 'U':
894    fmt_spec = 'u'; length_modifier = 'l'; break;
895  case 'O':
896    fmt_spec = 'o'; length_modifier = 'l'; break;
897  default:
898    break;
899  }
900
901  // get parameter value, do initial processing
902  switch (fmt_spec) {
903  // '%' and 'c' behave similar to 's' regarding flags and field
904  // widths
905  case '%':
906    return TYPE_PERCENT;
907
908  case 'c':
909    return TYPE_CHAR;
910
911  case 's':
912  case 'S':
913    return TYPE_STRING;
914
915  case 'd':
916  case 'u':
917  case 'b':
918  case 'B':
919  case 'o':
920  case 'x':
921  case 'X':
922  case '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
932    if (fmt_spec == 'p') {
933      return TYPE_POINTER;
934    } else if (fmt_spec == 'b' || fmt_spec == 'B') {
935      return TYPE_UNSIGNEDLONGLONGINT;
936    } else if (fmt_spec == 'd') {
937      // signed
938      switch (length_modifier) {
939      case NUL:
940      case 'h':
941        // char and short arguments are passed as int.
942        return TYPE_INT;
943      case 'l':
944        return TYPE_LONGINT;
945      case 'L':
946        return TYPE_LONGLONGINT;
947      case 'z':
948        return TYPE_SIGNEDSIZET;
949      }
950    } else {
951      // unsigned
952      switch (length_modifier) {
953      case NUL:
954      case 'h':
955        return TYPE_UNSIGNEDINT;
956      case 'l':
957        return TYPE_UNSIGNEDLONGINT;
958      case 'L':
959        return TYPE_UNSIGNEDLONGLONGINT;
960      case 'z':
961        return TYPE_SIZET;
962      }
963    }
964    break;
965
966  case 'f':
967  case 'F':
968  case 'e':
969  case 'E':
970  case 'g':
971  case 'G':
972    return TYPE_FLOAT;
973  }
974
975  return TYPE_UNKNOWN;
976}
977
978static const char *format_typename(const char *type)
979  FUNC_ATTR_NONNULL_ALL
980{
981  switch (format_typeof(type)) {
982  case TYPE_INT:
983    return typename_int;
984  case TYPE_LONGINT:
985    return typename_longint;
986  case TYPE_LONGLONGINT:
987    return typename_longlongint;
988  case TYPE_UNSIGNEDINT:
989    return typename_unsignedint;
990  case TYPE_SIGNEDSIZET:
991    return typename_signedsizet;
992  case TYPE_UNSIGNEDLONGINT:
993    return typename_unsignedlongint;
994  case TYPE_UNSIGNEDLONGLONGINT:
995    return typename_unsignedlonglongint;
996  case TYPE_SIZET:
997    return typename_sizet;
998  case TYPE_POINTER:
999    return _(typename_pointer);
1000  case TYPE_PERCENT:
1001    return _(typename_percent);
1002  case TYPE_CHAR:
1003    return typename_char;
1004  case TYPE_STRING:
1005    return _(typename_string);
1006  case TYPE_FLOAT:
1007    return typename_float;
1008  }
1009
1010  return _(typename_unknown);
1011}
1012
1013static int adjust_types(const char ***ap_types, int arg, int *num_posarg, const char *type)
1014  FUNC_ATTR_NONNULL_ALL
1015{
1016  if (arg <= 0) {
1017    semsg(_(e_invalid_format_specifier_str), type);
1018    return FAIL;
1019  }
1020
1021  if (*ap_types == NULL || *num_posarg < arg) {
1022    const 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
1026    for (int idx = *num_posarg; idx < arg; idx++) {
1027      new_types[idx] = NULL;
1028    }
1029
1030    *ap_types = new_types;
1031    *num_posarg = arg;
1032  }
1033
1034  if ((*ap_types)[arg - 1] != NULL) {
1035    if ((*ap_types)[arg - 1][0] == '*' || type[0] == '*') {
1036      const char *pt = type;
1037      if (pt[0] == '*') {
1038        pt = (*ap_types)[arg - 1];
1039      }
1040
1041      if (pt[0] != '*') {
1042        switch (pt[0]) {
1043        case 'd':
1044        case 'i':
1045          break;
1046        default:
1047          semsg(_(e_positional_num_field_spec_reused_str_str), arg,
1048                format_typename((*ap_types)[arg - 1]), format_typename(type));
1049          return FAIL;
1050        }
1051      }
1052    } else {
1053      if (format_typeof(type) != format_typeof((*ap_types)[arg - 1])) {
1054        semsg(_(e_positional_arg_num_type_inconsistent_str_str), arg,
1055              format_typename(type), format_typename((*ap_types)[arg - 1]));
1056        return FAIL;
1057      }
1058    }
1059  }
1060
1061  (*ap_types)[arg - 1] = type;
1062
1063  return OK;
1064}
1065
1066static void format_overflow_error(const char *pstart)
1067{
1068  const char *p = pstart;
1069
1070  while (ascii_isdigit((int)(*p))) {
1071    p++;
1072  }
1073
1074  semsg(_(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
1084  while (ascii_isdigit((int)(**p)) && *uj < MAX_ALLOWED_STRING_WIDTH) {
1085    *uj = 10 * *uj + (unsigned)(**p - '0');
1086    (*p)++;
1087  }
1088
1089  if (*uj > MAX_ALLOWED_STRING_WIDTH) {
1090    if (overflow_err) {
1091      format_overflow_error(pstart);
1092      return FAIL;
1093    } else {
1094      *uj = MAX_ALLOWED_STRING_WIDTH;
1095    }
1096  }
1097
1098  return OK;
1099}
1100
1101static int parse_fmt_types(const char ***ap_types, int *num_posarg, const char *fmt, typval_T *tvs)
1102  FUNC_ATTR_NONNULL_ARG(1, 2)
1103{
1104  const char *p = fmt;
1105  const char *arg = NULL;
1106
1107  int any_pos = 0;
1108  int 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
1118  if (p == NULL) {
1119    return OK;
1120  }
1121
1122  while (*p != NUL) {
1123    if (*p != '%') {
1124      size_t n = (size_t)(xstrchrnul(p + 1, '%') - p);
1125      p += n;
1126    } else {
1127      // allowed values: \0, h, l, L
1128      char length_modifier = NUL;
1129
1130      // variable for positional arg
1131      int pos_arg = -1;
1132      const char *pstart = p + 1;
1133
1134      p++;  // skip '%'
1135
1136      // First check to see if we find a positional
1137      // argument specifier
1138      const char *ptype = p;
1139
1140      while (ascii_isdigit(*ptype)) {
1141        ptype++;
1142      }
1143
1144      if (*ptype == '$') {
1145        if (*p == '0') {
1146          // 0 flag at the wrong place
1147          semsg(_(e_invalid_format_specifier_str), fmt);
1148          goto error;
1149        }
1150
1151        // Positional argument
1152        unsigned uj;
1153
1154        if (get_unsigned_int(pstart, &p, &uj, tvs != NULL) == FAIL) {
1155          goto error;
1156        }
1157
1158        pos_arg = (int)uj;
1159
1160        any_pos = 1;
1161        CHECK_POS_ARG;
1162
1163        p++;
1164      }
1165
1166      // parse flags
1167      while (*p == '0' || *p == '-' || *p == '+' || *p == ' '
1168             || *p == '#' || *p == '\'') {
1169        switch (*p) {
1170        case '0':
1171          break;
1172        case '-':
1173          break;
1174        case '+':
1175          break;
1176        case ' ':  // If both the ' ' and '+' flags appear, the ' '
1177                   // flag should be ignored
1178          break;
1179        case '#':
1180          break;
1181        case '\'':
1182          break;
1183        }
1184        p++;
1185      }
1186      // If the '0' and '-' flags both appear, the '0' flag should be
1187      // ignored.
1188
1189      // parse field width
1190      if (*(arg = p) == '*') {
1191        p++;
1192
1193        if (ascii_isdigit((int)(*p))) {
1194          // Positional argument field width
1195          unsigned uj;
1196
1197          if (get_unsigned_int(arg + 1, &p, &uj, tvs != NULL) == FAIL) {
1198            goto error;
1199          }
1200
1201          if (*p != '$') {
1202            semsg(_(e_invalid_format_specifier_str), fmt);
1203            goto error;
1204          } else {
1205            p++;
1206            any_pos = 1;
1207            CHECK_POS_ARG;
1208
1209            if (adjust_types(ap_types, (int)uj, num_posarg, arg) == FAIL) {
1210              goto error;
1211            }
1212          }
1213        } else {
1214          any_arg = 1;
1215          CHECK_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
1220        const char *digstart = p;
1221        unsigned uj;
1222
1223        if (get_unsigned_int(digstart, &p, &uj, tvs != NULL) == FAIL) {
1224          goto error;
1225        }
1226
1227        if (*p == '$') {
1228          semsg(_(e_invalid_format_specifier_str), fmt);
1229          goto error;
1230        }
1231      }
1232
1233      // parse precision
1234      if (*p == '.') {
1235        p++;
1236
1237        if (*(arg = p) == '*') {
1238          p++;
1239
1240          if (ascii_isdigit((int)(*p))) {
1241            // Parse precision
1242            unsigned uj;
1243
1244            if (get_unsigned_int(arg + 1, &p, &uj, tvs != NULL) == FAIL) {
1245              goto error;
1246            }
1247
1248            if (*p == '$') {
1249              any_pos = 1;
1250              CHECK_POS_ARG;
1251
1252              p++;
1253
1254              if (adjust_types(ap_types, (int)uj, num_posarg, arg) == FAIL) {
1255                goto error;
1256              }
1257            } else {
1258              semsg(_(e_invalid_format_specifier_str), fmt);
1259              goto error;
1260            }
1261          } else {
1262            any_arg = 1;
1263            CHECK_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
1268          const char *digstart = p;
1269          unsigned uj;
1270
1271          if (get_unsigned_int(digstart, &p, &uj, tvs != NULL) == FAIL) {
1272            goto error;
1273          }
1274
1275          if (*p == '$') {
1276            semsg(_(e_invalid_format_specifier_str), fmt);
1277            goto error;
1278          }
1279        }
1280      }
1281
1282      if (pos_arg != -1) {
1283        any_pos = 1;
1284        CHECK_POS_ARG;
1285
1286        ptype = p;
1287      }
1288
1289      // parse 'h', 'l', 'll' and 'z' length modifiers
1290      if (*p == 'h' || *p == 'l' || *p == 'z') {
1291        length_modifier = *p;
1292        p++;
1293        if (length_modifier == 'l' && *p == 'l') {
1294          // double l = long long
1295          // length_modifier = 'L';
1296          p++;
1297        }
1298      }
1299
1300      switch (*p) {
1301      // Check for known format specifiers. % is special!
1302      case 'i':
1303      case '*':
1304      case 'd':
1305      case 'u':
1306      case 'o':
1307      case 'D':
1308      case 'U':
1309      case 'O':
1310      case 'x':
1311      case 'X':
1312      case 'b':
1313      case 'B':
1314      case 'c':
1315      case 's':
1316      case 'S':
1317      case 'p':
1318      case 'f':
1319      case 'F':
1320      case 'e':
1321      case 'E':
1322      case 'g':
1323      case 'G':
1324        if (pos_arg != -1) {
1325          if (adjust_types(ap_types, pos_arg, num_posarg, ptype) == FAIL) {
1326            goto error;
1327          }
1328        } else {
1329          any_arg = 1;
1330          CHECK_POS_ARG;
1331        }
1332        break;
1333
1334      default:
1335        if (pos_arg != -1) {
1336          semsg(_(e_cannot_mix_positional_and_non_positional_str), fmt);
1337          goto error;
1338        }
1339      }
1340
1341      if (*p != NUL) {
1342        p++;     // step over the just processed conversion specifier
1343      }
1344    }
1345  }
1346
1347  for (int arg_idx = 0; arg_idx < *num_posarg; arg_idx++) {
1348    if ((*ap_types)[arg_idx] == NULL) {
1349      semsg(_(e_fmt_arg_nr_unused_str), arg_idx + 1, fmt);
1350      goto error;
1351    }
1352
1353    if (tvs != NULL && tvs[arg_idx].v_type == VAR_UNKNOWN) {
1354      semsg(_(e_positional_nr_out_of_bounds_str), arg_idx + 1, fmt);
1355      goto error;
1356    }
1357  }
1358
1359  return OK;
1360
1361error:
1362  xfree(*ap_types);
1363  *ap_types = NULL;
1364  *num_posarg = 0;
1365  return FAIL;
1366}
1367
1368static void skip_to_arg(const char **ap_types, va_list ap_start, va_list *ap, int *arg_idx,
1369                        int *arg_cur, const char *fmt)
1370  FUNC_ATTR_NONNULL_ARG(3, 4, 5)
1371{
1372  int arg_min = 0;
1373
1374  if (*arg_cur + 1 == *arg_idx) {
1375    (*arg_cur)++;
1376    (*arg_idx)++;
1377    return;
1378  }
1379
1380  if (*arg_cur >= *arg_idx) {
1381    // Reset ap to ap_start and skip arg_idx - 1 types
1382    va_end(*ap);
1383    va_copy(*ap, ap_start);
1384  } else {
1385    // Skip over any we should skip
1386    arg_min = *arg_cur;
1387  }
1388
1389  for (*arg_cur = arg_min; *arg_cur < *arg_idx - 1; (*arg_cur)++) {
1390    if (ap_types == NULL || ap_types[*arg_cur] == NULL) {
1391      siemsg(e_aptypes_is_null_nr_str, fmt, *arg_cur);
1392      return;
1393    }
1394
1395    const char *p = ap_types[*arg_cur];
1396
1397    int fmt_type = format_typeof(p);
1398
1399    // get parameter value, do initial processing
1400    switch (fmt_type) {
1401    case TYPE_PERCENT:
1402    case TYPE_UNKNOWN:
1403      break;
1404
1405    case TYPE_CHAR:
1406      va_arg(*ap, int);
1407      break;
1408
1409    case TYPE_STRING:
1410      va_arg(*ap, const char *);
1411      break;
1412
1413    case TYPE_POINTER:
1414      va_arg(*ap, void *);
1415      break;
1416
1417    case TYPE_INT:
1418      va_arg(*ap, int);
1419      break;
1420
1421    case TYPE_LONGINT:
1422      va_arg(*ap, long);
1423      break;
1424
1425    case TYPE_LONGLONGINT:
1426      va_arg(*ap, long long);  // NOLINT(runtime/int)
1427      break;
1428
1429    case TYPE_SIGNEDSIZET:  // implementation-defined, usually ptrdiff_t
1430      va_arg(*ap, ptrdiff_t);
1431      break;
1432
1433    case TYPE_UNSIGNEDINT:
1434      va_arg(*ap, unsigned);
1435      break;
1436
1437    case TYPE_UNSIGNEDLONGINT:
1438      va_arg(*ap, unsigned long);
1439      break;
1440
1441    case TYPE_UNSIGNEDLONGLONGINT:
1442      va_arg(*ap, unsigned long long);  // NOLINT(runtime/int)
1443      break;
1444
1445    case TYPE_SIZET:
1446      va_arg(*ap, size_t);
1447      break;
1448
1449    case TYPE_FLOAT:
1450      va_arg(*ap, double);
1451      break;
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,
1474                         typval_T *const tvs)
1475{
1476  size_t str_l = 0;
1477  bool str_avail = str_l < str_m;
1478  const char *p = fmt;
1479  int arg_cur = 0;
1480  int num_posarg = 0;
1481  int arg_idx = 1;
1482  va_list ap;
1483  const char **ap_types = NULL;
1484
1485  if (parse_fmt_types(&ap_types, &num_posarg, fmt, tvs) == FAIL) {
1486    return 0;
1487  }
1488
1489  va_copy(ap, ap_start);
1490
1491  if (!p) {
1492    p = "";
1493  }
1494  while (*p) {
1495    if (*p != '%') {
1496      // copy up to the next '%' or NUL without any changes
1497      size_t n = (size_t)(xstrchrnul(p + 1, '%') - p);
1498      if (str_avail) {
1499        size_t avail = str_m - str_l;
1500        memmove(str + str_l, p, MIN(n, avail));
1501        str_avail = n < avail;
1502      }
1503      p += n;
1504      assert(n <= SIZE_MAX - str_l);
1505      str_l += n;
1506    } else {
1507      size_t min_field_width = 0;
1508      size_t precision = 0;
1509      bool zero_padding = false;
1510      bool precision_specified = false;
1511      bool justify_left = false;
1512      bool alternate_form = false;
1513      bool force_sign = false;
1514
1515      // if both ' ' and '+' flags appear, ' ' flag should be ignored
1516      int space_for_positive = 1;
1517
1518      // allowed values: \0, h, l, 2 (for ll), z, L
1519      char length_modifier = NUL;
1520
1521      // temporary buffer for simple numeric->string conversion
1522#define TMP_LEN 350    // 1e308 seems reasonable as the maximum printable
1523      char tmp[TMP_LEN];
1524
1525      // string address in case of string argument
1526      const char *str_arg = NULL;
1527
1528      // natural field width of arg without padding and sign
1529      size_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
1534      unsigned char uchar_arg;
1535
1536      // number of zeros to be inserted for numeric conversions as
1537      // required by the precision or minimal field width
1538      size_t number_of_zeros_to_pad = 0;
1539
1540      // index into tmp where zero padding is to be inserted
1541      size_t zero_padding_insertion_ind = 0;
1542
1543      // current conversion specifier character
1544      char fmt_spec = NUL;
1545
1546      // buffer for 's' and 'S' specs
1547      char *tofree = NULL;
1548
1549      // variable for positional arg
1550      int pos_arg = -1;
1551
1552      p++;  // skip '%'
1553
1554      // First check to see if we find a positional
1555      // argument specifier
1556      const char *ptype = p;
1557
1558      while (ascii_isdigit(*ptype)) {
1559        ptype++;
1560      }
1561
1562      if (*ptype == '$') {
1563        // Positional argument
1564        const char *digstart = p;
1565        unsigned uj;
1566
1567        if (get_unsigned_int(digstart, &p, &uj, tvs != NULL) == FAIL) {
1568          goto error;
1569        }
1570
1571        pos_arg = (int)uj;
1572
1573        p++;
1574      }
1575
1576      // parse flags
1577      while (true) {
1578        switch (*p) {
1579        case '0':
1580          zero_padding = true; p++; continue;
1581        case '-':
1582          justify_left = true; p++; continue;
1583        // if both '0' and '-' flags appear, '0' should be ignored
1584        case '+':
1585          force_sign = true; space_for_positive = 0; p++; continue;
1586        case ' ':
1587          force_sign = true; p++; continue;
1588        // if both ' ' and '+' flags appear, ' ' should be ignored
1589        case '#':
1590          alternate_form = true; p++; continue;
1591        case '\'':
1592          p++; continue;
1593        default:
1594          break;
1595        }
1596        break;
1597      }
1598
1599      // parse field width
1600      if (*p == '*') {
1601        const char *digstart = p + 1;
1602
1603        p++;
1604
1605        if (ascii_isdigit((int)(*p))) {
1606          // Positional argument field width
1607          unsigned uj;
1608
1609          if (get_unsigned_int(digstart, &p, &uj, tvs != NULL) == FAIL) {
1610            goto error;
1611          }
1612
1613          arg_idx = (int)uj;
1614
1615          p++;
1616        }
1617
1618        int j = (tvs
1619                 ? (int)tv_nr(tvs, &arg_idx)
1620                 : (skip_to_arg(ap_types, ap_start, &ap, &arg_idx,
1621                                &arg_cur, fmt),
1622                    va_arg(ap, int)));
1623
1624        if (j > MAX_ALLOWED_STRING_WIDTH) {
1625          if (tvs != NULL) {
1626            format_overflow_error(digstart);
1627            goto error;
1628          } else {
1629            j = MAX_ALLOWED_STRING_WIDTH;
1630          }
1631        }
1632
1633        if (j >= 0) {
1634          min_field_width = (size_t)j;
1635        } else {
1636          min_field_width = (size_t)-j;
1637          justify_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
1642        const char *digstart = p;
1643        unsigned uj;
1644
1645        if (get_unsigned_int(digstart, &p, &uj, tvs != NULL) == FAIL) {
1646          goto error;
1647        }
1648
1649        min_field_width = uj;
1650      }
1651
1652      // parse precision
1653      if (*p == '.') {
1654        p++;
1655        precision_specified = true;
1656
1657        if (ascii_isdigit((int)(*p))) {
1658          // size_t could be wider than unsigned int; make sure we
1659          // treat argument like common implementations do
1660          const char *digstart = p;
1661          unsigned uj;
1662
1663          if (get_unsigned_int(digstart, &p, &uj, tvs != NULL) == FAIL) {
1664            goto error;
1665          }
1666
1667          precision = uj;
1668        } else if (*p == '*') {
1669          const char *digstart = p;
1670
1671          p++;
1672
1673          if (ascii_isdigit((int)(*p))) {
1674            // positional argument
1675            unsigned uj;
1676
1677            if (get_unsigned_int(digstart, &p, &uj, tvs != NULL) == FAIL) {
1678              goto error;
1679            }
1680
1681            arg_idx = (int)uj;
1682
1683            p++;
1684          }
1685
1686          int j = (tvs
1687                   ? (int)tv_nr(tvs, &arg_idx)
1688                   : (skip_to_arg(ap_types, ap_start, &ap, &arg_idx,
1689                                  &arg_cur, fmt),
1690                      va_arg(ap, int)));
1691
1692          if (j > MAX_ALLOWED_STRING_WIDTH) {
1693            if (tvs != NULL) {
1694              format_overflow_error(digstart);
1695              goto error;
1696            } else {
1697              j = MAX_ALLOWED_STRING_WIDTH;
1698            }
1699          }
1700
1701          if (j >= 0) {
1702            precision = (size_t)j;
1703          } else {
1704            precision_specified = false;
1705            precision = 0;
1706          }
1707        }
1708      }
1709
1710      // parse 'h', 'l', 'll' and 'z' length modifiers
1711      if (*p == 'h' || *p == 'l' || *p == 'z') {
1712        length_modifier = *p;
1713        p++;
1714        if (length_modifier == 'l' && *p == 'l') {
1715          // double l = long long
1716          length_modifier = 'L';
1717          p++;
1718        }
1719      }
1720
1721      fmt_spec = *p;
1722
1723      // common synonyms
1724      switch (fmt_spec) {
1725      case 'i':
1726        fmt_spec = 'd'; break;
1727      case 'D':
1728        fmt_spec = 'd'; length_modifier = 'l'; break;
1729      case 'U':
1730        fmt_spec = 'u'; length_modifier = 'l'; break;
1731      case 'O':
1732        fmt_spec = 'o'; length_modifier = 'l'; break;
1733      default:
1734        break;
1735      }
1736
1737      switch (fmt_spec) {
1738      case 'd':
1739      case 'u':
1740      case 'o':
1741      case 'x':
1742      case 'X':
1743        if (tvs && length_modifier == NUL) {
1744          length_modifier = 'L';
1745        }
1746      }
1747
1748      if (pos_arg != -1) {
1749        arg_idx = pos_arg;
1750      }
1751
1752      // get parameter value, do initial processing
1753      switch (fmt_spec) {
1754      // '%' and 'c' behave similar to 's' regarding flags and field widths
1755      case '%':
1756      case 'c':
1757      case 's':
1758      case 'S':
1759        str_arg_l = 1;
1760        switch (fmt_spec) {
1761        case '%':
1762          str_arg = p;
1763          break;
1764
1765        case 'c': {
1766          const 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),
1770                            va_arg(ap, int)));
1771
1772          // standard demands unsigned char
1773          uchar_arg = (unsigned char)j;
1774          str_arg = (char *)&uchar_arg;
1775          break;
1776        }
1777
1778        case 's':
1779        case 'S':
1780          str_arg = (tvs
1781                     ? tv_str(tvs, &arg_idx, &tofree)
1782                     : (skip_to_arg(ap_types, ap_start, &ap, &arg_idx,
1783                                    &arg_cur, fmt),
1784                        va_arg(ap, const char *)));
1785
1786          if (!str_arg) {
1787#ifdef ENABLE_ASAN_UBSAN
1788            // this is only for vsnprintf() emulation, v:_null_string handled in tv_str()
1789            if (!tvs) {
1790              __sanitizer_print_stack_trace();
1791              __sanitizer_report_error_summary("SUMMARY: NULL argument passed to %s");
1792            }
1793#endif
1794            str_arg = "[NULL]";
1795            str_arg_l = 6;
1796          } else if (!precision_specified) {
1797            // make sure not to address string beyond the specified
1798            // precision
1799            str_arg_l = strlen(str_arg);
1800          } else if (precision == 0) {
1801            // truncate string if necessary as requested by precision
1802            str_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
1806            str_arg_l = (size_t)((char *)xmemscan(str_arg,
1807                                                  NUL,
1808                                                  MIN(precision,
1809                                                      0x7fffffff))
1810                                 - str_arg);
1811          }
1812          if (fmt_spec == 'S') {
1813            const char *p1;
1814            size_t i;
1815
1816            for (i = 0, p1 = str_arg; *p1; p1 += utfc_ptr2len(p1)) {
1817              size_t cell = (size_t)utf_ptr2cells(p1);
1818              if (precision_specified && i + cell > precision) {
1819                break;
1820              }
1821              i += cell;
1822            }
1823
1824            str_arg_l = (size_t)(p1 - str_arg);
1825            if (min_field_width != 0) {
1826              min_field_width += str_arg_l - i;
1827            }
1828          }
1829          break;
1830
1831        default:
1832          break;
1833        }
1834        break;
1835
1836      case 'd':
1837      case 'u':
1838      case 'b':
1839      case 'B':
1840      case 'o':
1841      case 'x':
1842      case 'X':
1843      case '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)
1850        int arg_sign = 0;
1851
1852        intmax_t arg = 0;
1853        uintmax_t uarg = 0;
1854
1855        // only defined for p conversion
1856        const void *ptr_arg = NULL;
1857
1858        if (fmt_spec == 'p') {
1859          ptr_arg = (tvs
1860                     ? tv_ptr(tvs, &arg_idx)
1861                     : (skip_to_arg(ap_types, ap_start, &ap, &arg_idx,
1862                                    &arg_cur, fmt),
1863                        va_arg(ap, void *)));
1864
1865          if (ptr_arg) {
1866            arg_sign = 1;
1867          }
1868        } else if (fmt_spec == 'b' || fmt_spec == 'B') {
1869          uarg = (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),
1873                     va_arg(ap, unsigned long long)));  // NOLINT(runtime/int)
1874          arg_sign = (uarg != 0);
1875        } else if (fmt_spec == 'd') {
1876          // signed
1877          switch (length_modifier) {
1878          case NUL:
1879            arg = (tvs
1880                   ? (int)tv_nr(tvs, &arg_idx)
1881                   : (skip_to_arg(ap_types, ap_start, &ap, &arg_idx,
1882                                  &arg_cur, fmt),
1883                      va_arg(ap, int)));
1884            break;
1885          case 'h':
1886            // char and short arguments are passed as int16_t
1887            arg = (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),
1892                      va_arg(ap, int)));
1893            break;
1894          case 'l':
1895            arg = (tvs
1896                   ? (long)tv_nr(tvs, &arg_idx)
1897                   : (skip_to_arg(ap_types, ap_start, &ap, &arg_idx,
1898                                  &arg_cur, fmt),
1899                      va_arg(ap, long)));
1900            break;
1901          case 'L':
1902            arg = (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),
1906                      va_arg(ap, long long)));  // NOLINT(runtime/int)
1907            break;
1908          case 'z':  // implementation-defined, usually ptrdiff_t
1909            arg = (tvs
1910                   ? (ptrdiff_t)tv_nr(tvs, &arg_idx)
1911                   : (skip_to_arg(ap_types, ap_start, &ap, &arg_idx,
1912                                  &arg_cur, fmt),
1913                      va_arg(ap, ptrdiff_t)));
1914            break;
1915          }
1916          if (arg > 0) {
1917            arg_sign = 1;
1918          } else if (arg < 0) {
1919            arg_sign = -1;
1920          }
1921        } else {
1922          // unsigned
1923          switch (length_modifier) {
1924          case NUL:
1925            uarg = (tvs
1926                    ? (unsigned)tv_nr(tvs, &arg_idx)
1927                    : (skip_to_arg(ap_types, ap_start, &ap, &arg_idx,
1928                                   &arg_cur, fmt),
1929                       va_arg(ap, unsigned)));
1930            break;
1931          case 'h':
1932            uarg = (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),
1937                       va_arg(ap, unsigned)));
1938            break;
1939          case 'l':
1940            uarg = (tvs
1941                    ? (unsigned long)tv_nr(tvs, &arg_idx)
1942                    : (skip_to_arg(ap_types, ap_start, &ap, &arg_idx,
1943                                   &arg_cur, fmt),
1944                       va_arg(ap, unsigned long)));
1945            break;
1946          case 'L':
1947            uarg = (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),
1951                       va_arg(ap, unsigned long long)));  // NOLINT(runtime/int)
1952            break;
1953          case 'z':
1954            uarg = (tvs
1955                    ? (size_t)tv_nr(tvs, &arg_idx)
1956                    : (skip_to_arg(ap_types, ap_start, &ap, &arg_idx,
1957                                   &arg_cur, fmt),
1958                       va_arg(ap, size_t)));
1959            break;
1960          }
1961          arg_sign = (uarg != 0);
1962        }
1963
1964        str_arg = tmp;
1965        str_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.
1970        if (precision_specified) {
1971          zero_padding = false;
1972        }
1973
1974        if (fmt_spec == 'd') {
1975          if (force_sign && arg_sign >= 0) {
1976            tmp[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) {
1981          if (arg_sign != 0 && (fmt_spec == 'x' || fmt_spec == 'X'
1982                                || fmt_spec == 'b' || fmt_spec == 'B')) {
1983            tmp[str_arg_l++] = '0';
1984            tmp[str_arg_l++] = fmt_spec;
1985          }
1986          // alternate form should have no effect for p * conversion, but ...
1987        }
1988
1989        zero_padding_insertion_ind = str_arg_l;
1990        if (!precision_specified) {
1991          precision = 1;  // default precision is 1
1992        }
1993        if (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 {
1997          switch (fmt_spec) {
1998          case 'p':    // pointer
1999            str_arg_l += (size_t)snprintf(tmp + str_arg_l,
2000                                          sizeof(tmp) - str_arg_l,
2001                                          "%p", ptr_arg);
2002            break;
2003          case 'd':    // signed
2004            str_arg_l += (size_t)snprintf(tmp + str_arg_l,
2005                                          sizeof(tmp) - str_arg_l,
2006                                          "%" PRIdMAX, arg);
2007            break;
2008          case 'b':
2009          case 'B': {  // binary
2010            size_t bits = 0;
2011            for (bits = sizeof(uintmax_t) * 8; bits > 0; bits--) {
2012              if ((uarg >> (bits - 1)) & 0x1) {
2013                break;
2014              }
2015            }
2016
2017            while (bits > 0) {
2018              tmp[str_arg_l++] = ((uarg >> --bits) & 0x1) ? '1' : '0';
2019            }
2020            break;
2021          }
2022          default: {  // unsigned
2023            // construct a simple format string for snprintf
2024            char f[] = "%" PRIuMAX;
2025            f[sizeof("%" PRIuMAX) - 1 - 1] = fmt_spec;
2026            assert(PRIuMAX[sizeof(PRIuMAX) - 1 - 1] == 'u');
2027            str_arg_l += (size_t)snprintf(tmp + str_arg_l,
2028                                          sizeof(tmp) - str_arg_l,
2029                                          f, uarg);
2030            break;
2031          }
2032          }
2033          assert(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
2037          if (zero_padding_insertion_ind < str_arg_l
2038              && tmp[zero_padding_insertion_ind] == '-') {
2039            zero_padding_insertion_ind++;
2040          }
2041          if (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')) {
2047            zero_padding_insertion_ind += 2;
2048          }
2049        }
2050
2051        {
2052          size_t num_of_digits = str_arg_l - zero_padding_insertion_ind;
2053
2054          if (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
2059            if (!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
2063              precision = num_of_digits + 1;
2064            }
2065          }
2066          // zero padding to specified precision?
2067          if (num_of_digits < precision) {
2068            number_of_zeros_to_pad = precision - num_of_digits;
2069          }
2070        }
2071        // zero padding to specified minimal field width?
2072        if (!justify_left && zero_padding) {
2073          const int n = (int)(min_field_width - (str_arg_l
2074                                                 + number_of_zeros_to_pad));
2075          if (n > 0) {
2076            number_of_zeros_to_pad += (size_t)n;
2077          }
2078        }
2079        break;
2080      }
2081
2082      case 'f':
2083      case 'F':
2084      case 'e':
2085      case 'E':
2086      case 'g':
2087      case 'G': {
2088        // floating point
2089        char format[40];
2090        bool remove_trailing_zeroes = false;
2091
2092        double f = (tvs
2093                    ? tv_float(tvs, &arg_idx)
2094                    : (skip_to_arg(ap_types, ap_start, &ap, &arg_idx,
2095                                   &arg_cur, fmt),
2096                       va_arg(ap, double)));
2097
2098        double abs_f = f < 0 ? -f : f;
2099
2100        if (fmt_spec == 'g' || fmt_spec == 'G') {
2101          // can't use %g directly, cause it prints "1.0" as "1"
2102          if ((abs_f >= 0.001 && abs_f < 10000000.0) || abs_f == 0.0) {
2103            fmt_spec = ASCII_ISUPPER(fmt_spec) ? 'F' : 'f';
2104          } else {
2105            fmt_spec = fmt_spec == 'g' ? 'e' : 'E';
2106          }
2107          remove_trailing_zeroes = true;
2108        }
2109
2110        if (xisinf(f)
2111            || (strchr("fF", fmt_spec) != NULL && abs_f > 1.0e307)) {
2112          xstrlcpy(tmp, infinity_str(f > 0.0, fmt_spec,
2113                                     force_sign, space_for_positive),
2114                   sizeof(tmp));
2115          str_arg_l = strlen(tmp);
2116          zero_padding = false;
2117        } else if (xisnan(f)) {
2118          // Not a number: nan or NAN
2119          memmove(tmp, ASCII_ISUPPER(fmt_spec) ? "NAN" : "nan", 4);
2120          str_arg_l = 3;
2121          zero_padding = false;
2122        } else {
2123          // Regular float number
2124          format[0] = '%';
2125          size_t l = 1;
2126          if (force_sign) {
2127            format[l++] = space_for_positive ? ' ' : '+';
2128          }
2129          if (precision_specified) {
2130            size_t max_prec = TMP_LEN - 10;
2131
2132            // make sure we don't get more digits than we have room for
2133            if ((fmt_spec == 'f' || fmt_spec == 'F') && abs_f > 1.0) {
2134              max_prec -= (size_t)log10(abs_f);
2135            }
2136            if (precision > max_prec) {
2137              precision = max_prec;
2138            }
2139            l += (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.
2144          assert(l + 1 < sizeof(format));
2145          format[l] = (char)(fmt_spec == 'F' ? 'f' : fmt_spec);
2146          format[l + 1] = NUL;
2147
2148          str_arg_l = (size_t)snprintf(tmp, sizeof(tmp), format, f);
2149          assert(str_arg_l < sizeof(tmp));
2150
2151          if (remove_trailing_zeroes) {
2152            char *tp;
2153
2154            // using %g or %G: remove superfluous zeroes
2155            if (fmt_spec == 'f' || fmt_spec == 'F') {
2156              tp = tmp + str_arg_l - 1;
2157            } else {
2158              tp = vim_strchr(tmp, fmt_spec == 'e' ? 'e' : 'E');
2159              if (tp) {
2160                // remove superfluous '+' and leading zeroes from exponent
2161                if (tp[1] == '+') {
2162                  // change "1.0e+07" to "1.0e07"
2163                  STRMOVE(tp + 1, tp + 2);
2164                  str_arg_l--;
2165                }
2166                int i = (tp[1] == '-') ? 2 : 1;
2167                while (tp[i] == '0') {
2168                  // change "1.0e07" to "1.0e7"
2169                  STRMOVE(tp + i, tp + i + 1);
2170                  str_arg_l--;
2171                }
2172                tp--;
2173              }
2174            }
2175
2176            if (tp != NULL && !precision_specified) {
2177              // remove trailing zeroes, but keep the one just after a dot
2178              while (tp > tmp + 2 && *tp == '0' && tp[-1] != '.') {
2179                STRMOVE(tp, tp + 1);
2180                tp--;
2181                str_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.
2187            char *tp = vim_strchr(tmp, fmt_spec == 'e' ? 'e' : 'E');
2188            if (tp && (tp[1] == '+' || tp[1] == '-') && tp[2] == '0'
2189                && ascii_isdigit(tp[3]) && ascii_isdigit(tp[4])) {
2190              STRMOVE(tp + 2, tp + 3);
2191              str_arg_l--;
2192            }
2193          }
2194        }
2195        if (zero_padding && min_field_width > str_arg_l
2196            && (tmp[0] == '-' || force_sign)) {
2197          // Padding 0's should be inserted after the sign.
2198          number_of_zeros_to_pad = min_field_width - str_arg_l;
2199          zero_padding_insertion_ind = 1;
2200        }
2201        str_arg = tmp;
2202        break;
2203      }
2204
2205      default:
2206        // unrecognized conversion specifier, keep format string as-is
2207        zero_padding = false;  // turn zero padding off for non-numeric conversion
2208        justify_left = true;
2209        min_field_width = 0;  // reset flags
2210
2211        // discard the unrecognized conversion, just keep
2212        // the unrecognized conversion character
2213        str_arg = p;
2214        str_arg_l = 0;
2215        if (*p) {
2216          str_arg_l++;  // include invalid conversion specifier
2217        }
2218        // unchanged if not at end-of-string
2219        break;
2220      }
2221
2222      if (*p) {
2223        p++;  // 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
2228      if (!justify_left) {
2229        assert(str_arg_l <= SIZE_MAX - number_of_zeros_to_pad);
2230        if (min_field_width > str_arg_l + number_of_zeros_to_pad) {
2231          // left padding with blank or zero
2232          size_t pn = min_field_width - (str_arg_l + number_of_zeros_to_pad);
2233          if (str_avail) {
2234            size_t avail = str_m - str_l;
2235            memset(str + str_l, zero_padding ? '0' : ' ', MIN(pn, avail));
2236            str_avail = pn < avail;
2237          }
2238          assert(pn <= SIZE_MAX - str_l);
2239          str_l += pn;
2240        }
2241      }
2242
2243      // zero padding as requested by the precision or by the minimal
2244      // field width for numeric conversions required?
2245      if (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
2248        zero_padding_insertion_ind = 0;
2249      } else {
2250        // insert first part of numerics (sign or '0x') before zero padding
2251        if (zero_padding_insertion_ind > 0) {
2252          size_t zn = zero_padding_insertion_ind;
2253          if (str_avail) {
2254            size_t avail = str_m - str_l;
2255            memmove(str + str_l, str_arg, MIN(zn, avail));
2256            str_avail = zn < avail;
2257          }
2258          assert(zn <= SIZE_MAX - str_l);
2259          str_l += zn;
2260        }
2261
2262        // insert zero padding as requested by precision or min field width
2263        size_t zn = number_of_zeros_to_pad;
2264        if (str_avail) {
2265          size_t avail = str_m - str_l;
2266          memset(str + str_l, '0', MIN(zn, avail));
2267          str_avail = zn < avail;
2268        }
2269        assert(zn <= SIZE_MAX - str_l);
2270        str_l += zn;
2271      }
2272
2273      // insert formatted string
2274      // (or as-is conversion specifier for unknown conversions)
2275      if (str_arg_l > zero_padding_insertion_ind) {
2276        size_t sn = str_arg_l - zero_padding_insertion_ind;
2277        if (str_avail) {
2278          size_t avail = str_m - str_l;
2279          memmove(str + str_l,
2280                  str_arg + zero_padding_insertion_ind,
2281                  MIN(sn, avail));
2282          str_avail = sn < avail;
2283        }
2284        assert(sn <= SIZE_MAX - str_l);
2285        str_l += sn;
2286      }
2287
2288      // insert right padding
2289      if (justify_left) {
2290        assert(str_arg_l <= SIZE_MAX - number_of_zeros_to_pad);
2291        if (min_field_width > str_arg_l + number_of_zeros_to_pad) {
2292          // right blank padding to the field width
2293          size_t pn = min_field_width - (str_arg_l + number_of_zeros_to_pad);
2294          if (str_avail) {
2295            size_t avail = str_m - str_l;
2296            memset(str + str_l, ' ', MIN(pn, avail));
2297            str_avail = pn < avail;
2298          }
2299          assert(pn <= SIZE_MAX - str_l);
2300          str_l += pn;
2301        }
2302      }
2303
2304      xfree(tofree);
2305    }
2306  }
2307
2308  if (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)
2311    str[str_l <= str_m - 1 ? str_l : str_m - 1] = NUL;
2312  }
2313
2314  if (tvs != NULL
2315      && tvs[num_posarg != 0 ? num_posarg : arg_idx - 1].v_type != VAR_UNKNOWN) {
2316    emsg(_("E767: Too many arguments to printf()"));
2317  }
2318
2319error:
2320  xfree(ap_types);
2321  va_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.
2326  return (int)str_l;
2327}
2328
2329int kv_do_printf(StringBuilder *str, const char *fmt, ...)
2330  FUNC_ATTR_PRINTF(2, 3)
2331{
2332  size_t remaining = str->capacity - str->size;
2333
2334  va_list ap;
2335  va_start(ap, fmt);
2336  int printed = vsnprintf(str->items ? str->items + str->size : NULL, remaining, fmt, ap);
2337  va_end(ap);
2338
2339  if (printed < 0) {
2340    return -1;
2341  }
2342
2343  // printed string didn't fit, resize and try again
2344  if ((size_t)printed >= remaining) {
2345    kv_ensure_space(*str, (size_t)printed + 1);  // include space for NUL terminator at the end
2346    assert(str->items != NULL);
2347    va_start(ap, fmt);
2348    printed = vsnprintf(str->items + str->size, str->capacity - str->size, fmt, ap);
2349    va_end(ap);
2350    if (printed < 0) {
2351      return -1;
2352    }
2353  }
2354
2355  str->size += (size_t)printed;
2356  return printed;
2357}
2358
2359String arena_printf(Arena *arena, const char *fmt, ...)
2360  FUNC_ATTR_PRINTF(2, 3)
2361{
2362  size_t remaining = 0;
2363  char *buf = NULL;
2364  if (arena) {
2365    if (!arena->cur_blk) {
2366      arena_alloc_block(arena);
2367    }
2368
2369    // happy case, we can fit the printed string in the rest of the current
2370    // block (one pass):
2371    remaining = arena->size - arena->pos;
2372    buf = arena->cur_blk + arena->pos;
2373  }
2374
2375  va_list ap;
2376  va_start(ap, fmt);
2377  int printed = vsnprintf(buf, remaining, fmt, ap);
2378  va_end(ap);
2379
2380  if (printed < 0) {
2381    return (String)STRING_INIT;
2382  }
2383
2384  // printed string didn't fit, allocate and try again
2385  if ((size_t)printed >= remaining) {
2386    buf = arena_alloc(arena, (size_t)printed + 1, false);
2387    va_start(ap, fmt);
2388    printed = vsnprintf(buf, (size_t)printed + 1, fmt, ap);
2389    va_end(ap);
2390    if (printed < 0) {
2391      return (String)STRING_INIT;
2392    }
2393  } else {
2394    arena->pos += (size_t)printed + 1;
2395  }
2396
2397  return 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)
2404  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET
2405{
2406  size_t len = strlen(s);
2407  char *rev = xmalloc(len + 1);
2408  for (size_t s_i = 0, rev_i = len; s_i < len; s_i++) {
2409    const int mb_len = utfc_ptr2len(s + s_i);
2410    rev_i -= (size_t)mb_len;
2411    memmove(rev + rev_i, s + s_i, (size_t)mb_len);
2412    s_i += (size_t)mb_len - 1;
2413  }
2414  rev[len] = NUL;
2415  return 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{
2428  const char *pos = src;
2429  size_t whatlen = strlen(what);
2430
2431  // Count occurrences
2432  size_t count = 0;
2433  while ((pos = strstr(pos, what)) != NULL) {
2434    count++;
2435    pos += whatlen;
2436  }
2437
2438  if (count == 0) {
2439    return NULL;
2440  }
2441
2442  size_t replen = strlen(rep);
2443  char *ret = xmalloc(strlen(src) + count * (replen - whatlen) + 1);
2444  char *ptr = ret;
2445  while ((pos = strstr(src, what)) != NULL) {
2446    size_t idx = (size_t)(pos - src);
2447    memcpy(ptr, src, idx);
2448    ptr += idx;
2449    STRCPY(ptr, rep);
2450    ptr += replen;
2451    src = pos + whatlen;
2452  }
2453
2454  // Copy remaining
2455  STRCPY(ptr, src);
2456
2457  return ret;
2458}
2459
2460/// Implementation of "byteidx()" and "byteidxcomp()" functions
2461static void byteidx_common(typval_T *argvars, typval_T *rettv, bool comp)
2462{
2463  rettv->vval.v_number = -1;
2464
2465  const char *const str = tv_get_string_chk(&argvars[0]);
2466  varnumber_T idx = tv_get_number_chk(&argvars[1], NULL);
2467  if (str == NULL || idx < 0) {
2468    return;
2469  }
2470
2471  varnumber_T utf16idx = false;
2472  if (argvars[2].v_type != VAR_UNKNOWN) {
2473    bool error = false;
2474    utf16idx = tv_get_bool_chk(&argvars[2], &error);
2475    if (error) {
2476      return;
2477    }
2478    if (utf16idx < 0 || utf16idx > 1) {
2479      semsg(_(e_using_number_as_bool_nr), utf16idx);
2480      return;
2481    }
2482  }
2483
2484  int (*ptr2len)(const char *);
2485  if (comp) {
2486    ptr2len = utf_ptr2len;
2487  } else {
2488    ptr2len = utfc_ptr2len;
2489  }
2490
2491  const char *t = str;
2492  for (; idx > 0; idx--) {
2493    if (*t == NUL) {  // EOL reached.
2494      return;
2495    }
2496    if (utf16idx) {
2497      const int clen = ptr2len(t);
2498      const int c = (clen > 1) ? utf_ptr2char(t) : *t;
2499      if (c > 0xFFFF) {
2500        idx--;
2501      }
2502      if (idx > 0) {
2503        t += clen;
2504      }
2505    } else if (idx > 0) {
2506      t += ptr2len(t);
2507    }
2508  }
2509  rettv->vval.v_number = (varnumber_T)(t - str);
2510}
2511
2512/// "byteidx()" function
2513void f_byteidx(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
2514{
2515  byteidx_common(argvars, rettv, false);
2516}
2517
2518/// "byteidxcomp()" function
2519void f_byteidxcomp(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
2520{
2521  byteidx_common(argvars, rettv, true);
2522}
2523
2524/// "charidx()" function
2525void f_charidx(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
2526{
2527  rettv->vval.v_number = -1;
2528
2529  if (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)) {
2534    return;
2535  }
2536
2537  const char *const str = tv_get_string_chk(&argvars[0]);
2538  varnumber_T idx = tv_get_number_chk(&argvars[1], NULL);
2539  if (str == NULL || idx < 0) {
2540    return;
2541  }
2542
2543  varnumber_T countcc = false;
2544  varnumber_T utf16idx = false;
2545  if (argvars[2].v_type != VAR_UNKNOWN) {
2546    countcc = tv_get_bool(&argvars[2]);
2547    if (argvars[3].v_type != VAR_UNKNOWN) {
2548      utf16idx = tv_get_bool(&argvars[3]);
2549    }
2550  }
2551
2552  int (*ptr2len)(const char *);
2553  if (countcc) {
2554    ptr2len = utf_ptr2len;
2555  } else {
2556    ptr2len = utfc_ptr2len;
2557  }
2558
2559  const char *p;
2560  int len;
2561  for (p = str, len = 0; utf16idx ? idx >= 0 : p <= str + idx; len++) {
2562    if (*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.
2565      if (utf16idx ? (idx == 0) : (p == (str + idx))) {
2566        rettv->vval.v_number = len;
2567      }
2568      return;
2569    }
2570    if (utf16idx) {
2571      idx--;
2572      const int clen = ptr2len(p);
2573      const int c = (clen > 1) ? utf_ptr2char(p) : *p;
2574      if (c > 0xFFFF) {
2575        idx--;
2576      }
2577    }
2578    p += ptr2len(p);
2579  }
2580
2581  rettv->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{
2587  tv_list_alloc_ret(rettv, kListLenUnknown);
2588  const char *p = tv_get_string(&argvars[0]);
2589
2590  for (; *p != NUL; p += utf_ptr2len(p)) {
2591    tv_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{
2598  int base = 10;
2599  int what = 0;
2600
2601  if (argvars[1].v_type != VAR_UNKNOWN) {
2602    base = (int)tv_get_number(&argvars[1]);
2603    if (base != 2 && base != 8 && base != 10 && base != 16) {
2604      emsg(_(e_invarg));
2605      return;
2606    }
2607    if (argvars[2].v_type != VAR_UNKNOWN && tv_get_bool(&argvars[2])) {
2608      what |= STR2NR_QUOTE;
2609    }
2610  }
2611
2612  char *p = skipwhite(tv_get_string(&argvars[0]));
2613  bool isneg = (*p == '-');
2614  if (*p == '+' || *p == '-') {
2615    p = skipwhite(p + 1);
2616  }
2617  switch (base) {
2618  case 2:
2619    what |= STR2NR_BIN | STR2NR_FORCE;
2620    break;
2621  case 8:
2622    what |= STR2NR_OCT | STR2NR_OOCT | STR2NR_FORCE;
2623    break;
2624  case 16:
2625    what |= STR2NR_HEX | STR2NR_FORCE;
2626    break;
2627  }
2628  varnumber_T n;
2629  vim_str2nr(p, NULL, NULL, what, &n, NULL, 0, false, NULL);
2630  // Text after the number is silently ignored.
2631  if (isneg) {
2632    rettv->vval.v_number = -n;
2633  } else {
2634    rettv->vval.v_number = n;
2635  }
2636}
2637
2638/// "strgetchar()" function
2639void f_strgetchar(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
2640{
2641  rettv->vval.v_number = -1;
2642
2643  const char *const str = tv_get_string_chk(&argvars[0]);
2644  if (str == NULL) {
2645    return;
2646  }
2647  bool error = false;
2648  varnumber_T charidx = tv_get_number_chk(&argvars[1], &error);
2649  if (error) {
2650    return;
2651  }
2652
2653  const size_t len = strlen(str);
2654  size_t byteidx = 0;
2655
2656  while (charidx >= 0 && byteidx < len) {
2657    if (charidx == 0) {
2658      rettv->vval.v_number = utf_ptr2char(str + byteidx);
2659      break;
2660    }
2661    charidx--;
2662    byteidx += (size_t)utf_ptr2len(str + byteidx);
2663  }
2664}
2665
2666/// "stridx()" function
2667void f_stridx(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
2668{
2669  rettv->vval.v_number = -1;
2670
2671  char buf[NUMBUFLEN];
2672  const char *const needle = tv_get_string_chk(&argvars[1]);
2673  const char *haystack = tv_get_string_buf_chk(&argvars[0], buf);
2674  const char *const haystack_start = haystack;
2675  if (needle == NULL || haystack == NULL) {
2676    return;  // Type error; errmsg already given.
2677  }
2678
2679  if (argvars[2].v_type != VAR_UNKNOWN) {
2680    bool error = false;
2681
2682    const ptrdiff_t start_idx = (ptrdiff_t)tv_get_number_chk(&argvars[2],
2683                                                             &error);
2684    if (error || start_idx >= (ptrdiff_t)strlen(haystack)) {
2685      return;
2686    }
2687    if (start_idx >= 0) {
2688      haystack += start_idx;
2689    }
2690  }
2691
2692  const char *pos = strstr(haystack, needle);
2693  if (pos != NULL) {
2694    rettv->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{
2701  rettv->v_type = VAR_STRING;
2702  rettv->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{
2708  rettv->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{
2713  const char *s = tv_get_string(&argvars[0]);
2714  varnumber_T len = 0;
2715  int (*func_mb_ptr2char_adv)(const char **pp);
2716
2717  func_mb_ptr2char_adv = skipcc ? mb_ptr2char_adv : mb_cptr2char_adv;
2718  while (*s != NUL) {
2719    func_mb_ptr2char_adv(&s);
2720    len++;
2721  }
2722  rettv->vval.v_number = len;
2723}
2724
2725/// "strcharlen()" function
2726void f_strcharlen(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
2727{
2728  strchar_common(argvars, rettv, true);
2729}
2730
2731/// "strchars()" function
2732void f_strchars(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
2733{
2734  varnumber_T skipcc = false;
2735
2736  if (argvars[1].v_type != VAR_UNKNOWN) {
2737    bool error = false;
2738    skipcc = tv_get_bool_chk(&argvars[1], &error);
2739    if (error) {
2740      return;
2741    }
2742    if (skipcc < 0 || skipcc > 1) {
2743      semsg(_(e_using_number_as_bool_nr), skipcc);
2744      return;
2745    }
2746  }
2747
2748  strchar_common(argvars, rettv, skipcc);
2749}
2750
2751/// "strutf16len()" function
2752void f_strutf16len(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
2753{
2754  rettv->vval.v_number = -1;
2755
2756  if (tv_check_for_string_arg(argvars, 0) == FAIL
2757      || tv_check_for_opt_bool_arg(argvars, 1) == FAIL) {
2758    return;
2759  }
2760
2761  varnumber_T countcc = false;
2762  if (argvars[1].v_type != VAR_UNKNOWN) {
2763    countcc = tv_get_bool(&argvars[1]);
2764  }
2765
2766  const char *s = tv_get_string(&argvars[0]);
2767  varnumber_T len = 0;
2768  int (*func_mb_ptr2char_adv)(const char **pp);
2769
2770  func_mb_ptr2char_adv = countcc ? mb_cptr2char_adv : mb_ptr2char_adv;
2771  while (*s != NUL) {
2772    const int ch = func_mb_ptr2char_adv(&s);
2773    if (ch > 0xFFFF) {
2774      len++;
2775    }
2776    len++;
2777  }
2778  rettv->vval.v_number = len;
2779}
2780
2781/// "strdisplaywidth()" function
2782void f_strdisplaywidth(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
2783{
2784  const char *const s = tv_get_string(&argvars[0]);
2785  int col = 0;
2786
2787  if (argvars[1].v_type != VAR_UNKNOWN) {
2788    col = (int)tv_get_number(&argvars[1]);
2789  }
2790
2791  rettv->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{
2797  const char *const s = tv_get_string(&argvars[0]);
2798
2799  rettv->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{
2805  const char *const p = tv_get_string(&argvars[0]);
2806  const size_t slen = strlen(p);
2807
2808  int nbyte = 0;
2809  varnumber_T skipcc = false;
2810  bool error = false;
2811  varnumber_T nchar = tv_get_number_chk(&argvars[1], &error);
2812  if (!error) {
2813    if (argvars[2].v_type != VAR_UNKNOWN
2814        && argvars[3].v_type != VAR_UNKNOWN) {
2815      skipcc = tv_get_bool_chk(&argvars[3], &error);
2816      if (error) {
2817        return;
2818      }
2819      if (skipcc < 0 || skipcc > 1) {
2820        semsg(_(e_using_number_as_bool_nr), skipcc);
2821        return;
2822      }
2823    }
2824
2825    if (nchar > 0) {
2826      while (nchar > 0 && (size_t)nbyte < slen) {
2827        if (skipcc) {
2828          nbyte += utfc_ptr2len(p + nbyte);
2829        } else {
2830          nbyte += utf_ptr2len(p + nbyte);
2831        }
2832        nchar--;
2833      }
2834    } else {
2835      nbyte = (int)nchar;
2836    }
2837  }
2838  int len = 0;
2839  if (argvars[2].v_type != VAR_UNKNOWN) {
2840    int charlen = (int)tv_get_number(&argvars[2]);
2841    while (charlen > 0 && nbyte + len < (int)slen) {
2842      int off = nbyte + len;
2843
2844      if (off < 0) {
2845        len += 1;
2846      } else {
2847        if (skipcc) {
2848          len += utfc_ptr2len(p + off);
2849        } else {
2850          len += utf_ptr2len(p + off);
2851        }
2852      }
2853      charlen--;
2854    }
2855  } else {
2856    len = (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.
2861  if (nbyte < 0) {
2862    len += nbyte;
2863    nbyte = 0;
2864  } else if ((size_t)nbyte > slen) {
2865    nbyte = (int)slen;
2866  }
2867  if (len < 0) {
2868    len = 0;
2869  } else if (nbyte + len > (int)slen) {
2870    len = (int)slen - nbyte;
2871  }
2872
2873  rettv->v_type = VAR_STRING;
2874  rettv->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{
2880  bool error = false;
2881
2882  const char *const p = tv_get_string(&argvars[0]);
2883  const size_t slen = strlen(p);
2884
2885  varnumber_T n = tv_get_number_chk(&argvars[1], &error);
2886  varnumber_T len;
2887  if (error) {
2888    len = 0;
2889  } else if (argvars[2].v_type != VAR_UNKNOWN) {
2890    len = tv_get_number(&argvars[2]);
2891  } else {
2892    len = (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.
2897  if (n < 0) {
2898    len += n;
2899    n = 0;
2900  } else if (n > (varnumber_T)slen) {
2901    n = (varnumber_T)slen;
2902  }
2903  if (len < 0) {
2904    len = 0;
2905  } else if (n + len > (varnumber_T)slen) {
2906    len = (varnumber_T)slen - n;
2907  }
2908
2909  if (argvars[2].v_type != VAR_UNKNOWN && argvars[3].v_type != VAR_UNKNOWN) {
2910    int64_t off;
2911
2912    // length in characters
2913    for (off = n; off < (int64_t)slen && len > 0; len--) {
2914      off += utfc_ptr2len(p + off);
2915    }
2916    len = off - n;
2917  }
2918
2919  rettv->v_type = VAR_STRING;
2920  rettv->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{
2926  char buf[NUMBUFLEN];
2927  const char *const needle = tv_get_string_chk(&argvars[1]);
2928  const char *const haystack = tv_get_string_buf_chk(&argvars[0], buf);
2929
2930  rettv->vval.v_number = -1;
2931  if (needle == NULL || haystack == NULL) {
2932    return;  // Type error; errmsg already given.
2933  }
2934
2935  const size_t haystack_len = strlen(haystack);
2936  ptrdiff_t end_idx;
2937  if (argvars[2].v_type != VAR_UNKNOWN) {
2938    // Third argument: upper limit for index.
2939    end_idx = (ptrdiff_t)tv_get_number_chk(&argvars[2], NULL);
2940    if (end_idx < 0) {
2941      return;  // Can never find a match.
2942    }
2943  } else {
2944    end_idx = (ptrdiff_t)haystack_len;
2945  }
2946
2947  const char *lastmatch = NULL;
2948  if (*needle == NUL) {
2949    // Empty string matches past the end.
2950    lastmatch = haystack + end_idx;
2951  } else {
2952    for (const char *rest = haystack; *rest != NUL; rest++) {
2953      rest = strstr(rest, needle);
2954      if (rest == NULL || rest > haystack + end_idx) {
2955        break;
2956      }
2957      lastmatch = rest;
2958    }
2959  }
2960
2961  if (lastmatch != NULL) {
2962    rettv->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{
2969  rettv->v_type = VAR_STRING;
2970  rettv->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{
2979  rettv->vval.v_number = -1;
2980
2981  if (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)) {
2986    return;
2987  }
2988
2989  const char *const str = tv_get_string_chk(&argvars[0]);
2990  varnumber_T idx = tv_get_number_chk(&argvars[1], NULL);
2991  if (str == NULL || idx < 0) {
2992    return;
2993  }
2994
2995  varnumber_T countcc = false;
2996  varnumber_T charidx = false;
2997  if (argvars[2].v_type != VAR_UNKNOWN) {
2998    countcc = tv_get_bool(&argvars[2]);
2999    if (argvars[3].v_type != VAR_UNKNOWN) {
3000      charidx = tv_get_bool(&argvars[3]);
3001    }
3002  }
3003
3004  int (*ptr2len)(const char *);
3005  if (countcc) {
3006    ptr2len = utf_ptr2len;
3007  } else {
3008    ptr2len = utfc_ptr2len;
3009  }
3010
3011  const char *p;
3012  int len;
3013  int utf16idx = 0;
3014  for (p = str, len = 0; charidx ? idx >= 0 : p <= str + idx; len++) {
3015    if (*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.
3018      if (charidx ? (idx == 0) : (p == (str + idx))) {
3019        rettv->vval.v_number = len;
3020      }
3021      return;
3022    }
3023    utf16idx = len;
3024    const int clen = ptr2len(p);
3025    const int c = (clen > 1) ? utf_ptr2char(p) : *p;
3026    if (c > 0xFFFF) {
3027      len++;
3028    }
3029    p += clen;
3030    if (charidx) {
3031      idx--;
3032    }
3033  }
3034
3035  rettv->vval.v_number = utf16idx;
3036}
3037
3038/// "tolower(string)" function
3039void f_tolower(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
3040{
3041  rettv->v_type = VAR_STRING;
3042  rettv->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{
3048  rettv->v_type = VAR_STRING;
3049  rettv->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{
3055  char buf[NUMBUFLEN];
3056  char buf2[NUMBUFLEN];
3057
3058  const char *in_str = tv_get_string(&argvars[0]);
3059  const char *fromstr = tv_get_string_buf_chk(&argvars[1], buf);
3060  const char *tostr = tv_get_string_buf_chk(&argvars[2], buf2);
3061
3062  // Default return value: empty string.
3063  rettv->v_type = VAR_STRING;
3064  rettv->vval.v_string = NULL;
3065  if (fromstr == NULL || tostr == NULL) {
3066    return;  // Type error; errmsg already given.
3067  }
3068  garray_T ga;
3069  ga_init(&ga, (int)sizeof(char), 80);
3070
3071  // fromstr and tostr have to contain the same number of chars.
3072  bool first = true;
3073  while (*in_str != NUL) {
3074    const char *cpstr = in_str;
3075    const int inlen = utfc_ptr2len(in_str);
3076    int cplen = inlen;
3077    int idx = 0;
3078    int fromlen;
3079    for (const char *p = fromstr; *p != NUL; p += fromlen) {
3080      fromlen = utfc_ptr2len(p);
3081      if (fromlen == inlen && strncmp(in_str, p, (size_t)inlen) == 0) {
3082        int tolen;
3083        for (p = tostr; *p != NUL; p += tolen) {
3084          tolen = utfc_ptr2len(p);
3085          if (idx-- == 0) {
3086            cplen = tolen;
3087            cpstr = p;
3088            break;
3089          }
3090        }
3091        if (*p == NUL) {  // tostr is shorter than fromstr.
3092          goto error;
3093        }
3094        break;
3095      }
3096      idx++;
3097    }
3098
3099    if (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.
3103      first = false;
3104      int tolen;
3105      for (const char *p = tostr; *p != NUL; p += tolen) {
3106        tolen = utfc_ptr2len(p);
3107        idx--;
3108      }
3109      if (idx != 0) {
3110        goto error;
3111      }
3112    }
3113
3114    ga_grow(&ga, cplen);
3115    memmove((char *)ga.ga_data + ga.ga_len, cpstr, (size_t)cplen);
3116    ga.ga_len += cplen;
3117
3118    in_str += inlen;
3119  }
3120
3121  // add a terminating NUL
3122  ga_append(&ga, NUL);
3123
3124  rettv->vval.v_string = ga.ga_data;
3125  return;
3126error:
3127  semsg(_(e_invarg2), fromstr);
3128  ga_clear(&ga);
3129}
3130
3131/// "trim({expr})" function
3132void f_trim(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
3133{
3134  char buf1[NUMBUFLEN];
3135  char buf2[NUMBUFLEN];
3136  const char *head = tv_get_string_buf_chk(&argvars[0], buf1);
3137  const char *mask = NULL;
3138  const char *prev;
3139  const char *p;
3140  int dir = 0;
3141
3142  rettv->v_type = VAR_STRING;
3143  rettv->vval.v_string = NULL;
3144  if (head == NULL) {
3145    return;
3146  }
3147
3148  if (tv_check_for_opt_string_arg(argvars, 1) == FAIL) {
3149    return;
3150  }
3151
3152  if (argvars[1].v_type == VAR_STRING) {
3153    mask = tv_get_string_buf_chk(&argvars[1], buf2);
3154    if (*mask == NUL) {
3155      mask = NULL;
3156    }
3157
3158    if (argvars[2].v_type != VAR_UNKNOWN) {
3159      bool error = false;
3160      // leading or trailing characters to trim
3161      dir = (int)tv_get_number_chk(&argvars[2], &error);
3162      if (error) {
3163        return;
3164      }
3165      if (dir < 0 || dir > 2) {
3166        semsg(_(e_invarg2), tv_get_string(&argvars[2]));
3167        return;
3168      }
3169    }
3170  }
3171
3172  if (dir == 0 || dir == 1) {
3173    // Trim leading characters
3174    while (*head != NUL) {
3175      int c1 = utf_ptr2char(head);
3176      if (mask == NULL) {
3177        if (c1 > ' ' && c1 != 0xa0) {
3178          break;
3179        }
3180      } else {
3181        for (p = mask; *p != NUL; MB_PTR_ADV(p)) {
3182          if (c1 == utf_ptr2char(p)) {
3183            break;
3184          }
3185        }
3186        if (*p == NUL) {
3187          break;
3188        }
3189      }
3190      MB_PTR_ADV(head);
3191    }
3192  }
3193
3194  const char *tail = head + strlen(head);
3195  if (dir == 0 || dir == 2) {
3196    // Trim trailing characters
3197    for (; tail > head; tail = prev) {
3198      prev = tail;
3199      MB_PTR_BACK(head, prev);
3200      int c1 = utf_ptr2char(prev);
3201      if (mask == NULL) {
3202        if (c1 > ' ' && c1 != 0xa0) {
3203          break;
3204        }
3205      } else {
3206        for (p = mask; *p != NUL; MB_PTR_ADV(p)) {
3207          if (c1 == utf_ptr2char(p)) {
3208            break;
3209          }
3210        }
3211        if (*p == NUL) {
3212          break;
3213        }
3214      }
3215    }
3216  }
3217  rettv->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{
3223  keyvalue_T *kv1 = (keyvalue_T *)a;
3224  keyvalue_T *kv2 = (keyvalue_T *)b;
3225
3226  return 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{
3232  keyvalue_T *kv1 = (keyvalue_T *)a;
3233  keyvalue_T *kv2 = (keyvalue_T *)b;
3234
3235  return 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{
3241  keyvalue_T *kv1 = (keyvalue_T *)a;
3242  keyvalue_T *kv2 = (keyvalue_T *)b;
3243
3244  return 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{
3250  keyvalue_T *kv1 = (keyvalue_T *)a;
3251  keyvalue_T *kv2 = (keyvalue_T *)b;
3252
3253  return STRNICMP(kv1->value, kv2->value, MAX(kv1->length, kv2->length));
3254}