robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
36.4 KiB1374 linesraw
1/// @file charset.c
2///
3/// Code related to character sets.
4
5#include <assert.h>
6#include <errno.h>
7#include <inttypes.h>
8#include <limits.h>
9#include <stdlib.h>
10#include <string.h>
11#include <uv.h>
12
13#include "auto/config.h"
14#include "klib/kvec.h"
15#include "nvim/ascii_defs.h"
16#include "nvim/buffer_defs.h"
17#include "nvim/charset.h"
18#include "nvim/cursor.h"
19#include "nvim/eval/typval_defs.h"
20#include "nvim/garray.h"
21#include "nvim/garray_defs.h"
22#include "nvim/globals.h"
23#include "nvim/keycodes.h"
24#include "nvim/macros_defs.h"
25#include "nvim/mbyte.h"
26#include "nvim/memory.h"
27#include "nvim/option.h"
28#include "nvim/path.h"
29#include "nvim/pos_defs.h"
30#include "nvim/strings.h"
31#include "nvim/types_defs.h"
32#include "nvim/vim_defs.h"
33
34#include "charset.c.generated.h"
35
36// a chartab is an array with 256 bits, each bit representing one of the characters 0-255.
37#define SET_CHARTAB(chartab, c) (chartab)[(unsigned)(c) >> 6] |= (1ull << ((c) & 0x3f))
38#define RESET_CHARTAB(chartab, c) (chartab)[(unsigned)(c) >> 6] &= ~(1ull << ((c) & 0x3f))
39#define GET_CHARTAB(chartab, c) ((chartab)[(unsigned)(c) >> 6] & (1ull << ((c) & 0x3f)))
40
41static uint64_t isf_chartab[4];  // chartab for 'isfname'
42static uint64_t isi_chartab[4];  // chartab for 'isindent'
43
44int buf_init_isk_chartab(buf_T *buf)
45{
46  uint64_t save_chartab[4];
47  memcpy(save_chartab, buf->b_chartab, sizeof save_chartab);
48  memset(buf->b_chartab, 0, sizeof buf->b_chartab);
49  if (buf->b_p_lisp) {  // don't ask
50    SET_CHARTAB(buf->b_chartab, '-');
51  }
52  if (parse_isopt(buf->b_p_isk, buf->b_chartab) == FAIL) {
53    memcpy(buf->b_chartab, save_chartab, sizeof save_chartab);
54    return FAIL;
55  }
56  return OK;
57}
58
59int init_isf_chartab(void)
60{
61  uint64_t save_chartab[4];
62  memcpy(save_chartab, isf_chartab, sizeof save_chartab);
63  memset(isf_chartab, 0, sizeof isf_chartab);
64  isf_chartab[2] = 0xFFFFFFFF00000000;  // there is no need
65  isf_chartab[3] = 0xFFFFFFFFFFFFFFFF;  // to worry
66  if (parse_isopt(p_isf, isf_chartab) == FAIL) {
67    memcpy(isf_chartab, save_chartab, sizeof save_chartab);
68    return FAIL;
69  }
70  return OK;
71}
72
73int init_isi_chartab(void)
74{
75  uint64_t save_chartab[4];
76  memcpy(save_chartab, isi_chartab, sizeof save_chartab);
77  memset(isi_chartab, 0, sizeof isi_chartab);
78  if (parse_isopt(p_isi, isi_chartab) == FAIL) {
79    memcpy(isi_chartab, save_chartab, sizeof save_chartab);
80    return FAIL;
81  }
82  return OK;
83}
84
85/// Checks the format for the option settings 'iskeyword', 'isident', 'isfname'
86/// Returns FAIL if has an error, OK otherwise.
87int check_isopt(char *var)
88{
89  return parse_isopt(var, NULL);
90}
91
92/// @param chartab  if NULL only check if option string is valid
93int parse_isopt(const char *var, uint64_t *chartab)
94{
95  const char *p = var;
96
97  // Parses the 'isident', 'iskeyword', 'isfname' options.
98  // Each option is a list of characters, character numbers or ranges,
99  // separated by commas, e.g.: "200-210,x,#-178,-"
100  while (*p) {
101    bool tilde = false;
102    bool do_isalpha = false;
103
104    if (*p == '^' && p[1] != NUL) {
105      tilde = true;
106      p++;
107    }
108
109    int c;
110    if (ascii_isdigit(*p)) {
111      c = getdigits_int((char **)&p, true, 0);
112    } else {
113      c = mb_ptr2char_adv(&p);
114    }
115    int c2 = -1;
116
117    if (*p == '-' && p[1] != NUL) {
118      p++;
119
120      if (ascii_isdigit(*p)) {
121        c2 = getdigits_int((char **)&p, true, 0);
122      } else {
123        c2 = mb_ptr2char_adv(&p);
124      }
125    }
126
127    if (c <= 0 || c >= 256 || (c2 < c && c2 != -1) || c2 >= 256
128        || !(*p == NUL || *p == ',')) {
129      return FAIL;
130    }
131
132    bool trail_comma = *p == ',';
133    p = skip_to_option_part(p);
134    if (trail_comma && *p == NUL) {
135      // Trailing comma is not allowed.
136      return FAIL;
137    }
138
139    if (chartab == NULL) {  // only check!
140      continue;
141    }
142
143    if (c2 == -1) {  // not a range
144      // A single '@' (not "@-@"):
145      // Decide on letters being ID/printable/keyword chars with
146      // standard function isalpha(). This takes care of locale for
147      // single-byte characters).
148      if (c == '@') {
149        do_isalpha = true;
150        c = 1;
151        c2 = 255;
152      } else {
153        c2 = c;
154      }
155    }
156
157    while (c <= c2) {
158      // Use the MB_ functions here, because isalpha() doesn't
159      // work properly when 'encoding' is "latin1" and the locale is
160      // "C".
161      if (!do_isalpha || mb_islower(c) || mb_isupper(c)) {
162        if (tilde) {
163          RESET_CHARTAB(chartab, c);
164        } else {
165          SET_CHARTAB(chartab, c);
166        }
167      }
168      c++;
169    }
170  }
171
172  return OK;
173}
174
175/// Translate any special characters in buf[bufsize] in-place.
176///
177/// The result is a string with only printable characters, but if there is not
178/// enough room, not all characters will be translated.
179///
180/// @param buf
181/// @param bufsize
182void trans_characters(char *buf, int bufsize)
183{
184  char *trs;                   // translated character
185  int len = (int)strlen(buf);  // length of string needing translation
186  int room = bufsize - len;    // room in buffer after string
187
188  while (*buf != 0) {
189    int trs_len;      // length of trs[]
190    // Assume a multi-byte character doesn't need translation.
191    if ((trs_len = utfc_ptr2len(buf)) > 1) {
192      len -= trs_len;
193    } else {
194      trs = transchar_byte((uint8_t)(*buf));
195      trs_len = (int)strlen(trs);
196
197      if (trs_len > 1) {
198        room -= trs_len - 1;
199        if (room <= 0) {
200          return;
201        }
202        memmove(buf + trs_len, buf + 1, (size_t)len);
203      }
204      memmove(buf, trs, (size_t)trs_len);
205      len--;
206    }
207    buf += trs_len;
208  }
209}
210
211/// Find length of a string capable of holding s with all specials replaced
212///
213/// Assumes replacing special characters with printable ones just like
214/// strtrans() does.
215///
216/// @param[in]  s  String to check.
217///
218/// @return number of bytes needed to hold a translation of `s`, NUL byte not
219///         included.
220size_t transstr_len(const char *const s, bool untab)
221  FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE
222{
223  const char *p = s;
224  size_t len = 0;
225
226  while (*p) {
227    const size_t l = (size_t)utfc_ptr2len(p);
228    if (l > 1) {
229      if (vim_isprintc(utf_ptr2char(p))) {
230        len += l;
231      } else {
232        for (size_t off = 0; off < l; off += (size_t)utf_ptr2len(p + off)) {
233          int c = utf_ptr2char(p + off);
234          char hexbuf[9];
235          len += transchar_hex(hexbuf, c);
236        }
237      }
238      p += l;
239    } else if (*p == TAB && !untab) {
240      len += 1;
241      p++;
242    } else {
243      // Illegal byte sequence may occupy up to 4 characters.
244      uint8_t c = (uint8_t)(*p++);
245      len += (size_t)(c < 0x80 ? ascii2cells(c) : 4);
246    }
247  }
248  return len;
249}
250
251/// Replace special characters with printable ones
252///
253/// @param[in]  s  String to replace characters from.
254/// @param[out]  buf  Buffer to which result should be saved.
255/// @param[in]  len  Buffer length. Resulting string may not occupy more then
256///                  len - 1 bytes (one for trailing NUL byte).
257/// @param[in]  untab  remove tab characters
258///
259/// @return length of the resulting string, without the NUL byte.
260size_t transstr_buf(const char *const s, const ssize_t slen, char *const buf, const size_t buflen,
261                    bool untab)
262  FUNC_ATTR_NONNULL_ALL
263{
264  const char *p = s;
265  char *buf_p = buf;
266  char *const buf_e = buf_p + buflen - 1;
267
268  while ((slen < 0 || (p - s) < slen) && *p != NUL && buf_p < buf_e) {
269    const size_t l = (size_t)utfc_ptr2len(p);
270    if (l > 1) {
271      if (buf_p + l > buf_e) {
272        break;  // Exceeded `buf` size.
273      }
274
275      if (vim_isprintc(utf_ptr2char(p))) {
276        memmove(buf_p, p, l);
277        buf_p += l;
278      } else {
279        for (size_t off = 0; off < l; off += (size_t)utf_ptr2len(p + off)) {
280          int c = utf_ptr2char(p + off);
281          char hexbuf[9];  // <up to 6 bytes>NUL
282          const size_t hexlen = transchar_hex(hexbuf, c);
283          if (buf_p + hexlen > buf_e) {
284            break;
285          }
286          memmove(buf_p, hexbuf, hexlen);
287          buf_p += hexlen;
288        }
289      }
290      p += l;
291    } else if (*p == TAB && !untab) {
292      *buf_p++ = *p++;
293    } else {
294      const char *const tb = transchar_byte((uint8_t)(*p++));
295      const size_t tb_len = strlen(tb);
296      if (buf_p + tb_len > buf_e) {
297        break;  // Exceeded `buf` size.
298      }
299      memmove(buf_p, tb, tb_len);
300      buf_p += tb_len;
301    }
302  }
303  *buf_p = NUL;
304  assert(buf_p <= buf_e);
305  return (size_t)(buf_p - buf);
306}
307
308/// Copy string and replace special characters with printable characters
309///
310/// Works like `strtrans()` does, used for that and in some other places.
311///
312/// @param[in]  s  String to replace characters from.
313///
314/// @return [allocated] translated string
315char *transstr(const char *const s, bool untab)
316  FUNC_ATTR_NONNULL_RET
317{
318  // Compute the length of the result, taking account of unprintable
319  // multi-byte characters.
320  const size_t len = transstr_len(s, untab) + 1;
321  char *const buf = xmalloc(len);
322  transstr_buf(s, -1, buf, len, untab);
323  return buf;
324}
325
326size_t kv_transstr(StringBuilder *str, const char *const s, bool untab)
327  FUNC_ATTR_NONNULL_ARG(1)
328{
329  if (!s) {
330    return 0;
331  }
332
333  // Compute the length of the result, taking account of unprintable
334  // multi-byte characters.
335  const size_t len = transstr_len(s, untab);
336  kv_ensure_space(*str, len + 1);
337  transstr_buf(s, -1, str->items + str->size, len + 1, untab);
338  str->size += len;  // do not include NUL byte
339  return len;
340}
341
342/// Convert the string "str[orglen]" to do ignore-case comparing.
343/// Use the current locale.
344///
345/// When "buf" is NULL, return an allocated string.
346/// Otherwise, put the result in buf, limited by buflen, and return buf.
347char *str_foldcase(char *str, int orglen, char *buf, int buflen)
348  FUNC_ATTR_NONNULL_RET
349{
350  garray_T ga;
351  int len = orglen;
352
353#define GA_CHAR(i) ((char *)ga.ga_data)[i]
354#define GA_PTR(i) ((char *)ga.ga_data + (i))
355#define STR_CHAR(i) (buf == NULL ? GA_CHAR(i) : buf[i])
356#define STR_PTR(i) (buf == NULL ? GA_PTR(i) : buf + (i))
357
358  // Copy "str" into "buf" or allocated memory, unmodified.
359  if (buf == NULL) {
360    ga_init(&ga, 1, 10);
361
362    ga_grow(&ga, len + 1);
363    memmove(ga.ga_data, str, (size_t)len);
364    ga.ga_len = len;
365  } else {
366    if (len >= buflen) {
367      // Ugly!
368      len = buflen - 1;
369    }
370    memmove(buf, str, (size_t)len);
371  }
372
373  if (buf == NULL) {
374    GA_CHAR(len) = NUL;
375  } else {
376    buf[len] = NUL;
377  }
378
379  // Make each character lower case.
380  int i = 0;
381  while (STR_CHAR(i) != NUL) {
382    int c = utf_ptr2char(STR_PTR(i));
383    int olen = utf_ptr2len(STR_PTR(i));
384    int lc = mb_tolower(c);
385
386    // Only replace the character when it is not an invalid
387    // sequence (ASCII character or more than one byte) and
388    // mb_tolower() doesn't return the original character.
389    if (((c < 0x80) || (olen > 1)) && (c != lc)) {
390      int nlen = utf_char2len(lc);
391
392      // If the byte length changes need to shift the following
393      // characters forward or backward.
394      if (olen != nlen) {
395        if (nlen > olen) {
396          if (buf == NULL) {
397            ga_grow(&ga, nlen - olen + 1);
398          } else {
399            if (len + nlen - olen >= buflen) {
400              // out of memory, keep old char
401              lc = c;
402              nlen = olen;
403            }
404          }
405        }
406
407        if (olen != nlen) {
408          if (buf == NULL) {
409            STRMOVE(GA_PTR(i) + nlen, GA_PTR(i) + olen);
410            ga.ga_len += nlen - olen;
411          } else {
412            STRMOVE(buf + i + nlen, buf + i + olen);
413            len += nlen - olen;
414          }
415        }
416      }
417      utf_char2bytes(lc, STR_PTR(i));
418    }
419
420    // skip to next multi-byte char
421    i += utfc_ptr2len(STR_PTR(i));
422  }
423
424  if (buf == NULL) {
425    return ga.ga_data;
426  }
427  return buf;
428}
429
430// Does NOT work for multi-byte characters, c must be <= 255.
431// Also doesn't work for the first byte of a multi-byte, "c" must be a
432// character!
433static uint8_t transchar_charbuf[11];
434
435/// Translate a character into a printable one, leaving printable ASCII intact
436///
437/// All unicode characters are considered non-printable in this function.
438///
439/// @param[in]  c  Character to translate.
440///
441/// @return translated character into a static buffer.
442char *transchar(int c)
443{
444  return transchar_buf(curbuf, c);
445}
446
447char *transchar_buf(const buf_T *buf, int c)
448{
449  int i = 0;
450  if (IS_SPECIAL(c)) {
451    // special key code, display as ~@ char
452    transchar_charbuf[0] = '~';
453    transchar_charbuf[1] = '@';
454    i = 2;
455    c = K_SECOND(c);
456  }
457
458  if ((c <= 0xFF) && vim_isprintc(c)) {
459    // printable character
460    transchar_charbuf[i] = (uint8_t)c;
461    transchar_charbuf[i + 1] = NUL;
462  } else if (c <= 0xFF) {
463    transchar_nonprint(buf, (char *)transchar_charbuf + i, c);
464  } else {
465    transchar_hex((char *)transchar_charbuf + i, c);
466  }
467  return (char *)transchar_charbuf;
468}
469
470/// Like transchar(), but called with a byte instead of a character.
471///
472/// Checks for an illegal UTF-8 byte.  Uses 'fileformat' of the current buffer.
473///
474/// @param[in]  c  Byte to translate.
475///
476/// @return pointer to translated character in transchar_charbuf.
477char *transchar_byte(const int c)
478  FUNC_ATTR_WARN_UNUSED_RESULT
479{
480  return transchar_byte_buf(curbuf, c);
481}
482
483/// Like transchar_buf(), but called with a byte instead of a character.
484///
485/// Checks for an illegal UTF-8 byte.  Uses 'fileformat' of "buf", unless it is NULL.
486///
487/// @param[in]  c  Byte to translate.
488///
489/// @return pointer to translated character in transchar_charbuf.
490char *transchar_byte_buf(const buf_T *buf, const int c)
491  FUNC_ATTR_WARN_UNUSED_RESULT
492{
493  if (c >= 0x80) {
494    transchar_nonprint(buf, (char *)transchar_charbuf, c);
495    return (char *)transchar_charbuf;
496  }
497  return transchar_buf(buf, c);
498}
499
500/// Convert non-printable characters to 2..4 printable ones
501///
502/// @warning Does not work for multi-byte characters, c must be <= 255.
503///
504/// @param[in]  buf  Required to check the file format
505/// @param[out]  charbuf  Buffer to store result in, must be able to hold
506///                       at least 5 bytes (conversion result + NUL).
507/// @param[in]  c  Character to convert. NUL is assumed to be NL according to
508///                `:h NL-used-for-NUL`.
509void transchar_nonprint(const buf_T *buf, char *charbuf, int c)
510{
511  if (c == NL) {
512    // we use newline in place of a NUL
513    c = NUL;
514  } else if (buf != NULL && c == CAR && get_fileformat(buf) == EOL_MAC) {
515    // we use CR in place of  NL in this case
516    c = NL;
517  }
518  assert(c <= 0xff);
519
520  if (dy_flags & kOptDyFlagUhex || c > 0x7f) {
521    // 'display' has "uhex"
522    transchar_hex(charbuf, c);
523  } else {
524    // 0x00 - 0x1f and 0x7f
525    charbuf[0] = '^';
526    // DEL displayed as ^?
527    charbuf[1] = (char)(uint8_t)(c ^ 0x40);
528
529    charbuf[2] = NUL;
530  }
531}
532
533/// Convert a non-printable character to hex C string like "<FFFF>"
534///
535/// @param[out]  buf  Buffer to store result in.
536/// @param[in]  c  Character to convert.
537///
538/// @return Number of bytes stored in buffer, excluding trailing NUL byte.
539size_t transchar_hex(char *const buf, const int c)
540  FUNC_ATTR_NONNULL_ALL
541{
542  size_t i = 0;
543
544  buf[i++] = '<';
545  if (c > 0xFF) {
546    if (c > 0xFFFF) {
547      buf[i++] = (char)nr2hex((unsigned)c >> 20);
548      buf[i++] = (char)nr2hex((unsigned)c >> 16);
549    }
550    buf[i++] = (char)nr2hex((unsigned)c >> 12);
551    buf[i++] = (char)nr2hex((unsigned)c >> 8);
552  }
553  buf[i++] = (char)(nr2hex((unsigned)c >> 4));
554  buf[i++] = (char)(nr2hex((unsigned)c));
555  buf[i++] = '>';
556  buf[i] = NUL;
557  return i;
558}
559
560/// Mirror text "str" for right-left displaying.
561/// Only works for single-byte characters (e.g., numbers).
562void rl_mirror_ascii(char *str, char *end)
563{
564  for (char *p1 = str, *p2 = (end ? end : str + strlen(str)) - 1; p1 < p2; p1++, p2--) {
565    char t = *p1;
566    *p1 = *p2;
567    *p2 = t;
568  }
569}
570
571/// Convert the lower 4 bits of byte "c" to its hex character
572///
573/// Lower case letters are used to avoid the confusion of <F1> being 0xf1 or
574/// function key 1.
575///
576/// @param[in]  n  Number to convert.
577///
578/// @return the hex character.
579static inline unsigned nr2hex(unsigned n)
580  FUNC_ATTR_CONST FUNC_ATTR_WARN_UNUSED_RESULT
581{
582  if ((n & 0xf) <= 9) {
583    return (n & 0xf) + '0';
584  }
585  return (n & 0xf) - 10 + 'a';
586}
587
588/// Return number of display cells occupied by character "c".
589///
590/// "c" can be a special key (negative number) in which case 3 or 4 is returned.
591/// A TAB is counted as two cells: "^I" or four: "<09>".
592///
593/// @param c
594///
595/// @return Number of display cells.
596int char2cells(int c)
597{
598  if (c >= 0x80) {
599    // UTF-8: above 0x80 need to check the value
600    return utf_char2cells(c);
601  }
602  return ascii2cells(c);
603}
604
605/// Return the number of character cells string "s" will take on the screen,
606/// counting TABs as two characters: "^I".
607///
608/// 's' must be non-null.
609///
610/// @param s
611///
612/// @return number of character cells.
613int vim_strsize(const char *s)
614{
615  return vim_strnsize(s, MAXCOL);
616}
617
618/// Return the number of character cells string "s[len]" will take on the
619/// screen, counting TABs as two characters: "^I".
620///
621/// 's' must be non-null.
622///
623/// @param s
624/// @param len
625///
626/// @return Number of character cells.
627int vim_strnsize(const char *s, int len)
628{
629  assert(s != NULL);
630  int size = 0;
631  while (*s != NUL && --len >= 0) {
632    int l = utfc_ptr2len(s);
633    size += ptr2cells(s);
634    s += l;
635    len -= l - 1;
636  }
637  return size;
638}
639
640/// Check that "c" is a normal identifier character:
641/// Letters and characters from the 'isident' option.
642///
643/// @param  c  character to check
644bool vim_isIDc(int c)
645  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
646{
647  return c > 0 && c < 0x100 && GET_CHARTAB(isi_chartab, c);
648}
649
650/// Check that "c" is a keyword character:
651/// Letters and characters from 'iskeyword' option for the current buffer.
652/// For multi-byte characters mb_get_class() is used (builtin rules).
653///
654/// @param  c  character to check
655bool vim_iswordc(const int c)
656  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
657{
658  return vim_iswordc_buf(c, curbuf);
659}
660
661/// Check that "c" is a keyword character
662/// Letters and characters from 'iskeyword' option for given buffer.
663/// For multi-byte characters mb_get_class() is used (builtin rules).
664///
665/// @param[in]  c  Character to check.
666/// @param[in]  chartab  Buffer chartab.
667bool vim_iswordc_tab(const int c, const uint64_t *const chartab)
668  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
669{
670  return (c >= 0x100
671          ? (utf_class_tab(c, chartab) >= 2)
672          : (c > 0 && GET_CHARTAB(chartab, c) != 0));
673}
674
675/// Check that "c" is a keyword character:
676/// Letters and characters from 'iskeyword' option for given buffer.
677/// For multi-byte characters mb_get_class() is used (builtin rules).
678///
679/// @param  c    character to check
680/// @param  buf  buffer whose keywords to use
681bool vim_iswordc_buf(const int c, buf_T *const buf)
682  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ARG(2)
683{
684  return vim_iswordc_tab(c, buf->b_chartab);
685}
686
687/// Just like vim_iswordc() but uses a pointer to the (multi-byte) character.
688///
689/// @param  p  pointer to the multi-byte character
690///
691/// @return true if "p" points to a keyword character.
692bool vim_iswordp(const char *const p)
693  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
694{
695  return vim_iswordp_buf(p, curbuf);
696}
697
698/// Just like vim_iswordc_buf() but uses a pointer to the (multi-byte)
699/// character.
700///
701/// @param  p    pointer to the multi-byte character
702/// @param  buf  buffer whose keywords to use
703///
704/// @return true if "p" points to a keyword character.
705bool vim_iswordp_buf(const char *const p, buf_T *const buf)
706  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
707{
708  int c = (uint8_t)(*p);
709
710  if (MB_BYTE2LEN(c) > 1) {
711    c = utf_ptr2char(p);
712  }
713  return vim_iswordc_buf(c, buf);
714}
715
716/// Check that "c" is a valid file-name character as specified with the
717/// 'isfname' option.
718/// Assume characters above 0x100 are valid (multi-byte).
719/// To be used for commands like "gf".
720///
721/// @param  c  character to check
722bool vim_isfilec(int c)
723  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
724{
725  return c >= 0x100 || (c > 0 && GET_CHARTAB(isf_chartab, c));
726}
727
728/// Check if "c" is a valid file-name character, including characters left
729/// out of 'isfname' to make "gf" work, such as ',', ' ', '@', ':', etc.
730bool vim_is_fname_char(int c)
731  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
732{
733  return vim_isfilec(c) || c == ',' || c == ' ' || c == '@' || c == ':';
734}
735
736/// Check that "c" is a valid file-name character or a wildcard character
737/// Assume characters above 0x100 are valid (multi-byte).
738/// Explicitly interpret ']' as a wildcard character as path_has_wildcard("]")
739/// returns false.
740///
741/// @param  c  character to check
742bool vim_isfilec_or_wc(int c)
743  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
744{
745  char buf[2];
746  buf[0] = (char)c;
747  buf[1] = NUL;
748  return vim_isfilec(c) || c == ']' || path_has_wildcard(buf, true);
749}
750
751/// Check that "c" is a printable character.
752///
753/// @param  c  character to check
754bool vim_isprintc(int c)
755  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
756{
757  if (c >= 0x100) {
758    return utf_printable(c);
759  }
760  return c > 0 && ((c & 0x60) != 0 && c != 0x7f);
761}
762
763/// skipwhite: skip over ' ' and '\t'.
764///
765/// @param[in]  p  String to skip in.
766///
767/// @return Pointer to character after the skipped whitespace.
768char *skipwhite(const char *p)
769  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
770  FUNC_ATTR_NONNULL_RET
771{
772  while (ascii_iswhite(*p)) {
773    p++;
774  }
775  return (char *)p;
776}
777
778/// Like `skipwhite`, but skip up to `len` characters.
779/// @see skipwhite
780///
781/// @param[in]  p    String to skip in.
782/// @param[in]  len  Max length to skip.
783///
784/// @return Pointer to character after the skipped whitespace, or the `len`-th
785///         character in the string.
786char *skipwhite_len(const char *p, size_t len)
787  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
788  FUNC_ATTR_NONNULL_RET
789{
790  for (; len > 0 && ascii_iswhite(*p); len--) {
791    p++;
792  }
793  return (char *)p;
794}
795
796// getwhitecols: return the number of whitespace
797// columns (bytes) at the start of a given line
798intptr_t getwhitecols_curline(void)
799{
800  return getwhitecols(get_cursor_line_ptr());
801}
802
803intptr_t getwhitecols(const char *p)
804  FUNC_ATTR_PURE
805{
806  return skipwhite(p) - p;
807}
808
809/// Skip over digits
810///
811/// @param[in]  q  String to skip digits in.
812///
813/// @return Pointer to the character after the skipped digits.
814char *skipdigits(const char *q)
815  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
816  FUNC_ATTR_NONNULL_RET
817{
818  const char *p = q;
819  while (ascii_isdigit(*p)) {
820    // skip to next non-digit
821    p++;
822  }
823  return (char *)p;
824}
825
826/// skip over binary digits
827///
828/// @param q pointer to string
829///
830/// @return Pointer to the character after the skipped digits.
831const char *skipbin(const char *q)
832  FUNC_ATTR_PURE
833  FUNC_ATTR_NONNULL_ALL
834  FUNC_ATTR_NONNULL_RET
835{
836  const char *p = q;
837  while (ascii_isbdigit(*p)) {
838    // skip to next non-digit
839    p++;
840  }
841  return p;
842}
843
844/// skip over digits and hex characters
845///
846/// @param q
847///
848/// @return Pointer to the character after the skipped digits and hex
849///         characters.
850char *skiphex(char *q)
851  FUNC_ATTR_PURE
852{
853  char *p = q;
854  while (ascii_isxdigit(*p)) {
855    // skip to next non-digit
856    p++;
857  }
858  return p;
859}
860
861/// skip to digit (or NUL after the string)
862///
863/// @param q
864///
865/// @return Pointer to the digit or (NUL after the string).
866char *skiptodigit(char *q)
867  FUNC_ATTR_PURE
868{
869  char *p = q;
870  while (*p != NUL && !ascii_isdigit(*p)) {
871    // skip to next digit
872    p++;
873  }
874  return p;
875}
876
877/// skip to binary character (or NUL after the string)
878///
879/// @param q pointer to string
880///
881/// @return Pointer to the binary character or (NUL after the string).
882const char *skiptobin(const char *q)
883  FUNC_ATTR_PURE
884  FUNC_ATTR_NONNULL_ALL
885  FUNC_ATTR_NONNULL_RET
886{
887  const char *p = q;
888  while (*p != NUL && !ascii_isbdigit(*p)) {
889    // skip to next digit
890    p++;
891  }
892  return p;
893}
894
895/// skip to hex character (or NUL after the string)
896///
897/// @param q
898///
899/// @return Pointer to the hex character or (NUL after the string).
900char *skiptohex(char *q)
901  FUNC_ATTR_PURE
902{
903  char *p = q;
904  while (*p != NUL && !ascii_isxdigit(*p)) {
905    // skip to next digit
906    p++;
907  }
908  return p;
909}
910
911/// Skip over text until ' ' or '\t' or NUL
912///
913/// @param[in]  p  Text to skip over.
914///
915/// @return Pointer to the next whitespace or NUL character.
916char *skiptowhite(const char *p)
917  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE
918{
919  while (*p != ' ' && *p != '\t' && *p != NUL) {
920    p++;
921  }
922  return (char *)p;
923}
924
925/// skiptowhite_esc: Like skiptowhite(), but also skip escaped chars
926///
927/// @param p
928///
929/// @return Pointer to the next whitespace character.
930char *skiptowhite_esc(const char *p)
931  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE
932{
933  while (*p != ' ' && *p != '\t' && *p != NUL) {
934    if (((*p == '\\') || (*p == Ctrl_V)) && (*(p + 1) != NUL)) {
935      p++;
936    }
937    p++;
938  }
939  return (char *)p;
940}
941
942/// Skip over text until '\n' or NUL.
943///
944/// @param[in]  p  Text to skip over.
945///
946/// @return Pointer to the next '\n' or NUL character.
947char *skip_to_newline(const char *const p)
948  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
949  FUNC_ATTR_NONNULL_RET
950{
951  return xstrchrnul(p, NL);
952}
953
954/// Gets a number from a string and skips over it, signalling overflow.
955///
956/// @param[out]  pp  A pointer to a pointer to char.
957///                  It will be advanced past the read number.
958/// @param[out]  nr  Number read from the string.
959///
960/// @return true on success, false on error/overflow
961bool try_getdigits(char **pp, intmax_t *nr)
962{
963  errno = 0;
964  *nr = strtoimax(*pp, pp, 10);
965  if (errno == ERANGE && (*nr == INTMAX_MIN || *nr == INTMAX_MAX)) {
966    return false;
967  }
968  return true;
969}
970
971/// Gets a number from a string and skips over it.
972///
973/// @param[out]  pp  Pointer to a pointer to char.
974///                  It will be advanced past the read number.
975/// @param strict    Abort on overflow.
976/// @param def       Default value, if parsing fails or overflow occurs.
977///
978/// @return Number read from the string, or `def` on parse failure or overflow.
979intmax_t getdigits(char **pp, bool strict, intmax_t def)
980{
981  intmax_t number;
982  int ok = try_getdigits(pp, &number);
983  if (strict && !ok) {
984    abort();
985  }
986  return ok ? number : def;
987}
988
989/// Gets an int number from a string.
990///
991/// @see getdigits
992int getdigits_int(char **pp, bool strict, int def)
993{
994  intmax_t number = getdigits(pp, strict, def);
995#if SIZEOF_INTMAX_T > SIZEOF_INT
996  if (strict) {
997    assert(number >= INT_MIN && number <= INT_MAX);
998  } else if (!(number >= INT_MIN && number <= INT_MAX)) {
999    return def;
1000  }
1001#endif
1002  return (int)number;
1003}
1004
1005/// Gets a long number from a string.
1006///
1007/// @see getdigits
1008long getdigits_long(char **pp, bool strict, long def)
1009{
1010  intmax_t number = getdigits(pp, strict, def);
1011#if SIZEOF_INTMAX_T > SIZEOF_LONG
1012  if (strict) {
1013    assert(number >= LONG_MIN && number <= LONG_MAX);
1014  } else if (!(number >= LONG_MIN && number <= LONG_MAX)) {
1015    return def;
1016  }
1017#endif
1018  return (long)number;
1019}
1020
1021/// Gets a int32_t number from a string.
1022///
1023/// @see getdigits
1024int32_t getdigits_int32(char **pp, bool strict, int32_t def)
1025{
1026  intmax_t number = getdigits(pp, strict, def);
1027#if SIZEOF_INTMAX_T > 4
1028  if (strict) {
1029    assert(number >= INT32_MIN && number <= INT32_MAX);
1030  } else if (!(number >= INT32_MIN && number <= INT32_MAX)) {
1031    return def;
1032  }
1033#endif
1034  return (int32_t)number;
1035}
1036
1037/// Check that "lbuf" is empty or only contains blanks.
1038///
1039/// @param  lbuf  line buffer to check
1040bool vim_isblankline(char *lbuf)
1041  FUNC_ATTR_PURE
1042{
1043  char *p = skipwhite(lbuf);
1044  return *p == NUL || *p == '\r' || *p == '\n';
1045}
1046
1047/// Convert a string into a long and/or unsigned long, taking care of
1048/// hexadecimal, octal and binary numbers.  Accepts a '-' sign.
1049/// If "prep" is not NULL, returns a flag to indicate the type of the number:
1050///   0      decimal
1051///   '0'    octal
1052///   'O'    octal
1053///   'o'    octal
1054///   'B'    bin
1055///   'b'    bin
1056///   'X'    hex
1057///   'x'    hex
1058/// If "len" is not NULL, the length of the number in characters is returned.
1059/// If "nptr" is not NULL, the signed result is returned in it.
1060/// If "unptr" is not NULL, the unsigned result is returned in it.
1061/// If "what" contains STR2NR_BIN recognize binary numbers.
1062/// If "what" contains STR2NR_OCT recognize octal numbers.
1063/// If "what" contains STR2NR_HEX recognize hex numbers.
1064/// If "what" contains STR2NR_FORCE always assume bin/oct/hex.
1065/// If "what" contains STR2NR_QUOTE ignore embedded single quotes
1066/// If maxlen > 0, check at a maximum maxlen chars.
1067/// If strict is true, check the number strictly. return *len = 0 if fail.
1068///
1069/// @param start
1070/// @param prep Returns guessed type of number 0 = decimal, 'x' or 'X' is
1071///             hexadecimal, '0', 'o' or 'O' is octal, 'b' or 'B' is binary.
1072///             When using STR2NR_FORCE is always zero.
1073/// @param len Returns the detected length of number.
1074/// @param what Recognizes what number passed, @see ChStr2NrFlags.
1075/// @param nptr Returns the signed result.
1076/// @param unptr Returns the unsigned result.
1077/// @param maxlen Max length of string to check.
1078/// @param strict If true, fail if the number has unexpected trailing
1079///               alphanumeric chars: *len is set to 0 and nothing else is
1080///               returned.
1081/// @param overflow When not NULL, set to true for overflow.
1082void vim_str2nr(const char *const start, int *const prep, int *const len, const int what,
1083                varnumber_T *const nptr, uvarnumber_T *const unptr, const int maxlen,
1084                const bool strict, bool *const overflow)
1085  FUNC_ATTR_NONNULL_ARG(1)
1086{
1087  const char *ptr = start;
1088#define STRING_ENDED(ptr) \
1089  (!(maxlen == 0 || (int)((ptr) - start) < maxlen))
1090  int pre = 0;  // default is decimal
1091  const bool negative = (ptr[0] == '-');
1092  uvarnumber_T un = 0;
1093
1094  if (len != NULL) {
1095    *len = 0;
1096  }
1097
1098  if (negative) {
1099    ptr++;
1100  }
1101
1102  if (what & STR2NR_FORCE) {
1103    // When forcing main consideration is skipping the prefix. Decimal numbers
1104    // have no prefixes to skip. pre is not set.
1105    switch (what & ~(STR2NR_FORCE | STR2NR_QUOTE)) {
1106    case STR2NR_HEX:
1107      if (!STRING_ENDED(ptr + 2)
1108          && ptr[0] == '0'
1109          && (ptr[1] == 'x' || ptr[1] == 'X')
1110          && ascii_isxdigit(ptr[2])) {
1111        ptr += 2;
1112      }
1113      goto vim_str2nr_hex;
1114    case STR2NR_BIN:
1115      if (!STRING_ENDED(ptr + 2)
1116          && ptr[0] == '0'
1117          && (ptr[1] == 'b' || ptr[1] == 'B')
1118          && ascii_isbdigit(ptr[2])) {
1119        ptr += 2;
1120      }
1121      goto vim_str2nr_bin;
1122    // Make STR2NR_OOCT work the same as STR2NR_OCT when forcing.
1123    case STR2NR_OCT:
1124    case STR2NR_OOCT:
1125    case STR2NR_OCT | STR2NR_OOCT:
1126      if (!STRING_ENDED(ptr + 2)
1127          && ptr[0] == '0'
1128          && (ptr[1] == 'o' || ptr[1] == 'O')
1129          && ascii_isodigit(ptr[2])) {
1130        ptr += 2;
1131      }
1132      goto vim_str2nr_oct;
1133    case 0:
1134      goto vim_str2nr_dec;
1135    default:
1136      abort();
1137    }
1138  } else if ((what & (STR2NR_HEX | STR2NR_OCT | STR2NR_OOCT | STR2NR_BIN))
1139             && !STRING_ENDED(ptr + 1) && ptr[0] == '0' && ptr[1] != '8'
1140             && ptr[1] != '9') {
1141    pre = (uint8_t)ptr[1];
1142    // Detect hexadecimal: 0x or 0X followed by hex digit.
1143    if ((what & STR2NR_HEX)
1144        && !STRING_ENDED(ptr + 2)
1145        && (pre == 'X' || pre == 'x')
1146        && ascii_isxdigit(ptr[2])) {
1147      ptr += 2;
1148      goto vim_str2nr_hex;
1149    }
1150    // Detect binary: 0b or 0B followed by 0 or 1.
1151    if ((what & STR2NR_BIN)
1152        && !STRING_ENDED(ptr + 2)
1153        && (pre == 'B' || pre == 'b')
1154        && ascii_isbdigit(ptr[2])) {
1155      ptr += 2;
1156      goto vim_str2nr_bin;
1157    }
1158    // Detect octal: 0o or 0O followed by octal digits (without '8' or '9').
1159    if ((what & STR2NR_OOCT)
1160        && !STRING_ENDED(ptr + 2)
1161        && (pre == 'O' || pre == 'o')
1162        && ascii_isodigit(ptr[2])) {
1163      ptr += 2;
1164      goto vim_str2nr_oct;
1165    }
1166    // Detect old octal format: 0 followed by octal digits.
1167    pre = 0;
1168    if (!(what & STR2NR_OCT)
1169        || !ascii_isodigit(ptr[1])) {
1170      goto vim_str2nr_dec;
1171    }
1172    for (int i = 2; !STRING_ENDED(ptr + i) && ascii_isdigit(ptr[i]); i++) {
1173      if (ptr[i] > '7') {
1174        goto vim_str2nr_dec;
1175      }
1176    }
1177    pre = '0';
1178    goto vim_str2nr_oct;
1179  } else {
1180    goto vim_str2nr_dec;
1181  }
1182
1183  // Do the conversion manually to avoid sscanf() quirks.
1184  abort();  // Should’ve used goto earlier.
1185#define PARSE_NUMBER(base, cond, conv) \
1186  do { \
1187    const char *const after_prefix = ptr; \
1188    while (!STRING_ENDED(ptr)) { \
1189      if ((what & STR2NR_QUOTE) && ptr > after_prefix && *ptr == '\'') { \
1190        ptr++; \
1191        if (!STRING_ENDED(ptr) && (cond)) { \
1192          continue; \
1193        } \
1194        ptr--; \
1195      } \
1196      if (!(cond)) { \
1197        break; \
1198      } \
1199      const uvarnumber_T digit = (uvarnumber_T)(conv); \
1200      /* avoid ubsan error for overflow */ \
1201      if (un < UVARNUMBER_MAX / (base) \
1202          || (un == UVARNUMBER_MAX / (base) \
1203              && ((base) != 10 || digit <= UVARNUMBER_MAX % 10))) { \
1204        un = (base) * un + digit; \
1205      } else { \
1206        un = UVARNUMBER_MAX; \
1207        if (overflow != NULL) { \
1208          *overflow = true; \
1209        } \
1210      } \
1211      ptr++; \
1212    } \
1213  } while (0)
1214vim_str2nr_bin:
1215  PARSE_NUMBER(2, (*ptr == '0' || *ptr == '1'), (*ptr - '0'));
1216  goto vim_str2nr_proceed;
1217vim_str2nr_oct:
1218  PARSE_NUMBER(8, (ascii_isodigit(*ptr)), (*ptr - '0'));
1219  goto vim_str2nr_proceed;
1220vim_str2nr_dec:
1221  PARSE_NUMBER(10, (ascii_isdigit(*ptr)), (*ptr - '0'));
1222  goto vim_str2nr_proceed;
1223vim_str2nr_hex:
1224  PARSE_NUMBER(16, (ascii_isxdigit(*ptr)), (hex2nr(*ptr)));
1225  goto vim_str2nr_proceed;
1226#undef PARSE_NUMBER
1227
1228vim_str2nr_proceed:
1229  // Check for an alphanumeric character immediately following, that is
1230  // most likely a typo.
1231  if (strict && ptr - start != maxlen && ASCII_ISALNUM(*ptr)) {
1232    return;
1233  }
1234
1235  if (prep != NULL) {
1236    *prep = pre;
1237  }
1238
1239  if (len != NULL) {
1240    *len = (int)(ptr - start);
1241  }
1242
1243  if (nptr != NULL) {
1244    if (negative) {  // account for leading '-' for decimal numbers
1245      // avoid ubsan error for overflow
1246      if (un > VARNUMBER_MAX) {
1247        *nptr = VARNUMBER_MIN;
1248        if (overflow != NULL) {
1249          *overflow = true;
1250        }
1251      } else {
1252        *nptr = -(varnumber_T)un;
1253      }
1254    } else {
1255      if (un > VARNUMBER_MAX) {
1256        un = VARNUMBER_MAX;
1257        if (overflow != NULL) {
1258          *overflow = true;
1259        }
1260      }
1261      *nptr = (varnumber_T)un;
1262    }
1263  }
1264
1265  if (unptr != NULL) {
1266    *unptr = un;
1267  }
1268#undef STRING_ENDED
1269}
1270
1271/// Return the value of a single hex character.
1272/// Only valid when the argument is '0' - '9', 'A' - 'F' or 'a' - 'f'.
1273///
1274/// @param c
1275///
1276/// @return The value of the hex character.
1277int hex2nr(int c)
1278  FUNC_ATTR_CONST
1279{
1280  if ((c >= 'a') && (c <= 'f')) {
1281    return c - 'a' + 10;
1282  }
1283
1284  if ((c >= 'A') && (c <= 'F')) {
1285    return c - 'A' + 10;
1286  }
1287  return c - '0';
1288}
1289
1290/// Convert two hex characters to a byte.
1291///
1292/// @return  -1 if one of the characters is not hex.
1293int hexhex2nr(const char *p)
1294  FUNC_ATTR_PURE
1295{
1296  if (!ascii_isxdigit(p[0]) || !ascii_isxdigit(p[1])) {
1297    return -1;
1298  }
1299  return (hex2nr(p[0]) << 4) + hex2nr(p[1]);
1300}
1301
1302/// Check that "str" starts with a backslash that should be removed.
1303/// For Windows this is only done when the character after the
1304/// backslash is not a normal file name character.
1305/// '$' is a valid file name character, we don't remove the backslash before
1306/// it.  This means it is not possible to use an environment variable after a
1307/// backslash.  "C:\$VIM\doc" is taken literally, only "$VIM\doc" works.
1308/// Although "\ name" is valid, the backslash in "Program\ files" must be
1309/// removed.  Assume a file name doesn't start with a space.
1310/// For multi-byte names, never remove a backslash before a non-ascii
1311/// character, assume that all multi-byte characters are valid file name
1312/// characters.
1313///
1314/// @param  str  file path string to check
1315bool rem_backslash(const char *str)
1316  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
1317{
1318#ifdef BACKSLASH_IN_FILENAME
1319  return str[0] == '\\'
1320         && (uint8_t)str[1] < 0x80
1321         && (str[1] == ' '
1322             || (str[1] != NUL
1323                 && str[1] != '*'
1324                 && str[1] != '?'
1325                 && !vim_isfilec((uint8_t)str[1])));
1326
1327#else
1328  return str[0] == '\\' && str[1] != NUL;
1329#endif
1330}
1331
1332/// Halve the number of backslashes in a file name argument.
1333///
1334/// @param p
1335void backslash_halve(char *p)
1336{
1337  for (; *p && !rem_backslash(p); p++) {}
1338  if (*p != NUL) {
1339    char *dst = p;
1340    goto start;
1341    while (*p != NUL) {
1342      if (rem_backslash(p)) {
1343start:
1344        *dst++ = *(p + 1);
1345        p += 2;
1346      } else {
1347        *dst++ = *p++;
1348      }
1349    }
1350    *dst = NUL;
1351  }
1352}
1353
1354/// backslash_halve() plus save the result in allocated memory.
1355///
1356/// @param p
1357///
1358/// @return String with the number of backslashes halved.
1359char *backslash_halve_save(const char *p)
1360  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET
1361{
1362  char *res = xmalloc(strlen(p) + 1);
1363  char *dst = res;
1364  while (*p != NUL) {
1365    if (rem_backslash(p)) {
1366      *dst++ = *(p + 1);
1367      p += 2;
1368    } else {
1369      *dst++ = *p++;
1370    }
1371  }
1372  *dst = NUL;
1373  return res;
1374}