robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
116.3 KiB3645 linesraw
1// search.c: code for normal mode searching commands
2
3#include <assert.h>
4#include <inttypes.h>
5#include <limits.h>
6#include <stdbool.h>
7#include <stdio.h>
8#include <stdlib.h>
9#include <string.h>
10
11#include "nvim/ascii_defs.h"
12#include "nvim/autocmd.h"
13#include "nvim/autocmd_defs.h"
14#include "nvim/buffer.h"
15#include "nvim/buffer_defs.h"
16#include "nvim/change.h"
17#include "nvim/charset.h"
18#include "nvim/cmdhist.h"
19#include "nvim/cursor.h"
20#include "nvim/drawscreen.h"
21#include "nvim/errors.h"
22#include "nvim/eval/typval.h"
23#include "nvim/eval/typval_defs.h"
24#include "nvim/eval/vars.h"
25#include "nvim/ex_cmds.h"
26#include "nvim/ex_cmds_defs.h"
27#include "nvim/ex_docmd.h"
28#include "nvim/ex_getln.h"
29#include "nvim/file_search.h"
30#include "nvim/fileio.h"
31#include "nvim/fold.h"
32#include "nvim/gettext_defs.h"
33#include "nvim/globals.h"
34#include "nvim/highlight_defs.h"
35#include "nvim/indent_c.h"
36#include "nvim/input.h"
37#include "nvim/insexpand.h"
38#include "nvim/macros_defs.h"
39#include "nvim/mark.h"
40#include "nvim/mark_defs.h"
41#include "nvim/mbyte.h"
42#include "nvim/memline.h"
43#include "nvim/memory.h"
44#include "nvim/message.h"
45#include "nvim/mouse.h"
46#include "nvim/move.h"
47#include "nvim/normal.h"
48#include "nvim/option.h"
49#include "nvim/option_vars.h"
50#include "nvim/os/fs.h"
51#include "nvim/os/input.h"
52#include "nvim/os/time.h"
53#include "nvim/path.h"
54#include "nvim/plines.h"
55#include "nvim/profile.h"
56#include "nvim/regexp.h"
57#include "nvim/search.h"
58#include "nvim/state_defs.h"
59#include "nvim/strings.h"
60#include "nvim/tag.h"
61#include "nvim/ui.h"
62#include "nvim/ui_defs.h"
63#include "nvim/vim_defs.h"
64#include "nvim/window.h"
65
66#include "search.c.generated.h"
67
68static const char e_search_hit_top_without_match_for_str[]
69  = N_("E384: Search hit TOP without match for: %s");
70static const char e_search_hit_bottom_without_match_for_str[]
71  = N_("E385: Search hit BOTTOM without match for: %s");
72
73//  This file contains various searching-related routines. These fall into
74//  three groups:
75//  1. string searches (for /, ?, n, and N)
76//  2. character searches within a single line (for f, F, t, T, etc)
77//  3. "other" kinds of searches like the '%' command, and 'word' searches.
78//
79//
80//  String searches
81//
82//  The string search functions are divided into two levels:
83//  lowest:  searchit(); uses a pos_T for starting position and found match.
84//  Highest: do_search(); uses curwin->w_cursor; calls searchit().
85//
86//  The last search pattern is remembered for repeating the same search.
87//  This pattern is shared between the :g, :s, ? and / commands.
88//  This is in search_regcomp().
89//
90//  The actual string matching is done using a heavily modified version of
91//  Henry Spencer's regular expression library.  See regexp.c.
92//
93//
94//
95// Two search patterns are remembered: One for the :substitute command and
96// one for other searches.  last_idx points to the one that was used the last
97// time.
98
99static SearchPattern spats[2] = {
100  // Last used search pattern
101  [0] = { NULL, 0, true, false, 0, { '/', false, false, 0 }, NULL },
102  // Last used substitute pattern
103  [1] = { NULL, 0, true, false, 0, { '/', false, false, 0 }, NULL }
104};
105
106static int last_idx = 0;        // index in spats[] for RE_LAST
107
108static uint8_t lastc[2] = { NUL, NUL };   // last character searched for
109static Direction lastcdir = FORWARD;      // last direction of character search
110static bool last_t_cmd = true;            // last search t_cmd
111static char lastc_bytes[MAX_SCHAR_SIZE + 1];
112static int lastc_bytelen = 1;             // >1 for multi-byte char
113
114// copy of spats[], for keeping the search patterns while executing autocmds
115static SearchPattern saved_spats[ARRAY_SIZE(spats)];
116static char *saved_mr_pattern = NULL;
117static size_t saved_mr_patternlen = 0;
118static int saved_spats_last_idx = 0;
119static bool saved_spats_no_hlsearch = false;
120
121// allocated copy of pattern used by search_regcomp()
122static char *mr_pattern = NULL;
123static size_t mr_patternlen = 0;
124
125// Type used by find_pattern_in_path() to remember which included files have
126// been searched already.
127typedef struct {
128  FILE *fp;              // File pointer
129  char *name;            // Full name of file
130  linenr_T lnum;                // Line we were up to in file
131  int matched;                  // Found a match in this file
132} SearchedFile;
133
134/// translate search pattern for vim_regcomp()
135///
136/// pat_save == RE_SEARCH: save pat in spats[RE_SEARCH].pat (normal search cmd)
137/// pat_save == RE_SUBST: save pat in spats[RE_SUBST].pat (:substitute command)
138/// pat_save == RE_BOTH: save pat in both patterns (:global command)
139/// pat_use  == RE_SEARCH: use previous search pattern if "pat" is NULL
140/// pat_use  == RE_SUBST: use previous substitute pattern if "pat" is NULL
141/// pat_use  == RE_LAST: use last used pattern if "pat" is NULL
142/// options & SEARCH_HIS: put search string in history
143/// options & SEARCH_KEEP: keep previous search pattern
144///
145/// @param regmatch  return: pattern and ignore-case flag
146///
147/// @return          FAIL if failed, OK otherwise.
148int search_regcomp(char *pat, size_t patlen, char **used_pat, int pat_save, int pat_use,
149                   int options, bool magic, regmmatch_T *regmatch)
150{
151  rc_did_emsg = false;
152
153  // If no pattern given, use a previously defined pattern.
154  if (pat == NULL || *pat == NUL) {
155    int i;
156    if (pat_use == RE_LAST) {
157      i = last_idx;
158    } else {
159      i = pat_use;
160    }
161    if (spats[i].pat == NULL) {         // pattern was never defined
162      if (pat_use == RE_SUBST) {
163        emsg(_(e_nopresub));
164      } else {
165        emsg(_(e_noprevre));
166      }
167      rc_did_emsg = true;
168      return FAIL;
169    }
170    pat = spats[i].pat;
171    patlen = spats[i].patlen;
172    magic = spats[i].magic;
173    Search.no_smartcase = spats[i].no_scs;
174  } else if (options & SEARCH_HIS) {      // put new pattern in history
175    add_to_history(HIST_SEARCH, pat, patlen, true, NUL);
176  }
177
178  if (used_pat) {
179    *used_pat = pat;
180  }
181
182  xfree(mr_pattern);
183  if (curwin->w_p_rl && *curwin->w_p_rlc == 's') {
184    mr_pattern = reverse_text(pat);
185  } else {
186    mr_pattern = xstrnsave(pat, patlen);
187  }
188  mr_patternlen = patlen;
189
190  // Save the currently used pattern in the appropriate place,
191  // unless the pattern should not be remembered.
192  if (!(options & SEARCH_KEEP) && (cmdmod.cmod_flags & CMOD_KEEPPATTERNS) == 0) {
193    // search or global command
194    if (pat_save == RE_SEARCH || pat_save == RE_BOTH) {
195      save_re_pat(RE_SEARCH, pat, patlen, magic);
196    }
197    // substitute or global command
198    if (pat_save == RE_SUBST || pat_save == RE_BOTH) {
199      save_re_pat(RE_SUBST, pat, patlen, magic);
200    }
201  }
202
203  regmatch->rmm_ic = ignorecase(pat);
204  regmatch->rmm_maxcol = 0;
205  regmatch->regprog = vim_regcomp(pat, magic ? RE_MAGIC : 0);
206  if (regmatch->regprog == NULL) {
207    return FAIL;
208  }
209  return OK;
210}
211
212/// Get search pattern used by search_regcomp().
213char *get_search_pat(void)
214{
215  return mr_pattern;
216}
217
218void save_re_pat(int idx, char *pat, size_t patlen, int magic)
219{
220  if (spats[idx].pat == pat) {
221    return;
222  }
223
224  free_spat(&spats[idx]);
225  spats[idx].pat = xstrnsave(pat, patlen);
226  spats[idx].patlen = patlen;
227  spats[idx].magic = magic;
228  spats[idx].no_scs = Search.no_smartcase;
229  spats[idx].timestamp = os_time();
230  spats[idx].additional_data = NULL;
231  last_idx = idx;
232  // If 'hlsearch' set and search pat changed: need redraw.
233  if (p_hls) {
234    redraw_all_later(UPD_SOME_VALID);
235  }
236  set_no_hlsearch(false);
237}
238
239// Save the search patterns, so they can be restored later.
240// Used before/after executing autocommands and user functions.
241static int save_level = 0;
242
243void save_search_patterns(void)
244{
245  if (save_level++ != 0) {
246    return;
247  }
248
249  for (size_t i = 0; i < ARRAY_SIZE(spats); i++) {
250    saved_spats[i] = spats[i];
251    if (spats[i].pat != NULL) {
252      saved_spats[i].pat = xstrnsave(spats[i].pat, spats[i].patlen);
253      saved_spats[i].patlen = spats[i].patlen;
254    }
255  }
256  if (mr_pattern == NULL) {
257    saved_mr_pattern = NULL;
258    saved_mr_patternlen = 0;
259  } else {
260    saved_mr_pattern = xstrnsave(mr_pattern, mr_patternlen);
261    saved_mr_patternlen = mr_patternlen;
262  }
263  saved_spats_last_idx = last_idx;
264  saved_spats_no_hlsearch = Search.no_hlsearch;
265}
266
267void restore_search_patterns(void)
268{
269  if (--save_level != 0) {
270    return;
271  }
272
273  for (size_t i = 0; i < ARRAY_SIZE(spats); i++) {
274    free_spat(&spats[i]);
275    spats[i] = saved_spats[i];
276  }
277  set_vv_searchforward();
278  xfree(mr_pattern);
279  mr_pattern = saved_mr_pattern;
280  mr_patternlen = saved_mr_patternlen;
281  last_idx = saved_spats_last_idx;
282  set_no_hlsearch(saved_spats_no_hlsearch);
283}
284
285static inline void free_spat(SearchPattern *const spat)
286{
287  xfree(spat->pat);
288  xfree(spat->additional_data);
289}
290
291#ifdef EXITFREE
292void free_search_patterns(void)
293{
294  for (size_t i = 0; i < ARRAY_SIZE(spats); i++) {
295    free_spat(&spats[i]);
296  }
297  CLEAR_FIELD(spats);
298
299  XFREE_CLEAR(mr_pattern);
300  mr_patternlen = 0;
301}
302
303#endif
304
305// copy of spats[RE_SEARCH], for keeping the search patterns while incremental
306// searching
307static SearchPattern saved_last_search_spat;
308static int did_save_last_search_spat = 0;
309static int saved_last_idx = 0;
310static bool saved_no_hlsearch = false;
311static colnr_T saved_search_match_endcol;
312static linenr_T saved_search_match_lines;
313
314/// Save and restore the search pattern for incremental highlight search
315/// feature.
316///
317/// It's similar to but different from save_search_patterns() and
318/// restore_search_patterns(), because the search pattern must be restored when
319/// cancelling incremental searching even if it's called inside user functions.
320void save_last_search_pattern(void)
321{
322  if (++did_save_last_search_spat != 1) {
323    // nested call, nothing to do
324    return;
325  }
326
327  saved_last_search_spat = spats[RE_SEARCH];
328  if (spats[RE_SEARCH].pat != NULL) {
329    saved_last_search_spat.pat = xstrnsave(spats[RE_SEARCH].pat, spats[RE_SEARCH].patlen);
330    saved_last_search_spat.patlen = spats[RE_SEARCH].patlen;
331  }
332  saved_last_idx = last_idx;
333  saved_no_hlsearch = Search.no_hlsearch;
334}
335
336void restore_last_search_pattern(void)
337{
338  if (--did_save_last_search_spat > 0) {
339    // nested call, nothing to do
340    return;
341  }
342  if (did_save_last_search_spat != 0) {
343    iemsg("restore_last_search_pattern() called more often than"
344          " save_last_search_pattern()");
345    return;
346  }
347
348  xfree(spats[RE_SEARCH].pat);
349  spats[RE_SEARCH] = saved_last_search_spat;
350  saved_last_search_spat.pat = NULL;
351  saved_last_search_spat.patlen = 0;
352  set_vv_searchforward();
353  last_idx = saved_last_idx;
354  set_no_hlsearch(saved_no_hlsearch);
355}
356
357/// Save and restore the incsearch highlighting variables.
358/// This is required so that calling searchcount() at does not invalidate the
359/// incsearch highlighting.
360static void save_incsearch_state(void)
361{
362  saved_search_match_endcol = Search.match_endcol;
363  saved_search_match_lines = Search.match_lines;
364}
365
366static void restore_incsearch_state(void)
367{
368  Search.match_endcol = saved_search_match_endcol;
369  Search.match_lines = saved_search_match_lines;
370}
371
372char *last_search_pattern(void)
373{
374  return spats[RE_SEARCH].pat;
375}
376
377size_t last_search_pattern_len(void)
378{
379  return spats[RE_SEARCH].patlen;
380}
381
382/// Return true when case should be ignored for search pattern "pat".
383/// Uses the 'ignorecase' and 'smartcase' options.
384int ignorecase(char *pat)
385{
386  return ignorecase_opt(pat, p_ic, p_scs);
387}
388
389/// As ignorecase() but pass the "ic" and "scs" flags.
390int ignorecase_opt(char *pat, int ic_in, int scs)
391{
392  int ic = ic_in;
393  if (ic && !Search.no_smartcase && scs
394      && !(ctrl_x_mode_not_default()
395           && curbuf->b_p_inf)) {
396    ic = !pat_has_uppercase(pat);
397  }
398  Search.no_smartcase = false;
399
400  return ic;
401}
402
403/// Returns true if pattern `pat` has an uppercase character.
404bool pat_has_uppercase(char *pat)
405  FUNC_ATTR_NONNULL_ALL
406{
407  char *p = pat;
408  magic_T magic_val = MAGIC_ON;
409
410  // get the magicness of the pattern
411  skip_regexp_ex(pat, NUL, p_magic, NULL, NULL, &magic_val);
412
413  while (*p != NUL) {
414    const int l = utfc_ptr2len(p);
415
416    if (l > 1) {
417      if (mb_isupper(utf_ptr2char(p))) {
418        return true;
419      }
420      p += l;
421    } else if (*p == '\\' && magic_val <= MAGIC_ON) {
422      if (p[1] == '_' && p[2] != NUL) {  // skip "\_X"
423        p += 3;
424      } else if (p[1] == '%' && p[2] != NUL) {  // skip "\%X"
425        p += 3;
426      } else if (p[1] != NUL) {  // skip "\X"
427        p += 2;
428      } else {
429        p += 1;
430      }
431    } else if ((*p == '%' || *p == '_') && magic_val == MAGIC_ALL) {
432      if (p[1] != NUL) {  // skip "_X" and %X
433        p += 2;
434      } else {
435        p++;
436      }
437    } else if (mb_isupper((uint8_t)(*p))) {
438      return true;
439    } else {
440      p++;
441    }
442  }
443  return false;
444}
445
446const char *last_csearch(void)
447  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
448{
449  return lastc_bytes;
450}
451
452int last_csearch_forward(void)
453{
454  return lastcdir == FORWARD;
455}
456
457int last_csearch_until(void)
458{
459  return last_t_cmd;
460}
461
462void set_last_csearch(int c, char *s, int len)
463{
464  *lastc = (uint8_t)c;
465  lastc_bytelen = len;
466  if (len) {
467    memcpy(lastc_bytes, s, (size_t)len);
468  } else {
469    CLEAR_FIELD(lastc_bytes);
470  }
471}
472
473void set_csearch_direction(Direction cdir)
474{
475  lastcdir = cdir;
476}
477
478void set_csearch_until(int t_cmd)
479{
480  last_t_cmd = t_cmd;
481}
482
483char *last_search_pat(void)
484{
485  return spats[last_idx].pat;
486}
487
488// Reset search direction to forward.  For "gd" and "gD" commands.
489void reset_search_dir(void)
490{
491  spats[0].off.dir = '/';
492  set_vv_searchforward();
493}
494
495// Set the last search pattern.  For ":let @/ =" and ShaDa file.
496// Also set the saved search pattern, so that this works in an autocommand.
497void set_last_search_pat(const char *s, int idx, int magic, bool setlast)
498{
499  free_spat(&spats[idx]);
500  // An empty string means that nothing should be matched.
501  if (*s == NUL) {
502    spats[idx].pat = NULL;
503    spats[idx].patlen = 0;
504  } else {
505    spats[idx].patlen = strlen(s);
506    spats[idx].pat = xstrnsave(s, spats[idx].patlen);
507  }
508  spats[idx].timestamp = os_time();
509  spats[idx].additional_data = NULL;
510  spats[idx].magic = magic;
511  spats[idx].no_scs = false;
512  spats[idx].off.dir = '/';
513  set_vv_searchforward();
514  spats[idx].off.line = false;
515  spats[idx].off.end = false;
516  spats[idx].off.off = 0;
517  if (setlast) {
518    last_idx = idx;
519  }
520  if (save_level) {
521    free_spat(&saved_spats[idx]);
522    saved_spats[idx] = spats[0];
523    if (spats[idx].pat == NULL) {
524      saved_spats[idx].pat = NULL;
525      saved_spats[idx].patlen = 0;
526    } else {
527      saved_spats[idx].pat = xstrnsave(spats[idx].pat, spats[idx].patlen);
528      saved_spats[idx].patlen = spats[idx].patlen;
529    }
530    saved_spats_last_idx = last_idx;
531  }
532  // If 'hlsearch' set and search pat changed: need redraw.
533  if (p_hls && idx == last_idx && !Search.no_hlsearch) {
534    redraw_all_later(UPD_SOME_VALID);
535  }
536}
537
538// Get a regexp program for the last used search pattern.
539// This is used for highlighting all matches in a window.
540// Values returned in regmatch->regprog and regmatch->rmm_ic.
541void last_pat_prog(regmmatch_T *regmatch)
542{
543  if (spats[last_idx].pat == NULL) {
544    regmatch->regprog = NULL;
545    return;
546  }
547  emsg_off++;           // So it doesn't beep if bad expr
548  search_regcomp("", 0, NULL, 0, last_idx, SEARCH_KEEP, p_magic, regmatch);
549  emsg_off--;
550}
551
552/// Lowest level search function.
553/// Search for 'count'th occurrence of pattern "pat" in direction "dir".
554/// Start at position "pos" and return the found position in "pos".
555///
556/// if (options & SEARCH_MSG) == 0 don't give any messages
557/// if (options & SEARCH_MSG) == SEARCH_NFMSG don't give 'notfound' messages
558/// if (options & SEARCH_MSG) == SEARCH_MSG give all messages
559/// if (options & SEARCH_HIS) put search pattern in history
560/// if (options & SEARCH_END) return position at end of match
561/// if (options & SEARCH_START) accept match at pos itself
562/// if (options & SEARCH_KEEP) keep previous search pattern
563/// if (options & SEARCH_FOLD) match only once in a closed fold
564/// if (options & SEARCH_PEEK) check for typed char, cancel search
565/// if (options & SEARCH_COL) start at pos->col instead of zero
566///
567/// @param win        window to search in; can be NULL for a buffer without a window!
568/// @param end_pos    set to end of the match, unless NULL
569/// @param pat_use    which pattern to use when "pat" is empty
570/// @param extra_arg  optional extra arguments, can be NULL
571///
572/// @returns          FAIL (zero) for failure, non-zero for success.
573///                   the index of the first matching
574///                   subpattern plus one; one if there was none.
575int searchit(win_T *win, buf_T *buf, pos_T *pos, pos_T *end_pos, Direction dir, char *pat,
576             size_t patlen, int count, int options, int pat_use, bool magic,
577             searchit_arg_T *extra_arg)
578{
579  int found;
580  linenr_T lnum;                // no init to shut up Apollo cc
581  regmmatch_T regmatch;
582  char *ptr;
583  colnr_T matchcol;
584  lpos_T endpos;
585  lpos_T matchpos;
586  int loop;
587  int extra_col;
588  int start_char_len;
589  bool match_ok;
590  int nmatched;
591  int submatch = 0;
592  bool first_match = true;
593  const int called_emsg_before = called_emsg;
594  bool break_loop = false;
595  linenr_T stop_lnum = 0;  // stop after this line number when != 0
596  proftime_T *tm = NULL;   // timeout limit or NULL
597  int *timed_out = NULL;   // set when timed out or NULL
598
599  if (extra_arg != NULL) {
600    stop_lnum = extra_arg->sa_stop_lnum;
601    tm = extra_arg->sa_tm;
602    timed_out = &extra_arg->sa_timed_out;
603  }
604
605  if (search_regcomp(pat, patlen, NULL, RE_SEARCH, pat_use,
606                     (options & (SEARCH_HIS + SEARCH_KEEP)), magic, &regmatch) == FAIL) {
607    if ((options & SEARCH_MSG) && !rc_did_emsg) {
608      semsg(_("E383: Invalid search string: %s"), mr_pattern);
609    }
610    return FAIL;
611  }
612
613  const bool search_from_match_end = vim_strchr(p_cpo, kCpoSearch) != NULL;
614
615  // find the string
616  do {  // loop for count
617    // When not accepting a match at the start position set "extra_col" to a
618    // non-zero value.  Don't do that when starting at MAXCOL, since MAXCOL + 1
619    // is zero.
620    if (pos->col == MAXCOL) {
621      start_char_len = 0;
622    } else if (pos->lnum >= 1
623               && pos->lnum <= buf->b_ml.ml_line_count
624               && pos->col < MAXCOL - 2) {
625      // Watch out for the "col" being MAXCOL - 2, used in a closed fold.
626      ptr = ml_get_buf(buf, pos->lnum);
627      if (ml_get_buf_len(buf, pos->lnum) <= pos->col) {
628        start_char_len = 1;
629      } else {
630        start_char_len = utfc_ptr2len(ptr + pos->col);
631      }
632    } else {
633      start_char_len = 1;
634    }
635    if (dir == FORWARD) {
636      extra_col = (options & SEARCH_START) ? 0 : start_char_len;
637    } else {
638      extra_col = (options & SEARCH_START) ? start_char_len : 0;
639    }
640
641    pos_T start_pos = *pos;           // remember start pos for detecting no match
642    found = 0;                  // default: not found
643    int at_first_line = true;       // default: start in first line
644    if (pos->lnum == 0) {       // correct lnum for when starting in line 0
645      pos->lnum = 1;
646      pos->col = 0;
647      at_first_line = false;        // not in first line now
648    }
649
650    // Start searching in current line, unless searching backwards and
651    // we're in column 0.
652    // If we are searching backwards, in column 0, and not including the
653    // current position, gain some efficiency by skipping back a line.
654    // Otherwise begin the search in the current line.
655    if (dir == BACKWARD && start_pos.col == 0
656        && (options & SEARCH_START) == 0) {
657      lnum = pos->lnum - 1;
658      at_first_line = false;
659    } else {
660      lnum = pos->lnum;
661    }
662
663    for (loop = 0; loop <= 1; loop++) {     // loop twice if 'wrapscan' set
664      for (; lnum > 0 && lnum <= buf->b_ml.ml_line_count;
665           lnum += dir, at_first_line = false) {
666        // Stop after checking "stop_lnum", if it's set.
667        if (stop_lnum != 0 && (dir == FORWARD
668                               ? lnum > stop_lnum : lnum < stop_lnum)) {
669          break;
670        }
671        // Stop after passing the "tm" time limit.
672        if (tm != NULL && profile_passed_limit(*tm)) {
673          break;
674        }
675
676        // Look for a match somewhere in line "lnum".
677        colnr_T col = at_first_line && (options & SEARCH_COL) ? pos->col : 0;
678        nmatched = vim_regexec_multi(&regmatch, win, buf,
679                                     lnum, col, tm, timed_out);
680        // vim_regexec_multi() may clear "regprog"
681        if (regmatch.regprog == NULL) {
682          break;
683        }
684        // Abort searching on an error (e.g., out of stack).
685        if (called_emsg > called_emsg_before || (timed_out != NULL && *timed_out)) {
686          break;
687        }
688        if (nmatched > 0) {
689          // match may actually be in another line when using \zs
690          matchpos = regmatch.startpos[0];
691          endpos = regmatch.endpos[0];
692          submatch = first_submatch(&regmatch);
693          // "lnum" may be past end of buffer for "\n\zs".
694          if (lnum + matchpos.lnum > buf->b_ml.ml_line_count) {
695            ptr = "";
696          } else {
697            ptr = ml_get_buf(buf, lnum + matchpos.lnum);
698          }
699
700          // Forward search in the first line: match should be after
701          // the start position. If not, continue at the end of the
702          // match (this is vi compatible) or on the next char.
703          if (dir == FORWARD && at_first_line) {
704            match_ok = true;
705
706            // When the match starts in a next line it's certainly
707            // past the start position.
708            // When match lands on a NUL the cursor will be put
709            // one back afterwards, compare with that position,
710            // otherwise "/$" will get stuck on end of line.
711            while (matchpos.lnum == 0
712                   && (((options & SEARCH_END) && first_match)
713                       ? (nmatched == 1
714                          && (int)endpos.col - 1
715                          < (int)start_pos.col + extra_col)
716                       : ((int)matchpos.col
717                          - (ptr[matchpos.col] == NUL)
718                          < (int)start_pos.col + extra_col))) {
719              // If vi-compatible searching, continue at the end
720              // of the match, otherwise continue one position
721              // forward.
722              if (search_from_match_end) {
723                if (nmatched > 1) {
724                  // end is in next line, thus no match in
725                  // this line
726                  match_ok = false;
727                  break;
728                }
729                matchcol = endpos.col;
730                // for empty match: advance one char
731                if (matchcol == matchpos.col && ptr[matchcol] != NUL) {
732                  matchcol += utfc_ptr2len(ptr + matchcol);
733                }
734              } else {
735                // Advance "matchcol" to the next character.
736                // This uses rmm_matchcol, the actual start of
737                // the match, ignoring "\zs".
738                matchcol = regmatch.rmm_matchcol;
739                if (ptr[matchcol] != NUL) {
740                  matchcol += utfc_ptr2len(ptr + matchcol);
741                }
742              }
743              if (matchcol == 0 && (options & SEARCH_START)) {
744                break;
745              }
746              if (ptr[matchcol] == NUL
747                  || (nmatched = vim_regexec_multi(&regmatch, win, buf,
748                                                   lnum, matchcol, tm,
749                                                   timed_out)) == 0) {
750                match_ok = false;
751                break;
752              }
753              // vim_regexec_multi() may clear "regprog"
754              if (regmatch.regprog == NULL) {
755                break;
756              }
757              matchpos = regmatch.startpos[0];
758              endpos = regmatch.endpos[0];
759              submatch = first_submatch(&regmatch);
760
761              // This while-loop only works with matchpos.lnum == 0.
762              // For bigger values the next line pointer ptr might not be a
763              // buffer line.
764              if (matchpos.lnum != 0) {
765                break;
766              }
767              // Need to get the line pointer again, a multi-line search may
768              // have made it invalid.
769              ptr = ml_get_buf(buf, lnum);
770            }
771            if (!match_ok) {
772              continue;
773            }
774          }
775          if (dir == BACKWARD) {
776            // Now, if there are multiple matches on this line,
777            // we have to get the last one. Or the last one before
778            // the cursor, if we're on that line.
779            // When putting the new cursor at the end, compare
780            // relative to the end of the match.
781            match_ok = false;
782            while (true) {
783              // Remember a position that is before the start
784              // position, we use it if it's the last match in
785              // the line.  Always accept a position after
786              // wrapping around.
787              if (loop
788                  || ((options & SEARCH_END)
789                      ? (lnum + regmatch.endpos[0].lnum
790                         < start_pos.lnum
791                         || (lnum + regmatch.endpos[0].lnum
792                             == start_pos.lnum
793                             && (int)regmatch.endpos[0].col - 1
794                             < (int)start_pos.col + extra_col))
795                      : (lnum + regmatch.startpos[0].lnum
796                         < start_pos.lnum
797                         || (lnum + regmatch.startpos[0].lnum
798                             == start_pos.lnum
799                             && (int)regmatch.startpos[0].col
800                             < (int)start_pos.col + extra_col)))) {
801                match_ok = true;
802                matchpos = regmatch.startpos[0];
803                endpos = regmatch.endpos[0];
804                submatch = first_submatch(&regmatch);
805              } else {
806                break;
807              }
808
809              // We found a valid match, now check if there is
810              // another one after it.
811              // If vi-compatible searching, continue at the end
812              // of the match, otherwise continue one position
813              // forward.
814              if (search_from_match_end) {
815                if (nmatched > 1) {
816                  break;
817                }
818                matchcol = endpos.col;
819                // for empty match: advance one char
820                if (matchcol == matchpos.col
821                    && ptr[matchcol] != NUL) {
822                  matchcol += utfc_ptr2len(ptr + matchcol);
823                }
824              } else {
825                // Stop when the match is in a next line.
826                if (matchpos.lnum > 0) {
827                  break;
828                }
829                matchcol = matchpos.col;
830                if (ptr[matchcol] != NUL) {
831                  matchcol += utfc_ptr2len(ptr + matchcol);
832                }
833              }
834              if (ptr[matchcol] == NUL
835                  || (nmatched = vim_regexec_multi(&regmatch, win, buf, lnum + matchpos.lnum,
836                                                   matchcol, tm, timed_out)) == 0) {
837                // If the search timed out, we did find a match
838                // but it might be the wrong one, so that's not
839                // OK.
840                if (tm != NULL && profile_passed_limit(*tm)) {
841                  match_ok = false;
842                }
843                break;
844              }
845              // vim_regexec_multi() may clear "regprog"
846              if (regmatch.regprog == NULL) {
847                break;
848              }
849              // Need to get the line pointer again, a
850              // multi-line search may have made it invalid.
851              ptr = ml_get_buf(buf, lnum + matchpos.lnum);
852            }
853
854            // If there is only a match after the cursor, skip
855            // this match.
856            if (!match_ok) {
857              continue;
858            }
859          }
860
861          // With the SEARCH_END option move to the last character
862          // of the match.  Don't do it for an empty match, end
863          // should be same as start then.
864          if ((options & SEARCH_END) && !(options & SEARCH_NOOF)
865              && !(matchpos.lnum == endpos.lnum
866                   && matchpos.col == endpos.col)) {
867            // For a match in the first column, set the position
868            // on the NUL in the previous line.
869            pos->lnum = lnum + endpos.lnum;
870            pos->col = endpos.col;
871            if (endpos.col == 0) {
872              if (pos->lnum > 1) {              // just in case
873                pos->lnum--;
874                pos->col = ml_get_buf_len(buf, pos->lnum);
875              }
876            } else {
877              pos->col--;
878              if (pos->lnum <= buf->b_ml.ml_line_count) {
879                ptr = ml_get_buf(buf, pos->lnum);
880                pos->col -= utf_head_off(ptr, ptr + pos->col);
881              }
882            }
883            if (end_pos != NULL) {
884              end_pos->lnum = lnum + matchpos.lnum;
885              end_pos->col = matchpos.col;
886            }
887          } else {
888            pos->lnum = lnum + matchpos.lnum;
889            pos->col = matchpos.col;
890            if (end_pos != NULL) {
891              end_pos->lnum = lnum + endpos.lnum;
892              end_pos->col = endpos.col;
893            }
894          }
895          pos->coladd = 0;
896          if (end_pos != NULL) {
897            end_pos->coladd = 0;
898          }
899          found = 1;
900          first_match = false;
901
902          // Set variables used for 'incsearch' highlighting.
903          Search.match_lines = endpos.lnum - matchpos.lnum;
904          Search.match_endcol = endpos.col;
905          break;
906        }
907        line_breakcheck();              // stop if ctrl-C typed
908        if (got_int) {
909          break;
910        }
911
912        // Cancel searching if a character was typed.  Used for
913        // 'incsearch'.  Don't check too often, that would slowdown
914        // searching too much.
915        if ((options & SEARCH_PEEK)
916            && ((lnum - pos->lnum) & 0x3f) == 0
917            && char_avail()) {
918          break_loop = true;
919          break;
920        }
921
922        if (loop && lnum == start_pos.lnum) {
923          break;                    // if second loop, stop where started
924        }
925      }
926      at_first_line = false;
927
928      // vim_regexec_multi() may clear "regprog"
929      if (regmatch.regprog == NULL) {
930        break;
931      }
932
933      // Stop the search if wrapscan isn't set, "stop_lnum" is
934      // specified, after an interrupt, after a match and after looping
935      // twice.
936      if (!p_ws || stop_lnum != 0 || got_int
937          || called_emsg > called_emsg_before
938          || (timed_out != NULL && *timed_out)
939          || break_loop
940          || found || loop) {
941        break;
942      }
943
944      // If 'wrapscan' is set we continue at the other end of the file.
945      // If 'shortmess' does not contain 's', we give a message, but
946      // only, if we won't show the search stat later anyhow,
947      // (so SEARCH_COUNT must be absent).
948      // This message is also remembered in keep_msg for when the screen
949      // is redrawn. The keep_msg is cleared whenever another message is
950      // written.
951      lnum = dir == BACKWARD  // start second loop at the other end
952             ? buf->b_ml.ml_line_count
953             : 1;
954      if (!shortmess(kShmSearch)
955          && shortmess(kShmSearchcount)
956          && (options & SEARCH_MSG)) {
957        give_warning(_(dir == BACKWARD ? top_bot_msg : bot_top_msg), true, false);
958      }
959      if (extra_arg != NULL) {
960        extra_arg->sa_wrapped = true;
961      }
962    }
963    if (got_int || called_emsg > called_emsg_before
964        || (timed_out != NULL && *timed_out)
965        || break_loop) {
966      break;
967    }
968  } while (--count > 0 && found);   // stop after count matches or no match
969
970  vim_regfree(regmatch.regprog);
971
972  if (!found) {             // did not find it
973    if (got_int) {
974      emsg(_(e_interr));
975    } else if ((options & SEARCH_MSG) == SEARCH_MSG) {
976      if (p_ws) {
977        semsg(_(e_patnotf2), mr_pattern);
978      } else if (lnum == 0) {
979        semsg(_(e_search_hit_top_without_match_for_str), mr_pattern);
980      } else {
981        semsg(_(e_search_hit_bottom_without_match_for_str), mr_pattern);
982      }
983    }
984    return FAIL;
985  }
986
987  // A pattern like "\n\zs" may go past the last line.
988  if (pos->lnum > buf->b_ml.ml_line_count) {
989    pos->lnum = buf->b_ml.ml_line_count;
990    pos->col = ml_get_buf_len(buf, pos->lnum);
991    if (pos->col > 0) {
992      pos->col--;
993    }
994  }
995
996  return submatch + 1;
997}
998
999void set_search_direction(int cdir)
1000{
1001  spats[0].off.dir = (char)cdir;
1002}
1003
1004static void set_vv_searchforward(void)
1005{
1006  set_vim_var_nr(VV_SEARCHFORWARD, spats[0].off.dir == '/');
1007}
1008
1009// Return the number of the first subpat that matched.
1010// Return zero if none of them matched.
1011static int first_submatch(regmmatch_T *rp)
1012{
1013  int submatch;
1014
1015  for (submatch = 1;; submatch++) {
1016    if (rp->startpos[submatch].lnum >= 0) {
1017      break;
1018    }
1019    if (submatch == 9) {
1020      submatch = 0;
1021      break;
1022    }
1023  }
1024  return submatch;
1025}
1026
1027/// Parse a search pattern followed by an optional offset (e.g. "pat/e+1").
1028/// On entry "*pat" points at the start of the pattern and "*patlen" is its
1029/// length.  Updates the in/out parameters:
1030///    *pat / *patlen      - moved past the pattern and offset
1031///    *strcopy            - allocated copy if "\?" or "\/" was unescaped
1032///                          (caller must vim_free() it)
1033///    *searchstr and *searchstrlen - pointer/length of the search pattern only
1034///    *dircp              - location of the trailing delimiter that was
1035///                          replaced with NUL (or NULL); caller may restore
1036///                          it
1037///    *offset             - parsed offset (line/end/off)
1038///
1039/// Returns the length of the parsed pattern + offset (used by get_address()
1040/// to know how much of the command line was consumed).
1041int parse_search_pattern_offset(char **pat, size_t *patlen, int search_delim, int options,
1042                                char **strcopy, char **searchstr, size_t *searchstrlen,
1043                                char **dircp, SearchOffset *offset)
1044{
1045  if (*pat == NULL || **pat == NUL) {
1046    return 0;
1047  }
1048
1049  int cmdlen = 0;
1050  char *p;
1051  char *ps = *strcopy;
1052
1053  *searchstr = *pat;
1054  *searchstrlen = *patlen;
1055  *dircp = NULL;
1056
1057  // Find end of regular expression.
1058  // If there is a matching '/' or '?', toss it.
1059  p = skip_regexp_ex(*pat, search_delim, p_magic, strcopy, NULL, NULL);
1060  if (*strcopy != ps) {
1061    size_t len = strlen(*strcopy);
1062    // made a copy of "pat" to change "\?" to "?"
1063    cmdlen += (int)(*patlen - len);
1064    *pat = *strcopy;
1065    *patlen = len;
1066    *searchstr = *strcopy;
1067    *searchstrlen = len;
1068  }
1069  if (*p == search_delim) {
1070    *searchstrlen = (size_t)(p - *pat);
1071    *dircp = p;              // remember where we put the NUL
1072    *p++ = NUL;
1073  }
1074
1075  offset->line = false;
1076  offset->end = false;
1077  offset->off = 0;
1078  // Check for a line offset or a character offset.
1079  // For get_address (echo off) we don't check for a character
1080  // offset, because it is meaningless and the 's' could be a
1081  // substitute command.
1082  if (*p == '+' || *p == '-' || ascii_isdigit(*p)) {
1083    offset->line = true;
1084  } else if ((options & SEARCH_OPT) && (*p == 'e' || *p == 's' || *p == 'b')) {
1085    if (*p == 'e') {  // end
1086      offset->end = true;
1087    }
1088    p++;
1089  }
1090  if (ascii_isdigit(*p) || *p == '+' || *p == '-') {      // got an offset
1091    if (ascii_isdigit(*p) || ascii_isdigit(*(p + 1))) {
1092      offset->off = atol(p);
1093    } else if (*p == '-') {                      // single '-'
1094      offset->off = -1;
1095    } else {  // single '+'
1096      offset->off = 1;
1097    }
1098    p++;
1099    while (ascii_isdigit(*p)) {  // skip number
1100      p++;
1101    }
1102  }
1103
1104  // compute length of search command for get_address()
1105  cmdlen += (int)(p - *pat);
1106  *patlen -= (size_t)(p - *pat);
1107  *pat = p;  // put pat after search command
1108
1109  return cmdlen;
1110}
1111
1112/// Highest level string search function.
1113/// Search for the 'count'th occurrence of pattern 'pat' in direction 'dirc'
1114///
1115/// Careful: If spats[0].off.line == true and spats[0].off.off == 0 this
1116/// makes the movement linewise without moving the match position.
1117///
1118/// @param dirc          if 0: use previous dir.
1119/// @param pat           NULL or empty : use previous string.
1120/// @param options       if true and
1121///                      SEARCH_REV   == true : go in reverse of previous dir.
1122///                      SEARCH_ECHO  == true : echo the search command and handle options
1123///                      SEARCH_MSG   == true : may give error message
1124///                      SEARCH_OPT   == true : interpret optional flags
1125///                      SEARCH_HIS   == true : put search pattern in history
1126///                      SEARCH_NOOF  == true : don't add offset to position
1127///                      SEARCH_MARK  == true : set previous context mark
1128///                      SEARCH_KEEP  == true : keep previous search pattern
1129///                      SEARCH_START == true : accept match at curpos itself
1130///                      SEARCH_PEEK  == true : check for typed char, cancel search
1131/// @param oap           can be NULL
1132/// @param dirc          '/' or '?'
1133/// @param search_delim  delimiter for search, e.g. '%' in s%regex%replacement
1134/// @param sia           optional arguments or NULL
1135///
1136/// @return              0 for failure, 1 for found, 2 for found and line offset added.
1137int do_search(oparg_T *oap, int dirc, int search_delim, char *pat, size_t patlen, int count,
1138              int options, bool magic, searchit_arg_T *sia)
1139{
1140  char *searchstr;
1141  size_t searchstrlen;
1142  int retval;                   // Return value
1143  char *p;
1144  int64_t c;
1145  char *dircp;
1146  char *strcopy = NULL;
1147  char *msgbuf = NULL;
1148  size_t msgbuflen = 0;
1149  bool has_offset = false;
1150
1151  Search.cmdlen = 0;
1152
1153  // A line offset is not remembered, this is vi compatible.
1154  if (spats[0].off.line && vim_strchr(p_cpo, kCpoLineoff) != NULL) {
1155    spats[0].off.line = false;
1156    spats[0].off.off = 0;
1157  }
1158
1159  // Save the values for when (options & SEARCH_KEEP) is used.
1160  // (there is no "if ()" around this because gcc wants them initialized)
1161  SearchOffset old_off = spats[0].off;
1162
1163  pos_T pos = curwin->w_cursor;  // Position of the last match.
1164                                 // Start searching at the cursor position.
1165
1166  // Find out the direction of the search.
1167  if (dirc == 0) {
1168    dirc = (uint8_t)spats[0].off.dir;
1169  } else {
1170    spats[0].off.dir = (char)dirc;
1171    set_vv_searchforward();
1172  }
1173  if (options & SEARCH_REV) {
1174    dirc = dirc == '/' ? '?' : '/';
1175  }
1176
1177  // If the cursor is in a closed fold, don't find another match in the same
1178  // fold.
1179  if (dirc == '/') {
1180    if (hasFolding(curwin, pos.lnum, NULL, &pos.lnum)) {
1181      pos.col = MAXCOL - 2;             // avoid overflow when adding 1
1182    }
1183  } else {
1184    if (hasFolding(curwin, pos.lnum, &pos.lnum, NULL)) {
1185      pos.col = 0;
1186    }
1187  }
1188
1189  // Turn 'hlsearch' highlighting back on.
1190  if (Search.no_hlsearch && !(options & SEARCH_KEEP)) {
1191    redraw_all_later(UPD_SOME_VALID);
1192    set_no_hlsearch(false);
1193  }
1194
1195  // Repeat the search when pattern followed by ';', e.g. "/foo/;?bar".
1196  while (true) {
1197    bool show_top_bot_msg = false;
1198
1199    searchstr = pat;
1200    searchstrlen = patlen;
1201
1202    dircp = NULL;
1203    // use previous pattern
1204    if (pat == NULL || *pat == NUL || *pat == search_delim) {
1205      if (spats[RE_SEARCH].pat == NULL) {           // no previous pattern
1206        if (spats[RE_SUBST].pat == NULL) {
1207          emsg(_(e_noprevre));
1208          retval = 0;
1209          goto end_do_search;
1210        }
1211        searchstr = spats[RE_SUBST].pat;
1212        searchstrlen = spats[RE_SUBST].patlen;
1213      } else {
1214        // make search_regcomp() use spats[RE_SEARCH].pat
1215        searchstr = "";
1216        searchstrlen = 0;
1217      }
1218    }
1219
1220    if (pat != NULL && *pat != NUL) {   // look for (new) offset
1221      Search.cmdlen += parse_search_pattern_offset(&pat, &patlen, search_delim,
1222                                                   options, &strcopy, &searchstr,
1223                                                   &searchstrlen, &dircp,
1224                                                   &spats[0].off);
1225    }
1226
1227    bool show_search_stats = false;
1228    if ((options & SEARCH_ECHO) && messaging() && !msg_silent
1229        && (!cmd_silent || !shortmess(kShmSearchcount))) {
1230      char off_buf[40];
1231      size_t off_len = 0;
1232
1233      // Compute msg_row early.
1234      msg_start();
1235      msg_ext_set_kind("search_cmd");
1236
1237      // Get the offset, so we know how long it is.
1238      if (!cmd_silent
1239          && (spats[0].off.line || spats[0].off.end || spats[0].off.off)) {
1240        off_buf[off_len++] = (char)dirc;
1241        if (spats[0].off.end) {
1242          off_buf[off_len++] = 'e';
1243        } else if (!spats[0].off.line) {
1244          off_buf[off_len++] = 's';
1245        }
1246        off_buf[off_len] = NUL;
1247        if (spats[0].off.off != 0 || spats[0].off.line) {
1248          off_len += (size_t)snprintf(off_buf + off_len, sizeof(off_buf) - off_len,
1249                                      "%+" PRId64, spats[0].off.off);
1250        }
1251      }
1252
1253      size_t plen;
1254      if (*searchstr == NUL) {
1255        p = spats[0].pat;
1256        plen = spats[0].patlen;
1257      } else {
1258        p = searchstr;
1259        plen = searchstrlen;
1260      }
1261
1262      size_t msgbufsize;
1263      if (!shortmess(kShmSearchcount) || cmd_silent) {
1264        // Reserve enough space for the search pattern + offset +
1265        // search stat.  Use all the space available, so that the
1266        // search state is right aligned.  If there is not enough space
1267        // msg_strtrunc() will shorten in the middle.
1268        if (ui_has(kUIMessages)) {
1269          msgbufsize = 0;  // adjusted below
1270        } else if (msg_scrolled != 0 && !cmd_silent) {
1271          // Use all the columns.
1272          msgbufsize = (size_t)((Rows - msg_row) * Columns - 1);
1273        } else {
1274          // Use up to 'showcmd' column.
1275          msgbufsize = (size_t)((Rows - msg_row - 1) * Columns + sc_col - 1);
1276        }
1277        if (msgbufsize < plen + off_len + SEARCH_STAT_BUF_LEN + 3) {
1278          msgbufsize = plen + off_len + SEARCH_STAT_BUF_LEN + 3;
1279        }
1280      } else {
1281        // Reserve enough space for the search pattern + offset.
1282        msgbufsize = plen + off_len + 3;
1283      }
1284
1285      xfree(msgbuf);
1286      msgbuf = xmalloc(msgbufsize);
1287      memset(msgbuf, ' ', msgbufsize);
1288      msgbuflen = msgbufsize - 1;
1289      msgbuf[msgbuflen] = NUL;
1290
1291      // do not fill the msgbuf buffer, if cmd_silent is set, leave it
1292      // empty for the search_stat feature.
1293      if (!cmd_silent) {
1294        ui_busy_start();
1295        msgbuf[0] = (char)dirc;
1296        if (utf_iscomposing_first(utf_ptr2char(p))) {
1297          // Use a space to draw the composing char on.
1298          msgbuf[1] = ' ';
1299          memmove(msgbuf + 2, p, plen);
1300        } else {
1301          memmove(msgbuf + 1, p, plen);
1302        }
1303        if (off_len > 0) {
1304          memmove(msgbuf + plen + 1, off_buf, off_len);
1305        }
1306
1307        char *trunc = msg_strtrunc(msgbuf, true);
1308        if (trunc != NULL) {
1309          xfree(msgbuf);
1310          msgbuf = trunc;
1311          msgbuflen = strlen(msgbuf);
1312        }
1313
1314        // The search pattern could be shown on the right in rightleft
1315        // mode, but the 'ruler' and 'showcmd' area use it too, thus
1316        // it would be blanked out again very soon.  Show it on the
1317        // left, but do reverse the text.
1318        if (curwin->w_p_rl && *curwin->w_p_rlc == 's') {
1319          char *r = reverse_text(msgbuf);
1320          xfree(msgbuf);
1321          msgbuf = r;
1322          msgbuflen = strlen(msgbuf);
1323          // move reversed text to beginning of buffer
1324          while (*r == ' ') {
1325            r++;
1326          }
1327          size_t pat_len = (size_t)(msgbuf + msgbuflen - r);
1328          memmove(msgbuf, r, pat_len);
1329          // overwrite old text
1330          if ((size_t)(r - msgbuf) >= pat_len) {
1331            memset(r, ' ', pat_len);
1332          } else {
1333            memset(msgbuf + pat_len, ' ', (size_t)(r - msgbuf));
1334          }
1335        }
1336        msg_outtrans(msgbuf, 0, false);
1337        msg_clr_eos();
1338        msg_check();
1339
1340        gotocmdline(false);
1341        ui_flush();
1342        ui_busy_stop();
1343        msg_nowait = true;  // don't wait for this message
1344      }
1345
1346      if (!shortmess(kShmSearchcount)) {
1347        show_search_stats = true;
1348      }
1349    }
1350
1351    // If there is a character offset, subtract it from the current
1352    // position, so we don't get stuck at "?pat?e+2" or "/pat/s-2".
1353    // Skip this if pos.col is near MAXCOL (closed fold).
1354    // This is not done for a line offset, because then we would not be vi
1355    // compatible.
1356    if (!spats[0].off.line && spats[0].off.off && pos.col < MAXCOL - 2) {
1357      if (spats[0].off.off > 0) {
1358        for (c = spats[0].off.off; c; c--) {
1359          if (decl(&pos) == -1) {
1360            break;
1361          }
1362        }
1363        if (c) {                        // at start of buffer
1364          pos.lnum = 0;                 // allow lnum == 0 here
1365          pos.col = MAXCOL;
1366        }
1367      } else {
1368        for (c = spats[0].off.off; c; c++) {
1369          if (incl(&pos) == -1) {
1370            break;
1371          }
1372        }
1373        if (c) {                        // at end of buffer
1374          pos.lnum = curbuf->b_ml.ml_line_count + 1;
1375          pos.col = 0;
1376        }
1377      }
1378    }
1379
1380    c = searchit(curwin, curbuf, &pos, NULL, dirc == '/' ? FORWARD : BACKWARD,
1381                 searchstr, searchstrlen, count,
1382                 (spats[0].off.end * SEARCH_END
1383                  + (options
1384                     & (SEARCH_KEEP + SEARCH_PEEK + SEARCH_HIS + SEARCH_MSG
1385                        + SEARCH_START
1386                        + ((pat != NULL && *pat == ';') ? 0 : SEARCH_NOOF)))),
1387                 RE_LAST, magic, sia);
1388
1389    if (dircp != NULL) {
1390      *dircp = (char)search_delim;  // restore second '/' or '?' for normal_cmd()
1391    }
1392
1393    if (!shortmess(kShmSearch) && sia && sia->sa_wrapped) {
1394      show_top_bot_msg = true;
1395    }
1396
1397    if (c == FAIL) {
1398      retval = 0;
1399      goto end_do_search;
1400    }
1401    if (spats[0].off.end && oap != NULL) {
1402      oap->inclusive = true;        // 'e' includes last character
1403    }
1404    retval = 1;                     // pattern found
1405
1406    if (sia && sia->sa_wrapped) {
1407      apply_autocmds(EVENT_SEARCHWRAPPED, NULL, NULL, false, NULL);
1408    }
1409
1410    // Add character and/or line offset
1411    if (!(options & SEARCH_NOOF) || (pat != NULL && *pat == ';')) {
1412      pos_T org_pos = pos;
1413
1414      if (spats[0].off.line) {  // Add the offset to the line number.
1415        c = pos.lnum + spats[0].off.off;
1416        if (c < 1) {
1417          pos.lnum = 1;
1418        } else if (c > curbuf->b_ml.ml_line_count) {
1419          pos.lnum = curbuf->b_ml.ml_line_count;
1420        } else {
1421          pos.lnum = (linenr_T)c;
1422        }
1423        pos.col = 0;
1424
1425        retval = 2;                 // pattern found, line offset added
1426      } else if (pos.col < MAXCOL - 2) {      // just in case
1427        // to the right, check for end of file
1428        c = spats[0].off.off;
1429        if (c > 0) {
1430          while (c-- > 0) {
1431            if (incl(&pos) == -1) {
1432              break;
1433            }
1434          }
1435        } else {  // to the left, check for start of file
1436          while (c++ < 0) {
1437            if (decl(&pos) == -1) {
1438              break;
1439            }
1440          }
1441        }
1442      }
1443      if (!equalpos(pos, org_pos)) {
1444        has_offset = true;
1445      }
1446    }
1447
1448    // Show [1/15] if 'S' is not in 'shortmess'.
1449    if (show_search_stats) {
1450      cmdline_search_stat(dirc, &pos, &curwin->w_cursor,
1451                          show_top_bot_msg, msgbuf, msgbuflen,
1452                          (count != 1 || has_offset
1453                           || (!(fdo_flags & kOptFdoFlagSearch)
1454                               && hasFolding(curwin, curwin->w_cursor.lnum, NULL,
1455                                             NULL))),
1456                          (int)p_msc,
1457                          SEARCH_STAT_DEF_TIMEOUT);
1458    }
1459
1460    // The search command can be followed by a ';' to do another search.
1461    // For example: "/pat/;/foo/+3;?bar"
1462    // This is like doing another search command, except:
1463    // - The remembered direction '/' or '?' is from the first search.
1464    // - When an error happens the cursor isn't moved at all.
1465    // Don't do this when called by get_address() (it handles ';' itself).
1466    if (!(options & SEARCH_OPT) || pat == NULL || *pat != ';') {
1467      break;
1468    }
1469
1470    dirc = (uint8_t)(*++pat);
1471    patlen--;
1472    search_delim = dirc;
1473    if (dirc != '?' && dirc != '/') {
1474      retval = 0;
1475      emsg(_("E386: Expected '?' or '/'  after ';'"));
1476      goto end_do_search;
1477    }
1478    pat++;
1479    patlen--;
1480  }
1481
1482  if (options & SEARCH_MARK) {
1483    setpcmark();
1484  }
1485  curwin->w_cursor = pos;
1486  curwin->w_set_curswant = true;
1487
1488end_do_search:
1489  if ((options & SEARCH_KEEP) || (cmdmod.cmod_flags & CMOD_KEEPPATTERNS)) {
1490    spats[0].off = old_off;
1491  }
1492  xfree(strcopy);
1493  xfree(msgbuf);
1494
1495  return retval;
1496}
1497
1498// search_for_exact_line(buf, pos, dir, pat)
1499//
1500// Search for a line starting with the given pattern (ignoring leading
1501// white-space), starting from pos and going in direction "dir". "pos" will
1502// contain the position of the match found.    Blank lines match only if
1503// ADDING is set.  If p_ic is set then the pattern must be in lowercase.
1504// Return OK for success, or FAIL if no line found.
1505int search_for_exact_line(buf_T *buf, pos_T *pos, Direction dir, char *pat)
1506{
1507  linenr_T start = 0;
1508  int compl_len = ins_compl_len();
1509
1510  if (buf->b_ml.ml_line_count == 0) {
1511    return FAIL;
1512  }
1513  while (true) {
1514    pos->lnum += dir;
1515    if (pos->lnum < 1) {
1516      if (p_ws) {
1517        pos->lnum = buf->b_ml.ml_line_count;
1518        if (!shortmess(kShmSearch)) {
1519          give_warning(_(top_bot_msg), true, false);
1520        }
1521      } else {
1522        pos->lnum = 1;
1523        break;
1524      }
1525    } else if (pos->lnum > buf->b_ml.ml_line_count) {
1526      if (p_ws) {
1527        pos->lnum = 1;
1528        if (!shortmess(kShmSearch)) {
1529          give_warning(_(bot_top_msg), true, false);
1530        }
1531      } else {
1532        pos->lnum = 1;
1533        break;
1534      }
1535    }
1536    if (pos->lnum == start) {
1537      break;
1538    }
1539    if (start == 0) {
1540      start = pos->lnum;
1541    }
1542    char *ptr = ml_get_buf(buf, pos->lnum);
1543    char *p = skipwhite(ptr);
1544    pos->col = (colnr_T)(p - ptr);
1545
1546    // when adding lines the matching line may be empty but it is not
1547    // ignored because we are interested in the next line -- Acevedo
1548    if (compl_status_adding() && !compl_status_sol()) {
1549      if (mb_strcmp_ic((bool)p_ic, p, pat) == 0) {
1550        return OK;
1551      }
1552    } else if (*p != NUL) {  // Ignore empty lines.
1553      // Expanding lines or words.
1554      assert(compl_len >= 0);
1555      if ((p_ic ? mb_strnicmp(p, pat, (size_t)compl_len)
1556                : strncmp(p, pat, (size_t)compl_len)) == 0) {
1557        return OK;
1558      }
1559    }
1560  }
1561  return FAIL;
1562}
1563
1564// Character Searches
1565
1566/// Search for a character in a line.  If "t_cmd" is false, move to the
1567/// position of the character, otherwise move to just before the char.
1568/// Do this "cap->count1" times.
1569/// Return FAIL or OK.
1570int searchc(cmdarg_T *cap, bool t_cmd)
1571  FUNC_ATTR_NONNULL_ALL
1572{
1573  int c = cap->nchar;                   // char to search for
1574  int dir = cap->arg;                   // true for searching forward
1575  int count = cap->count1;              // repeat count
1576  bool stop = true;
1577
1578  if (c != NUL) {       // normal search: remember args for repeat
1579    if (!KeyStuffed) {      // don't remember when redoing
1580      *lastc = (uint8_t)c;
1581      set_csearch_direction(dir);
1582      set_csearch_until(t_cmd);
1583      if (cap->nchar_len) {
1584        lastc_bytelen = cap->nchar_len;
1585        memcpy(lastc_bytes, cap->nchar_composing, (size_t)cap->nchar_len);
1586      } else {
1587        lastc_bytelen = utf_char2bytes(c, lastc_bytes);
1588      }
1589    }
1590  } else {            // repeat previous search
1591    if (*lastc == NUL && lastc_bytelen <= 1) {
1592      return FAIL;
1593    }
1594    dir = dir  // repeat in opposite direction
1595          ? -lastcdir
1596          : lastcdir;
1597    t_cmd = last_t_cmd;
1598    c = *lastc;
1599    // For multi-byte re-use last lastc_bytes[] and lastc_bytelen.
1600
1601    // Force a move of at least one char, so ";" and "," will move the
1602    // cursor, even if the cursor is right in front of char we are looking
1603    // at.
1604    if (vim_strchr(p_cpo, kCpoScolon) == NULL && count == 1 && t_cmd) {
1605      stop = false;
1606    }
1607  }
1608
1609  cap->oap->inclusive = dir != BACKWARD;
1610
1611  char *p = get_cursor_line_ptr();
1612  int col = curwin->w_cursor.col;
1613  int len = get_cursor_line_len();
1614
1615  while (count--) {
1616    while (true) {
1617      if (dir > 0) {
1618        col += utfc_ptr2len(p + col);
1619        if (col >= len) {
1620          return FAIL;
1621        }
1622      } else {
1623        if (col == 0) {
1624          return FAIL;
1625        }
1626        col -= utf_head_off(p, p + col - 1) + 1;
1627      }
1628      if (lastc_bytelen <= 1) {
1629        if (p[col] == c && stop) {
1630          break;
1631        }
1632      } else if (strncmp(p + col, lastc_bytes, (size_t)lastc_bytelen) == 0 && stop) {
1633        break;
1634      }
1635      stop = true;
1636    }
1637  }
1638
1639  if (t_cmd) {
1640    // Backup to before the character (possibly double-byte).
1641    col -= dir;
1642    if (dir < 0) {
1643      // Landed on the search char which is lastc_bytelen long.
1644      col += lastc_bytelen - 1;
1645    } else {
1646      // To previous char, which may be multi-byte.
1647      col -= utf_head_off(p, p + col);
1648    }
1649  }
1650  curwin->w_cursor.col = col;
1651
1652  return OK;
1653}
1654
1655// "Other" Searches
1656
1657// findmatch - find the matching paren or brace
1658//
1659// Improvement over vi: Braces inside quotes are ignored.
1660pos_T *findmatch(oparg_T *oap, int initc)
1661{
1662  return findmatchlimit(oap, initc, 0, 0);
1663}
1664
1665// Return true if the character before "linep[col]" equals "ch".
1666// Return false if "col" is zero.
1667// Update "*prevcol" to the column of the previous character, unless "prevcol"
1668// is NULL.
1669// Handles multibyte string correctly.
1670static bool check_prevcol(char *linep, int col, int ch, int *prevcol)
1671{
1672  col--;
1673  if (col > 0) {
1674    col -= utf_head_off(linep, linep + col);
1675  }
1676  if (prevcol) {
1677    *prevcol = col;
1678  }
1679  return col >= 0 && (uint8_t)linep[col] == ch;
1680}
1681
1682/// Raw string start is found at linep[startpos.col - 1].
1683///
1684/// @return  true if the matching end can be found between startpos and endpos.
1685static bool find_rawstring_end(char *linep, pos_T *startpos, pos_T *endpos)
1686{
1687  char *p;
1688  linenr_T lnum;
1689
1690  for (p = linep + startpos->col + 1; *p && *p != '('; p++) {}
1691
1692  size_t delim_len = (size_t)((p - linep) - startpos->col - 1);
1693  char *delim_copy = xmemdupz(linep + startpos->col + 1, delim_len);
1694  bool found = false;
1695  for (lnum = startpos->lnum; lnum <= endpos->lnum; lnum++) {
1696    char *line = ml_get(lnum);
1697
1698    for (p = line + (lnum == startpos->lnum ? startpos->col + 1 : 0); *p; p++) {
1699      if (lnum == endpos->lnum && (colnr_T)(p - line) >= endpos->col) {
1700        break;
1701      }
1702      if (*p == ')'
1703          && strncmp(delim_copy, p + 1, delim_len) == 0
1704          && p[delim_len + 1] == '"') {
1705        found = true;
1706        break;
1707      }
1708    }
1709    if (found) {
1710      break;
1711    }
1712  }
1713  xfree(delim_copy);
1714  return found;
1715}
1716
1717/// Check matchpairs option for "*initc".
1718/// If there is a match set "*initc" to the matching character and "*findc" to
1719/// the opposite character.  Set "*backwards" to the direction.
1720/// When "switchit" is true swap the direction.
1721static void find_mps_values(int *initc, int *findc, bool *backwards, bool switchit)
1722  FUNC_ATTR_NONNULL_ALL
1723{
1724  char *ptr = curbuf->b_p_mps;
1725
1726  while (*ptr != NUL) {
1727    if (utf_ptr2char(ptr) == *initc) {
1728      if (switchit) {
1729        *findc = *initc;
1730        *initc = utf_ptr2char(ptr + utfc_ptr2len(ptr) + 1);
1731        *backwards = true;
1732      } else {
1733        *findc = utf_ptr2char(ptr + utfc_ptr2len(ptr) + 1);
1734        *backwards = false;
1735      }
1736      return;
1737    }
1738    char *prev = ptr;
1739    ptr += utfc_ptr2len(ptr) + 1;
1740    if (utf_ptr2char(ptr) == *initc) {
1741      if (switchit) {
1742        *findc = *initc;
1743        *initc = utf_ptr2char(prev);
1744        *backwards = false;
1745      } else {
1746        *findc = utf_ptr2char(prev);
1747        *backwards = true;
1748      }
1749      return;
1750    }
1751    ptr += utfc_ptr2len(ptr);
1752    if (*ptr == ',') {
1753      ptr++;
1754    }
1755  }
1756}
1757
1758// findmatchlimit -- find the matching paren or brace, if it exists within
1759// maxtravel lines of the cursor.  A maxtravel of 0 means search until falling
1760// off the edge of the file.
1761//
1762// "initc" is the character to find a match for.  NUL means to find the
1763// character at or after the cursor. Special values:
1764// '*'  look for C-style comment / *
1765// '/'  look for C-style comment / *, ignoring comment-end
1766// '#'  look for preprocessor directives
1767// 'R'  look for raw string start: R"delim(text)delim" (only backwards)
1768//
1769// flags: FM_BACKWARD   search backwards (when initc is '/', '*' or '#')
1770//        FM_FORWARD    search forwards (when initc is '/', '*' or '#')
1771//        FM_BLOCKSTOP  stop at start/end of block ({ or } in column 0)
1772//        FM_SKIPCOMM   skip over comments (cursor must start outside a block comment)
1773//
1774// "oap" is only used to set oap->motion_type for a linewise motion, it can be
1775// NULL
1776pos_T *findmatchlimit(oparg_T *oap, int initc, int flags, int64_t maxtravel)
1777{
1778  static pos_T pos;                     // current search position
1779  int findc = 0;                        // matching brace
1780  int count = 0;                        // cumulative number of braces
1781  bool backwards = false;               // init for gcc
1782  bool raw_string = false;              // search for raw string
1783  bool inquote = false;                 // true when inside quotes
1784  char *ptr;
1785  int hash_dir = 0;                     // Direction searched for # things
1786  int comment_dir = 0;                  // Direction searched for comments
1787  int traveled = 0;                     // how far we've searched so far
1788  bool ignore_cend = false;             // ignore comment end
1789  int match_escaped = 0;                // search for escaped match
1790  int dir;                              // Direction to search
1791  int comment_col = MAXCOL;             // start of / / comment
1792  bool lispcomm = false;                // inside of Lisp-style comment
1793  bool lisp = curbuf->b_p_lisp;         // engage Lisp-specific hacks ;)
1794  bool skip_comments = (flags & FM_SKIPCOMM) != 0;
1795  bool in_block_comment = false;        // inside / * * / block comment
1796
1797  pos = curwin->w_cursor;
1798  pos.coladd = 0;
1799  char *linep = ml_get(pos.lnum);     // pointer to current line
1800
1801  // vi compatible matching
1802  bool cpo_match = (vim_strchr(p_cpo, kCpoMatch) != NULL);
1803  // don't recognize backslashes
1804  bool cpo_bsl = (vim_strchr(p_cpo, kCpoMatchbsl) != NULL);
1805
1806  // Direction to search when initc is '/', '*' or '#'
1807  if (flags & FM_BACKWARD) {
1808    dir = BACKWARD;
1809  } else if (flags & FM_FORWARD) {
1810    dir = FORWARD;
1811  } else {
1812    dir = 0;
1813  }
1814
1815  // if initc given, look in the table for the matching character
1816  // '/' and '*' are special cases: look for start or end of comment.
1817  // When '/' is used, we ignore running backwards into a star-slash, for
1818  // "[*" command, we just want to find any comment.
1819  if (initc == '/' || initc == '*' || initc == 'R') {
1820    comment_dir = dir;
1821    if (initc == '/') {
1822      ignore_cend = true;
1823    }
1824    backwards = (dir == FORWARD) ? false : true;
1825    raw_string = (initc == 'R');
1826    initc = NUL;
1827  } else if (initc != '#' && initc != NUL) {
1828    find_mps_values(&initc, &findc, &backwards, true);
1829    if (dir) {
1830      backwards = (dir == FORWARD) ? false : true;
1831    }
1832    if (findc == NUL) {
1833      return NULL;
1834    }
1835  } else {
1836    // Either initc is '#', or no initc was given and we need to look
1837    // under the cursor.
1838    if (initc == '#') {
1839      hash_dir = dir;
1840    } else {
1841      // initc was not given, must look for something to match under
1842      // or near the cursor.
1843      // Only check for special things when 'cpo' doesn't have '%'.
1844      if (!cpo_match) {
1845        // Are we before or at #if, #else etc.?
1846        ptr = skipwhite(linep);
1847        if (*ptr == '#' && pos.col <= (colnr_T)(ptr - linep)) {
1848          ptr = skipwhite(ptr + 1);
1849          if (strncmp(ptr, "if", 2) == 0
1850              || strncmp(ptr, "endif", 5) == 0
1851              || strncmp(ptr, "el", 2) == 0) {
1852            hash_dir = 1;
1853          }
1854        } else if (linep[pos.col] == '/') {  // Are we on a comment?
1855          if (linep[pos.col + 1] == '*') {
1856            comment_dir = FORWARD;
1857            backwards = false;
1858            pos.col++;
1859          } else if (pos.col > 0 && linep[pos.col - 1] == '*') {
1860            comment_dir = BACKWARD;
1861            backwards = true;
1862            pos.col--;
1863          }
1864        } else if (linep[pos.col] == '*') {
1865          if (linep[pos.col + 1] == '/') {
1866            comment_dir = BACKWARD;
1867            backwards = true;
1868          } else if (pos.col > 0 && linep[pos.col - 1] == '/') {
1869            comment_dir = FORWARD;
1870            backwards = false;
1871          }
1872        }
1873      }
1874
1875      // If we are not on a comment or the # at the start of a line, then
1876      // look for brace anywhere on this line after the cursor.
1877      if (!hash_dir && !comment_dir) {
1878        // Find the brace under or after the cursor.
1879        // If beyond the end of the line, use the last character in
1880        // the line.
1881        if (linep[pos.col] == NUL && pos.col) {
1882          pos.col--;
1883        }
1884        while (true) {
1885          initc = utf_ptr2char(linep + pos.col);
1886          if (initc == NUL) {
1887            break;
1888          }
1889
1890          find_mps_values(&initc, &findc, &backwards, false);
1891          if (findc) {
1892            break;
1893          }
1894          pos.col += utfc_ptr2len(linep + pos.col);
1895        }
1896        if (!findc) {
1897          // no brace in the line, maybe use "  #if" then
1898          if (!cpo_match && *skipwhite(linep) == '#') {
1899            hash_dir = 1;
1900          } else {
1901            return NULL;
1902          }
1903        } else if (!cpo_bsl) {
1904          int bslcnt = 0;
1905
1906          // Set "match_escaped" if there are an odd number of
1907          // backslashes.
1908          for (int col = pos.col; check_prevcol(linep, col, '\\', &col);) {
1909            bslcnt++;
1910          }
1911          match_escaped = (bslcnt & 1);
1912        }
1913      }
1914    }
1915    if (hash_dir) {
1916      // Look for matching #if, #else, #elif, or #endif
1917      if (oap != NULL) {
1918        oap->motion_type = kMTLineWise;  // Linewise for this case only
1919      }
1920      if (initc != '#') {
1921        ptr = skipwhite(skipwhite(linep) + 1);
1922        if (strncmp(ptr, "if", 2) == 0 || strncmp(ptr, "el", 2) == 0) {
1923          hash_dir = 1;
1924        } else if (strncmp(ptr, "endif", 5) == 0) {
1925          hash_dir = -1;
1926        } else {
1927          return NULL;
1928        }
1929      }
1930      pos.col = 0;
1931      while (!got_int) {
1932        if (hash_dir > 0) {
1933          if (pos.lnum == curbuf->b_ml.ml_line_count) {
1934            break;
1935          }
1936        } else if (pos.lnum == 1) {
1937          break;
1938        }
1939        pos.lnum += hash_dir;
1940        linep = ml_get(pos.lnum);
1941        line_breakcheck();              // check for CTRL-C typed
1942        ptr = skipwhite(linep);
1943        if (*ptr != '#') {
1944          continue;
1945        }
1946        pos.col = (colnr_T)(ptr - linep);
1947        ptr = skipwhite(ptr + 1);
1948        if (hash_dir > 0) {
1949          if (strncmp(ptr, "if", 2) == 0) {
1950            count++;
1951          } else if (strncmp(ptr, "el", 2) == 0) {
1952            if (count == 0) {
1953              return &pos;
1954            }
1955          } else if (strncmp(ptr, "endif", 5) == 0) {
1956            if (count == 0) {
1957              return &pos;
1958            }
1959            count--;
1960          }
1961        } else {
1962          if (strncmp(ptr, "if", 2) == 0) {
1963            if (count == 0) {
1964              return &pos;
1965            }
1966            count--;
1967          } else if (initc == '#' && strncmp(ptr, "el", 2) == 0) {
1968            if (count == 0) {
1969              return &pos;
1970            }
1971          } else if (strncmp(ptr, "endif", 5) == 0) {
1972            count++;
1973          }
1974        }
1975      }
1976      return NULL;
1977    }
1978  }
1979
1980  // This is just guessing: when 'rightleft' is set, search for a matching
1981  // paren/brace in the other direction.
1982  if (curwin->w_p_rl && vim_strchr("()[]{}<>", initc) != NULL) {
1983    backwards = !backwards;
1984  }
1985
1986  int do_quotes = -1;                 // check for quotes in current line
1987  int at_start;                       // do_quotes value at start position
1988  TriState start_in_quotes = kNone;   // start position is in quotes
1989  pos_T match_pos;                    // Where last slash-star was found
1990  clearpos(&match_pos);
1991
1992  // backward search: Check if this line contains a single-line comment
1993  if ((backwards && comment_dir) || lisp || skip_comments) {
1994    comment_col = check_linecomment(linep);
1995  }
1996  if (lisp && comment_col != MAXCOL && pos.col > (colnr_T)comment_col) {
1997    lispcomm = true;        // find match inside this comment
1998  }
1999  // skip // comment portion at starting position
2000  if (skip_comments && !in_block_comment && comment_col != MAXCOL
2001      && backwards && pos.col > (colnr_T)comment_col) {
2002    pos.col = comment_col;
2003  }
2004
2005  while (!got_int) {
2006    // Go to the next position, forward or backward. We could use
2007    // inc() and dec() here, but that is much slower
2008    if (backwards) {
2009      // char to match is inside of comment, don't search outside
2010      if (lispcomm && pos.col < (colnr_T)comment_col) {
2011        break;
2012      }
2013      if (pos.col == 0) {               // at start of line, go to prev. one
2014        if (pos.lnum == 1) {            // start of file
2015          break;
2016        }
2017        pos.lnum--;
2018
2019        if (maxtravel > 0 && ++traveled > maxtravel) {
2020          break;
2021        }
2022
2023        linep = ml_get(pos.lnum);
2024        pos.col = ml_get_len(pos.lnum);  // pos.col on trailing NUL
2025        do_quotes = -1;
2026        line_breakcheck();
2027
2028        // Check if this line contains a single-line comment
2029        if (comment_dir || lisp || skip_comments) {
2030          comment_col = check_linecomment(linep);
2031        }
2032        // skip comment
2033        if (lisp && comment_col != MAXCOL) {
2034          pos.col = comment_col;
2035        } else if (skip_comments && !in_block_comment
2036                   && comment_col != MAXCOL
2037                   && pos.col > (colnr_T)comment_col) {
2038          pos.col = comment_col;
2039        }
2040      } else {
2041        pos.col--;
2042        pos.col -= utf_head_off(linep, linep + pos.col);
2043      }
2044    } else {                          // forward search
2045      if (linep[pos.col] == NUL
2046          // at end of line, go to next one
2047          // For lisp don't search for match in comment
2048          || (lisp && comment_col != MAXCOL
2049              && pos.col == (colnr_T)comment_col)) {
2050        if (pos.lnum == curbuf->b_ml.ml_line_count          // end of file
2051            // line is exhausted and comment with it,
2052            // don't search for match in code
2053            || lispcomm) {
2054          break;
2055        }
2056        pos.lnum++;
2057
2058        if (maxtravel && traveled++ > maxtravel) {
2059          break;
2060        }
2061
2062        linep = ml_get(pos.lnum);
2063        pos.col = 0;
2064        do_quotes = -1;
2065        line_breakcheck();
2066        if (lisp || skip_comments) {  // find comment pos in new line
2067          comment_col = check_linecomment(linep);
2068        }
2069      } else {
2070        pos.col += utfc_ptr2len(linep + pos.col);
2071      }
2072    }
2073
2074    // Track block comment state when FM_SKIPCOMM is set.  Markers inside a
2075    // string are not comments, so skip them while "inquote" is set.
2076    // Backward: '/' of end-marker enters comment; '*' of start-marker exits.
2077    // Forward:  '/' of start-marker enters comment; '/' of end-marker exits.
2078    if (skip_comments && !comment_dir && !inquote) {
2079      if (backwards) {
2080        // Guard pos.col < comment_col: don't misread '* /' at the '//'
2081        // position as a block-comment end-marker.
2082        if (!in_block_comment && pos.col > 0
2083            && linep[pos.col - 1] == '*' && linep[pos.col] == '/'
2084            && (comment_col == MAXCOL || (int)pos.col < comment_col)) {
2085          in_block_comment = true;
2086        } else if (in_block_comment && pos.col > 0
2087                   && linep[pos.col - 1] == '/' && linep[pos.col] == '*') {
2088          in_block_comment = false;
2089        }
2090      } else {
2091        // Guard pos.col < comment_col: don't treat '/ *' inside a '//'
2092        // comment as a block-comment start-marker.
2093        if (!in_block_comment && linep[pos.col] == '/'
2094            && linep[pos.col + 1] == '*'
2095            && (comment_col == MAXCOL || (int)pos.col < comment_col)) {
2096          in_block_comment = true;
2097        } else if (in_block_comment && pos.col > 0
2098                   && linep[pos.col - 1] == '*' && linep[pos.col] == '/') {
2099          in_block_comment = false;
2100        }
2101      }
2102    }
2103
2104    // If FM_BLOCKSTOP given, stop at a '{' or '}' in column 0.
2105    if (pos.col == 0 && (flags & FM_BLOCKSTOP)
2106        && (linep[0] == '{' || linep[0] == '}')) {
2107      if (linep[0] == findc && count == 0) {  // match!
2108        return &pos;
2109      }
2110      break;  // out of scope
2111    }
2112
2113    if (comment_dir) {
2114      // Note: comments do not nest, and we ignore quotes in them
2115      // TODO(vim): ignore comment brackets inside strings
2116      if (comment_dir == FORWARD) {
2117        if (linep[pos.col] == '*' && linep[pos.col + 1] == '/') {
2118          pos.col++;
2119          return &pos;
2120        }
2121      } else {    // Searching backwards
2122        // A comment may contain / * or / /, it may also start or end
2123        // with / * /. Ignore a / * after / / and after *.
2124        if (pos.col == 0) {
2125          continue;
2126        } else if (raw_string) {
2127          if (linep[pos.col - 1] == 'R'
2128              && linep[pos.col] == '"'
2129              && vim_strchr(linep + pos.col + 1, '(') != NULL) {
2130            // Possible start of raw string. Now that we have the
2131            // delimiter we can check if it ends before where we
2132            // started searching, or before the previously found
2133            // raw string start.
2134            if (!find_rawstring_end(linep, &pos,
2135                                    count > 0 ? &match_pos : &curwin->w_cursor)) {
2136              count++;
2137              match_pos = pos;
2138              match_pos.col--;
2139            }
2140            linep = ml_get(pos.lnum);  // may have been released
2141          }
2142        } else if (linep[pos.col - 1] == '/'
2143                   && linep[pos.col] == '*'
2144                   && (pos.col == 1 || linep[pos.col - 2] != '*')
2145                   && (int)pos.col < comment_col) {
2146          count++;
2147          match_pos = pos;
2148          match_pos.col--;
2149        } else if (linep[pos.col - 1] == '*' && linep[pos.col] == '/') {
2150          if (count > 0) {
2151            pos = match_pos;
2152          } else if (pos.col > 1 && linep[pos.col - 2] == '/'
2153                     && (int)pos.col <= comment_col) {
2154            pos.col -= 2;
2155          } else if (ignore_cend) {
2156            continue;
2157          } else {
2158            return NULL;
2159          }
2160          return &pos;
2161        }
2162      }
2163      continue;
2164    }
2165
2166    // If smart matching ('cpoptions' does not contain '%'), braces inside
2167    // of quotes are ignored, but only if there is an even number of
2168    // quotes in the line.
2169    if (cpo_match) {
2170      do_quotes = 0;
2171    } else if (do_quotes == -1) {
2172      // Count the number of quotes in the line, skipping \" and '"'.
2173      // Watch out for "\\".
2174      at_start = do_quotes;
2175      for (ptr = linep; *ptr; ptr++) {
2176        if (ptr == linep + pos.col + backwards) {
2177          at_start = (do_quotes & 1);
2178        }
2179        if (*ptr == '"'
2180            && (ptr == linep || ptr[-1] != '\'' || ptr[1] != '\'')) {
2181          do_quotes++;
2182        }
2183        if (*ptr == '\\' && ptr[1] != NUL) {
2184          ptr++;
2185        }
2186      }
2187      do_quotes &= 1;               // result is 1 with even number of quotes
2188
2189      // If we find an uneven count, check current line and previous
2190      // one for a '\' at the end.
2191      if (!do_quotes) {
2192        inquote = false;
2193        if (ptr[-1] == '\\') {
2194          do_quotes = 1;
2195          if (start_in_quotes == kNone) {
2196            inquote = at_start;
2197            if (inquote) {
2198              start_in_quotes = kTrue;
2199            }
2200          } else if (backwards) {
2201            inquote = true;
2202          }
2203        }
2204        if (pos.lnum > 1) {
2205          ptr = ml_get(pos.lnum - 1);
2206          if (*ptr && *(ptr + ml_get_len(pos.lnum - 1) - 1) == '\\') {
2207            do_quotes = 1;
2208            if (start_in_quotes == kNone) {
2209              inquote = at_start;
2210              if (inquote) {
2211                start_in_quotes = kTrue;
2212              }
2213            } else if (!backwards) {
2214              inquote = true;
2215            }
2216          }
2217
2218          // ml_get() only keeps one line, need to get linep again
2219          linep = ml_get(pos.lnum);
2220        }
2221      }
2222    }
2223    if (start_in_quotes == kNone) {
2224      start_in_quotes = kFalse;
2225    }
2226
2227    // If 'smartmatch' is set:
2228    //   Things inside quotes are ignored by setting 'inquote'.  If we
2229    //   find a quote without a preceding '\' invert 'inquote'.  At the
2230    //   end of a line not ending in '\' we reset 'inquote'.
2231    //
2232    //   In lines with an uneven number of quotes (without preceding '\')
2233    //   we do not know which part to ignore. Therefore we only set
2234    //   inquote if the number of quotes in a line is even, unless this
2235    //   line or the previous one ends in a '\'.  Complicated, isn't it?
2236    const int c = utf_ptr2char(linep + pos.col);
2237    switch (c) {
2238    case NUL:
2239      // at end of line without trailing backslash, reset inquote
2240      if (pos.col == 0 || linep[pos.col - 1] != '\\') {
2241        inquote = false;
2242        start_in_quotes = kFalse;
2243      }
2244      break;
2245
2246    case '"':
2247      // a quote that is preceded with an odd number of backslashes is
2248      // ignored
2249      if (do_quotes) {
2250        int col;
2251
2252        for (col = pos.col - 1; col >= 0; col--) {
2253          if (linep[col] != '\\') {
2254            break;
2255          }
2256        }
2257        if ((((int)pos.col - 1 - col) & 1) == 0) {
2258          inquote = !inquote;
2259          start_in_quotes = kFalse;
2260        }
2261      }
2262      break;
2263
2264    // If smart matching ('cpoptions' does not contain '%'):
2265    //   Skip things in single quotes: 'x' or '\x'.  Be careful for single
2266    //   single quotes, eg jon's.  Things like '\233' or '\x3f' are not
2267    //   skipped, there is never a brace in them.
2268    //   Ignore this when finding matches for `'.
2269    case '\'':
2270      if (!cpo_match && initc != '\'' && findc != '\'') {
2271        if (backwards) {
2272          if (pos.col > 1) {
2273            if (linep[pos.col - 2] == '\'') {
2274              pos.col -= 2;
2275              break;
2276            } else if (linep[pos.col - 2] == '\\'
2277                       && pos.col > 2 && linep[pos.col - 3] == '\'') {
2278              pos.col -= 3;
2279              break;
2280            }
2281          }
2282        } else if (linep[pos.col + 1]) {  // forward search
2283          if (linep[pos.col + 1] == '\\'
2284              && linep[pos.col + 2] && linep[pos.col + 3] == '\'') {
2285            pos.col += 3;
2286            break;
2287          } else if (linep[pos.col + 2] == '\'') {
2288            pos.col += 2;
2289            break;
2290          }
2291        }
2292      }
2293      FALLTHROUGH;
2294
2295    default:
2296      // For Lisp skip over backslashed (), {} and [].
2297      // (actually, we skip #\( et al)
2298      if (curbuf->b_p_lisp
2299          && vim_strchr("(){}[]", c) != NULL
2300          && pos.col > 1
2301          && check_prevcol(linep, pos.col, '\\', NULL)
2302          && check_prevcol(linep, pos.col - 1, '#', NULL)) {
2303        break;
2304      }
2305
2306      // Skip matches inside comments when FM_SKIPCOMM is set.
2307      if (skip_comments
2308          && (in_block_comment
2309              || (comment_col != MAXCOL && (int)pos.col >= comment_col))) {
2310        break;
2311      }
2312
2313      // Check for match outside of quotes, and inside of
2314      // quotes when the start is also inside of quotes.
2315      if ((!inquote || start_in_quotes == kTrue)
2316          && (c == initc || c == findc)) {
2317        int bslcnt = 0;
2318
2319        if (!cpo_bsl) {
2320          for (int col = pos.col; check_prevcol(linep, col, '\\', &col);) {
2321            bslcnt++;
2322          }
2323        }
2324        // Only accept a match when 'M' is in 'cpo' or when escaping
2325        // is what we expect.
2326        if (cpo_bsl || (bslcnt & 1) == match_escaped) {
2327          if (c == initc) {
2328            count++;
2329          } else {
2330            if (count == 0) {
2331              return &pos;
2332            }
2333            count--;
2334          }
2335        }
2336      }
2337    }
2338  }
2339
2340  if (comment_dir == BACKWARD && count > 0) {
2341    pos = match_pos;
2342    return &pos;
2343  }
2344  return (pos_T *)NULL;         // never found it
2345}
2346
2347/// Move cursor briefly to character matching the one under the cursor.
2348/// Used for Insert mode and "r" command.
2349/// Show the match only if it is visible on the screen.
2350/// If there isn't a match, then beep.
2351///
2352/// @param c  char to show match for
2353void showmatch(int c)
2354{
2355  pos_T *lpos;
2356  colnr_T vcol;
2357  OptInt *so = curwin->w_p_so >= 0 ? &curwin->w_p_so : &p_so;
2358  OptInt *siso = curwin->w_p_siso >= 0 ? &curwin->w_p_siso : &p_siso;
2359  char *p;
2360
2361  // Only show match for chars in the 'matchpairs' option.
2362  // 'matchpairs' is "x:y,x:y"
2363  for (p = curbuf->b_p_mps; *p != NUL; p++) {
2364    if (utf_ptr2char(p) == c && (curwin->w_p_rl ^ p_ri)) {
2365      break;
2366    }
2367    p += utfc_ptr2len(p) + 1;
2368    if (utf_ptr2char(p) == c && !(curwin->w_p_rl ^ p_ri)) {
2369      break;
2370    }
2371    p += utfc_ptr2len(p);
2372    if (*p == NUL) {
2373      return;
2374    }
2375  }
2376  if (*p == NUL) {
2377    return;
2378  }
2379
2380  if ((lpos = findmatch(NULL, NUL)) == NULL) {  // no match, so beep
2381    vim_beep(kOptBoFlagShowmatch);
2382    return;
2383  }
2384
2385  if (lpos->lnum < curwin->w_topline || lpos->lnum >= curwin->w_botline) {
2386    return;
2387  }
2388
2389  if (!curwin->w_p_wrap) {
2390    getvcol(curwin, lpos, NULL, &vcol, NULL, 0);
2391  }
2392
2393  bool col_visible = curwin->w_p_wrap
2394                     || (vcol >= curwin->w_leftcol
2395                         && vcol < curwin->w_leftcol + curwin->w_view_width);
2396  if (!col_visible) {
2397    return;
2398  }
2399
2400  pos_T mpos = *lpos;  // save the pos, update_screen() may change it
2401  pos_T save_cursor = curwin->w_cursor;
2402  OptInt save_so = *so;
2403  OptInt save_siso = *siso;
2404  // Handle "$" in 'cpo': If the ')' is typed on top of the "$",
2405  // stop displaying the "$".
2406  if (dollar_vcol >= 0 && dollar_vcol == curwin->w_virtcol) {
2407    dollar_vcol = -1;
2408  }
2409  curwin->w_virtcol++;              // do display ')' just before "$"
2410
2411  colnr_T save_dollar_vcol = dollar_vcol;
2412  int save_state = State;
2413  State = MODE_SHOWMATCH;
2414  ui_cursor_shape();                // may show different cursor shape
2415  curwin->w_cursor = mpos;          // move to matching char
2416  *so = 0;                          // don't use 'scrolloff' here
2417  *siso = 0;                        // don't use 'sidescrolloff' here
2418  show_cursor_info_later(false);
2419  update_screen();                  // show the new char
2420  setcursor();
2421  ui_flush();
2422  // Restore dollar_vcol(), because setcursor() may call curs_rows()
2423  // which resets it if the matching position is in a previous line
2424  // and has a higher column number.
2425  dollar_vcol = save_dollar_vcol;
2426
2427  // brief pause, unless 'm' is present in 'cpo' and a character is
2428  // available.
2429  if (vim_strchr(p_cpo, kCpoShowmatch) != NULL) {
2430    os_delay((uint64_t)p_mat * 100 + 8, true);
2431  } else if (!char_avail()) {
2432    os_delay((uint64_t)p_mat * 100 + 9, false);
2433  }
2434  curwin->w_cursor = save_cursor;           // restore cursor position
2435  *so = save_so;
2436  *siso = save_siso;
2437  State = save_state;
2438  ui_cursor_shape();                // may show different cursor shape
2439}
2440
2441/// Find next search match under cursor, cursor at end.
2442/// Used while an operator is pending, and in Visual mode.
2443///
2444/// @param forward  true for forward, false for backward
2445int current_search(int count, bool forward)
2446{
2447  bool old_p_ws = p_ws;
2448  pos_T save_VIsual = Visual.start;
2449
2450  // Correct cursor when 'selection' is exclusive
2451  if (Visual.active && *p_sel == 'e' && lt(Visual.start, curwin->w_cursor)) {
2452    dec_cursor();
2453  }
2454
2455  // When searching forward and the cursor is at the start of the Visual
2456  // area, skip the first search backward, otherwise it doesn't move.
2457  const bool skip_first_backward = forward && Visual.active
2458                                   && lt(curwin->w_cursor, Visual.start);
2459
2460  pos_T pos = curwin->w_cursor;       // position after the pattern
2461  pos_T orig_pos = curwin->w_cursor;  // position of the cursor at beginning
2462  if (Visual.active) {
2463    // Searching further will extend the match.
2464    if (forward) {
2465      incl(&pos);
2466    } else {
2467      decl(&pos);
2468    }
2469  }
2470
2471  // Is the pattern is zero-width?, this time, don't care about the direction
2472  int zero_width = is_zero_width(spats[last_idx].pat, spats[last_idx].patlen,
2473                                 true, &curwin->w_cursor, FORWARD);
2474  if (zero_width == -1) {
2475    return FAIL;  // pattern not found
2476  }
2477
2478  pos_T end_pos;  // end position of the pattern match
2479  int result;     // result of various function calls
2480
2481  // The trick is to first search backwards and then search forward again,
2482  // so that a match at the current cursor position will be correctly
2483  // captured.  When "forward" is false do it the other way around.
2484  for (int i = 0; i < 2; i++) {
2485    int dir;
2486    if (forward) {
2487      if (i == 0 && skip_first_backward) {
2488        continue;
2489      }
2490      dir = i;
2491    } else {
2492      dir = !i;
2493    }
2494
2495    int flags = 0;
2496
2497    if (!dir && !zero_width) {
2498      flags = SEARCH_END;
2499    }
2500    end_pos = pos;
2501
2502    // wrapping should not occur in the first round
2503    if (i == 0) {
2504      p_ws = false;
2505    }
2506
2507    result = searchit(curwin, curbuf, &pos, &end_pos,
2508                      (dir ? FORWARD : BACKWARD),
2509                      spats[last_idx].pat, spats[last_idx].patlen, i ? count : 1,
2510                      SEARCH_KEEP | flags, RE_SEARCH, p_magic, NULL);
2511
2512    p_ws = old_p_ws;
2513
2514    // First search may fail, but then start searching from the
2515    // beginning of the file (cursor might be on the search match)
2516    // except when Visual mode is active, so that extending the visual
2517    // selection works.
2518    if (i == 1 && !result) {  // not found, abort
2519      curwin->w_cursor = orig_pos;
2520      if (Visual.active) {
2521        Visual.start = save_VIsual;
2522      }
2523      return FAIL;
2524    } else if (i == 0 && !result) {
2525      if (forward) {  // try again from start of buffer
2526        clearpos(&pos);
2527      } else {  // try again from end of buffer
2528                // searching backwards, so set pos to last line and col
2529        pos.lnum = curwin->w_buffer->b_ml.ml_line_count;
2530        pos.col = ml_get_len(curwin->w_buffer->b_ml.ml_line_count);
2531      }
2532    }
2533  }
2534
2535  pos_T start_pos = pos;
2536
2537  if (!Visual.active) {
2538    Visual.start = start_pos;
2539  }
2540
2541  // put the cursor after the match
2542  curwin->w_cursor = end_pos;
2543  if (lt(Visual.start, end_pos) && forward) {
2544    if (skip_first_backward) {
2545      // put the cursor on the start of the match
2546      curwin->w_cursor = pos;
2547    } else {
2548      // put the cursor on last character of match
2549      dec_cursor();
2550    }
2551  } else if (Visual.active && lt(curwin->w_cursor, Visual.start) && forward) {
2552    curwin->w_cursor = pos;   // put the cursor on the start of the match
2553  }
2554  Visual.active = true;
2555  Visual.mode = 'v';
2556
2557  if (*p_sel == 'e') {
2558    // Correction for exclusive selection depends on the direction.
2559    if (forward && ltoreq(Visual.start, curwin->w_cursor)) {
2560      inc_cursor();
2561    } else if (!forward && ltoreq(curwin->w_cursor, Visual.start)) {
2562      inc(&Visual.start);
2563    }
2564  }
2565
2566  if (fdo_flags & kOptFdoFlagSearch && KeyTyped) {
2567    foldOpenCursor();
2568  }
2569
2570  may_start_select('c');
2571  setmouse();
2572  redraw_curbuf_later(UPD_INVERTED);
2573  showmode();
2574
2575  return OK;
2576}
2577
2578/// Check if the pattern is zero-width.
2579/// If move is true, check from the beginning of the buffer,
2580/// else from position "cur".
2581/// "direction" is FORWARD or BACKWARD.
2582/// Returns true, false or -1 for failure.
2583static int is_zero_width(char *pattern, size_t patternlen, bool move, pos_T *cur,
2584                         Direction direction)
2585{
2586  regmmatch_T regmatch;
2587  int result = -1;
2588  pos_T pos;
2589  const int called_emsg_before = called_emsg;
2590  int flag = 0;
2591
2592  if (pattern == NULL) {
2593    pattern = spats[last_idx].pat;
2594    patternlen = spats[last_idx].patlen;
2595  }
2596
2597  if (search_regcomp(pattern, patternlen, NULL, RE_SEARCH, RE_SEARCH,
2598                     SEARCH_KEEP, p_magic, &regmatch) == FAIL) {
2599    return -1;
2600  }
2601
2602  // init startcol correctly
2603  regmatch.startpos[0].col = -1;
2604  // move to match
2605  if (move) {
2606    clearpos(&pos);
2607  } else {
2608    pos = *cur;
2609    // accept a match at the cursor position
2610    flag = SEARCH_START;
2611  }
2612  if (searchit(curwin, curbuf, &pos, NULL, direction, pattern, patternlen, 1,
2613               SEARCH_KEEP + flag, RE_SEARCH, p_magic, NULL) != FAIL) {
2614    int nmatched = 0;
2615    // Zero-width pattern should match somewhere, then we can check if
2616    // start and end are in the same position.
2617    do {
2618      regmatch.startpos[0].col++;
2619      nmatched = vim_regexec_multi(&regmatch, curwin, curbuf,
2620                                   pos.lnum, regmatch.startpos[0].col,
2621                                   NULL, NULL);
2622      if (nmatched != 0) {
2623        break;
2624      }
2625    } while (regmatch.regprog != NULL
2626             && (direction == FORWARD ? regmatch.startpos[0].col < pos.col
2627                                      : regmatch.startpos[0].col > pos.col));
2628
2629    if (called_emsg == called_emsg_before) {
2630      result = (nmatched != 0
2631                && regmatch.startpos[0].lnum == regmatch.endpos[0].lnum
2632                && regmatch.startpos[0].col == regmatch.endpos[0].col);
2633    }
2634  }
2635
2636  vim_regfree(regmatch.regprog);
2637  return result;
2638}
2639
2640/// @return  true if line 'lnum' is empty or has white chars only.
2641bool linewhite(linenr_T lnum)
2642{
2643  char *p = skipwhite(ml_get(lnum));
2644  return *p == NUL;
2645}
2646
2647/// Add the search count "[3/19]" to "msgbuf".
2648/// See update_search_stat() for other arguments.
2649static void cmdline_search_stat(int dirc, pos_T *pos, pos_T *cursor_pos, bool show_top_bot_msg,
2650                                char *msgbuf, size_t msgbuflen, bool recompute, int maxcount,
2651                                int timeout)
2652{
2653  searchstat_T stat;
2654
2655  update_search_stat(dirc, pos, cursor_pos, &stat, recompute, maxcount,
2656                     timeout);
2657  if (stat.cur <= 0) {
2658    return;
2659  }
2660
2661  char t[SEARCH_STAT_BUF_LEN];
2662  size_t len;
2663
2664  if (curwin->w_p_rl && *curwin->w_p_rlc == 's') {
2665    if (stat.incomplete == 1) {
2666      len = (size_t)vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[?/??]");
2667    } else if (stat.cnt > maxcount && stat.cur > maxcount) {
2668      len = (size_t)vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[>%d/>%d]",
2669                                 maxcount, maxcount);
2670    } else if (stat.cnt > maxcount) {
2671      len = (size_t)vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[>%d/%d]",
2672                                 maxcount, stat.cur);
2673    } else {
2674      len = (size_t)vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[%d/%d]",
2675                                 stat.cnt, stat.cur);
2676    }
2677  } else {
2678    if (stat.incomplete == 1) {
2679      len = (size_t)vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[?/??]");
2680    } else if (stat.cnt > maxcount && stat.cur > maxcount) {
2681      len = (size_t)vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[>%d/>%d]",
2682                                 maxcount, maxcount);
2683    } else if (stat.cnt > maxcount) {
2684      len = (size_t)vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[%d/>%d]",
2685                                 stat.cur, maxcount);
2686    } else {
2687      len = (size_t)vim_snprintf(t, SEARCH_STAT_BUF_LEN, "[%d/%d]",
2688                                 stat.cur, stat.cnt);
2689    }
2690  }
2691
2692  if (show_top_bot_msg && len + 2 < SEARCH_STAT_BUF_LEN) {
2693    memmove(t + 2, t, len);
2694    t[0] = 'W';
2695    t[1] = ' ';
2696    len += 2;
2697  }
2698
2699  if (len > msgbuflen) {
2700    len = msgbuflen;
2701  }
2702  memmove(msgbuf + msgbuflen - len, t, len);
2703
2704  if (dirc == '?' && stat.cur == maxcount + 1) {
2705    stat.cur = -1;
2706  }
2707
2708  // keep the message even after redraw, but don't put in history
2709  msg_ext_overwrite = true;
2710  msg_ext_set_kind("search_count");
2711  give_warning(msgbuf, false, false);
2712}
2713
2714// Add the search count information to "stat".
2715// "stat" must not be NULL.
2716// When "recompute" is true always recompute the numbers.
2717// dirc == 0: don't find the next/previous match (only set the result to "stat")
2718// dirc == '/': find the next match
2719// dirc == '?': find the previous match
2720static void update_search_stat(int dirc, pos_T *pos, pos_T *cursor_pos, searchstat_T *stat,
2721                               bool recompute, int maxcount, int timeout)
2722{
2723  int save_ws = p_ws;
2724  bool wraparound = false;
2725  pos_T p = (*pos);
2726  static pos_T lastpos = { 0, 0, 0 };
2727  static int cur = 0;
2728  static int cnt = 0;
2729  static bool exact_match = false;
2730  static int incomplete = 0;
2731  static int last_maxcount = 0;
2732  static int chgtick = 0;
2733  static char *lastpat = NULL;
2734  static size_t lastpatlen = 0;
2735  static buf_T *lbuf = NULL;
2736
2737  CLEAR_POINTER(stat);
2738
2739  if (dirc == 0 && !recompute && !EMPTY_POS(lastpos)) {
2740    stat->cur = cur;
2741    stat->cnt = cnt;
2742    stat->exact_match = exact_match;
2743    stat->incomplete = incomplete;
2744    stat->last_maxcount = last_maxcount;
2745    return;
2746  }
2747  last_maxcount = maxcount;
2748  wraparound = ((dirc == '?' && lt(lastpos, p))
2749                || (dirc == '/' && lt(p, lastpos)));
2750
2751  // If anything relevant changed the count has to be recomputed.
2752  if (!(chgtick == buf_get_changedtick(curbuf)
2753        && (lastpat != NULL  // suppress clang/NULL passed as nonnull parameter
2754            && strncmp(lastpat, spats[last_idx].pat, lastpatlen) == 0
2755            && lastpatlen == spats[last_idx].patlen)
2756        && equalpos(lastpos, *cursor_pos)
2757        && lbuf == curbuf)
2758      || wraparound || cur < 0 || (maxcount > 0 && cur > maxcount)
2759      || recompute) {
2760    cur = 0;
2761    cnt = 0;
2762    exact_match = false;
2763    incomplete = 0;
2764    clearpos(&lastpos);
2765    lbuf = curbuf;
2766  }
2767
2768  // when searching backwards and having jumped to the first occurrence,
2769  // cur must remain greater than 1
2770  if (equalpos(lastpos, *cursor_pos) && !wraparound
2771      && (dirc == 0 || dirc == '/' ? cur < cnt : cur > 1)) {
2772    cur += dirc == 0 ? 0 : dirc == '/' ? 1 : -1;
2773  } else {
2774    proftime_T start;
2775    bool done_search = false;
2776    pos_T endpos = { 0, 0, 0 };
2777    p_ws = false;
2778    if (timeout > 0) {
2779      start = profile_setlimit(timeout);
2780    }
2781    while (!got_int && searchit(curwin, curbuf, &lastpos, &endpos,
2782                                FORWARD, NULL, 0, 1, SEARCH_KEEP, RE_LAST,
2783                                p_magic, NULL) != FAIL) {
2784      done_search = true;
2785      // Stop after passing the time limit.
2786      if (timeout > 0 && profile_passed_limit(start)) {
2787        incomplete = 1;
2788        break;
2789      }
2790      cnt++;
2791      if (ltoreq(lastpos, p)) {
2792        cur = cnt;
2793        if (lt(p, endpos)) {
2794          exact_match = true;
2795        }
2796      }
2797      fast_breakcheck();
2798      if (maxcount > 0 && cnt > maxcount) {
2799        incomplete = 2;    // max count exceeded
2800        break;
2801      }
2802    }
2803    if (got_int) {
2804      cur = -1;  // abort
2805    }
2806    if (done_search) {
2807      xfree(lastpat);
2808      lastpat = xstrnsave(spats[last_idx].pat, spats[last_idx].patlen);
2809      lastpatlen = spats[last_idx].patlen;
2810      chgtick = (int)buf_get_changedtick(curbuf);
2811      lbuf = curbuf;
2812      lastpos = p;
2813    }
2814  }
2815  stat->cur = cur;
2816  stat->cnt = cnt;
2817  stat->exact_match = exact_match;
2818  stat->incomplete = incomplete;
2819  stat->last_maxcount = last_maxcount;
2820  p_ws = save_ws;
2821}
2822
2823// "searchcount()" function
2824void f_searchcount(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
2825{
2826  pos_T pos = curwin->w_cursor;
2827  char *pattern = NULL;
2828  int maxcount = (int)p_msc;
2829  int timeout = SEARCH_STAT_DEF_TIMEOUT;
2830  bool recompute = true;
2831  searchstat_T stat;
2832
2833  tv_dict_alloc_ret(rettv);
2834
2835  if (shortmess(kShmSearchcount)) {  // 'shortmess' contains 'S' flag
2836    recompute = true;
2837  }
2838
2839  if (argvars[0].v_type != VAR_UNKNOWN) {
2840    dict_T *dict;
2841    dictitem_T *di;
2842    bool error = false;
2843
2844    if (tv_check_for_nonnull_dict_arg(argvars, 0) == FAIL) {
2845      return;
2846    }
2847    dict = argvars[0].vval.v_dict;
2848    di = tv_dict_find(dict, "timeout", -1);
2849    if (di != NULL) {
2850      timeout = (int)tv_get_number_chk(&di->di_tv, &error);
2851      if (error) {
2852        return;
2853      }
2854    }
2855    di = tv_dict_find(dict, "maxcount", -1);
2856    if (di != NULL) {
2857      maxcount = (int)tv_get_number_chk(&di->di_tv, &error);
2858      if (error) {
2859        return;
2860      }
2861    }
2862    recompute = tv_dict_get_bool(dict, "recompute", recompute);
2863    di = tv_dict_find(dict, "pattern", -1);
2864    if (di != NULL) {
2865      pattern = (char *)tv_get_string_chk(&di->di_tv);
2866      if (pattern == NULL) {
2867        return;
2868      }
2869    }
2870    di = tv_dict_find(dict, "pos", -1);
2871    if (di != NULL) {
2872      if (di->di_tv.v_type != VAR_LIST) {
2873        semsg(_(e_invarg2), "pos");
2874        return;
2875      }
2876      if (tv_list_len(di->di_tv.vval.v_list) != 3) {
2877        semsg(_(e_invarg2), "List format should be [lnum, col, off]");
2878        return;
2879      }
2880      listitem_T *li = tv_list_find(di->di_tv.vval.v_list, 0);
2881      if (li != NULL) {
2882        pos.lnum = (linenr_T)tv_get_number_chk(TV_LIST_ITEM_TV(li), &error);
2883        if (error) {
2884          return;
2885        }
2886      }
2887      li = tv_list_find(di->di_tv.vval.v_list, 1);
2888      if (li != NULL) {
2889        pos.col = (colnr_T)tv_get_number_chk(TV_LIST_ITEM_TV(li), &error) - 1;
2890        if (error) {
2891          return;
2892        }
2893      }
2894      li = tv_list_find(di->di_tv.vval.v_list, 2);
2895      if (li != NULL) {
2896        pos.coladd = (colnr_T)tv_get_number_chk(TV_LIST_ITEM_TV(li), &error);
2897        if (error) {
2898          return;
2899        }
2900      }
2901    }
2902  }
2903
2904  save_last_search_pattern();
2905  save_incsearch_state();
2906  if (pattern != NULL) {
2907    if (*pattern == NUL) {
2908      goto the_end;
2909    }
2910    xfree(spats[last_idx].pat);
2911    spats[last_idx].patlen = strlen(pattern);
2912    spats[last_idx].pat = xstrnsave(pattern, spats[last_idx].patlen);
2913  }
2914  if (spats[last_idx].pat == NULL || *spats[last_idx].pat == NUL) {
2915    goto the_end;  // the previous pattern was never defined
2916  }
2917
2918  update_search_stat(0, &pos, &pos, &stat, recompute, maxcount, timeout);
2919
2920  tv_dict_add_nr(rettv->vval.v_dict, S_LEN("current"), stat.cur);
2921  tv_dict_add_nr(rettv->vval.v_dict, S_LEN("total"), stat.cnt);
2922  tv_dict_add_nr(rettv->vval.v_dict, S_LEN("exact_match"), stat.exact_match);
2923  tv_dict_add_nr(rettv->vval.v_dict, S_LEN("incomplete"), stat.incomplete);
2924  tv_dict_add_nr(rettv->vval.v_dict, S_LEN("maxcount"), stat.last_maxcount);
2925
2926the_end:
2927  restore_last_search_pattern();
2928  restore_incsearch_state();
2929}
2930
2931/// Get line "lnum" and copy it into "buf[LSIZE]".
2932/// The copy is made because the regexp may make the line invalid when using a
2933/// mark.
2934static char *get_line_and_copy(linenr_T lnum, char *buf)
2935{
2936  char *line = ml_get(lnum);
2937  xstrlcpy(buf, line, LSIZE);
2938  return buf;
2939}
2940
2941/// Find identifiers or defines in included files.
2942/// If p_ic && compl_status_sol() then ptr must be in lowercase.
2943///
2944/// @param ptr            pointer to search pattern
2945/// @param dir            direction of expansion
2946/// @param len            length of search pattern
2947/// @param whole          match whole words only
2948/// @param skip_comments  don't match inside comments
2949/// @param type           Type of search; are we looking for a type? a macro?
2950/// @param action         What to do when we find it
2951/// @param start_lnum     first line to start searching
2952/// @param end_lnum       last line for searching
2953/// @param forceit        If true, always switch to the found path
2954/// @param silent         Do not print messages when ACTION_EXPAND
2955void find_pattern_in_path(char *ptr, Direction dir, size_t len, bool whole, bool skip_comments,
2956                          int type, int count, int action, linenr_T start_lnum, linenr_T end_lnum,
2957                          bool forceit, bool silent)
2958{
2959  SearchedFile *files;                  // Stack of included files
2960  SearchedFile *bigger;                 // When we need more space
2961  int max_path_depth = 50;
2962  int match_count = 1;
2963
2964  char *new_fname;
2965  char *curr_fname = curbuf->b_fname;
2966  char *prev_fname = NULL;
2967  int depth_displayed;                  // For type==CHECK_PATH
2968  char *p;
2969  bool define_matched;
2970  regmatch_T regmatch;
2971  regmatch_T incl_regmatch;
2972  regmatch_T def_regmatch;
2973  bool matched = false;
2974  bool did_show = false;
2975  bool found = false;
2976  int i;
2977  char *already = NULL;
2978  char *startp = NULL;
2979  win_T *curwin_save = NULL;
2980  const int l_g_do_tagpreview = g_do_tagpreview;
2981
2982  regmatch.regprog = NULL;
2983  incl_regmatch.regprog = NULL;
2984  def_regmatch.regprog = NULL;
2985
2986  char *file_line = xmalloc(LSIZE);
2987
2988  if (type != CHECK_PATH && type != FIND_DEFINE
2989      // when CONT_SOL is set compare "ptr" with the beginning of the
2990      // line is faster than quote_meta/regcomp/regexec "ptr" -- Acevedo
2991      && !compl_status_sol()) {
2992    size_t patsize = len + 5;
2993    char *pat = xmalloc(patsize);
2994    assert(len <= INT_MAX);
2995    snprintf(pat, patsize, whole ? "\\<%.*s\\>" : "%.*s", (int)len, ptr);
2996    // ignore case according to p_ic, p_scs and pat
2997    regmatch.rm_ic = ignorecase(pat);
2998    regmatch.regprog = vim_regcomp(pat, p_magic ? RE_MAGIC : 0);
2999    xfree(pat);
3000    if (regmatch.regprog == NULL) {
3001      goto fpip_end;
3002    }
3003  }
3004  char *inc_opt = (*curbuf->b_p_inc == NUL) ? p_inc : curbuf->b_p_inc;
3005  if (*inc_opt != NUL) {
3006    incl_regmatch.regprog = vim_regcomp(inc_opt, p_magic ? RE_MAGIC : 0);
3007    if (incl_regmatch.regprog == NULL) {
3008      goto fpip_end;
3009    }
3010    incl_regmatch.rm_ic = false;        // don't ignore case in incl. pat.
3011  }
3012  if (type == FIND_DEFINE && (*curbuf->b_p_def != NUL || *p_def != NUL)) {
3013    def_regmatch.regprog = vim_regcomp(*curbuf->b_p_def == NUL ? p_def : curbuf->b_p_def,
3014                                       p_magic ? RE_MAGIC : 0);
3015    if (def_regmatch.regprog == NULL) {
3016      goto fpip_end;
3017    }
3018    def_regmatch.rm_ic = false;         // don't ignore case in define pat.
3019  }
3020  files = xcalloc((size_t)max_path_depth, sizeof(SearchedFile));
3021  int old_files = max_path_depth;
3022  int depth = depth_displayed = -1;
3023
3024  end_lnum = MIN(end_lnum, curbuf->b_ml.ml_line_count);
3025  linenr_T lnum = MIN(start_lnum, end_lnum);  // do at least one line
3026  char *line = get_line_and_copy(lnum, file_line);
3027
3028  while (true) {
3029    if (incl_regmatch.regprog != NULL
3030        && vim_regexec(&incl_regmatch, line, 0)) {
3031      char *p_fname = (curr_fname == curbuf->b_fname)
3032                      ? curbuf->b_ffname : curr_fname;
3033
3034      if (strstr(inc_opt, "\\zs") != NULL) {
3035        // Use text from '\zs' to '\ze' (or end) of 'include'.
3036        new_fname = find_file_name_in_path(incl_regmatch.startp[0],
3037                                           (size_t)(incl_regmatch.endp[0]
3038                                                    - incl_regmatch.startp[0]),
3039                                           FNAME_EXP|FNAME_INCL|FNAME_REL,
3040                                           1, p_fname);
3041      } else {
3042        // Use text after match with 'include'.
3043        new_fname = file_name_in_line(incl_regmatch.endp[0], 0,
3044                                      FNAME_EXP|FNAME_INCL|FNAME_REL, 1, p_fname,
3045                                      NULL);
3046      }
3047      TO_SLASH(new_fname);
3048      bool already_searched = false;
3049      if (new_fname != NULL) {
3050        // Check whether we have already searched in this file
3051        for (i = 0;; i++) {
3052          if (i == depth + 1) {
3053            i = old_files;
3054          }
3055          if (i == max_path_depth) {
3056            break;
3057          }
3058          if (path_equal(new_fname, files[i].name, kPathCmpExpand | kPathCmpFull)) {
3059            if (type != CHECK_PATH
3060                && action == ACTION_SHOW_ALL && files[i].matched) {
3061              msg_putchar('\n');  // cursor below last one
3062              if (!got_int) {  // don't display if 'q' typed at "--more--" message
3063                msg_home_replace(new_fname);
3064                msg_puts(_(" (includes previously listed match)"));
3065                prev_fname = NULL;
3066              }
3067            }
3068            XFREE_CLEAR(new_fname);
3069            already_searched = true;
3070            break;
3071          }
3072        }
3073      }
3074
3075      if (type == CHECK_PATH && (action == ACTION_SHOW_ALL
3076                                 || (new_fname == NULL && !already_searched))) {
3077        if (did_show) {
3078          msg_putchar('\n');  // cursor below last one
3079        } else {
3080          gotocmdline(true);  // cursor at status line
3081          msg_puts_title(_("--- Included files "));
3082          if (action != ACTION_SHOW_ALL) {
3083            msg_puts_title(_("not found "));
3084          }
3085          msg_puts_title(_("in path ---\n"));
3086        }
3087        did_show = true;
3088        while (depth_displayed < depth && !got_int) {
3089          depth_displayed++;
3090          for (i = 0; i < depth_displayed; i++) {
3091            msg_puts("  ");
3092          }
3093          msg_home_replace(files[depth_displayed].name);
3094          msg_puts(" -->\n");
3095        }
3096        if (!got_int) {                     // don't display if 'q' typed
3097                                            // for "--more--" message
3098          for (i = 0; i <= depth_displayed; i++) {
3099            msg_puts("  ");
3100          }
3101          if (new_fname != NULL) {
3102            // using "new_fname" is more reliable, e.g., when
3103            // 'includeexpr' is set.
3104            msg_outtrans(new_fname, HLF_D, false);
3105          } else {
3106            // Isolate the file name.
3107            // Include the surrounding "" or <> if present.
3108            if (strstr(inc_opt, "\\zs") != NULL) {
3109              // pattern contains \zs, use the match
3110              p = incl_regmatch.startp[0];
3111              i = (int)(incl_regmatch.endp[0]
3112                        - incl_regmatch.startp[0]);
3113            } else {
3114              // find the file name after the end of the match
3115              for (p = incl_regmatch.endp[0];
3116                   *p && !vim_isfilec((uint8_t)(*p)); p++) {}
3117              for (i = 0; vim_isfilec((uint8_t)p[i]); i++) {}
3118            }
3119
3120            if (i == 0) {
3121              // Nothing found, use the rest of the line.
3122              p = incl_regmatch.endp[0];
3123              i = (int)strlen(p);
3124            } else if (p > line) {
3125              // Avoid checking before the start of the line, can
3126              // happen if \zs appears in the regexp.
3127              if (p[-1] == '"' || p[-1] == '<') {
3128                p--;
3129                i++;
3130              }
3131              if (p[i] == '"' || p[i] == '>') {
3132                i++;
3133              }
3134            }
3135            char save_char = p[i];
3136            p[i] = NUL;
3137            msg_outtrans(p, HLF_D, false);
3138            p[i] = save_char;
3139          }
3140
3141          if (new_fname == NULL && action == ACTION_SHOW_ALL) {
3142            if (already_searched) {
3143              msg_puts(_("  (Already listed)"));
3144            } else {
3145              msg_puts(_("  NOT FOUND"));
3146            }
3147          }
3148        }
3149      }
3150
3151      if (new_fname != NULL) {
3152        // Push the new file onto the file stack
3153        if (depth + 1 == old_files) {
3154          bigger = xmalloc((size_t)max_path_depth * 2 * sizeof(SearchedFile));
3155          for (i = 0; i <= depth; i++) {
3156            bigger[i] = files[i];
3157          }
3158          for (i = depth + 1; i < old_files + max_path_depth; i++) {
3159            bigger[i].fp = NULL;
3160            bigger[i].name = NULL;
3161            bigger[i].lnum = 0;
3162            bigger[i].matched = false;
3163          }
3164          for (i = old_files; i < max_path_depth; i++) {
3165            bigger[i + max_path_depth] = files[i];
3166          }
3167          old_files += max_path_depth;
3168          max_path_depth *= 2;
3169          xfree(files);
3170          files = bigger;
3171        }
3172        if ((files[depth + 1].fp = os_fopen(new_fname, "r")) == NULL) {
3173          xfree(new_fname);
3174        } else {
3175          if (++depth == old_files) {
3176            // Something wrong. We will forget one of our already visited files
3177            // now.
3178            xfree(files[old_files].name);
3179            old_files++;
3180          }
3181          files[depth].name = curr_fname = new_fname;
3182          files[depth].lnum = 0;
3183          files[depth].matched = false;
3184          if (action == ACTION_EXPAND && !shortmess(kShmCompletionscan) && !silent) {
3185            msg_hist_off = true;                // reset in msg_trunc()
3186            vim_snprintf(IObuff, IOSIZE,
3187                         _("Scanning included file: %s"),
3188                         new_fname);
3189            msg_trunc(IObuff, true, HLF_R);
3190          } else if (p_verbose >= 5) {
3191            verbose_enter();
3192            smsg(0, _("Searching included file %s"), new_fname);
3193            verbose_leave();
3194          }
3195        }
3196      }
3197    } else {
3198      // Check if the line is a define (type == FIND_DEFINE)
3199      p = line;
3200search_line:
3201      define_matched = false;
3202      if (def_regmatch.regprog != NULL
3203          && vim_regexec(&def_regmatch, line, 0)) {
3204        // Pattern must be first identifier after 'define', so skip
3205        // to that position before checking for match of pattern.  Also
3206        // don't let it match beyond the end of this identifier.
3207        p = def_regmatch.endp[0];
3208        while (*p && !vim_iswordc((uint8_t)(*p))) {
3209          p++;
3210        }
3211        define_matched = true;
3212      }
3213
3214      // Look for a match.  Don't do this if we are looking for a
3215      // define and this line didn't match define_prog above.
3216      if (def_regmatch.regprog == NULL || define_matched) {
3217        if (define_matched || compl_status_sol()) {
3218          // compare the first "len" chars from "ptr"
3219          startp = skipwhite(p);
3220          if (p_ic) {
3221            matched = mb_strnicmp(startp, ptr, len) == 0;
3222          } else {
3223            matched = strncmp(startp, ptr, len) == 0;
3224          }
3225          if (matched && define_matched && whole
3226              && vim_iswordc((uint8_t)startp[len])) {
3227            matched = false;
3228          }
3229        } else if (regmatch.regprog != NULL
3230                   && vim_regexec(&regmatch, line, (colnr_T)(p - line))) {
3231          matched = true;
3232          startp = regmatch.startp[0];
3233          // Check if the line is not a comment line (unless we are
3234          // looking for a define).  A line starting with "# define"
3235          // is not considered to be a comment line.
3236          if (skip_comments) {
3237            if ((*line != '#'
3238                 || strncmp(skipwhite(line + 1), "define", 6) != 0)
3239                && get_leader_len(line, NULL, false, true)) {
3240              matched = false;
3241            }
3242
3243            // Also check for a "/ *" or "/ /" before the match.
3244            // Skips lines like "int backwards;  / * normal index
3245            // * /" when looking for "normal".
3246            // Note: Doesn't skip "/ *" in comments.
3247            p = skipwhite(line);
3248            if (matched
3249                || (p[0] == '/' && p[1] == '*') || p[0] == '*') {
3250              for (p = line; *p && p < startp; p++) {
3251                if (matched
3252                    && p[0] == '/'
3253                    && (p[1] == '*' || p[1] == '/')) {
3254                  matched = false;
3255                  // After "//" all text is comment
3256                  if (p[1] == '/') {
3257                    break;
3258                  }
3259                  p++;
3260                } else if (!matched && p[0] == '*' && p[1] == '/') {
3261                  // Can find match after "* /".
3262                  matched = true;
3263                  p++;
3264                }
3265              }
3266            }
3267          }
3268        }
3269      }
3270    }
3271    if (matched) {
3272      if (action == ACTION_EXPAND) {
3273        bool cont_s_ipos = false;
3274
3275        if (depth == -1 && lnum == curwin->w_cursor.lnum) {
3276          break;
3277        }
3278        found = true;
3279        char *aux = p = startp;
3280        if (compl_status_adding() && (int)strlen(p) >= ins_compl_len()) {
3281          p += ins_compl_len();
3282          if (vim_iswordp(p)) {
3283            goto exit_matched;
3284          }
3285          p = find_word_start(p);
3286        }
3287        p = find_word_end(p);
3288        i = (int)(p - aux);
3289
3290        if (compl_status_adding() && i == ins_compl_len()) {
3291          // IOSIZE > compl_length, so the strncpy works
3292          strncpy(IObuff, aux, (size_t)i);  // NOLINT(runtime/printf)
3293
3294          // Get the next line: when "depth" < 0  from the current
3295          // buffer, otherwise from the included file.  Jump to
3296          // exit_matched when past the last line.
3297          if (depth < 0) {
3298            if (lnum >= end_lnum) {
3299              goto exit_matched;
3300            }
3301            line = get_line_and_copy(++lnum, file_line);
3302          } else if (vim_fgets(line = file_line,
3303                               LSIZE, files[depth].fp)) {
3304            goto exit_matched;
3305          }
3306
3307          // we read a line, set "already" to check this "line" later
3308          // if depth >= 0 we'll increase files[depth].lnum far
3309          // below  -- Acevedo
3310          already = aux = p = skipwhite(line);
3311          p = find_word_start(p);
3312          p = find_word_end(p);
3313          if (p > aux) {
3314            if (*aux != ')' && IObuff[i - 1] != TAB) {
3315              if (IObuff[i - 1] != ' ') {
3316                IObuff[i++] = ' ';
3317              }
3318              // IObuf =~ "\(\k\|\i\).* ", thus i >= 2
3319              if (p_js
3320                  && (IObuff[i - 2] == '.'
3321                      || IObuff[i - 2] == '?'
3322                      || IObuff[i - 2] == '!')) {
3323                IObuff[i++] = ' ';
3324              }
3325            }
3326            // copy as much as possible of the new word
3327            if (p - aux >= IOSIZE - i) {
3328              p = aux + IOSIZE - i - 1;
3329            }
3330            strncpy(IObuff + i, aux, (size_t)(p - aux));  // NOLINT(runtime/printf)
3331            i += (int)(p - aux);
3332            cont_s_ipos = true;
3333          }
3334          IObuff[i] = NUL;
3335          aux = IObuff;
3336
3337          if (i == ins_compl_len()) {
3338            goto exit_matched;
3339          }
3340        }
3341
3342        const int add_r
3343          = ins_compl_add_infercase(aux, i, p_ic,
3344                                    curr_fname == curbuf->b_fname
3345                                    ? NULL : path_try_shorten_fname(curr_fname),
3346                                    dir, cont_s_ipos, 0);
3347        if (add_r == OK) {
3348          // if dir was BACKWARD then honor it just once
3349          dir = FORWARD;
3350        } else if (add_r == FAIL) {
3351          break;
3352        }
3353      } else if (action == ACTION_SHOW_ALL) {
3354        found = true;
3355        if (!did_show) {
3356          gotocmdline(true);                    // cursor at status line
3357        }
3358        if (curr_fname != prev_fname) {
3359          if (did_show) {
3360            msg_putchar('\n');                  // cursor below last one
3361          }
3362          if (!got_int) {             // don't display if 'q' typed
3363                                      // at "--more--" message
3364            msg_home_replace(curr_fname);
3365          }
3366          prev_fname = curr_fname;
3367        }
3368        did_show = true;
3369        if (!got_int) {
3370          show_pat_in_path(line, type, true, action,
3371                           (depth == -1) ? NULL : files[depth].fp,
3372                           (depth == -1) ? &lnum : &files[depth].lnum,
3373                           match_count++);
3374        }
3375
3376        // Set matched flag for this file and all the ones that
3377        // include it
3378        for (i = 0; i <= depth; i++) {
3379          files[i].matched = true;
3380        }
3381      } else if (--count <= 0) {
3382        found = true;
3383        if (depth == -1 && lnum == curwin->w_cursor.lnum
3384            && l_g_do_tagpreview == 0) {
3385          emsg(_("E387: Match is on current line"));
3386        } else if (action == ACTION_SHOW) {
3387          show_pat_in_path(line, type, did_show, action,
3388                           (depth == -1) ? NULL : files[depth].fp,
3389                           (depth == -1) ? &lnum : &files[depth].lnum, 1);
3390          did_show = true;
3391        } else {
3392          // ":psearch" uses the preview window
3393          if (l_g_do_tagpreview != 0) {
3394            curwin_save = curwin;
3395            prepare_tagpreview(true, *p_pvp != NUL);
3396          }
3397          if (action == ACTION_SPLIT) {
3398            if (win_split(0, 0) == FAIL) {
3399              break;
3400            }
3401            RESET_BINDING(curwin);
3402          }
3403          if (depth == -1) {
3404            // match in current file
3405            if (l_g_do_tagpreview != 0) {
3406              if (!win_valid(curwin_save)) {
3407                break;
3408              }
3409              if (!GETFILE_SUCCESS(getfile(curwin_save->w_buffer->b_fnum, NULL,
3410                                           NULL, true, lnum, forceit))) {
3411                break;    // failed to jump to file
3412              }
3413            } else {
3414              setpcmark();
3415            }
3416            curwin->w_cursor.lnum = lnum;
3417            check_cursor(curwin);
3418          } else {
3419            if (!GETFILE_SUCCESS(getfile(0, files[depth].name, NULL, true,
3420                                         files[depth].lnum, forceit))) {
3421              break;    // failed to jump to file
3422            }
3423            // autocommands may have changed the lnum, we don't
3424            // want that here
3425            curwin->w_cursor.lnum = files[depth].lnum;
3426          }
3427        }
3428        if (action != ACTION_SHOW) {
3429          curwin->w_cursor.col = (colnr_T)(startp - line);
3430          curwin->w_set_curswant = true;
3431        }
3432
3433        if (l_g_do_tagpreview != 0
3434            && curwin != curwin_save && win_valid(curwin_save)) {
3435          // Return cursor to where we were
3436          validate_cursor(curwin);
3437          redraw_later(curwin, UPD_VALID);
3438          win_enter(curwin_save, true);
3439        }
3440        break;
3441      }
3442exit_matched:
3443      matched = false;
3444      // look for other matches in the rest of the line if we
3445      // are not at the end of it already
3446      if (def_regmatch.regprog == NULL
3447          && action == ACTION_EXPAND
3448          && !compl_status_sol()
3449          && *startp != NUL
3450          && *(startp + utfc_ptr2len(startp)) != NUL) {
3451        goto search_line;
3452      }
3453    }
3454    line_breakcheck();
3455    if (action == ACTION_EXPAND) {
3456      ins_compl_check_keys(30, false);
3457    }
3458    if (got_int || ins_compl_interrupted()) {
3459      break;
3460    }
3461
3462    // Read the next line.  When reading an included file and encountering
3463    // end-of-file, close the file and continue in the file that included
3464    // it.
3465    while (depth >= 0 && !already
3466           && vim_fgets(line = file_line, LSIZE, files[depth].fp)) {
3467      fclose(files[depth].fp);
3468      old_files--;
3469      files[old_files].name = files[depth].name;
3470      files[old_files].matched = files[depth].matched;
3471      depth--;
3472      curr_fname = (depth == -1) ? curbuf->b_fname
3473                                 : files[depth].name;
3474      depth_displayed = MIN(depth_displayed, depth);
3475    }
3476    if (depth >= 0) {           // we could read the line
3477      files[depth].lnum++;
3478      // Remove any CR and LF from the line.
3479      i = (int)strlen(line);
3480      if (i > 0 && line[i - 1] == '\n') {
3481        line[--i] = NUL;
3482      }
3483      if (i > 0 && line[i - 1] == '\r') {
3484        line[--i] = NUL;
3485      }
3486    } else if (!already) {
3487      if (++lnum > end_lnum) {
3488        break;
3489      }
3490      line = get_line_and_copy(lnum, file_line);
3491    }
3492    already = NULL;
3493  }
3494  // End of big while (true) loop.
3495
3496  // Close any files that are still open.
3497  for (i = 0; i <= depth; i++) {
3498    fclose(files[i].fp);
3499    xfree(files[i].name);
3500  }
3501  for (i = old_files; i < max_path_depth; i++) {
3502    xfree(files[i].name);
3503  }
3504  xfree(files);
3505
3506  if (type == CHECK_PATH) {
3507    if (!did_show) {
3508      if (action != ACTION_SHOW_ALL) {
3509        msg(_("All included files were found"), 0);
3510      } else {
3511        msg(_("No included files"), 0);
3512      }
3513    }
3514  } else if (!found && action != ACTION_EXPAND && !silent) {
3515    if (got_int || ins_compl_interrupted()) {
3516      emsg(_(e_interr));
3517    } else if (type == FIND_DEFINE) {
3518      emsg(_("E388: Couldn't find definition"));
3519    } else {
3520      emsg(_("E389: Couldn't find pattern"));
3521    }
3522  }
3523  if (action == ACTION_SHOW || action == ACTION_SHOW_ALL) {
3524    msg_end();
3525  }
3526
3527fpip_end:
3528  xfree(file_line);
3529  vim_regfree(regmatch.regprog);
3530  vim_regfree(incl_regmatch.regprog);
3531  vim_regfree(def_regmatch.regprog);
3532}
3533
3534static void show_pat_in_path(char *line, int type, bool did_show, int action, FILE *fp,
3535                             linenr_T *lnum, int count)
3536  FUNC_ATTR_NONNULL_ARG(1, 6)
3537{
3538  if (did_show) {
3539    msg_putchar('\n');          // cursor below last one
3540  } else if (!msg_silent) {
3541    gotocmdline(true);          // cursor at status line
3542  }
3543  if (got_int) {                // 'q' typed at "--more--" message
3544    return;
3545  }
3546  size_t linelen = strlen(line);
3547  while (true) {
3548    char *p = line + linelen - 1;
3549    if (fp != NULL) {
3550      // We used fgets(), so get rid of newline at end
3551      if (p >= line && *p == '\n') {
3552        p--;
3553      }
3554      if (p >= line && *p == '\r') {
3555        p--;
3556      }
3557      *(p + 1) = NUL;
3558    }
3559    if (action == ACTION_SHOW_ALL) {
3560      snprintf(IObuff, IOSIZE, "%3d: ", count);  // Show match nr.
3561      msg_puts(IObuff);
3562      snprintf(IObuff, IOSIZE, "%4" PRIdLINENR, *lnum);  // Show line nr.
3563      // Highlight line numbers.
3564      msg_puts_hl(IObuff, HLF_N, false);
3565      msg_puts(" ");
3566    }
3567    msg_prt_line(line, false);
3568
3569    // Definition continues until line that doesn't end with '\'
3570    if (got_int || type != FIND_DEFINE || p < line || *p != '\\') {
3571      break;
3572    }
3573
3574    if (fp != NULL) {
3575      if (vim_fgets(line, LSIZE, fp)) {     // end of file
3576        break;
3577      }
3578      linelen = strlen(line);
3579      (*lnum)++;
3580    } else {
3581      if (++*lnum > curbuf->b_ml.ml_line_count) {
3582        break;
3583      }
3584      line = ml_get(*lnum);
3585      linelen = (size_t)ml_get_len(*lnum);
3586    }
3587    msg_putchar('\n');
3588  }
3589}
3590
3591/// Get last search pattern
3592void get_search_pattern(SearchPattern *const pat)
3593{
3594  memcpy(pat, &(spats[0]), sizeof(spats[0]));
3595}
3596
3597/// Get last substitute pattern
3598void get_substitute_pattern(SearchPattern *const pat)
3599{
3600  memcpy(pat, &(spats[1]), sizeof(spats[1]));
3601  CLEAR_FIELD(pat->off);
3602}
3603
3604/// Get timestamp of last search or substitute pattern
3605Timestamp get_search_pattern_timestamp(bool substitute)
3606{
3607  return spats[substitute ? RE_SUBST : RE_SEARCH].timestamp;
3608}
3609
3610/// Check whether last search or substitute pattern is cleared
3611bool search_pattern_cleared(bool substitute)
3612{
3613  return spats[substitute ? RE_SUBST : RE_SEARCH].pat == NULL;
3614}
3615
3616/// Set last search pattern
3617void set_search_pattern(const SearchPattern pat)
3618{
3619  free_spat(&spats[0]);
3620  memcpy(&(spats[0]), &pat, sizeof(spats[0]));
3621  set_vv_searchforward();
3622}
3623
3624/// Set last substitute pattern
3625void set_substitute_pattern(const SearchPattern pat)
3626{
3627  free_spat(&spats[1]);
3628  memcpy(&(spats[1]), &pat, sizeof(spats[1]));
3629  CLEAR_FIELD(spats[1].off);
3630}
3631
3632/// Set last used search pattern
3633///
3634/// @param[in]  is_substitute_pattern  If true set substitute pattern as last
3635///                                    used. Otherwise sets search pattern.
3636void set_last_used_pattern(const bool is_substitute_pattern)
3637{
3638  last_idx = (is_substitute_pattern ? 1 : 0);
3639}
3640
3641/// Returns true if search pattern was the last used one
3642bool search_was_last_used(void)
3643{
3644  return last_idx == 0;
3645}