robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
212.5 KiB6808 linesraw
1// insexpand.c: functions for Insert mode completion
2
3#include <assert.h>
4#include <limits.h>
5#include <stdbool.h>
6#include <stddef.h>
7#include <stdint.h>
8#include <stdio.h>
9#include <stdlib.h>
10#include <string.h>
11
12#include "klib/kvec.h"
13#include "nvim/api/private/helpers.h"
14#include "nvim/ascii_defs.h"
15#include "nvim/autocmd.h"
16#include "nvim/autocmd_defs.h"
17#include "nvim/buffer.h"
18#include "nvim/buffer_defs.h"
19#include "nvim/change.h"
20#include "nvim/charset.h"
21#include "nvim/cmdexpand.h"
22#include "nvim/cmdexpand_defs.h"
23#include "nvim/cursor.h"
24#include "nvim/drawscreen.h"
25#include "nvim/errors.h"
26#include "nvim/eval.h"
27#include "nvim/eval/executor.h"
28#include "nvim/eval/typval.h"
29#include "nvim/eval/typval_defs.h"
30#include "nvim/eval/userfunc.h"
31#include "nvim/eval/vars.h"
32#include "nvim/ex_eval.h"
33#include "nvim/ex_getln.h"
34#include "nvim/extmark.h"
35#include "nvim/extmark_defs.h"
36#include "nvim/fileio.h"
37#include "nvim/fuzzy.h"
38#include "nvim/garray.h"
39#include "nvim/garray_defs.h"
40#include "nvim/gettext_defs.h"
41#include "nvim/globals.h"
42#include "nvim/highlight_defs.h"
43#include "nvim/highlight_group.h"
44#include "nvim/indent.h"
45#include "nvim/indent_c.h"
46#include "nvim/input.h"
47#include "nvim/insert.h"
48#include "nvim/insexpand.h"
49#include "nvim/keycodes.h"
50#include "nvim/lua/executor.h"
51#include "nvim/macros_defs.h"
52#include "nvim/mark_defs.h"
53#include "nvim/mbyte.h"
54#include "nvim/mbyte_defs.h"
55#include "nvim/memline.h"
56#include "nvim/memory.h"
57#include "nvim/message.h"
58#include "nvim/move.h"
59#include "nvim/option.h"
60#include "nvim/option_defs.h"
61#include "nvim/option_vars.h"
62#include "nvim/os/fs.h"
63#include "nvim/os/input.h"
64#include "nvim/os/time.h"
65#include "nvim/path.h"
66#include "nvim/popupmenu.h"
67#include "nvim/pos_defs.h"
68#include "nvim/regexp.h"
69#include "nvim/regexp_defs.h"
70#include "nvim/register.h"
71#include "nvim/search.h"
72#include "nvim/spell.h"
73#include "nvim/state.h"
74#include "nvim/state_defs.h"
75#include "nvim/strings.h"
76#include "nvim/tag.h"
77#include "nvim/textformat.h"
78#include "nvim/types_defs.h"
79#include "nvim/ui.h"
80#include "nvim/undo.h"
81#include "nvim/vim_defs.h"
82#include "nvim/window.h"
83#include "nvim/winfloat.h"
84
85// Definitions used for CTRL-X submode.
86// Note: If you change CTRL-X submode, you must also maintain ctrl_x_msgs[]
87// and ctrl_x_mode_names[].
88
89#define CTRL_X_WANT_IDENT       0x100
90
91enum {
92  CTRL_X_NORMAL = 0,  ///< CTRL-N CTRL-P completion, default
93  CTRL_X_NOT_DEFINED_YET = 1,
94  CTRL_X_SCROLL = 2,
95  CTRL_X_WHOLE_LINE = 3,
96  CTRL_X_FILES = 4,
97  CTRL_X_TAGS = (5 + CTRL_X_WANT_IDENT),
98  CTRL_X_PATH_PATTERNS = (6 + CTRL_X_WANT_IDENT),
99  CTRL_X_PATH_DEFINES = (7 + CTRL_X_WANT_IDENT),
100  CTRL_X_FINISHED = 8,
101  CTRL_X_DICTIONARY = (9 + CTRL_X_WANT_IDENT),
102  CTRL_X_THESAURUS = (10 + CTRL_X_WANT_IDENT),
103  CTRL_X_CMDLINE = 11,
104  CTRL_X_FUNCTION = 12,
105  CTRL_X_OMNI = 13,
106  CTRL_X_SPELL = 14,
107  CTRL_X_LOCAL_MSG = 15,       ///< only used in "ctrl_x_msgs"
108  CTRL_X_EVAL = 16,            ///< for builtin function complete()
109  CTRL_X_CMDLINE_CTRL_X = 17,  ///< CTRL-X typed in CTRL_X_CMDLINE
110  CTRL_X_BUFNAMES = 18,
111  CTRL_X_REGISTER = 19,        ///< complete words from registers
112};
113
114#define CTRL_X_MSG(i) ctrl_x_msgs[(i) & ~CTRL_X_WANT_IDENT]
115
116/// Message for CTRL-X mode, index is ctrl_x_mode.
117static char *ctrl_x_msgs[] = {
118  N_(" Keyword completion (^N^P)"),  // CTRL_X_NORMAL, ^P/^N compl.
119  N_(" ^X mode (^]^D^E^F^I^K^L^N^O^P^Rs^U^V^Y)"),
120  NULL,  // CTRL_X_SCROLL: depends on state
121  N_(" Whole line completion (^L^N^P)"),
122  N_(" File name completion (^F^N^P)"),
123  N_(" Tag completion (^]^N^P)"),
124  N_(" Path pattern completion (^N^P)"),
125  N_(" Definition completion (^D^N^P)"),
126  NULL,  // CTRL_X_FINISHED
127  N_(" Dictionary completion (^K^N^P)"),
128  N_(" Thesaurus completion (^T^N^P)"),
129  N_(" Command-line completion (^V^N^P)"),
130  N_(" User defined completion (^U^N^P)"),
131  N_(" Omni completion (^O^N^P)"),
132  N_(" Spelling suggestion (^S^N^P)"),
133  N_(" Keyword Local completion (^N^P)"),
134  NULL,  // CTRL_X_EVAL doesn't use msg.
135  N_(" Command-line completion (^V^N^P)"),
136  NULL,
137  N_(" Register completion (^N^P)"),
138};
139
140static String ctrl_x_mode_names[] = {
141  STATIC_CSTR_STRING_INIT("keyword"),
142  STATIC_CSTR_STRING_INIT("ctrl_x"),
143  STATIC_CSTR_STRING_INIT("scroll"),
144  STATIC_CSTR_STRING_INIT("whole_line"),
145  STATIC_CSTR_STRING_INIT("files"),
146  STATIC_CSTR_STRING_INIT("tags"),
147  STATIC_CSTR_STRING_INIT("path_patterns"),
148  STATIC_CSTR_STRING_INIT("path_defines"),
149  STATIC_CSTR_STRING_INIT("unknown"),  // CTRL_X_FINISHED
150  STATIC_CSTR_STRING_INIT("dictionary"),
151  STATIC_CSTR_STRING_INIT("thesaurus"),
152  STATIC_CSTR_STRING_INIT("cmdline"),
153  STATIC_CSTR_STRING_INIT("function"),
154  STATIC_CSTR_STRING_INIT("omni"),
155  STATIC_CSTR_STRING_INIT("spell"),
156  STRING_INIT,  // CTRL_X_LOCAL_MSG is only used in "ctrl_x_msgs"
157  STATIC_CSTR_STRING_INIT("eval"),
158  STATIC_CSTR_STRING_INIT("cmdline"),
159  STRING_INIT,  // CTRL_X_BUFNAME
160  STATIC_CSTR_STRING_INIT("register"),
161};
162
163/// Structure used to store one match for insert completion.
164typedef struct compl_S compl_T;
165struct compl_S {
166  compl_T *cp_next;
167  compl_T *cp_prev;
168  compl_T *cp_match_next;        ///< matched next compl_T
169  String cp_str;                 ///< matched text
170  char *(cp_text[CPT_COUNT]);    ///< text for the menu
171  typval_T cp_user_data;
172  char *cp_fname;                ///< file containing the match, allocated when
173                                 ///< cp_flags has CP_FREE_FNAME
174  char *cp_commit_chars;         ///< commit characters, allocated. May be NULL.
175  int cp_flags;                  ///< CP_ values
176  int cp_number;                 ///< sequence number
177  bool cp_preselect;             ///< preselect item
178  int cp_score;                  ///< fuzzy match score or proximity score
179  bool cp_in_match_array;        ///< collected by compl_match_array
180  int cp_user_abbr_hl_id;        ///< highlight group ID for abbr
181  int cp_user_kind_hl_id;        ///< highlight group ID for kind
182  int cp_cpt_source_idx;         ///< index of this match's source in 'cpt' option
183};
184
185/// state information used for getting the next set of insert completion
186/// matches.
187typedef struct {
188  char *e_cpt_copy;       ///< copy of 'complete'
189  char *e_cpt;            ///< current entry in "e_cpt_copy"
190  buf_T *ins_buf;         ///< buffer being scanned
191  pos_T *cur_match_pos;   ///< current match position
192  pos_T prev_match_pos;   ///< previous match position
193  bool set_match_pos;     ///< save first_match_pos/last_match_pos
194  pos_T first_match_pos;  ///< first match position
195  pos_T last_match_pos;   ///< last match position
196  bool found_all;         ///< found all matches of a certain type.
197  char *dict;             ///< dictionary file to search
198  int dict_f;             ///< "dict" is an exact file name or not
199  Callback *func_cb;      ///< callback of function in 'cpt' option
200} ins_compl_next_state_T;
201
202#include "insexpand.c.generated.h"
203
204/// values for cp_flags
205typedef enum {
206  CP_ORIGINAL_TEXT = 1,  ///< the original text when the expansion begun
207  CP_FREE_FNAME = 2,     ///< cp_fname is allocated
208  CP_CONT_S_IPOS = 4,    ///< use CONT_S_IPOS for compl_cont_status
209  CP_EQUAL = 8,          ///< ins_compl_equal() always returns true
210  CP_ICASE = 16,         ///< ins_compl_equal ignores case
211  CP_FAST = 32,          ///< use fast_breakcheck instead of os_breakcheck
212} cp_flags_T;
213
214static const char e_compldel[] = N_("E840: Completion function deleted text");
215
216// All the current matches are stored in a list.
217// "compl_first_match" points to the start of the list.
218// "compl_curr_match" points to the currently selected entry.
219// "compl_shown_match" is different from compl_curr_match during
220// ins_compl_get_exp(), when new matches are added to the list.
221// "compl_old_match" points to previous "compl_curr_match".
222
223static compl_T *compl_first_match = NULL;
224static compl_T *compl_curr_match = NULL;
225static compl_T *compl_shown_match = NULL;
226static compl_T *compl_old_match = NULL;
227static compl_T *compl_preselect_match = NULL;
228
229/// Hashtab with the strings of the matches in the list above, except the
230/// original-text entries.  Each entry owns a copy of the string and counts
231/// the matches with that string, so that when matches were added with "adup"
232/// the entry remains until the last match with the string is removed.
233typedef struct {
234  int cse_count;   // number of matches with this string
235  char cse_str[];  // the string
236} complstr_T;
237
238#define CSE_OFF         (offsetof(complstr_T, cse_str))
239#define HI2CSE(hi)      ((complstr_T *)((hi)->hi_key - CSE_OFF))
240
241static hashtab_T compl_strings_ht;
242
243/// Count the string of a new match in the duplicate-check hashtab.
244/// "hash" is the hash of "str" when it is not zero.
245static void compl_strings_add(const char *str, size_t len, hash_T hash)
246{
247  if (compl_strings_ht.ht_array == NULL) {
248    hash_init(&compl_strings_ht);
249  }
250  if (hash == 0) {
251    hash = hash_hash(str);
252  }
253  hashitem_T *hi = hash_lookup(&compl_strings_ht, str, len, hash);
254  if (HASHITEM_EMPTY(hi)) {
255    complstr_T *entry = xmalloc(CSE_OFF + len + 1);
256    entry->cse_count = 1;
257    xmemcpyz(entry->cse_str, str, len);
258    hash_add_item(&compl_strings_ht, hi, entry->cse_str, hash);
259  } else {
260    HI2CSE(hi)->cse_count++;
261  }
262}
263
264/// list used to store the compl_T which have the max score
265static compl_T **compl_best_matches = NULL;
266static int compl_num_bests = 0;
267
268/// After using a cursor key <Enter> selects a match in the popup menu,
269/// otherwise it inserts a line break.
270static bool compl_enter_selects = false;
271
272/// When "compl_leader" is not NULL only matches that start with this string
273/// are used.
274static String compl_leader = STRING_INIT;
275
276static bool compl_get_longest = false;  ///< put longest common string in compl_leader
277
278/// This flag is false when no match is selected (by ^N/^P) or the match was
279/// edited or using the longest common string.
280static bool compl_used_match;
281
282/// didn't finish finding completions.
283static bool compl_was_interrupted = false;
284
285// Set when character typed while looking for matches and it means we should
286// stop looking for matches.
287static bool compl_interrupted = false;
288
289static bool compl_restarting = false;   ///< don't insert match
290
291/// When the first completion is done "compl_started" is set.  When it's
292/// false the word to be completed must be located.
293static bool compl_started = false;
294
295/// Which Ctrl-X mode are we in?
296static int ctrl_x_mode = CTRL_X_NORMAL;
297
298static int compl_matches = 0;           ///< number of completion matches
299static String compl_pattern = STRING_INIT;      ///< search pattern for matching items
300static String cpt_compl_pattern = STRING_INIT;  ///< pattern returned by func in 'cpt'
301static Direction compl_direction = FORWARD;
302static Direction compl_shows_dir = FORWARD;
303static int compl_pending = 0;           ///< > 1 for postponed CTRL-N
304static pos_T compl_startpos;
305/// Length in bytes of the text being completed (this is deleted to be replaced
306/// by the match.)
307static int compl_length = 0;
308static linenr_T compl_lnum = 0;         ///< lnum where the completion start
309static colnr_T compl_col = 0;           ///< column where the text starts
310                                        ///< that is being completed
311static colnr_T compl_ins_end_col = 0;
312static colnr_T compl_longest_end_col = 0;  ///< end of 'longest' inserted text
313static String compl_orig_text = STRING_INIT;  ///< text as it was before
314                                              ///< completion started
315/// Undo information to restore extmarks for original text.
316static extmark_undo_vec_t compl_orig_extmarks;
317static int compl_cont_mode = 0;
318static expand_T compl_xp;
319
320static win_T *compl_curr_win = NULL;  ///< win where completion is active
321static buf_T *compl_curr_buf = NULL;  ///< buf where completion is active
322
323#define COMPL_INITIAL_TIMEOUT_MS    80
324// Autocomplete uses a decaying timeout: starting from COMPL_INITIAL_TIMEOUT_MS,
325// if the current source exceeds its timeout, it is interrupted and the next
326// begins with half the time. A small minimum timeout ensures every source
327// gets at least a brief chance.
328// Special case: when 'complete' contains "F" or "o" (function sources), a
329// longer fixed timeout is used (COMPL_FUNC_TIMEOUT_MS or
330// COMPL_FUNC_TIMEOUT_NON_KW_MS). - girish
331static bool compl_autocomplete = false;        ///< whether autocompletion is active
332static bool compl_autostarted = false;         ///< Vim started this completion
333static bool compl_autostart_pending = false;   ///< the trigger armed one
334static bool compl_autocomplete_pending = false;
335static uint64_t compl_autocomplete_start_tv;   ///< when the delay was armed
336static uint64_t compl_timeout_ms = COMPL_INITIAL_TIMEOUT_MS;
337static bool compl_time_slice_expired = false;  ///< time budget exceeded for current source
338static bool compl_from_nonkeyword = false;     ///< completion started from non-keyword
339static bool compl_hi_on_autocompl_longest = false;  ///< apply "PreInsert" highlight
340
341// Halve the current completion timeout, simulating exponential decay.
342#define COMPL_MIN_TIMEOUT_MS    5
343#define DECAY_COMPL_TIMEOUT() \
344  do { \
345    if (compl_timeout_ms > COMPL_MIN_TIMEOUT_MS) { \
346      compl_timeout_ms /= 2; \
347    } \
348  } while (0)
349
350// Timeout values for F{func}, F and o values in 'complete'
351#define COMPL_FUNC_TIMEOUT_MS           300
352#define COMPL_FUNC_TIMEOUT_NON_KW_MS    1000
353
354// List of flags for method of completion.
355static int compl_cont_status = 0;
356#define CONT_ADDING    1        ///< "normal" or "adding" expansion
357#define CONT_INTRPT    (2 + 4)  ///< a ^X interrupted the current expansion
358                                ///< it's set only iff N_ADDS is set
359#define CONT_N_ADDS    4        ///< next ^X<> will add-new or expand-current
360#define CONT_S_IPOS    8        ///< next ^X<> will set initial_pos?
361                                ///< if so, word-wise-expansion will set SOL
362#define CONT_SOL       16       ///< pattern includes start of line, just for
363                                ///< word-wise expansion, not set for ^X^L
364#define CONT_LOCAL     32       ///< for ctrl_x_mode 0, ^X^P/^X^N do a local
365                                ///< expansion, (eg use complete=.)
366
367static bool compl_opt_refresh_always = false;
368
369static size_t spell_bad_len = 0;   // length of located bad word
370
371static int compl_selected_item = -1;
372
373static int *compl_fuzzy_scores;
374
375/// Define the structure for completion source (in 'cpt' option) information
376typedef struct cpt_source_T {
377  bool cs_refresh_always;   ///< Whether 'refresh:always' is set for func
378  int cs_startcol;          ///< Start column returned by func
379  int cs_max_matches;       ///< Max items to display from this source
380  uint64_t compl_start_tv;  ///< Timestamp when match collection starts
381  char cs_flag;             ///< Flag indicating the type of source
382} cpt_source_T;
383
384/// Pointer to the array of completion sources
385static cpt_source_T *cpt_sources_array;
386/// Total number of completion sources specified in the 'cpt' option
387static int cpt_sources_count;
388/// Index of the current completion source being expanded
389static int cpt_sources_index = -1;
390
391// "compl_match_array" points the currently displayed list of entries in the
392// popup menu.  It is NULL when there is no popup menu.
393static pumitem_T *compl_match_array = NULL;
394static int compl_match_arraysize;
395
396/// CTRL-X pressed in Insert mode.
397void ins_ctrl_x(void)
398{
399  if (!ctrl_x_mode_cmdline()) {
400    // if the next ^X<> won't ADD nothing, then reset compl_cont_status
401    if (compl_cont_status & CONT_N_ADDS) {
402      compl_cont_status |= CONT_INTRPT;
403    } else {
404      compl_cont_status = 0;
405    }
406    // We're not sure which CTRL-X mode it will be yet
407    ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
408    edit_submode = _(CTRL_X_MSG(ctrl_x_mode));
409    edit_submode_pre = NULL;
410    redraw_mode = true;
411  } else {
412    // CTRL-X in CTRL-X CTRL-V mode behaves differently to make CTRL-X
413    // CTRL-V look like CTRL-N
414    ctrl_x_mode = CTRL_X_CMDLINE_CTRL_X;
415  }
416
417  may_trigger_modechanged();
418}
419
420// Functions to check the current CTRL-X mode.
421
422bool ctrl_x_mode_none(void)
423  FUNC_ATTR_PURE
424{
425  return ctrl_x_mode == 0;
426}
427
428bool ctrl_x_mode_normal(void)
429  FUNC_ATTR_PURE
430{
431  return ctrl_x_mode == CTRL_X_NORMAL;
432}
433
434bool ctrl_x_mode_scroll(void)
435  FUNC_ATTR_PURE
436{
437  return ctrl_x_mode == CTRL_X_SCROLL;
438}
439
440bool ctrl_x_mode_whole_line(void)
441  FUNC_ATTR_PURE
442{
443  return ctrl_x_mode == CTRL_X_WHOLE_LINE;
444}
445
446bool ctrl_x_mode_files(void)
447  FUNC_ATTR_PURE
448{
449  return ctrl_x_mode == CTRL_X_FILES;
450}
451
452bool ctrl_x_mode_tags(void)
453  FUNC_ATTR_PURE
454{
455  return ctrl_x_mode == CTRL_X_TAGS;
456}
457
458bool ctrl_x_mode_path_patterns(void)
459  FUNC_ATTR_PURE
460{
461  return ctrl_x_mode == CTRL_X_PATH_PATTERNS;
462}
463
464bool ctrl_x_mode_path_defines(void)
465  FUNC_ATTR_PURE
466{
467  return ctrl_x_mode == CTRL_X_PATH_DEFINES;
468}
469
470bool ctrl_x_mode_dictionary(void)
471  FUNC_ATTR_PURE
472{
473  return ctrl_x_mode == CTRL_X_DICTIONARY;
474}
475
476bool ctrl_x_mode_thesaurus(void)
477  FUNC_ATTR_PURE
478{
479  return ctrl_x_mode == CTRL_X_THESAURUS;
480}
481
482bool ctrl_x_mode_cmdline(void)
483  FUNC_ATTR_PURE
484{
485  return ctrl_x_mode == CTRL_X_CMDLINE || ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X;
486}
487
488bool ctrl_x_mode_function(void)
489  FUNC_ATTR_PURE
490{
491  return ctrl_x_mode == CTRL_X_FUNCTION;
492}
493
494bool ctrl_x_mode_omni(void)
495  FUNC_ATTR_PURE
496{
497  return ctrl_x_mode == CTRL_X_OMNI;
498}
499
500bool ctrl_x_mode_spell(void)
501  FUNC_ATTR_PURE
502{
503  return ctrl_x_mode == CTRL_X_SPELL;
504}
505
506bool ctrl_x_mode_eval(void)
507  FUNC_ATTR_PURE
508{
509  return ctrl_x_mode == CTRL_X_EVAL;
510}
511
512bool ctrl_x_mode_line_or_eval(void)
513  FUNC_ATTR_PURE
514{
515  return ctrl_x_mode == CTRL_X_WHOLE_LINE || ctrl_x_mode == CTRL_X_EVAL;
516}
517
518bool ctrl_x_mode_register(void)
519  FUNC_ATTR_PURE
520{
521  return ctrl_x_mode == CTRL_X_REGISTER;
522}
523
524/// Whether other than default completion has been selected.
525bool ctrl_x_mode_not_default(void)
526  FUNC_ATTR_PURE
527{
528  return ctrl_x_mode != CTRL_X_NORMAL;
529}
530
531/// Whether CTRL-X was typed without a following character,
532/// not including when in CTRL-X CTRL-V mode.
533bool ctrl_x_mode_not_defined_yet(void)
534  FUNC_ATTR_PURE
535{
536  return ctrl_x_mode == CTRL_X_NOT_DEFINED_YET;
537}
538
539/// @return  true if currently in "normal" or "adding" insert completion matches state
540bool compl_status_adding(void)
541{
542  return compl_cont_status & CONT_ADDING;
543}
544
545/// @return  true if the completion pattern includes start of line, just for
546///          word-wise expansion.
547bool compl_status_sol(void)
548{
549  return compl_cont_status & CONT_SOL;
550}
551
552/// @return  true if ^X^P/^X^N will do a local completion (i.e. use complete=.)
553bool compl_status_local(void)
554{
555  return compl_cont_status & CONT_LOCAL;
556}
557
558/// Clear the completion status flags
559void compl_status_clear(void)
560{
561  compl_cont_status = 0;
562}
563
564/// @return  true if completion is using the forward direction matches
565static bool compl_dir_forward(void)
566{
567  return compl_direction == FORWARD;
568}
569
570/// @return  true if currently showing forward completion matches
571static bool compl_shows_dir_forward(void)
572{
573  return compl_shows_dir == FORWARD;
574}
575
576/// @return  true if currently showing backward completion matches
577static bool compl_shows_dir_backward(void)
578{
579  return compl_shows_dir == BACKWARD;
580}
581
582/// Check that the 'dictionary' or 'thesaurus' option can be used.
583///
584/// @param  dict_opt  check 'dictionary' when true, 'thesaurus' when false.
585bool check_compl_option(bool dict_opt)
586{
587  if (dict_opt
588      ? (*curbuf->b_p_dict == NUL && *p_dict == NUL && !curwin->w_p_spell)
589      : (*curbuf->b_p_tsr == NUL && *p_tsr == NUL
590         && curbuf->b_p_tsrfu.type == kCallbackNone && p_tsrfu.type == kCallbackNone)) {
591    ctrl_x_mode = CTRL_X_NORMAL;
592    edit_submode = NULL;
593    emsg(dict_opt ? _("'dictionary' option is empty") : _("'thesaurus' option is empty"));
594    if (emsg_silent == 0 && !in_assert_fails) {
595      vim_beep(kOptBoFlagComplete);
596      setcursor();
597      msg_delay(2004, false);
598    }
599    return false;
600  }
601  return true;
602}
603
604/// Check that the character "c" a valid key to go to or keep us in CTRL-X mode?
605/// This depends on the current mode.
606///
607/// @param  c  character to check
608bool vim_is_ctrl_x_key(int c)
609  FUNC_ATTR_WARN_UNUSED_RESULT
610{
611  // Accept <PageUp> and <PageDown> if the popup menu is visible.
612  if (ins_compl_pum_key(c)) {
613    return true;
614  }
615
616  switch (ctrl_x_mode) {
617  case 0:  // Not in any CTRL-X mode
618    return c == Ctrl_N || c == Ctrl_P || c == Ctrl_X;
619  case CTRL_X_NOT_DEFINED_YET:
620  case CTRL_X_CMDLINE_CTRL_X:
621    return c == Ctrl_X || c == Ctrl_Y || c == Ctrl_E
622           || c == Ctrl_L || c == Ctrl_F || c == Ctrl_RSB
623           || c == Ctrl_I || c == Ctrl_D || c == Ctrl_P
624           || c == Ctrl_N || c == Ctrl_T || c == Ctrl_V
625           || c == Ctrl_Q || c == Ctrl_U || c == Ctrl_O
626           || c == Ctrl_S || c == Ctrl_K || c == 's'
627           || c == Ctrl_Z || c == Ctrl_R;
628  case CTRL_X_SCROLL:
629    return c == Ctrl_Y || c == Ctrl_E;
630  case CTRL_X_WHOLE_LINE:
631    return c == Ctrl_L || c == Ctrl_P || c == Ctrl_N;
632  case CTRL_X_FILES:
633    return c == Ctrl_F || c == Ctrl_P || c == Ctrl_N;
634  case CTRL_X_DICTIONARY:
635    return c == Ctrl_K || c == Ctrl_P || c == Ctrl_N;
636  case CTRL_X_THESAURUS:
637    return c == Ctrl_T || c == Ctrl_P || c == Ctrl_N;
638  case CTRL_X_TAGS:
639    return c == Ctrl_RSB || c == Ctrl_P || c == Ctrl_N;
640  case CTRL_X_PATH_PATTERNS:
641    return c == Ctrl_P || c == Ctrl_N;
642  case CTRL_X_PATH_DEFINES:
643    return c == Ctrl_D || c == Ctrl_P || c == Ctrl_N;
644  case CTRL_X_CMDLINE:
645    return c == Ctrl_V || c == Ctrl_Q || c == Ctrl_P || c == Ctrl_N
646           || c == Ctrl_X;
647  case CTRL_X_FUNCTION:
648    return c == Ctrl_U || c == Ctrl_P || c == Ctrl_N;
649  case CTRL_X_OMNI:
650    return c == Ctrl_O || c == Ctrl_P || c == Ctrl_N;
651  case CTRL_X_SPELL:
652    return c == Ctrl_S || c == Ctrl_P || c == Ctrl_N;
653  case CTRL_X_EVAL:
654    return (c == Ctrl_P || c == Ctrl_N);
655  case CTRL_X_BUFNAMES:
656    return (c == Ctrl_P || c == Ctrl_N);
657  case CTRL_X_REGISTER:
658    return (c == Ctrl_R || c == Ctrl_P || c == Ctrl_N);
659  }
660  internal_error("vim_is_ctrl_x_key()");
661  return false;
662}
663
664/// @return  true if "match" is the original text when the completion began.
665static bool match_at_original_text(const compl_T *const match)
666{
667  return match->cp_flags & CP_ORIGINAL_TEXT;
668}
669
670/// @return  true if "match" is the first match in the completion list.
671static bool is_first_match(const compl_T *const match)
672{
673  return match == compl_first_match;
674}
675
676/// Return the entry holding the original text, NULL if not found.
677/// It is the first item, or the last one for backward completion.
678static compl_T *find_original_text_match(void)
679{
680  if (compl_first_match == NULL) {
681    return NULL;
682  }
683  if (match_at_original_text(compl_first_match)) {
684    return compl_first_match;
685  }
686  if (compl_first_match->cp_prev != NULL
687      && match_at_original_text(compl_first_match->cp_prev)) {
688    return compl_first_match->cp_prev;
689  }
690  return NULL;
691}
692
693static void do_autocmd_completedone(int c, int mode, String *word)
694{
695  save_v_event_T save_v_event;
696  dict_T *v_event = get_v_event(&save_v_event);
697
698  if (word == NULL || word->data == NULL) {
699    tv_dict_add_str_len(v_event, S_LEN("complete_word"), "", 0);
700  } else {
701    tv_dict_add_str_len(v_event, S_LEN("complete_word"), word->data, (int)word->size);
702  }
703
704  String *mode_str = &ctrl_x_mode_names[mode & ~CTRL_X_WANT_IDENT];
705  tv_dict_add_str_len(v_event, S_LEN("complete_type"),
706                      mode_str->data == NULL ? "" : mode_str->data,
707                      (int)mode_str->size);
708
709  tv_dict_add_str(v_event, S_LEN("reason"),
710                  (c == Ctrl_Y || (word != NULL && word->data != NULL)
711                   ? "accept" : (c == Ctrl_E ? "cancel" : "discard")));
712  tv_dict_set_keys_readonly(v_event);
713
714  ins_apply_autocmds(EVENT_COMPLETEDONE);
715  restore_v_event(v_event, &save_v_event);
716}
717
718/// Check that character "c" is part of the item currently being
719/// completed.  Used to decide whether to abandon complete mode when the menu
720/// is visible.
721///
722/// @param  c  character to check
723bool ins_compl_accept_char(int c)
724  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
725{
726  if (compl_autocomplete && compl_from_nonkeyword) {
727    return false;
728  }
729
730  if (ctrl_x_mode & CTRL_X_WANT_IDENT) {
731    // When expanding an identifier only accept identifier chars.
732    return vim_isIDc(c);
733  }
734
735  switch (ctrl_x_mode) {
736  case CTRL_X_FILES:
737    // When expanding file name only accept file name chars. But not
738    // path separators, so that "proto/<Tab>" expands files in
739    // "proto", not "proto/" as a whole
740    return vim_isfilec(c) && !vim_ispathsep(c);
741
742  case CTRL_X_CMDLINE:
743  case CTRL_X_CMDLINE_CTRL_X:
744  case CTRL_X_OMNI:
745    // Command line and Omni completion can work with just about any
746    // printable character, but do stop at white space.
747    return vim_isprintc(c) && !ascii_iswhite(c);
748
749  case CTRL_X_WHOLE_LINE:
750    // For while line completion a space can be part of the line.
751    return vim_isprintc(c);
752  }
753  return vim_iswordc(c);
754}
755
756/// Check if "c" is a commit character for the currently selected completion
757/// match: typing it accepts the match, then "c" is inserted as usual.
758/// Set with the "commit_chars" item property, see |complete-items|.
759bool ins_compl_commit_char(int c)
760{
761  // Control characters and special keys (negative) are never commit
762  // characters: CR/NL must keep their compl_enter_selects semantics.
763  if (c < ' ') {
764    return false;
765  }
766  return compl_shown_match != NULL
767         && !match_at_original_text(compl_shown_match)
768         && compl_shown_match->cp_commit_chars != NULL
769         && vim_strchr(compl_shown_match->cp_commit_chars, c) != NULL;
770}
771
772/// Get the completed text by inferring the case of the originally typed text.
773/// If the result is in allocated memory "tofree" is set to it.
774static char *ins_compl_infercase_gettext(const char *str, int char_len, int compl_char_len,
775                                         int min_len, char **tofree)
776{
777  bool has_lower = false;
778
779  // Allocate wide character array for the completion and fill it.
780  int *const wca = xmalloc((size_t)char_len * sizeof(*wca));
781  {
782    const char *p = str;
783    for (int i = 0; i < char_len; i++) {
784      wca[i] = mb_ptr2char_adv(&p);
785    }
786  }
787
788  // Rule 1: Were any chars converted to lower?
789  {
790    const char *p = compl_orig_text.data;
791    for (int i = 0; i < min_len; i++) {
792      const int c = mb_ptr2char_adv(&p);
793      if (mb_islower(c)) {
794        has_lower = true;
795        if (mb_isupper(wca[i])) {
796          // Rule 1 is satisfied.
797          for (i = compl_char_len; i < char_len; i++) {
798            wca[i] = mb_tolower(wca[i]);
799          }
800          break;
801        }
802      }
803    }
804  }
805
806  // Rule 2: No lower case, 2nd consecutive letter converted to
807  // upper case.
808  if (!has_lower) {
809    bool was_letter = false;
810    const char *p = compl_orig_text.data;
811    for (int i = 0; i < min_len; i++) {
812      const int c = mb_ptr2char_adv(&p);
813      if (was_letter && mb_isupper(c) && mb_islower(wca[i])) {
814        // Rule 2 is satisfied.
815        for (i = compl_char_len; i < char_len; i++) {
816          wca[i] = mb_toupper(wca[i]);
817        }
818        break;
819      }
820      was_letter = mb_islower(c) || mb_isupper(c);
821    }
822  }
823
824  // Copy the original case of the part we typed.
825  {
826    const char *p = compl_orig_text.data;
827    for (int i = 0; i < min_len; i++) {
828      const int c = mb_ptr2char_adv(&p);
829      if (mb_islower(c)) {
830        wca[i] = mb_tolower(wca[i]);
831      } else if (mb_isupper(c)) {
832        wca[i] = mb_toupper(wca[i]);
833      }
834    }
835  }
836
837  // Generate encoding specific output from wide character array.
838  garray_T gap;
839  char *p = IObuff;
840  int i = 0;
841  ga_init(&gap, 1, 500);
842  while (i < char_len) {
843    if (gap.ga_data != NULL) {
844      ga_grow(&gap, 10);
845      assert(gap.ga_data != NULL);  // suppress clang "Dereference of NULL pointer"
846      p = (char *)gap.ga_data + gap.ga_len;
847      gap.ga_len += utf_char2bytes(wca[i++], p);
848    } else if ((p - IObuff) + 6 >= IOSIZE) {
849      // Multi-byte characters can occupy up to five bytes more than
850      // ASCII characters, and we also need one byte for NUL, so when
851      // getting to six bytes from the edge of IObuff switch to using a
852      // growarray.  Add the character in the next round.
853      ga_grow(&gap, IOSIZE);
854      *p = NUL;
855      STRCPY(gap.ga_data, IObuff);
856      gap.ga_len = (int)(p - IObuff);
857    } else {
858      p += utf_char2bytes(wca[i++], p);
859    }
860  }
861  xfree(wca);
862
863  if (gap.ga_data != NULL) {
864    *tofree = gap.ga_data;
865    return gap.ga_data;
866  }
867
868  *p = NUL;
869  return IObuff;
870}
871
872/// This is like ins_compl_add(), but if 'ic' and 'inf' are set, then the
873/// case of the originally typed text is used, and the case of the completed
874/// text is inferred, ie this tries to work out what case you probably wanted
875/// the rest of the word to be in -- webb
876///
877/// @param[in]  cont_s_ipos  next ^X<> will set initial_pos
878int ins_compl_add_infercase(char *str_arg, int len, bool icase, char *fname, Direction dir,
879                            bool cont_s_ipos, int score)
880  FUNC_ATTR_NONNULL_ARG(1)
881{
882  char *str = str_arg;
883  int char_len;  // count multi-byte characters
884  int compl_char_len;
885  int flags = 0;
886  char *tofree = NULL;
887
888  if (p_ic && curbuf->b_p_inf && len > 0) {
889    // Infer case of completed part.
890
891    // Find actual length of completion.
892    {
893      const char *p = str;
894      char_len = 0;
895      while (*p != NUL) {
896        MB_PTR_ADV(p);
897        char_len++;
898      }
899    }
900
901    // Find actual length of original text.
902    {
903      const char *p = compl_orig_text.data;
904      compl_char_len = 0;
905      while (*p != NUL) {
906        MB_PTR_ADV(p);
907        compl_char_len++;
908      }
909    }
910
911    // "char_len" may be smaller than "compl_char_len" when using
912    // thesaurus, only use the minimum when comparing.
913    int min_len = MIN(char_len, compl_char_len);
914
915    str = ins_compl_infercase_gettext(str, char_len, compl_char_len, min_len, &tofree);
916  }
917  if (cont_s_ipos) {
918    flags |= CP_CONT_S_IPOS;
919  }
920  if (icase) {
921    flags |= CP_ICASE;
922  }
923
924  int res = ins_compl_add(str, len, fname, NULL, false, NULL, dir, flags, false, NULL, score,
925                          false, NULL);
926  xfree(tofree);
927  return res;
928}
929
930/// free cptext
931static inline void free_cptext(char *const *const cptext)
932{
933  if (cptext != NULL) {
934    for (size_t i = 0; i < CPT_COUNT; i++) {
935      xfree(cptext[i]);
936    }
937  }
938}
939
940/// Check if fuzzy matching is enabled
941static bool cot_fuzzy(void)
942{
943  return (get_cot_flags() & kOptCotFlagFuzzy) != 0 && !ctrl_x_mode_thesaurus();
944}
945
946/// Returns true if matches should be sorted based on proximity to the cursor.
947static bool is_nearest_active(void)
948{
949  return (compl_autocomplete || (get_cot_flags() & kOptCotFlagNearest))
950         && !cot_fuzzy();
951}
952
953/// True if a match is selected (even if it is not inserted).
954bool ins_compl_is_match_selected(void)
955{
956  return compl_shown_match != NULL && !is_first_match(compl_shown_match);
957}
958
959/// Returns true if autocomplete is active and the pre-insert effect targets the
960/// longest prefix.
961bool ins_compl_preinsert_longest(void)
962{
963  return compl_autocomplete
964         && (get_cot_flags() & (kOptCotFlagLongest | kOptCotFlagPreinsert | kOptCotFlagFuzzy))
965         == kOptCotFlagLongest;
966}
967
968/// Add a match to the list of matches
969///
970/// @param[in]  str     text of the match to add
971/// @param[in]  len     length of "str". If -1, then the length of "str" is computed.
972/// @param[in]  fname   file name to associate with this match. May be NULL.
973/// @param[in]  cptext  list of strings to use with this match (for abbr, menu, info
974///                     and kind). May be NULL.
975///                     If not NULL, must have exactly #CPT_COUNT items.
976/// @param[in]  cptext_allocated  If true, will not copy cptext strings.
977///
978///                               @note Will free strings in case of error.
979///                                     cptext itself will not be freed.
980/// @param[in]  user_data  user supplied data (any vim type) for this match
981/// @param[in]  cdir       match direction. If 0, use "compl_direction".
982/// @param[in]  flags_arg  match flags (cp_flags)
983/// @param[in]  adup       accept this match even if it is already present.
984/// @param[in]  user_hl    list of extra highlight attributes for abbr kind.
985/// @param[in]  commit_chars  commit characters for this match. May be NULL.
986///                           Must be allocated, ownership is transferred:
987///                           freed here when the match is not added.
988///
989/// If "cdir" is FORWARD, then the match is added after the current match.
990/// Otherwise, it is added before the current match.
991///
992/// @return NOTDONE if the given string is already in the list of completions,
993///         otherwise it is added to the list and  OK is returned. FAIL will be
994///         returned in case of error.
995static int ins_compl_add(char *const str, int len, char *const fname, char *const *const cptext,
996                         const bool cptext_allocated, typval_T *user_data, const Direction cdir,
997                         int flags_arg, const bool adup, const int *user_hl, const int score,
998                         bool preselect, char *const commit_chars)
999  FUNC_ATTR_NONNULL_ARG(1)
1000{
1001  compl_T *match;
1002  const Direction dir = (cdir == kDirectionNotSet ? compl_direction : cdir);
1003  int flags = flags_arg;
1004  bool inserted = false;
1005  char *new_str = NULL;
1006  hash_T str_hash = 0;  // hash of the match string, when not 0
1007
1008  if (flags & CP_FAST) {
1009    fast_breakcheck();
1010  } else {
1011    os_breakcheck();
1012  }
1013  if (got_int) {
1014    if (cptext_allocated) {
1015      free_cptext(cptext);
1016    }
1017    xfree(commit_chars);
1018    return FAIL;
1019  }
1020  if (len < 0) {
1021    len = (int)strlen(str);
1022  }
1023
1024  // If the same match is already present, don't add it.
1025  if (compl_first_match != NULL && !adup && compl_strings_ht.ht_used > 0) {
1026    // The key must be NUL terminated.
1027    char keybuf[128];
1028    char *key;
1029    if (len < (int)sizeof(keybuf)) {
1030      memmove(keybuf, str, (size_t)len);
1031      keybuf[len] = NUL;
1032      key = keybuf;
1033    } else {
1034      new_str = xstrnsave(str, (size_t)len);
1035      key = new_str;
1036    }
1037    str_hash = hash_hash(key);
1038    hashitem_T *hi = hash_lookup(&compl_strings_ht, key, (size_t)len, str_hash);
1039    if (!HASHITEM_EMPTY(hi)) {
1040      if (is_nearest_active() && score > 0) {
1041        // The duplicate may need its score updated, scan the
1042        // matches to find it.
1043        match = compl_first_match;
1044        do {
1045          if (!match_at_original_text(match)
1046              && strncmp(match->cp_str.data, str, (size_t)len) == 0
1047              && ((int)match->cp_str.size <= len || match->cp_str.data[len] == NUL)) {
1048            if (score < match->cp_score) {
1049              match->cp_score = score;
1050            }
1051            break;
1052          }
1053          match = match->cp_next;
1054        } while (match != NULL && !is_first_match(match));
1055      }
1056      xfree(new_str);
1057      if (cptext_allocated) {
1058        free_cptext(cptext);
1059      }
1060      xfree(commit_chars);
1061      return NOTDONE;
1062    }
1063  }
1064
1065  // Remove any popup menu before changing the list of matches.
1066  ins_compl_del_pum();
1067
1068  // Allocate a new match structure.
1069  // Copy the values to the new match structure.
1070  match = xcalloc(1, sizeof(compl_T));
1071  match->cp_number = flags & CP_ORIGINAL_TEXT ? 0 : -1;
1072  new_str = new_str == NULL ? xstrnsave(str, (size_t)len) : new_str;
1073  match->cp_str = cbuf_as_string(new_str, (size_t)len);
1074  match->cp_commit_chars = commit_chars;
1075  match->cp_preselect = preselect;
1076  if (preselect && compl_preselect_match == NULL
1077      && (get_cot_flags() & kOptCotFlagPreselect)) {
1078    compl_preselect_match = match;
1079  }
1080
1081  // match-fname is:
1082  // - compl_curr_match->cp_fname if it is a string equal to fname.
1083  // - a copy of fname, CP_FREE_FNAME is set to free later THE allocated mem.
1084  // - NULL otherwise.  --Acevedo
1085  if (fname != NULL
1086      && compl_curr_match != NULL
1087      && compl_curr_match->cp_fname != NULL
1088      && strcmp(fname, compl_curr_match->cp_fname) == 0) {
1089    match->cp_fname = compl_curr_match->cp_fname;
1090  } else if (fname != NULL) {
1091    match->cp_fname = xstrdup(fname);
1092    flags |= CP_FREE_FNAME;
1093  } else {
1094    match->cp_fname = NULL;
1095  }
1096  match->cp_flags = flags;
1097  match->cp_user_abbr_hl_id = user_hl ? user_hl[0] : 0;
1098  match->cp_user_kind_hl_id = user_hl ? user_hl[1] : 0;
1099  match->cp_score = score;
1100  match->cp_cpt_source_idx = cpt_sources_index;
1101
1102  if (cptext != NULL) {
1103    for (int i = 0; i < CPT_COUNT; i++) {
1104      if (cptext[i] == NULL) {
1105        continue;
1106      }
1107      if (*cptext[i] != NUL) {
1108        match->cp_text[i] = (cptext_allocated ? cptext[i] : xstrdup(cptext[i]));
1109      } else if (cptext_allocated) {
1110        xfree(cptext[i]);
1111      }
1112    }
1113  }
1114
1115  if (user_data != NULL) {
1116    match->cp_user_data = *user_data;
1117  }
1118
1119  // Link the new match structure after (FORWARD) or before (BACKWARD) the
1120  // current match in the list of matches .
1121  if (compl_first_match == NULL) {
1122    match->cp_next = match->cp_prev = NULL;
1123  } else if (cot_fuzzy() && score != FUZZY_SCORE_NONE && compl_get_longest) {
1124    compl_T *current = compl_first_match->cp_next;
1125    compl_T *prev = compl_first_match;
1126    inserted = false;
1127    // The direction is ignored when using longest and fuzzy match, because
1128    // matches are inserted and sorted by score.
1129    while (current != NULL && current != compl_first_match) {
1130      if (current->cp_score < score) {
1131        match->cp_next = current;
1132        match->cp_prev = current->cp_prev;
1133        if (current->cp_prev) {
1134          current->cp_prev->cp_next = match;
1135        }
1136        current->cp_prev = match;
1137        inserted = true;
1138        break;
1139      }
1140      prev = current;
1141      current = current->cp_next;
1142    }
1143    if (!inserted) {
1144      prev->cp_next = match;
1145      match->cp_prev = prev;
1146      match->cp_next = compl_first_match;
1147      compl_first_match->cp_prev = match;
1148    }
1149  } else if (dir == FORWARD) {
1150    match->cp_next = compl_curr_match->cp_next;
1151    match->cp_prev = compl_curr_match;
1152  } else {    // BACKWARD
1153    match->cp_next = compl_curr_match;
1154    match->cp_prev = compl_curr_match->cp_prev;
1155  }
1156  if (match->cp_next) {
1157    match->cp_next->cp_prev = match;
1158  }
1159  if (match->cp_prev) {
1160    match->cp_prev->cp_next = match;
1161  } else {        // if there's nothing before, it is the first match
1162    compl_first_match = match;
1163  }
1164  compl_curr_match = match;
1165
1166  if (!match_at_original_text(match)) {
1167    compl_strings_add(match->cp_str.data, match->cp_str.size, str_hash);
1168  }
1169
1170  // Find the longest common string if still doing that.
1171  if (compl_get_longest && (flags & CP_ORIGINAL_TEXT) == 0 && !cot_fuzzy()
1172      && !ins_compl_preinsert_longest() && !ctrl_x_mode_thesaurus()) {
1173    ins_compl_longest_match(match);
1174  }
1175
1176  return OK;
1177}
1178
1179/// Check that "str[len]" matches with "match->cp_str", considering
1180/// "match->cp_flags".
1181///
1182/// @param  match  completion match
1183/// @param  str    character string to check
1184/// @param  len    length of "str"
1185static bool ins_compl_equal(compl_T *match, char *str, size_t len)
1186  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
1187{
1188  if (match->cp_flags & CP_EQUAL) {
1189    return true;
1190  }
1191  if (match->cp_flags & CP_ICASE) {
1192    return STRNICMP(match->cp_str.data, str, len) == 0;
1193  }
1194  return strncmp(match->cp_str.data, str, len) == 0;
1195}
1196
1197/// Like ins_compl_equal(), but ignore case in the 'longest'-inserted part of
1198/// the leader, so CTRL-N and CTRL-P filter the same way.
1199static bool ins_compl_equal_sc(compl_T *match, char *str, size_t len)
1200  FUNC_ATTR_NONNULL_ALL
1201{
1202  int typed = compl_length;
1203  int longest_end = (compl_get_longest && compl_longest_end_col > compl_col)
1204                    ? (int)(compl_longest_end_col - compl_col) : typed;
1205
1206  if ((match->cp_flags & (CP_EQUAL | CP_ICASE)) || longest_end <= typed) {
1207    return ins_compl_equal(match, str, len);
1208  }
1209
1210  if (match->cp_str.size < len) {
1211    return false;
1212  }
1213
1214  for (int i = 0; (size_t)i < len; i++) {
1215    if (i >= typed && i < longest_end
1216        ? TOLOWER_LOC((uint8_t)match->cp_str.data[i]) != TOLOWER_LOC((uint8_t)str[i])
1217        : match->cp_str.data[i] != str[i]) {
1218      return false;
1219    }
1220  }
1221  return true;
1222}
1223
1224/// when len is -1 mean use whole length of p otherwise part of p
1225static void ins_compl_insert_bytes(char *p, int len)
1226  FUNC_ATTR_NONNULL_ALL
1227{
1228  if (len == -1) {
1229    len = (int)strlen(p);
1230  }
1231  assert(len >= 0);
1232  ins_bytes_len(p, (size_t)len);
1233  compl_ins_end_col = curwin->w_cursor.col;
1234}
1235
1236/// Get current completion leader
1237char *ins_compl_leader(void)
1238{
1239  return compl_leader.data != NULL ? compl_leader.data : compl_orig_text.data;
1240}
1241
1242/// Get current completion leader length
1243static size_t ins_compl_leader_len(void)
1244{
1245  return compl_leader.data != NULL ? compl_leader.size : compl_orig_text.size;
1246}
1247
1248/// Checks if the column is within the currently inserted completion text
1249/// column range. If it is, it returns a special highlight attribute.
1250/// -1 means normal item.
1251int ins_compl_col_range_attr(linenr_T lnum, int col)
1252{
1253  const bool has_preinsert = ins_compl_has_preinsert() || ins_compl_preinsert_longest();
1254
1255  int attr;
1256  if (cot_fuzzy()
1257      || (!compl_hi_on_autocompl_longest && ins_compl_preinsert_longest())
1258      || (attr = syn_name2attr(has_preinsert ? "PreInsert" : "ComplMatchIns")) == 0) {
1259    return -1;
1260  }
1261
1262  int start_col = compl_col + (int)ins_compl_leader_len();
1263  if (!ins_compl_has_multiple()) {
1264    return (col >= start_col && col < compl_ins_end_col) ? attr : -1;
1265  }
1266
1267  // Multiple lines
1268  if ((lnum == compl_lnum && col >= start_col && col < MAXCOL)
1269      || (lnum > compl_lnum && lnum < curwin->w_cursor.lnum)
1270      || (lnum == curwin->w_cursor.lnum && col <= compl_ins_end_col)) {
1271    return attr;
1272  }
1273
1274  return -1;
1275}
1276
1277/// Returns true if the current completion string contains newline characters,
1278/// indicating it's a multi-line completion.
1279static bool ins_compl_has_multiple(void)
1280{
1281  return vim_strchr(compl_shown_match->cp_str.data, '\n') != NULL;
1282}
1283
1284/// Returns true if the given line number falls within the range of a multi-line
1285/// completion, i.e. between the starting line (compl_lnum) and current cursor
1286/// line. Always returns false for single-line completions.
1287bool ins_compl_lnum_in_range(linenr_T lnum)
1288{
1289  if (!ins_compl_has_multiple()) {
1290    return false;
1291  }
1292  return lnum >= compl_lnum && lnum <= curwin->w_cursor.lnum;
1293}
1294
1295/// Reduce the longest common string for match "match".
1296static void ins_compl_longest_match(compl_T *match)
1297{
1298  if (compl_leader.data == NULL) {
1299    // First match, use it as a whole.
1300    compl_leader = copy_string(match->cp_str, NULL);
1301
1302    bool had_match = (curwin->w_cursor.col > compl_col);
1303    ins_compl_longest_insert(compl_leader.data);
1304
1305    // When the match isn't there (to avoid matching itself) remove it
1306    // again after redrawing.
1307    if (!had_match) {
1308      ins_compl_delete(false);
1309    }
1310    compl_used_match = false;
1311
1312    return;
1313  }
1314
1315  // Reduce the text if this match differs from compl_leader.
1316  char *p = compl_leader.data;
1317  char *s = match->cp_str.data;
1318  while (*p != NUL) {
1319    int c1 = utf_ptr2char(p);
1320    int c2 = utf_ptr2char(s);
1321
1322    if ((match->cp_flags & CP_ICASE)
1323        ? (mb_tolower(c1) != mb_tolower(c2))
1324        : (c1 != c2)) {
1325      break;
1326    }
1327    MB_PTR_ADV(p);
1328    MB_PTR_ADV(s);
1329  }
1330
1331  if (*p != NUL) {
1332    // Leader was shortened, need to change the inserted text.
1333    *p = NUL;
1334    compl_leader.size = (size_t)(p - compl_leader.data);
1335
1336    bool had_match = (curwin->w_cursor.col > compl_col);
1337    ins_compl_longest_insert(compl_leader.data);
1338
1339    // When the match isn't there (to avoid matching itself) remove it
1340    // again after redrawing.
1341    if (!had_match) {
1342      ins_compl_delete(false);
1343    }
1344  }
1345
1346  compl_used_match = false;
1347}
1348
1349/// Add an array of matches to the list of matches.
1350/// Frees matches[].
1351static void ins_compl_add_matches(int num_matches, char **matches, int icase)
1352{
1353  int add_r = OK;
1354  Direction dir = compl_direction;
1355
1356  for (int i = 0; i < num_matches && add_r != FAIL; i++) {
1357    add_r = ins_compl_add(matches[i], -1, NULL, NULL, false, NULL, dir,
1358                          CP_FAST | (icase ? CP_ICASE : 0), false, NULL,
1359                          FUZZY_SCORE_NONE, false, NULL);
1360    if (add_r == OK) {
1361      // If dir was BACKWARD then honor it just once.
1362      dir = FORWARD;
1363    }
1364  }
1365  FreeWild(num_matches, matches);
1366}
1367
1368/// Make the completion list cyclic.
1369/// Return the number of matches (excluding the original).
1370static int ins_compl_make_cyclic(void)
1371{
1372  if (compl_first_match == NULL) {
1373    return 0;
1374  }
1375
1376  // Find the end of the list.
1377  compl_T *match = compl_first_match;
1378  int count = 0;
1379  // there's always an entry for the compl_orig_text, it doesn't count.
1380  while (match->cp_next != NULL && !is_first_match(match->cp_next)) {
1381    match = match->cp_next;
1382    count++;
1383  }
1384  match->cp_next = compl_first_match;
1385  compl_first_match->cp_prev = match;
1386
1387  return count;
1388}
1389
1390/// Return whether there currently is a shown match.
1391bool ins_compl_has_shown_match(void)
1392{
1393  return compl_shown_match == NULL || compl_shown_match != compl_shown_match->cp_next;
1394}
1395
1396/// Return whether the shown match is long enough.
1397bool ins_compl_long_shown_match(void)
1398{
1399  return compl_shown_match != NULL && compl_shown_match->cp_str.data != NULL
1400         && (colnr_T)compl_shown_match->cp_str.size > curwin->w_cursor.col - compl_col;
1401}
1402
1403/// Get the local or global value of 'completeopt' flags.
1404unsigned get_cot_flags(void)
1405{
1406  return curbuf->b_cot_flags != 0 ? curbuf->b_cot_flags : cot_flags;
1407}
1408
1409/// Remove any popup menu.
1410static void ins_compl_del_pum(void)
1411{
1412  if (compl_match_array == NULL) {
1413    return;
1414  }
1415
1416  pum_undisplay(false);
1417  XFREE_CLEAR(compl_match_array);
1418}
1419
1420/// Check if the popup menu should be displayed.
1421bool pum_wanted(void)
1422  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
1423{
1424  // "completeopt" must contain "menu" or "menuone"
1425  return (get_cot_flags() & (kOptCotFlagMenu | kOptCotFlagMenuone)) != 0 || compl_autocomplete;
1426}
1427
1428/// Check that there are two or more matches to be shown in the popup menu.
1429/// One if "completopt" contains "menuone".
1430static bool pum_enough_matches(void)
1431  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
1432{
1433  // Don't display the popup menu if there are no matches or there is only
1434  // one (ignoring the original text).
1435  compl_T *comp = compl_first_match;
1436  int i = 0;
1437  do {
1438    if (comp == NULL || (!match_at_original_text(comp) && ++i == 2)) {
1439      break;
1440    }
1441    comp = comp->cp_next;
1442  } while (!is_first_match(comp));
1443
1444  if ((get_cot_flags() & kOptCotFlagMenuone) || compl_autocomplete) {
1445    return i >= 1;
1446  }
1447  return i >= 2;
1448}
1449
1450/// Convert to complete item dict
1451static dict_T *ins_compl_dict_alloc(compl_T *match)
1452{
1453  // { word, abbr, menu, kind, info }
1454  dict_T *dict = tv_dict_alloc_lock(VAR_FIXED);
1455  fill_complete_info_dict(dict, match, false);
1456  return dict;
1457}
1458
1459/// Trigger the CompleteChanged autocmd event. Invoked each time the Insert mode
1460/// completion menu is changed.
1461static void trigger_complete_changed_event(int cur)
1462{
1463  static bool recursive = false;
1464  save_v_event_T save_v_event;
1465
1466  if (recursive) {
1467    return;
1468  }
1469
1470  dict_T *item = cur < 0 ? tv_dict_alloc() : ins_compl_dict_alloc(compl_curr_match);
1471  dict_T *v_event = get_v_event(&save_v_event);
1472  tv_dict_add_dict(v_event, S_LEN("completed_item"), item);
1473  pum_set_event_info(v_event);
1474  tv_dict_set_keys_readonly(v_event);
1475
1476  recursive = true;
1477  textlock++;
1478  apply_autocmds(EVENT_COMPLETECHANGED, NULL, NULL, false, curbuf);
1479  textlock--;
1480  recursive = false;
1481
1482  restore_v_event(v_event, &save_v_event);
1483}
1484
1485// Helper functions for mergesort_list().
1486
1487static void *cp_get_next(void *node)
1488{
1489  return ((compl_T *)node)->cp_next;
1490}
1491
1492static void cp_set_next(void *node, void *next)
1493{
1494  ((compl_T *)node)->cp_next = (compl_T *)next;
1495}
1496
1497static void *cp_get_prev(void *node)
1498{
1499  return ((compl_T *)node)->cp_prev;
1500}
1501
1502static void cp_set_prev(void *node, void *prev)
1503{
1504  ((compl_T *)node)->cp_prev = (compl_T *)prev;
1505}
1506
1507static int cp_compare_fuzzy(const void *a, const void *b)
1508{
1509  int score_a = ((compl_T *)a)->cp_score;
1510  int score_b = ((compl_T *)b)->cp_score;
1511  return (score_b > score_a) ? 1 : (score_b < score_a) ? -1 : 0;
1512}
1513
1514static int cp_compare_nearest(const void *a, const void *b)
1515{
1516  int score_a = ((compl_T *)a)->cp_score;
1517  int score_b = ((compl_T *)b)->cp_score;
1518  if (score_a == FUZZY_SCORE_NONE || score_b == FUZZY_SCORE_NONE) {
1519    return 0;
1520  }
1521  return (score_a > score_b) ? 1 : (score_a < score_b) ? -1 : 0;
1522}
1523
1524/// Constructs a new string by prepending text from the current line (from
1525/// startcol to compl_col) to the given source string. Stores the result in
1526/// dest.
1527static void prepend_startcol_text(String *dest, String *src, int startcol)
1528{
1529  int prepend_len = compl_col - startcol;
1530  int new_length = prepend_len + (int)src->size;
1531
1532  dest->size = (size_t)new_length;
1533  dest->data = xmalloc((size_t)new_length + 1);  // +1 for NUL
1534
1535  char *line = ml_get(curwin->w_cursor.lnum);
1536
1537  memmove(dest->data, line + startcol, (size_t)prepend_len);
1538  memmove(dest->data + prepend_len, src->data, src->size);
1539  dest->data[new_length] = NUL;
1540}
1541
1542/// Returns the completion leader string adjusted for a specific source's
1543/// startcol. If the source's startcol is before compl_col, prepends text from
1544/// the buffer line to the original compl_leader.
1545static String *get_leader_for_startcol(compl_T *match, bool cached)
1546{
1547  static String adjusted_leader = STRING_INIT;
1548
1549  if (match == NULL) {
1550    API_CLEAR_STRING(adjusted_leader);
1551    return NULL;
1552  }
1553
1554  if (cpt_sources_array == NULL) {
1555    goto theend;
1556  }
1557
1558  int cpt_idx = match->cp_cpt_source_idx;
1559  if (cpt_idx < 0) {
1560    goto theend;
1561  }
1562  int startcol = cpt_sources_array[cpt_idx].cs_startcol;
1563
1564  if (compl_leader.data == NULL) {
1565    // When leader is not set (e.g. 'autocomplete' first fires before
1566    // compl_leader is initialised), fall back to compl_orig_text for
1567    // matches starting at or after compl_col.  Matches starting before
1568    // compl_col carry pre-compl_col text and must not be compared with
1569    // compl_orig_text, so return &compl_leader (NULL string) to signal
1570    // "pass through" (no prefix filter).
1571    if (startcol < 0 || startcol >= compl_col) {
1572      return &compl_orig_text;
1573    }
1574    return &compl_leader;  // pass through (startcol < compl_col)
1575  }
1576
1577  if (compl_col <= 0) {
1578    goto theend;
1579  }
1580
1581  if (startcol >= 0 && startcol < compl_col) {
1582    int prepend_len = compl_col - startcol;
1583    int new_length = prepend_len + (int)compl_leader.size;
1584    if (cached && (size_t)new_length == adjusted_leader.size
1585        && adjusted_leader.data != NULL) {
1586      return &adjusted_leader;
1587    }
1588
1589    API_CLEAR_STRING(adjusted_leader);
1590    prepend_startcol_text(&adjusted_leader, &compl_leader, startcol);
1591    return &adjusted_leader;
1592  }
1593theend:
1594  return &compl_leader;
1595}
1596
1597/// Set fuzzy score for completion matches.
1598static void set_fuzzy_score(void)
1599{
1600  if (compl_first_match == NULL) {
1601    return;
1602  }
1603
1604  // Determine the pattern to match against
1605  bool use_leader = (compl_leader.data != NULL && compl_leader.size > 0);
1606  char *pattern;
1607  if (!use_leader) {
1608    if (compl_orig_text.data == NULL || compl_orig_text.size == 0) {
1609      return;
1610    }
1611    pattern = compl_orig_text.data;
1612  } else {
1613    // Clear the leader cache once before the loop
1614    (void)get_leader_for_startcol(NULL, true);
1615    pattern = NULL;  // Will be computed per-completion
1616  }
1617
1618  // Score all completion matches
1619  compl_T *comp = compl_first_match;
1620  do {
1621    if (use_leader) {
1622      pattern = get_leader_for_startcol(comp, true)->data;
1623    }
1624
1625    comp->cp_score = fuzzy_match_str(comp->cp_str.data, pattern);
1626    comp = comp->cp_next;
1627  } while (comp != NULL && !is_first_match(comp));
1628}
1629
1630/// Sort completion matches, leaving the entry with the original text in place.
1631static void sort_compl_match_list(MergeSortCompareFunc compare)
1632{
1633  if (!compl_first_match || is_first_match(compl_first_match->cp_next)) {
1634    return;
1635  }
1636
1637  compl_T *orig_text = find_original_text_match();
1638  if (orig_text == NULL) {
1639    return;
1640  }
1641
1642  ins_compl_make_linear();
1643  if (orig_text == compl_first_match) {
1644    compl_first_match->cp_next->cp_prev = NULL;
1645    compl_first_match->cp_next = mergesort_list(compl_first_match->cp_next,
1646                                                cp_get_next, cp_set_next,
1647                                                cp_get_prev, cp_set_prev,
1648                                                compare);
1649    compl_first_match->cp_next->cp_prev = compl_first_match;
1650  } else {
1651    orig_text->cp_prev->cp_next = NULL;
1652    compl_first_match = mergesort_list(compl_first_match, cp_get_next, cp_set_next,
1653                                       cp_get_prev, cp_set_prev, compare);
1654    compl_T *tail = compl_first_match;
1655    while (tail->cp_next != NULL) {
1656      tail = tail->cp_next;
1657    }
1658    tail->cp_next = orig_text;
1659    orig_text->cp_prev = tail;
1660  }
1661  (void)ins_compl_make_cyclic();
1662}
1663
1664/// Return the attribute for highlight group "hl_id", -1 when it has none.
1665static int get_user_highlight_attr(int hl_id)
1666{
1667  int attr;
1668
1669  if (hl_id <= 0) {
1670    return -1;
1671  }
1672  attr = syn_id2attr(hl_id);
1673  return attr > 0 ? attr : -1;
1674}
1675
1676/// Build a popup menu to show the completion matches.
1677///
1678/// @return  the popup menu entry that should be selected,
1679///          -1 if nothing should be selected.
1680static int ins_compl_build_pum(void)
1681{
1682  // Need to build the popup menu list.
1683  compl_match_arraysize = 0;
1684
1685  // If it's user complete function and refresh_always,
1686  // do not use "compl_leader" as prefix filter.
1687  if (ins_compl_need_restart()) {
1688    API_CLEAR_STRING(compl_leader);
1689  }
1690
1691  bool compl_no_select = (get_cot_flags() & kOptCotFlagNoselect) != 0
1692                         || (compl_autocomplete && !ins_compl_has_preinsert());
1693
1694  compl_T *match_head = NULL, *match_tail = NULL;
1695  int *match_count = NULL;
1696  bool is_forward = compl_shows_dir_forward();
1697  bool is_cpt_completion = (cpt_sources_array != NULL);
1698
1699  // If the current match is the original text don't find the first
1700  // match after it, don't highlight anything.
1701  bool shown_match_ok = match_at_original_text(compl_shown_match);
1702
1703  if (strequal(compl_leader.data, compl_orig_text.data) && !shown_match_ok) {
1704    compl_shown_match = compl_no_select ? compl_first_match : compl_first_match->cp_next;
1705  }
1706
1707  bool did_find_shown_match = false;
1708  bool preselect_ok = false;
1709  compl_T *comp;
1710  compl_T *shown_compl = NULL;
1711  int i = 0;
1712  int cur = -1;
1713
1714  if (is_cpt_completion) {
1715    match_count = xcalloc((size_t)cpt_sources_count, sizeof(int));
1716  }
1717
1718  (void)get_leader_for_startcol(NULL, true);  // Clear the cache
1719
1720  comp = compl_first_match;
1721  do {
1722    comp->cp_in_match_array = false;
1723
1724    String *leader = get_leader_for_startcol(comp, true);
1725
1726    // Apply 'smartcase': judge case from compl_orig_text, not the leader
1727    // which 'longest' may fill with uppercase the user never typed.
1728    if (ctrl_x_mode_normal() && !p_inf && compl_orig_text.data
1729        && !ignorecase(compl_orig_text.data) && !cot_fuzzy()) {
1730      comp->cp_flags &= ~CP_ICASE;
1731    }
1732
1733    if (!match_at_original_text(comp)
1734        && (leader->data == NULL
1735            || ins_compl_equal_sc(comp, leader->data, leader->size)
1736            || (cot_fuzzy() && comp->cp_score != FUZZY_SCORE_NONE))) {
1737      // Limit number of items from each source if max_items is set.
1738      bool match_limit_exceeded = false;
1739      int cur_source = comp->cp_cpt_source_idx;
1740      if (is_forward && cur_source != -1 && is_cpt_completion) {
1741        match_count[cur_source]++;
1742        int max_matches = cpt_sources_array[cur_source].cs_max_matches;
1743        if (max_matches > 0 && match_count[cur_source] > max_matches) {
1744          match_limit_exceeded = true;
1745        }
1746      }
1747
1748      if (!match_limit_exceeded) {
1749        compl_match_arraysize++;
1750        comp->cp_in_match_array = true;
1751        if (match_head == NULL) {
1752          match_head = comp;
1753        } else {
1754          match_tail->cp_match_next = comp;
1755        }
1756        match_tail = comp;
1757
1758        if (!shown_match_ok && !cot_fuzzy()) {
1759          if (comp == compl_shown_match || did_find_shown_match) {
1760            // This item is the shown match or this is the
1761            // first displayed item after the shown match.
1762            compl_shown_match = comp;
1763            did_find_shown_match = true;
1764            shown_match_ok = true;
1765          } else {
1766            // Remember this displayed match for when the
1767            // shown match is just below it.
1768            shown_compl = comp;
1769          }
1770          cur = i;
1771        } else if (cot_fuzzy()) {
1772          if (i == 0) {
1773            shown_compl = comp;
1774          }
1775
1776          if (!shown_match_ok && comp == compl_shown_match) {
1777            cur = i;
1778            shown_match_ok = true;
1779          }
1780        }
1781        if (compl_preselect_match != NULL && comp->cp_preselect && !preselect_ok) {
1782          cur = i;
1783          compl_shown_match = comp;
1784          shown_match_ok = true;
1785          preselect_ok = true;
1786        }
1787        i++;
1788      }
1789    }
1790
1791    if (comp == compl_shown_match && !cot_fuzzy()) {
1792      did_find_shown_match = true;
1793      // When the original text is the shown match don't set
1794      // compl_shown_match.
1795      if (match_at_original_text(comp)) {
1796        shown_match_ok = true;
1797      }
1798      if (!shown_match_ok && shown_compl != NULL) {
1799        // The shown match isn't displayed, set it to the
1800        // previously displayed match.
1801        compl_shown_match = shown_compl;
1802        shown_match_ok = true;
1803      }
1804    }
1805    comp = comp->cp_next;
1806  } while (comp != NULL && !is_first_match(comp));
1807
1808  xfree(match_count);
1809
1810  if (compl_match_arraysize == 0) {
1811    return -1;
1812  }
1813
1814  if (cot_fuzzy() && !compl_no_select && !shown_match_ok) {
1815    compl_shown_match = shown_compl;
1816    shown_match_ok = true;
1817    cur = 0;
1818  }
1819
1820  assert(compl_match_arraysize >= 0);
1821  compl_match_array = xcalloc((size_t)compl_match_arraysize, sizeof(pumitem_T));
1822
1823  i = 0;
1824  comp = match_head;
1825  while (comp != NULL) {
1826    compl_match_array[i].pum_text = comp->cp_text[CPT_ABBR] != NULL
1827                                    ? comp->cp_text[CPT_ABBR] : comp->cp_str.data;
1828    compl_match_array[i].pum_kind = comp->cp_text[CPT_KIND];
1829    compl_match_array[i].pum_info = comp->cp_text[CPT_INFO];
1830    compl_match_array[i].pum_cpt_source_idx = comp->cp_cpt_source_idx;
1831    compl_match_array[i].pum_user_abbr_hlattr = get_user_highlight_attr(comp->cp_user_abbr_hl_id);
1832    compl_match_array[i].pum_user_kind_hlattr = get_user_highlight_attr(comp->cp_user_kind_hl_id);
1833    compl_match_array[i++].pum_extra = comp->cp_text[CPT_MENU] != NULL
1834                                       ? comp->cp_text[CPT_MENU] : comp->cp_fname;
1835    compl_T *match_next = comp->cp_match_next;
1836    comp->cp_match_next = NULL;
1837    comp = match_next;
1838  }
1839
1840  if (!shown_match_ok) {  // no displayed match at all
1841    cur = -1;
1842  }
1843
1844  return cur;
1845}
1846
1847/// Show the popup menu for the list of matches.
1848/// Also adjusts "compl_shown_match" to an entry that is actually displayed.
1849void ins_compl_show_pum(void)
1850{
1851  if (!pum_wanted() || !pum_enough_matches()) {
1852    return;
1853  }
1854
1855  // Update the screen before drawing the popup menu over it.
1856  update_screen();
1857
1858  int cur = -1;
1859  bool array_changed = false;
1860
1861  if (compl_match_array == NULL) {
1862    array_changed = true;
1863    // Need to build the popup menu list.
1864    cur = ins_compl_build_pum();
1865  } else {
1866    // popup menu already exists, only need to find the current item.
1867    for (int i = 0; i < compl_match_arraysize; i++) {
1868      if (compl_match_array[i].pum_text == compl_shown_match->cp_str.data
1869          || compl_match_array[i].pum_text == compl_shown_match->cp_text[CPT_ABBR]) {
1870        cur = i;
1871        break;
1872      }
1873    }
1874  }
1875
1876  if (compl_match_array == NULL) {
1877    if (compl_started && has_event(EVENT_COMPLETECHANGED)) {
1878      trigger_complete_changed_event(cur);
1879    }
1880    return;
1881  }
1882
1883  // In Replace mode when a $ is displayed at the end of the line only
1884  // part of the screen would be updated.  We do need to redraw here.
1885  dollar_vcol = -1;
1886
1887  // Compute the screen column of the start of the completed text.
1888  // Use the cursor to get all wrapping and other settings right.
1889  const colnr_T col = curwin->w_cursor.col;
1890  curwin->w_cursor.col = compl_col;
1891  compl_selected_item = cur;
1892  pum_display(compl_match_array, compl_match_arraysize, cur, array_changed, 0);
1893  curwin->w_cursor.col = col;
1894
1895  // The cursor was temporarily moved to "compl_col" above to position the
1896  // menu, so the screen update left w_wcol conceal-corrected for that column
1897  // rather than for the real cursor.  Redraw the cursor line so the caret is
1898  // positioned correctly when the cursor line has concealed text.
1899  if (curwin->w_p_cole > 0 && conceal_cursor_line(curwin)) {
1900    redrawWinline(curwin, curwin->w_cursor.lnum);
1901  }
1902
1903  // After adding leader, set the current match to shown match.
1904  if (compl_started && compl_curr_match != compl_shown_match) {
1905    compl_curr_match = compl_shown_match;
1906  }
1907
1908  if (has_event(EVENT_COMPLETECHANGED)) {
1909    trigger_complete_changed_event(cur);
1910  }
1911}
1912
1913/// check selected is current match.
1914///
1915/// @param selected the item which is selected.
1916/// @return bool    return true when is current match otherwise is false.
1917bool compl_match_curr_select(int selected)
1918{
1919  if (selected < 0) {
1920    return false;
1921  }
1922  compl_T *match = compl_first_match;
1923  int selected_idx = -1, list_idx = 0;
1924  do {
1925    if (!match_at_original_text(match)) {
1926      if (compl_curr_match != NULL
1927          && compl_curr_match->cp_number == match->cp_number) {
1928        selected_idx = list_idx;
1929        break;
1930      }
1931      list_idx += 1;
1932    }
1933    match = match->cp_next;
1934  } while (match != NULL && !is_first_match(match));
1935
1936  return selected == selected_idx;
1937}
1938
1939#define DICT_FIRST      (1)     ///< use just first element in "dict"
1940#define DICT_EXACT      (2)     ///< "dict" is the exact name of a file
1941
1942/// Add any identifiers that match the given pattern "pat" in the list of
1943/// dictionary files "dict_start" to the list of completions.
1944///
1945/// @param flags      DICT_FIRST and/or DICT_EXACT
1946/// @param thesaurus  Thesaurus completion
1947static void ins_compl_dictionaries(char *dict_start, char *pat, int flags, bool thesaurus)
1948{
1949  char *dict = dict_start;
1950  char *ptr;
1951  regmatch_T regmatch;
1952  char **files;
1953  int count;
1954  Direction dir = compl_direction;
1955
1956  if (*dict == NUL) {
1957    // When 'dictionary' is empty and spell checking is enabled use
1958    // "spell".
1959    if (!thesaurus && curwin->w_p_spell) {
1960      dict = "spell";
1961    } else {
1962      return;
1963    }
1964  }
1965
1966  char *buf = xmalloc(LSIZE);
1967  regmatch.regprog = NULL;      // so that we can goto theend
1968
1969  // If 'infercase' is set, don't use 'smartcase' here
1970  int save_p_scs = p_scs;
1971  if (curbuf->b_p_inf) {
1972    p_scs = false;
1973  }
1974
1975  // When invoked to match whole lines for CTRL-X CTRL-L adjust the pattern
1976  // to only match at the start of a line.  Otherwise just match the
1977  // pattern. Also need to double backslashes.
1978  if (ctrl_x_mode_line_or_eval()) {
1979    char *pat_esc = vim_strsave_escaped(pat, "\\");
1980
1981    size_t len = strlen(pat_esc) + 10;
1982    ptr = xmalloc(len);
1983    vim_snprintf(ptr, len, "^\\s*\\zs\\V%s", pat_esc);
1984    regmatch.regprog = vim_regcomp(ptr, RE_MAGIC);
1985    xfree(pat_esc);
1986    xfree(ptr);
1987  } else {
1988    regmatch.regprog = vim_regcomp(pat, p_magic ? RE_MAGIC : 0);
1989    if (regmatch.regprog == NULL) {
1990      goto theend;
1991    }
1992  }
1993
1994  // ignore case depends on 'ignorecase', 'smartcase' and "pat"
1995  regmatch.rm_ic = ignorecase(pat);
1996  while (*dict != NUL && !got_int && !compl_interrupted) {
1997    // copy one dictionary file name into buf
1998    if (flags == DICT_EXACT) {
1999      count = 1;
2000      files = &dict;
2001    } else {
2002      // Expand wildcards in the dictionary name, but do not allow
2003      // backticks (for security, the 'dict' option may have been set in
2004      // a modeline).
2005      copy_option_part(&dict, buf, LSIZE, ",");
2006      if (!thesaurus && strcmp(buf, "spell") == 0) {
2007        count = -1;
2008      } else if (vim_strchr(buf, '`') != NULL
2009                 || expand_wildcards(1, &buf, &count, &files,
2010                                     EW_FILE|EW_SILENT) != OK) {
2011        count = 0;
2012      }
2013    }
2014
2015    if (count == -1) {
2016      // Complete from active spelling.  Skip "\<" in the pattern, we
2017      // don't use it as a RE.
2018      if (pat[0] == '\\' && pat[1] == '<') {
2019        ptr = pat + 2;
2020      } else {
2021        ptr = pat;
2022      }
2023      spell_dump_compl(ptr, regmatch.rm_ic, &dir, 0);
2024    } else if (count > 0) {  // avoid warning for using "files" uninit
2025      ins_compl_files(count, files, thesaurus, flags, &regmatch, buf, &dir);
2026      if (flags != DICT_EXACT) {
2027        FreeWild(count, files);
2028      }
2029    }
2030    if (flags != 0) {
2031      break;
2032    }
2033  }
2034
2035theend:
2036  p_scs = save_p_scs;
2037  vim_regfree(regmatch.regprog);
2038  xfree(buf);
2039}
2040
2041/// Add all the words in the line "*buf_arg" from the thesaurus file "fname"
2042/// skipping the word at 'skip_word'.
2043///
2044/// @return  OK on success.
2045static int thesaurus_add_words_in_line(char *fname, char **buf_arg, int dir, const char *skip_word)
2046{
2047  int status = OK;
2048
2049  // Add the other matches on the line
2050  char *ptr = *buf_arg;
2051  while (!got_int) {
2052    // Find start of the next word.  Skip white
2053    // space and punctuation.
2054    ptr = find_word_start(ptr);
2055    if (*ptr == NUL || *ptr == NL) {
2056      break;
2057    }
2058    char *wstart = ptr;
2059
2060    // Find end of the word.
2061    // Japanese words may have characters in
2062    // different classes, only separate words
2063    // with single-byte non-word characters.
2064    while (*ptr != NUL) {
2065      const int l = utfc_ptr2len(ptr);
2066
2067      if (l < 2 && !vim_iswordc((uint8_t)(*ptr))) {
2068        break;
2069      }
2070      ptr += l;
2071    }
2072
2073    // Add the word. Skip the regexp match.
2074    if (wstart != skip_word) {
2075      status = ins_compl_add_infercase(wstart, (int)(ptr - wstart), p_ic,
2076                                       fname, dir, false, FUZZY_SCORE_NONE);
2077      if (status == FAIL) {
2078        break;
2079      }
2080    }
2081  }
2082
2083  *buf_arg = ptr;
2084  return status;
2085}
2086
2087/// Process "count" dictionary/thesaurus "files" and add the text matching
2088/// "regmatch".
2089static void ins_compl_files(int count, char **files, bool thesaurus, int flags,
2090                            regmatch_T *regmatch, char *buf, Direction *dir)
2091  FUNC_ATTR_NONNULL_ARG(2, 7)
2092{
2093  char *leader = cot_fuzzy() ? ins_compl_leader() : NULL;
2094  int leader_len = cot_fuzzy() ? (int)ins_compl_leader_len() : 0;
2095
2096  for (int i = 0; i < count && !got_int && !ins_compl_interrupted(); i++) {
2097    FILE *fp = os_fopen(files[i], "r");  // open dictionary file
2098    if (flags != DICT_EXACT && !shortmess(kShmCompletionscan) && !compl_autocomplete) {
2099      vim_snprintf(IObuff, IOSIZE, _("Scanning dictionary: %s"), files[i]);
2100      msg_progress(IObuff, "nvim.completion", "running", HLF_R, false, true, false);
2101    }
2102
2103    if (fp == NULL) {
2104      continue;
2105    }
2106
2107    // Read dictionary file line by line.
2108    // Check each line for a match.
2109    while (!got_int && !ins_compl_interrupted() && !vim_fgets(buf, LSIZE, fp)) {
2110      char *ptr = buf;
2111      if (cot_fuzzy() && leader_len > 0) {
2112        char *line_end = find_line_end(ptr);
2113        while (ptr < line_end) {
2114          int score = 0;
2115          int len = 0;
2116          if (fuzzy_match_str_in_line(&ptr, leader, &len, NULL, &score)) {
2117            char *end_ptr = ctrl_x_mode_line_or_eval()
2118                            ? find_line_end(ptr) : find_word_end(ptr);
2119            int add_r = ins_compl_add_infercase(ptr, (int)(end_ptr - ptr),
2120                                                p_ic, files[i], *dir, false, score);
2121            if (add_r == FAIL) {
2122              break;
2123            }
2124            ptr = end_ptr;  // start from next word
2125            if (compl_get_longest && ctrl_x_mode_normal()
2126                && compl_first_match->cp_next
2127                && score == compl_first_match->cp_next->cp_score) {
2128              compl_num_bests++;
2129            }
2130          }
2131        }
2132      } else if (regmatch != NULL) {
2133        while (vim_regexec(regmatch, buf, (colnr_T)(ptr - buf))) {
2134          ptr = regmatch->startp[0];
2135          ptr = ctrl_x_mode_line_or_eval() ? find_line_end(ptr) : find_word_end(ptr);
2136          int add_r = ins_compl_add_infercase(regmatch->startp[0],
2137                                              (int)(ptr - regmatch->startp[0]),
2138                                              p_ic, files[i], *dir, false,
2139                                              FUZZY_SCORE_NONE);
2140          if (thesaurus) {
2141            // For a thesaurus, add all the words in the line
2142            ptr = buf;
2143            add_r = thesaurus_add_words_in_line(files[i], &ptr, *dir, regmatch->startp[0]);
2144          }
2145          if (add_r == OK) {
2146            // if dir was BACKWARD then honor it just once
2147            *dir = FORWARD;
2148          } else if (add_r == FAIL) {
2149            break;
2150          }
2151          // avoid expensive call to vim_regexec() when at end
2152          // of line
2153          if (*ptr == '\n' || got_int) {
2154            break;
2155          }
2156        }
2157      }
2158      line_breakcheck();
2159      ins_compl_check_keys(50, false);
2160    }
2161    fclose(fp);
2162  }
2163}
2164
2165/// Find the start of the next word.
2166/// Returns a pointer to the first char of the word.  Also stops at a NUL.
2167char *find_word_start(char *ptr)
2168  FUNC_ATTR_PURE
2169{
2170  while (*ptr != NUL && *ptr != '\n' && mb_get_class(ptr) <= 1) {
2171    ptr += utfc_ptr2len(ptr);
2172  }
2173  return ptr;
2174}
2175
2176/// Find the end of the word.  Assumes it starts inside a word.
2177/// Returns a pointer to just after the word.
2178char *find_word_end(char *ptr)
2179  FUNC_ATTR_PURE
2180{
2181  const int start_class = mb_get_class(ptr);
2182  if (start_class > 1) {
2183    while (*ptr != NUL) {
2184      ptr += utfc_ptr2len(ptr);
2185      if (mb_get_class(ptr) != start_class) {
2186        break;
2187      }
2188    }
2189  }
2190  return ptr;
2191}
2192
2193/// Find the end of the line, omitting CR and NL at the end.
2194///
2195/// @return  a pointer to just after the line.
2196char *find_line_end(char *ptr)
2197{
2198  char *s = ptr + strlen(ptr);
2199  while (s > ptr && (s[-1] == CAR || s[-1] == NL)) {
2200    s--;
2201  }
2202  return s;
2203}
2204
2205/// Free a completion item in the list
2206static void ins_compl_item_free(compl_T *match)
2207{
2208  // Uncount the match string in the duplicate-check hashtab; the entry is
2209  // only removed with its last match.  The hashtab is empty when it was
2210  // already cleared as a whole by ins_compl_free().
2211  if (compl_strings_ht.ht_used > 0 && match->cp_str.data != NULL
2212      && !match_at_original_text(match)) {
2213    hashitem_T *hi = hash_find(&compl_strings_ht, match->cp_str.data);
2214    if (!HASHITEM_EMPTY(hi)) {
2215      complstr_T *entry = HI2CSE(hi);
2216      if (--entry->cse_count <= 0) {
2217        hash_remove(&compl_strings_ht, hi);
2218        xfree(entry);
2219      }
2220    }
2221  }
2222  API_CLEAR_STRING(match->cp_str);
2223  // several entries may use the same fname, free it just once.
2224  if (match->cp_flags & CP_FREE_FNAME) {
2225    xfree(match->cp_fname);
2226  }
2227  free_cptext(match->cp_text);
2228  tv_clear(&match->cp_user_data);
2229  xfree(match->cp_commit_chars);
2230  xfree(match);
2231}
2232
2233/// Free the list of completions
2234static void ins_compl_free(void)
2235{
2236  API_CLEAR_STRING(compl_pattern);
2237  API_CLEAR_STRING(compl_leader);
2238
2239  if (compl_first_match == NULL) {
2240    return;
2241  }
2242
2243  ins_compl_del_pum();
2244  pum_clear();
2245
2246  // Free the duplicate-check hashtab entries all at once, then freeing
2247  // the matches below does not need to uncount them one by one.
2248  hash_clear_all(&compl_strings_ht, CSE_OFF);
2249  hash_init(&compl_strings_ht);
2250
2251  compl_curr_match = compl_first_match;
2252  do {
2253    compl_T *match = compl_curr_match;
2254    compl_curr_match = compl_curr_match->cp_next;
2255    ins_compl_item_free(match);
2256  } while (compl_curr_match != NULL && !is_first_match(compl_curr_match));
2257  compl_first_match = compl_curr_match = NULL;
2258  compl_shown_match = NULL;
2259  compl_preselect_match = NULL;
2260  compl_old_match = NULL;
2261}
2262
2263/// Reset/clear the completion state.
2264void ins_compl_clear(void)
2265{
2266  compl_cont_status = 0;
2267  compl_started = false;
2268  compl_matches = 0;
2269  compl_selected_item = -1;
2270  compl_ins_end_col = 0;
2271  compl_longest_end_col = 0;
2272  compl_curr_win = NULL;
2273  compl_curr_buf = NULL;
2274  API_CLEAR_STRING(compl_pattern);
2275  API_CLEAR_STRING(compl_leader);
2276  edit_submode_extra = NULL;
2277  kv_destroy(compl_orig_extmarks);
2278  API_CLEAR_STRING(compl_orig_text);
2279  compl_enter_selects = false;
2280  cpt_sources_clear();
2281  compl_autocomplete = false;
2282  compl_from_nonkeyword = false;
2283  compl_autostarted = false;
2284  compl_num_bests = 0;
2285  // clear v:completed_item
2286  set_vim_var_dict(VV_COMPLETED_ITEM, tv_dict_alloc_lock(VAR_FIXED));
2287}
2288
2289/// Check that Insert completion is active.
2290bool ins_compl_active(void)
2291  FUNC_ATTR_PURE
2292{
2293  return compl_started;
2294}
2295
2296/// Return true when wp is the actual completion window
2297bool ins_compl_win_active(win_T *wp)
2298{
2299  return ins_compl_active() && wp == compl_curr_win && wp->w_buffer == compl_curr_buf;
2300}
2301
2302/// Selected one of the matches.  When false, the match was edited or
2303/// using the longest common string.
2304bool ins_compl_used_match(void)
2305{
2306  return compl_used_match;
2307}
2308
2309/// Initialize get longest common string.
2310void ins_compl_init_get_longest(void)
2311{
2312  compl_get_longest = false;
2313}
2314
2315/// Returns true when insert completion is interrupted.
2316bool ins_compl_interrupted(void)
2317{
2318  return compl_interrupted || compl_time_slice_expired;
2319}
2320
2321/// Returns true if the <Enter> key selects a match in the completion popup
2322/// menu.
2323bool ins_compl_enter_selects(void)
2324{
2325  return compl_enter_selects;
2326}
2327
2328/// Return the column where the text starts that is being completed
2329colnr_T ins_compl_col(void)
2330{
2331  return compl_col;
2332}
2333
2334/// Return the length in bytes of the text being completed
2335int ins_compl_len(void)
2336{
2337  return compl_length;
2338}
2339
2340/// Return true when the 'completeopt' "preinsert" flag is in effect,
2341/// otherwise return false.
2342bool ins_compl_has_preinsert(void)
2343{
2344  unsigned cur_cot_flags = get_cot_flags();
2345  if (compl_autocomplete && p_ic && !p_inf) {
2346    return false;
2347  }
2348  return (!compl_autocomplete
2349          ? (cur_cot_flags & (kOptCotFlagPreinsert|kOptCotFlagFuzzy|kOptCotFlagMenuone))
2350          == (kOptCotFlagPreinsert|kOptCotFlagMenuone)
2351          : (cur_cot_flags & (kOptCotFlagPreinsert|kOptCotFlagFuzzy))
2352          == kOptCotFlagPreinsert);
2353}
2354
2355/// Returns true if the pre-insert effect is valid and the cursor is within
2356/// the `compl_ins_end_col` range.
2357bool ins_compl_preinsert_effect(void)
2358{
2359  if (!ins_compl_has_preinsert() && !ins_compl_preinsert_longest()) {
2360    return false;
2361  }
2362
2363  return curwin->w_cursor.col < compl_ins_end_col;
2364}
2365
2366/// Delete one character before the cursor and show the subset of the matches
2367/// that match the word that is now before the cursor.
2368/// Returns the character to be used, NUL if the work is done and another char
2369/// to be got from the user.
2370int ins_compl_bs(void)
2371{
2372  if (ins_compl_preinsert_effect()) {
2373    ins_compl_delete(false);
2374  }
2375
2376  char *line = get_cursor_line_ptr();
2377  char *p = line + curwin->w_cursor.col;
2378  MB_PTR_BACK(line, p);
2379  ptrdiff_t p_off = p - line;
2380
2381  // Stop completion when the whole word was deleted.  For Omni completion
2382  // allow the word to be deleted, we won't match everything.
2383  // Respect the 'backspace' option.
2384  if ((int)(p - line) - (int)compl_col < 0
2385      || ((int)(p - line) - (int)compl_col == 0 && !ctrl_x_mode_omni())
2386      || ctrl_x_mode_eval()
2387      || (!can_bs(BS_START) && (int)(p - line) - (int)compl_col
2388          - compl_length < 0)) {
2389    return K_BS;
2390  }
2391
2392  // Deleted more than what was used to find matches or didn't finish
2393  // finding all matches: need to look for matches all over again.
2394  if (curwin->w_cursor.col <= compl_col + compl_length
2395      || ins_compl_need_restart()) {
2396    ins_compl_restart();
2397  }
2398
2399  // ins_compl_restart() calls update_screen() which may invalidate the pointer
2400  // TODO(bfredl): get rid of random update_screen() calls deep inside completion logic
2401  line = get_cursor_line_ptr();
2402
2403  API_CLEAR_STRING(compl_leader);
2404  compl_leader = cbuf_to_string(line + compl_col,
2405                                (size_t)(p_off - (ptrdiff_t)compl_col));
2406
2407  // Clear selection if a menu item is currently selected in autocompletion
2408  if (compl_autocomplete && compl_first_match && !ins_compl_has_preinsert()) {
2409    compl_shown_match = compl_first_match;
2410  }
2411
2412  ins_compl_new_leader();
2413  if (compl_shown_match != NULL) {
2414    // Make sure current match is not a hidden item.
2415    compl_curr_match = compl_shown_match;
2416  }
2417  return NUL;
2418}
2419
2420/// Check if the complete function returned "always" in the "refresh" dictionary item.
2421static bool ins_compl_refresh_always(void)
2422  FUNC_ATTR_PURE
2423{
2424  return (ctrl_x_mode_function() || ctrl_x_mode_omni()) && compl_opt_refresh_always;
2425}
2426
2427/// Check that we need to find matches again, ins_compl_restart() is to
2428/// be called.
2429static bool ins_compl_need_restart(void)
2430  FUNC_ATTR_PURE
2431{
2432  // Return true if we didn't complete finding matches or when the
2433  // "completefunc" returned "always" in the "refresh" dictionary item.
2434  return compl_was_interrupted || ins_compl_refresh_always();
2435}
2436
2437/// Return true if 'autocomplete' option is set
2438bool ins_compl_has_autocomplete(void)
2439{
2440  // Use buffer-local setting if defined (>= 0), otherwise use global
2441  return curbuf->b_p_ac >= 0 ? curbuf->b_p_ac : p_ac;
2442}
2443
2444/// Calculate fuzzy score and sort completion matches unless sorting is disabled.
2445static void ins_compl_fuzzy_sort(void)
2446{
2447  unsigned cur_cot_flags = get_cot_flags();
2448
2449  // Set the fuzzy score in cp_score and sort
2450  set_fuzzy_score();
2451  if (!(cur_cot_flags & kOptCotFlagNosort)) {
2452    sort_compl_match_list(cp_compare_fuzzy);
2453    // Reset the shown item since sorting reorders items
2454    if ((cur_cot_flags & (kOptCotFlagNoinsert|kOptCotFlagNoselect)) == kOptCotFlagNoinsert) {
2455      bool none_selected = compl_shown_match == (compl_shows_dir_forward()
2456                                                 ? compl_first_match : compl_first_match->cp_prev);
2457      if (!none_selected) {
2458        compl_shown_match = (!compl_autocomplete && compl_shows_dir_forward())
2459                            ? compl_first_match->cp_next : compl_first_match;
2460      }
2461    }
2462  }
2463}
2464
2465/// Called after changing "compl_leader".
2466/// Show the popup menu with a different set of matches.
2467/// May also search for matches again if the previous search was interrupted.
2468static void ins_compl_new_leader(void)
2469{
2470  ins_compl_del_pum();
2471  ins_compl_delete(true);
2472  ins_compl_insert_bytes(compl_leader.data + get_compl_len(), -1);
2473  compl_used_match = false;
2474
2475  int save_w_wrow = curwin->w_wrow;
2476  int save_w_leftcol = curwin->w_leftcol;
2477  if (compl_started) {
2478    ins_compl_set_original_text(compl_leader.data, compl_leader.size);
2479    if (is_cpt_func_refresh_always()) {
2480      cpt_compl_refresh();
2481    }
2482    if (cot_fuzzy()) {
2483      ins_compl_fuzzy_sort();
2484    }
2485  } else {
2486    spell_bad_len = 0;  // need to redetect bad word
2487    // Matches were cleared, need to search for them now.
2488    // Set "compl_restarting" to avoid that the first match is inserted.
2489    compl_restarting = true;
2490    if (ins_compl_has_autocomplete()) {
2491      ins_compl_enable_autocomplete();
2492    } else {
2493      compl_autocomplete = false;
2494    }
2495    if (ins_complete(Ctrl_N, false) == FAIL) {
2496      compl_cont_status = 0;
2497    }
2498    compl_restarting = false;
2499  }
2500
2501  compl_enter_selects = !compl_used_match && compl_selected_item != -1;
2502
2503  // Show the popup menu with a different set of matches.  With
2504  // 'autocompletedelay' the menu is already visible here, so update it
2505  // immediately rather than re-arming the delay, like a zero delay does.
2506  if (!compl_interrupted) {
2507    show_pum(save_w_wrow, save_w_leftcol);
2508  }
2509
2510  // Don't let Enter select the original text when there is no popup menu.
2511  if (compl_match_array == NULL) {
2512    compl_enter_selects = false;
2513  } else if (ins_compl_has_preinsert() && compl_leader.size > 0) {
2514    ins_compl_insert(true, false);
2515  } else if (compl_started && ins_compl_preinsert_longest()
2516             && compl_leader.size > 0 && !ins_compl_preinsert_effect()) {
2517    ins_compl_insert(true, true);
2518  }
2519  // Don't let Enter select when use user function and refresh_always is set
2520  if (ins_compl_refresh_always()) {
2521    compl_enter_selects = false;
2522  }
2523}
2524
2525/// Return the length of the completion, from the completion start column to
2526/// the cursor column.  Making sure it never goes below zero.
2527static int get_compl_len(void)
2528{
2529  int off = (int)curwin->w_cursor.col - (int)compl_col;
2530  return MAX(0, off);
2531}
2532
2533/// Append one character to the match leader.  May reduce the number of
2534/// matches.
2535void ins_compl_addleader(int c)
2536{
2537  int cc;
2538
2539  if (ins_compl_preinsert_effect()) {
2540    ins_compl_delete(false);
2541  }
2542
2543  if (stop_arrow() == FAIL) {
2544    return;
2545  }
2546  if ((cc = utf_char2len(c)) > 1) {
2547    char buf[MB_MAXCHAR + 1];
2548
2549    utf_char2bytes(c, buf);
2550    buf[cc] = NUL;
2551    ins_char_bytes(buf, (size_t)cc);
2552  } else {
2553    ins_char(c);
2554  }
2555
2556  // If we didn't complete finding matches we must search again.
2557  if (ins_compl_need_restart()) {
2558    ins_compl_restart();
2559  }
2560
2561  API_CLEAR_STRING(compl_leader);
2562  compl_leader = cbuf_to_string(get_cursor_line_ptr() + compl_col,
2563                                (size_t)(curwin->w_cursor.col - compl_col));
2564  ins_compl_new_leader();
2565}
2566
2567/// Setup for finding completions again without leaving CTRL-X mode.  Used when
2568/// BS or a key was typed while still searching for matches.
2569static void ins_compl_restart(void)
2570{
2571  // update screen before restart.
2572  // so if complete is blocked,
2573  // will stay to the last popup menu and reduce flicker
2574  update_screen();  // TODO(bfredl): no.
2575  ins_compl_free();
2576  compl_started = false;
2577  compl_matches = 0;
2578  compl_cont_status = 0;
2579  compl_cont_mode = 0;
2580  cpt_sources_clear();
2581  compl_autocomplete = false;
2582  compl_from_nonkeyword = false;
2583  compl_autostarted = false;
2584  compl_num_bests = 0;
2585}
2586
2587/// Set the first match, the original text.
2588static void ins_compl_set_original_text(char *str, size_t len)
2589  FUNC_ATTR_NONNULL_ALL
2590{
2591  // Replace the original text entry.
2592  compl_T *match = find_original_text_match();
2593  if (match == NULL) {
2594    return;
2595  }
2596
2597  API_CLEAR_STRING(match->cp_str);
2598  match->cp_str = cbuf_to_string(str, len);
2599}
2600
2601/// Append one character to the match leader.  May reduce the number of
2602/// matches.
2603void ins_compl_addfrommatch(void)
2604{
2605  int len = (int)curwin->w_cursor.col - (int)compl_col;
2606  assert(compl_shown_match != NULL);
2607  char *p = compl_shown_match->cp_str.data;
2608  if ((int)compl_shown_match->cp_str.size <= len) {   // the match is too short
2609    // When still at the original match use the first entry that matches
2610    // the leader.
2611    if (!match_at_original_text(compl_shown_match)) {
2612      return;
2613    }
2614
2615    p = NULL;
2616    size_t plen = 0;
2617    for (compl_T *cp = compl_shown_match->cp_next; cp != NULL
2618         && !is_first_match(cp); cp = cp->cp_next) {
2619      if (compl_leader.data == NULL
2620          || ins_compl_equal(cp, compl_leader.data, compl_leader.size)) {
2621        p = cp->cp_str.data;
2622        plen = cp->cp_str.size;
2623        break;
2624      }
2625    }
2626    if (p == NULL || (int)plen <= len) {
2627      return;
2628    }
2629  }
2630  p += len;
2631  int c = utf_ptr2char(p);
2632  ins_compl_addleader(c);
2633}
2634
2635/// Set the CTRL-X completion mode based on the key "c" typed after a CTRL-X.
2636/// Uses the global variables: ctrl_x_mode, edit_submode, edit_submode_pre,
2637/// compl_cont_mode and compl_cont_status.
2638///
2639/// @return  true when the character is not to be inserted.
2640static bool set_ctrl_x_mode(const int c)
2641{
2642  bool retval = false;
2643
2644  switch (c) {
2645  case Ctrl_E:
2646  case Ctrl_Y:
2647    // scroll the window one line up or down
2648    ctrl_x_mode = CTRL_X_SCROLL;
2649    if (!(State & REPLACE_FLAG)) {
2650      edit_submode = _(" (insert) Scroll (^E/^Y)");
2651    } else {
2652      edit_submode = _(" (replace) Scroll (^E/^Y)");
2653    }
2654    edit_submode_pre = NULL;
2655    redraw_mode = true;
2656    break;
2657  case Ctrl_L:
2658    // complete whole line
2659    ctrl_x_mode = CTRL_X_WHOLE_LINE;
2660    break;
2661  case Ctrl_F:
2662    // complete filenames
2663    ctrl_x_mode = CTRL_X_FILES;
2664    break;
2665  case Ctrl_K:
2666    // complete words from a dictionary
2667    ctrl_x_mode = CTRL_X_DICTIONARY;
2668    break;
2669  case Ctrl_R:
2670    // When CTRL-R is followed by '=', don't trigger register completion
2671    // This allows expressions like <C-R>=func()<CR> to work normally
2672    if (vpeekc() == '=') {
2673      break;
2674    }
2675    ctrl_x_mode = CTRL_X_REGISTER;
2676    break;
2677  case Ctrl_T:
2678    // complete words from a thesaurus
2679    ctrl_x_mode = CTRL_X_THESAURUS;
2680    break;
2681  case Ctrl_U:
2682    // user defined completion
2683    ctrl_x_mode = CTRL_X_FUNCTION;
2684    break;
2685  case Ctrl_O:
2686    // omni completion
2687    ctrl_x_mode = CTRL_X_OMNI;
2688    break;
2689  case 's':
2690  case Ctrl_S:
2691    // complete spelling suggestions
2692    ctrl_x_mode = CTRL_X_SPELL;
2693    emsg_off++;  // Avoid getting the E756 error twice.
2694    spell_back_to_badword();
2695    emsg_off--;
2696    break;
2697  case Ctrl_RSB:
2698    // complete tag names
2699    ctrl_x_mode = CTRL_X_TAGS;
2700    break;
2701  case Ctrl_I:
2702  case K_S_TAB:
2703    // complete keywords from included files
2704    ctrl_x_mode = CTRL_X_PATH_PATTERNS;
2705    break;
2706  case Ctrl_D:
2707    // complete definitions from included files
2708    ctrl_x_mode = CTRL_X_PATH_DEFINES;
2709    break;
2710  case Ctrl_V:
2711  case Ctrl_Q:
2712    // complete vim commands
2713    ctrl_x_mode = CTRL_X_CMDLINE;
2714    break;
2715  case Ctrl_Z:
2716    // stop completion
2717    ctrl_x_mode = CTRL_X_NORMAL;
2718    edit_submode = NULL;
2719    redraw_mode = true;
2720    retval = true;
2721    break;
2722  case Ctrl_P:
2723  case Ctrl_N:
2724    // ^X^P means LOCAL expansion if nothing interrupted (eg we
2725    // just started ^X mode, or there were enough ^X's to cancel
2726    // the previous mode, say ^X^F^X^X^P or ^P^X^X^X^P, see below)
2727    // do normal expansion when interrupting a different mode (say
2728    // ^X^F^X^P or ^P^X^X^P, see below)
2729    // nothing changes if interrupting mode 0, (eg, the flag
2730    // doesn't change when going to ADDING mode  -- Acevedo
2731    if (!(compl_cont_status & CONT_INTRPT)) {
2732      compl_cont_status |= CONT_LOCAL;
2733    } else if (compl_cont_mode != 0) {
2734      compl_cont_status &= ~CONT_LOCAL;
2735    }
2736    FALLTHROUGH;
2737  default:
2738    // If we have typed at least 2 ^X's... for modes != 0, we set
2739    // compl_cont_status = 0 (eg, as if we had just started ^X
2740    // mode).
2741    // For mode 0, we set "compl_cont_mode" to an impossible
2742    // value, in both cases ^X^X can be used to restart the same
2743    // mode (avoiding ADDING mode).
2744    // Undocumented feature: In a mode != 0 ^X^P and ^X^X^P start
2745    // 'complete' and local ^P expansions respectively.
2746    // In mode 0 an extra ^X is needed since ^X^P goes to ADDING
2747    // mode  -- Acevedo
2748    if (c == Ctrl_X) {
2749      if (compl_cont_mode != 0) {
2750        compl_cont_status = 0;
2751      } else {
2752        compl_cont_mode = CTRL_X_NOT_DEFINED_YET;
2753      }
2754    }
2755    ctrl_x_mode = CTRL_X_NORMAL;
2756    edit_submode = NULL;
2757    redraw_mode = true;
2758    break;
2759  }
2760
2761  return retval;
2762}
2763
2764/// Stop insert completion mode
2765static bool ins_compl_stop(const int c, const int prev_mode, bool retval)
2766{
2767  // Remove pre-inserted text when present.
2768  if (ins_compl_preinsert_effect() && ins_compl_win_active(curwin)) {
2769    ins_compl_delete(false);
2770  }
2771
2772  // Get here when we have finished typing a sequence of ^N and
2773  // ^P or other completion characters in CTRL-X mode.  Free up
2774  // memory that was used, and make sure we can redo the insert.
2775  if (compl_curr_match != NULL || compl_leader.data != NULL || c == Ctrl_E) {
2776    // If any of the original typed text has been changed, eg when
2777    // ignorecase is set, we must add back-spaces to the redo
2778    // buffer.  We add as few as necessary to delete just the part
2779    // of the original text that has changed.
2780    // When using the longest match, edited the match or used
2781    // CTRL-E then don't use the current match.
2782    char *ptr = NULL;
2783    if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E) {
2784      ptr = compl_curr_match->cp_str.data;
2785    }
2786    ins_compl_fixRedoBufForLeader(ptr);
2787  }
2788
2789  bool want_cindent = (get_can_cindent() && cindent_on());
2790
2791  // When completing whole lines: fix indent for 'cindent'.
2792  // Otherwise, break line if it's too long.
2793  if (compl_cont_mode == CTRL_X_WHOLE_LINE) {
2794    // re-indent the current line
2795    if (want_cindent) {
2796      do_c_expr_indent();
2797      want_cindent = false;                 // don't do it again
2798    }
2799  } else if (!compl_autocomplete || compl_used_match) {
2800    const int prev_col = curwin->w_cursor.col;
2801
2802    // put the cursor on the last char, for 'tw' formatting
2803    if (prev_col > 0) {
2804      dec_cursor();
2805    }
2806
2807    // only format when something was inserted
2808    if (Ins.moved == kInsNone && !Ins.need_undo && c != Ctrl_E) {
2809      insertchar(NUL, 0, -1);
2810    }
2811
2812    if (prev_col > 0
2813        && get_cursor_line_ptr()[curwin->w_cursor.col] != NUL) {
2814      inc_cursor();
2815    }
2816  }
2817
2818  String word = STRING_INIT;
2819  const bool is_commit = pum_visible() && ins_compl_commit_char(c);
2820  // If the popup menu is displayed pressing CTRL-Y means accepting
2821  // the selection without inserting anything.  When
2822  // compl_enter_selects is set the Enter key does the same.
2823  // Note: Unlike Ctrl_Y, a commit-char accepts the match but does not consume the key.
2824  if ((c == Ctrl_Y || is_commit || (compl_enter_selects
2825                                    && (c == CAR || c == K_KENTER || c == NL)))
2826      && pum_visible()) {
2827    word = copy_string(compl_shown_match->cp_str, NULL);
2828    if (!is_commit) {
2829      retval = true;
2830    }
2831    // May need to remove ComplMatchIns highlight.
2832    redrawWinline(curwin, curwin->w_cursor.lnum);
2833  }
2834
2835  // When a match was inserted but the pum was never displayed
2836  // (eg: only one match with 'completeopt' "menu" without "menuone"),
2837  // the user had no opportunity to explicitly accept or dismiss it,
2838  // so treat this as an implicit accept (#38160).
2839  if (word.data == NULL && c != Ctrl_E && compl_used_match && compl_match_array == NULL
2840      && compl_curr_match != NULL
2841      && compl_curr_match->cp_str.data != NULL) {
2842    word = copy_string(compl_curr_match->cp_str, NULL);
2843  }
2844
2845  // CTRL-E means completion is Ended, go back to the typed text.
2846  // but only do this, if the Popup is still visible
2847  if (c == Ctrl_E) {
2848    ins_compl_delete(false);
2849    char *p = NULL;
2850    size_t plen = 0;
2851    if (compl_leader.data != NULL) {
2852      p = compl_leader.data;
2853      plen = compl_leader.size;
2854    } else if (compl_first_match != NULL) {
2855      p = compl_orig_text.data;
2856      plen = compl_orig_text.size;
2857    }
2858    if (p != NULL) {
2859      const int compl_len = get_compl_len();
2860      if ((int)plen > compl_len) {
2861        ins_compl_insert_bytes(p + compl_len, (int)plen - compl_len);
2862      }
2863    }
2864    restore_orig_extmarks();
2865    retval = true;
2866  }
2867
2868  auto_format(false, true);
2869
2870  // Trigger the CompleteDonePre event to give scripts a chance to
2871  // act upon the completion before clearing the info, and restore
2872  // ctrl_x_mode, so that complete_info() can be used.
2873  ctrl_x_mode = prev_mode;
2874  ins_apply_autocmds(EVENT_COMPLETEDONEPRE);
2875
2876  ins_compl_free();
2877  compl_started = false;
2878  compl_matches = 0;
2879  if (!shortmess(kShmCompletionmenu)) {
2880    msg_clr_cmdline();  // necessary for "noshowmode"
2881  }
2882  ctrl_x_mode = CTRL_X_NORMAL;
2883  compl_enter_selects = false;
2884  if (edit_submode != NULL) {
2885    edit_submode = NULL;
2886    redraw_mode = true;
2887  }
2888  compl_autocomplete = false;
2889  compl_from_nonkeyword = false;
2890  compl_autostarted = false;
2891  compl_num_bests = 0;
2892  compl_ins_end_col = 0;
2893
2894  if (c == Ctrl_C && bt_cmdwin(curbuf)) {
2895    // Avoid the popup menu remains displayed when leaving the
2896    // command line window.
2897    update_screen();
2898  }
2899
2900  // Indent now if a key was typed that is in 'cinkeys'.
2901  if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0))) {
2902    do_c_expr_indent();
2903  }
2904  // Trigger the CompleteDone event to give scripts a chance to act
2905  // upon the end of completion.
2906  do_autocmd_completedone(c, prev_mode, &word);
2907  xfree(word.data);
2908
2909  return retval;
2910}
2911
2912/// Cancel completion.
2913bool ins_compl_cancel(void)
2914{
2915  return ins_compl_stop(' ', ctrl_x_mode, true);
2916}
2917
2918/// Prepare for Insert mode completion, or stop it.
2919/// Called just after typing a character in Insert mode.
2920///
2921/// @param  c  character that was typed
2922///
2923/// @return true when the character is not to be inserted;
2924bool ins_compl_prep(int c)
2925{
2926  bool retval = false;
2927  const int prev_mode = ctrl_x_mode;
2928
2929  // Forget any previous 'special' messages if this is actually
2930  // a ^X mode key - bar ^R, in which case we wait to see what it gives us.
2931  if (c != Ctrl_R && vim_is_ctrl_x_key(c)) {
2932    edit_submode_extra = NULL;
2933  }
2934
2935  // Ignore end of Select mode mapping and mouse scroll/movement.
2936  if (c == K_SELECT || c == K_MOUSEDOWN || c == K_MOUSEUP
2937      || c == K_MOUSELEFT || c == K_MOUSERIGHT || c == K_MOUSEMOVE
2938      || c == K_EVENT || c == K_COMMAND || c == K_LUA) {
2939    return retval;
2940  }
2941
2942  if (ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X && c != Ctrl_X) {
2943    if (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_Z || ins_compl_pum_key(c)
2944        || !vim_is_ctrl_x_key(c)) {
2945      // Not starting another completion mode.
2946      ctrl_x_mode = CTRL_X_CMDLINE;
2947
2948      // CTRL-X CTRL-Z should stop completion without inserting anything
2949      if (c == Ctrl_Z) {
2950        retval = true;
2951      }
2952    } else {
2953      ctrl_x_mode = CTRL_X_CMDLINE;
2954
2955      // Other CTRL-X keys first stop completion, then start another
2956      // completion mode.
2957      ins_compl_prep(' ');
2958      ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
2959    }
2960  }
2961
2962  // Set "compl_get_longest" when finding the first matches.
2963  if (ctrl_x_mode_not_defined_yet()
2964      || (ctrl_x_mode_normal() && !compl_started)) {
2965    compl_get_longest = (get_cot_flags() & kOptCotFlagLongest) != 0;
2966    compl_used_match = true;
2967  }
2968
2969  if (ctrl_x_mode_not_defined_yet()) {
2970    // We have just typed CTRL-X and aren't quite sure which CTRL-X mode
2971    // it will be yet.  Now we decide.
2972    retval = set_ctrl_x_mode(c);
2973  } else if (ctrl_x_mode_not_default()) {
2974    // We're already in CTRL-X mode, do we stay in it?
2975    if (c != Ctrl_R && !vim_is_ctrl_x_key(c)) {
2976      ctrl_x_mode = ctrl_x_mode_scroll() ? CTRL_X_NORMAL : CTRL_X_FINISHED;
2977      edit_submode = NULL;
2978    }
2979    redraw_mode = true;
2980  }
2981
2982  if (compl_started || ctrl_x_mode == CTRL_X_FINISHED) {
2983    // Show error message from attempted keyword completion (probably
2984    // 'Pattern not found') until another key is hit, then go back to
2985    // showing what mode we are in.
2986    redraw_mode = true;
2987    if ((ctrl_x_mode_normal()
2988         && c != Ctrl_N
2989         && c != Ctrl_P
2990         && c != Ctrl_R
2991         && !ins_compl_pum_key(c))
2992        || ctrl_x_mode == CTRL_X_FINISHED) {
2993      retval = ins_compl_stop(c, prev_mode, retval);
2994    }
2995  } else if (ctrl_x_mode == CTRL_X_LOCAL_MSG) {
2996    // Trigger the CompleteDone event to give scripts a chance to act
2997    // upon the (possibly failed) completion.
2998    do_autocmd_completedone(c, ctrl_x_mode, NULL);
2999  }
3000
3001  may_trigger_modechanged();
3002
3003  // reset continue_* if we left expansion-mode, if we stay they'll be
3004  // (re)set properly in ins_complete()
3005  if (c != Ctrl_R && !vim_is_ctrl_x_key(c)) {
3006    compl_cont_status = 0;
3007    compl_cont_mode = 0;
3008  }
3009
3010  return retval;
3011}
3012
3013/// Fix the redo buffer for the completion leader replacing some of the typed
3014/// text.  This inserts backspaces and appends the changed text.
3015/// "ptr" is the known leader text or NUL.
3016static void ins_compl_fixRedoBufForLeader(char *ptr_arg)
3017{
3018  int len = 0;
3019  char *ptr = ptr_arg;
3020
3021  if (ptr == NULL) {
3022    if (compl_leader.data != NULL) {
3023      ptr = compl_leader.data;
3024    } else {
3025      return;        // nothing to do
3026    }
3027  }
3028  if (compl_orig_text.data != NULL) {
3029    char *p = compl_orig_text.data;
3030    // Find length of common prefix between original text and new completion
3031    while (p[len] != NUL && p[len] == ptr[len]) {
3032      len++;
3033    }
3034    // Adjust length to not break inside a multi-byte character
3035    if (len > 0) {
3036      len -= utf_head_off(p, p + len);
3037    }
3038    // Add backspace characters for each remaining character in original text
3039    for (p += len; *p != NUL; MB_PTR_ADV(p)) {
3040      redo_append_char(K_BS);
3041    }
3042  }
3043  redo_append_lit(ptr + len, -1);
3044}
3045
3046/// Loops through the list of windows, loaded-buffers or non-loaded-buffers
3047/// (depending on flag) starting from buf and looking for a non-scanned
3048/// buffer (other than curbuf).  curbuf is special, if it is called with
3049/// buf=curbuf then it has to be the first call for a given flag/expansion.
3050///
3051/// Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo
3052static buf_T *ins_compl_next_buf(buf_T *buf, int flag)
3053{
3054  static win_T *wp = NULL;
3055
3056  if (flag == 'w') {            // just windows
3057    if (buf == curbuf || !win_valid(wp)) {
3058      // first call for this flag/expansion or window was closed
3059      wp = curwin;
3060    }
3061
3062    assert(wp);
3063    while (true) {
3064      // Move to next window (wrap to first window if at the end)
3065      wp = (wp->w_next != NULL) ? wp->w_next : firstwin;
3066      // Break if we're back at start or found an unscanned buffer (in a focusable window)
3067      if (wp == curwin || (!wp->w_buffer->b_scanned && wp->w_config.focusable)) {
3068        break;
3069      }
3070    }
3071    buf = wp->w_buffer;
3072  } else {
3073    // 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U'
3074    // (unlisted buffers)
3075    // When completing whole lines skip unloaded buffers.
3076    while (true) {
3077      // Move to next buffer (wrap to first buffer if at the end)
3078      buf = (buf->b_next != NULL) ? buf->b_next : firstbuf;
3079      // Break if we're back at start buffer
3080      if (buf == curbuf) {
3081        break;
3082      }
3083
3084      bool skip_buffer;
3085      // Check buffer conditions based on flag
3086      if (flag == 'U') {
3087        skip_buffer = buf->b_p_bl;
3088      } else {
3089        skip_buffer = !buf->b_p_bl || (buf->b_ml.ml_mfp == NULL) != (flag == 'u');
3090      }
3091
3092      // Break if we found a buffer that matches our criteria
3093      if (!skip_buffer && !buf->b_scanned) {
3094        break;
3095      }
3096    }
3097  }
3098  return buf;
3099}
3100
3101/// Count the number of entries in the 'complete' option value "cpt".
3102/// Each non-empty, comma-separated segment is counted as one entry.
3103static int get_cpt_sources_count(char *cpt)
3104{
3105  char dummy[LSIZE];
3106  int count = 0;
3107
3108  for (char *p = cpt; *p != NUL;) {
3109    while (*p == ',' || *p == ' ') {
3110      p++;  // Skip delimiters
3111    }
3112    if (*p != NUL) {
3113      (void)copy_option_part(&p, dummy, LSIZE, ",");  // Advance p
3114      count++;
3115    }
3116  }
3117
3118  return count;
3119}
3120
3121static Callback *cpt_cb;   ///< Callback functions associated with F{func}
3122static int cpt_cb_count;   ///< Number of cpt callbacks
3123
3124/// Free an array of 'complete' F{func} callbacks and set the pointer to NULL.
3125void clear_cpt_callbacks(Callback **callbacks, int count)
3126{
3127  if (callbacks == NULL || *callbacks == NULL) {
3128    return;
3129  }
3130
3131  for (int i = 0; i < count; i++) {
3132    callback_free(&(*callbacks)[i]);
3133  }
3134
3135  XFREE_CLEAR(*callbacks);
3136}
3137
3138/// Copies a list of Callback structs from src to *dest, clearing any existing
3139/// entries and allocating memory for the destination.
3140static void copy_cpt_callbacks(Callback **dest, int *dest_cnt, Callback *src, int cnt)
3141{
3142  clear_cpt_callbacks(dest, *dest_cnt);
3143  *dest_cnt = 0;
3144
3145  if (cnt == 0) {
3146    return;
3147  }
3148
3149  *dest = xcalloc((size_t)cnt, sizeof(Callback));
3150  *dest_cnt = cnt;
3151
3152  for (int i = 0; i < cnt; i++) {
3153    if (src[i].type != kCallbackNone) {
3154      callback_copy(&(*dest)[i], &src[i]);
3155    }
3156  }
3157}
3158
3159/// Copy global 'complete' F{func} callbacks into the given buffer's local
3160/// callback array. Clears any existing buffer-local callbacks first.
3161void set_buflocal_cpt_callbacks(buf_T *buf)
3162{
3163  if (buf == NULL) {
3164    return;
3165  }
3166  copy_cpt_callbacks(&buf->b_p_cpt_cb, &buf->b_p_cpt_count, cpt_cb, cpt_cb_count);
3167}
3168
3169/// Parse the 'complete' option value "cpt" and store the callbacks for the
3170/// F{func} entries in a newly allocated array in "*cbp", setting "*cnt" to the
3171/// number of entries.  The array has one entry for every item in "cpt", also
3172/// for items that are not a function, so that it can be indexed with the item
3173/// index.  Any previous array in "*cbp" is cleared.
3174static void parse_cpt_callbacks(char *cpt, Callback **cbp, int *cnt)
3175{
3176  clear_cpt_callbacks(cbp, *cnt);
3177  *cnt = 0;
3178
3179  int count = get_cpt_sources_count(cpt);
3180  if (count == 0) {
3181    return;
3182  }
3183
3184  *cbp = xcalloc((size_t)count, sizeof(Callback));
3185  *cnt = count;
3186
3187  char buf[LSIZE];
3188  int idx = 0;
3189  for (char *p = cpt; *p != NUL;) {
3190    while (*p == ',' || *p == ' ') {
3191      p++;  // Skip delimiters
3192    }
3193    if (*p != NUL) {
3194      size_t slen = copy_option_part(&p, buf, LSIZE, ",");  // Advance p
3195      if (slen > 0 && buf[0] == 'F' && buf[1] != NUL) {
3196        char *caret = vim_strchr(buf, '^');
3197        if (caret != NULL) {
3198          *caret = NUL;
3199        }
3200        if (option_set_callback_func(buf + 1, &(*cbp)[idx]) != OK) {
3201          (*cbp)[idx].type = kCallbackNone;
3202        }
3203      }
3204      idx++;
3205    }
3206  }
3207}
3208
3209/// Parse 'complete' option and initialize F{func} callbacks.
3210/// Frees any existing callbacks and allocates new ones.
3211int set_cpt_callbacks(optset_T *args)
3212{
3213  int opt_flags = args->os_flags;
3214
3215  if (curbuf == NULL) {
3216    return FAIL;
3217  }
3218
3219  // ":setglobal" does not change the buffer-local option value
3220  if (!(opt_flags & OPT_GLOBAL)) {
3221    parse_cpt_callbacks(curbuf->b_p_cpt, &curbuf->b_p_cpt_cb, &curbuf->b_p_cpt_count);
3222  }
3223
3224  // ":setlocal" does not change the global option value
3225  if (opt_flags & OPT_LOCAL) {
3226    return OK;
3227  }
3228
3229  // Cache the callbacks for the global value
3230  if (opt_flags & OPT_GLOBAL) {
3231    parse_cpt_callbacks(p_cpt, &cpt_cb, &cpt_cb_count);
3232    return OK;
3233  }
3234
3235  // set case
3236  copy_cpt_callbacks(&cpt_cb, &cpt_cb_count, curbuf->b_p_cpt_cb, curbuf->b_p_cpt_count);
3237  return OK;
3238}
3239
3240/// Mark "copyID" references in an array of F{func} callbacks so that they are
3241/// not garbage collected.
3242bool set_ref_in_cpt_callbacks(Callback *callbacks, int count, int copyID)
3243{
3244  bool abort = false;
3245
3246  if (callbacks == NULL) {
3247    return false;
3248  }
3249
3250  for (int i = 0; i < count; i++) {
3251    abort = abort || set_ref_in_callback(&callbacks[i], copyID, NULL, NULL);
3252  }
3253  return abort;
3254}
3255
3256/// Mark the global 'completefunc' 'omnifunc' and 'thesaurusfunc' callbacks with
3257/// "copyID" so that they are not garbage collected.
3258bool set_ref_in_insexpand_funcs(int copyID)
3259{
3260  bool abort = set_ref_in_callback(&p_cfu, copyID, NULL, NULL);
3261  abort = abort || set_ref_in_callback(&p_ofu, copyID, NULL, NULL);
3262  abort = abort || set_ref_in_callback(&p_tsrfu, copyID, NULL, NULL);
3263  abort = abort || set_ref_in_cpt_callbacks(cpt_cb, cpt_cb_count, copyID);
3264
3265  return abort;
3266}
3267
3268/// Get the callback to use for insert mode completion of "type": 'completefunc', 'omnifunc', or
3269/// 'thesaurusfunc'. Returns `kCallbackNone` if the option is empty.
3270static Callback *get_insert_callback(int type)
3271{
3272  if (type == CTRL_X_FUNCTION) {
3273    return &curbuf->b_p_cfu;
3274  }
3275  if (type == CTRL_X_OMNI) {
3276    return &curbuf->b_p_ofu;
3277  }
3278  // CTRL_X_THESAURUS
3279  return curbuf->b_p_tsrfu.type != kCallbackNone ? &curbuf->b_p_tsrfu : &p_tsrfu;
3280}
3281
3282/// Execute user defined complete function 'completefunc', 'omnifunc' or
3283/// 'thesaurusfunc', and get matches in "matches".
3284///
3285/// @param type  one of CTRL_X_OMNI or CTRL_X_FUNCTION or CTRL_X_THESAURUS
3286/// @param cb    set if triggered by a function in 'cpt' option, otherwise NULL
3287static void expand_by_function(int type, char *base, Callback *cb)
3288{
3289  list_T *matchlist = NULL;
3290  dict_T *matchdict = NULL;
3291  typval_T rettv;
3292  const int save_State = State;
3293
3294  assert(curbuf != NULL);
3295
3296  const bool is_cpt_function = (cb != NULL);
3297  const bool use_sandbox = is_cpt_function && was_set_insecurely(curwin, kOptComplete, OPT_LOCAL);
3298  if (!is_cpt_function) {
3299    cb = get_insert_callback(type);
3300    if (cb->type == kCallbackNone) {
3301      return;
3302    }
3303  }
3304
3305  // Call 'completefunc' to obtain the list of matches.
3306  typval_T args[3];
3307  args[0].v_type = VAR_NUMBER;
3308  args[1].v_type = VAR_STRING;
3309  args[2].v_type = VAR_UNKNOWN;
3310  args[0].vval.v_number = 0;
3311  args[1].vval.v_string = base != NULL ? base : "";
3312
3313  pos_T pos = curwin->w_cursor;
3314  // Lock the text to avoid weird things from happening.  Also disallow
3315  // switching to another window, it should not be needed and may end up in
3316  // Insert mode in another buffer.
3317  textlock++;
3318  if (use_sandbox) {
3319    sandbox++;
3320  }
3321
3322  // Call a function, which returns a list or dict.
3323  const bool called = callback_call(cb, 2, args, &rettv);
3324  if (use_sandbox) {
3325    sandbox--;
3326  }
3327  if (called) {
3328    switch (rettv.v_type) {
3329    case VAR_LIST:
3330      matchlist = rettv.vval.v_list;
3331      break;
3332    case VAR_DICT:
3333      matchdict = rettv.vval.v_dict;
3334      break;
3335    case VAR_SPECIAL:
3336      FALLTHROUGH;
3337    default:
3338      // TODO(brammool): Give error message?
3339      tv_clear(&rettv);
3340      break;
3341    }
3342  }
3343  textlock--;
3344
3345  curwin->w_cursor = pos;  // restore the cursor position
3346  check_cursor(curwin);  // make sure cursor position is valid, just in case
3347  validate_cursor(curwin);
3348  if (!equalpos(curwin->w_cursor, pos)) {
3349    emsg(_(e_compldel));
3350    goto theend;
3351  }
3352
3353  if (matchlist != NULL) {
3354    ins_compl_add_list(matchlist);
3355  } else if (matchdict != NULL) {
3356    ins_compl_add_dict(matchdict);
3357  }
3358
3359theend:
3360  // Restore State, it might have been changed.
3361  State = save_State;
3362
3363  if (matchdict != NULL) {
3364    tv_dict_unref(matchdict);
3365  }
3366  if (matchlist != NULL) {
3367    tv_list_unref(matchlist);
3368  }
3369}
3370
3371static inline int get_user_highlight_id(char *hlname)
3372{
3373  if (hlname != NULL && *hlname != NUL) {
3374    return syn_check_group(hlname, strlen(hlname));
3375  }
3376  return 0;
3377}
3378
3379/// Add a match to the list of matches from Vimscript object
3380///
3381/// @param[in]  tv  Object to get matches from.
3382/// @param[in]  dir  Completion direction.
3383/// @param[in]  fast  use fast_breakcheck() instead of os_breakcheck().
3384///
3385/// @return NOTDONE if the given string is already in the list of completions,
3386///         otherwise it is added to the list and  OK is returned. FAIL will be
3387///         returned in case of error.
3388static int ins_compl_add_tv(typval_T *const tv, const Direction dir, bool fast)
3389  FUNC_ATTR_NONNULL_ALL
3390{
3391  const char *word;
3392  bool dup = false;
3393  bool empty = false;
3394  int flags = fast ? CP_FAST : 0;
3395  bool preselect = false;
3396  char *(cptext[CPT_COUNT]);
3397  char *user_abbr_hlname = NULL;
3398  char *user_kind_hlname = NULL;
3399  char *commit_chars = NULL;
3400  int user_hl[2] = { 0, 0 };
3401  typval_T user_data;
3402
3403  user_data.v_type = VAR_UNKNOWN;
3404  if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL) {
3405    word = tv_dict_get_string(tv->vval.v_dict, "word", false);
3406    cptext[CPT_ABBR] = tv_dict_get_string(tv->vval.v_dict, "abbr", true);
3407    cptext[CPT_MENU] = tv_dict_get_string(tv->vval.v_dict, "menu", true);
3408    cptext[CPT_KIND] = tv_dict_get_string(tv->vval.v_dict, "kind", true);
3409    cptext[CPT_INFO] = tv_dict_get_string(tv->vval.v_dict, "info", true);
3410    commit_chars = tv_dict_get_string(tv->vval.v_dict, "commit_chars", true);
3411
3412    user_abbr_hlname = tv_dict_get_string(tv->vval.v_dict, "abbr_hlgroup", false);
3413    user_hl[0] = get_user_highlight_id(user_abbr_hlname);
3414
3415    user_kind_hlname = tv_dict_get_string(tv->vval.v_dict, "kind_hlgroup", false);
3416    user_hl[1] = get_user_highlight_id(user_kind_hlname);
3417
3418    tv_dict_get_tv(tv->vval.v_dict, "user_data", &user_data);
3419
3420    if (tv_dict_get_number(tv->vval.v_dict, "icase")) {
3421      flags |= CP_ICASE;
3422    }
3423    dup = (bool)tv_dict_get_number(tv->vval.v_dict, "dup");
3424    empty = (bool)tv_dict_get_number(tv->vval.v_dict, "empty");
3425    preselect = (bool)tv_dict_get_number(tv->vval.v_dict, "preselect");
3426    if (tv_dict_get_string(tv->vval.v_dict, "equal", false) != NULL
3427        && tv_dict_get_number(tv->vval.v_dict, "equal")) {
3428      flags |= CP_EQUAL;
3429    }
3430  } else {
3431    word = tv_get_string_chk(tv);
3432    CLEAR_FIELD(cptext);
3433  }
3434  if (word == NULL || (!empty && *word == NUL)) {
3435    free_cptext(cptext);
3436    tv_clear(&user_data);
3437    xfree(commit_chars);
3438    return FAIL;
3439  }
3440  int status = ins_compl_add((char *)word, -1, NULL, cptext, true,
3441                             &user_data, dir, flags, dup, user_hl, FUZZY_SCORE_NONE, preselect,
3442                             commit_chars);
3443  if (status != OK) {
3444    tv_clear(&user_data);
3445  }
3446  return status;
3447}
3448
3449/// Add completions from a list.
3450static void ins_compl_add_list(list_T *const list)
3451{
3452  Direction dir = compl_direction;
3453
3454  // Go through the List with matches and add each of them.
3455  TV_LIST_ITER(list, li, {
3456    if (ins_compl_add_tv(TV_LIST_ITEM_TV(li), dir, true) == OK) {
3457      // If dir was BACKWARD then honor it just once.
3458      dir = FORWARD;
3459    } else if (did_emsg) {
3460      break;
3461    }
3462  });
3463}
3464
3465/// Add completions from a dict.
3466static void ins_compl_add_dict(dict_T *dict)
3467{
3468  // Check for optional "refresh" item.
3469  compl_opt_refresh_always = false;
3470  dictitem_T *di_refresh = tv_dict_find(dict, S_LEN("refresh"));
3471  if (di_refresh != NULL && di_refresh->di_tv.v_type == VAR_STRING) {
3472    const char *v = di_refresh->di_tv.vval.v_string;
3473
3474    if (v != NULL && strcmp(v, "always") == 0) {
3475      compl_opt_refresh_always = true;
3476    }
3477  }
3478
3479  // Add completions from a "words" list.
3480  dictitem_T *di_words = tv_dict_find(dict, S_LEN("words"));
3481  if (di_words != NULL && di_words->di_tv.v_type == VAR_LIST) {
3482    ins_compl_add_list(di_words->di_tv.vval.v_list);
3483  }
3484}
3485
3486/// Save extmarks in "compl_orig_text" so that they may be restored when the
3487/// completion is cancelled, or the original text is completed.
3488static void save_orig_extmarks(void)
3489{
3490  extmark_splice_delete(curbuf, curwin->w_cursor.lnum - 1, compl_col, curwin->w_cursor.lnum - 1,
3491                        compl_col + compl_length, &compl_orig_extmarks, true, kExtmarkUndo);
3492}
3493
3494static void restore_orig_extmarks(void)
3495{
3496  for (long i = (int)kv_size(compl_orig_extmarks) - 1; i > -1; i--) {
3497    ExtmarkUndoObject undo_info = kv_A(compl_orig_extmarks, i);
3498    extmark_apply_undo(undo_info, true);
3499  }
3500}
3501
3502/// Start completion for the complete() function.
3503///
3504/// @param startcol  where the matched text starts (1 is first column).
3505/// @param list      the list of matches.
3506static void set_completion(colnr_T startcol, list_T *list)
3507{
3508  int flags = CP_ORIGINAL_TEXT;
3509  unsigned cur_cot_flags = get_cot_flags();
3510  bool compl_longest = (cur_cot_flags & kOptCotFlagLongest) != 0;
3511  bool compl_no_insert = (cur_cot_flags & kOptCotFlagNoinsert) != 0;
3512  bool compl_no_select = (cur_cot_flags & kOptCotFlagNoselect) != 0;
3513
3514  // If already doing completions stop it.
3515  if (compl_started || ctrl_x_mode_not_default()) {
3516    ins_compl_prep(' ');
3517  }
3518  ins_compl_clear();
3519  ins_compl_free();
3520  compl_get_longest = compl_longest;
3521
3522  compl_direction = FORWARD;
3523  if (startcol > curwin->w_cursor.col) {
3524    startcol = curwin->w_cursor.col;
3525  }
3526  compl_col = startcol;
3527  compl_lnum = curwin->w_cursor.lnum;
3528  compl_length = curwin->w_cursor.col - startcol;
3529  // compl_pattern doesn't need to be set
3530  compl_orig_text = cbuf_to_string(get_cursor_line_ptr() + compl_col,
3531                                   (size_t)compl_length);
3532  save_orig_extmarks();
3533  if (p_ic) {
3534    flags |= CP_ICASE;
3535  }
3536  if (ins_compl_add(compl_orig_text.data, (int)compl_orig_text.size,
3537                    NULL, NULL, false, NULL, 0,
3538                    flags | CP_FAST, false, NULL, FUZZY_SCORE_NONE, false, NULL) != OK) {
3539    return;
3540  }
3541
3542  ctrl_x_mode = CTRL_X_EVAL;
3543
3544  ins_compl_add_list(list);
3545  compl_matches = ins_compl_make_cyclic();
3546  compl_started = true;
3547  compl_used_match = true;
3548  compl_cont_status = 0;
3549  int save_w_wrow = curwin->w_wrow;
3550  int save_w_leftcol = curwin->w_leftcol;
3551
3552  compl_curr_match = compl_first_match;
3553  bool no_select = compl_no_select || compl_longest;
3554  if (compl_preselect_match && !no_select) {
3555    compl_curr_match = compl_preselect_match->cp_prev;
3556    ins_complete(compl_no_insert ? K_DOWN : Ctrl_N, false);
3557  } else if (compl_no_insert || no_select) {
3558    ins_complete(K_DOWN, false);
3559    if (no_select) {
3560      ins_complete(K_UP, false);
3561    }
3562  } else {
3563    ins_complete(Ctrl_N, false);
3564  }
3565  compl_enter_selects = compl_no_insert;
3566
3567  // Lazily show the popup menu, unless we got interrupted.
3568  if (!compl_interrupted) {
3569    show_pum(save_w_wrow, save_w_leftcol);
3570  }
3571
3572  may_trigger_modechanged();
3573  ui_flush();
3574}
3575
3576/// "complete()" function
3577void f_complete(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
3578{
3579  if ((State & MODE_INSERT) == 0) {
3580    emsg(_("E785: complete() can only be used in Insert mode"));
3581    return;
3582  }
3583
3584  // Check for undo allowed here, because if something was already inserted
3585  // the line was already saved for undo and this check isn't done.
3586  if (!undo_allowed(curbuf)) {
3587    return;
3588  }
3589
3590  if (argvars[1].v_type != VAR_LIST) {
3591    emsg(_(e_invarg));
3592  } else {
3593    const colnr_T startcol = (colnr_T)tv_get_number_chk(&argvars[0], NULL);
3594    if (startcol > 0) {
3595      set_completion(startcol - 1, argvars[1].vval.v_list);
3596    }
3597  }
3598}
3599
3600/// "complete_add()" function
3601void f_complete_add(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
3602{
3603  rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0, false);
3604}
3605
3606/// "complete_check()" function
3607void f_complete_check(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
3608{
3609  int saved = RedrawingDisabled;
3610
3611  RedrawingDisabled = 0;
3612  ins_compl_check_keys(0, true);
3613  rettv->vval.v_number = ins_compl_interrupted();
3614  RedrawingDisabled = saved;
3615}
3616
3617/// Return Insert completion mode name string
3618static String ins_compl_mode(void)
3619{
3620  if (ctrl_x_mode_not_defined_yet() || ctrl_x_mode_scroll() || compl_started) {
3621    String *mode = &ctrl_x_mode_names[ctrl_x_mode & ~CTRL_X_WANT_IDENT];
3622    return cbuf_as_string(mode->data == NULL ? "" : mode->data, mode->size);
3623  }
3624  return cbuf_as_string("", 0);
3625}
3626
3627/// Assign the sequence number to all the completion matches which don't have
3628/// one assigned yet.
3629static void ins_compl_update_sequence_numbers(void)
3630{
3631  int number = 0;
3632  compl_T *match;
3633
3634  if (compl_dir_forward()) {
3635    // Search backwards for the first valid (!= -1) number.
3636    // This should normally succeed already at the first loop
3637    // cycle, so it's fast!
3638    for (match = compl_curr_match->cp_prev;
3639         match != NULL && !is_first_match(match); match = match->cp_prev) {
3640      if (match->cp_number != -1) {
3641        number = match->cp_number;
3642        break;
3643      }
3644    }
3645    if (match != NULL) {
3646      // go up and assign all numbers which are not assigned yet
3647      for (match = match->cp_next;
3648           match != NULL && match->cp_number == -1;
3649           match = match->cp_next) {
3650        match->cp_number = ++number;
3651      }
3652    }
3653  } else {  // BACKWARD
3654    assert(compl_direction == BACKWARD);
3655    // Search forwards (upwards) for the first valid (!= -1)
3656    // number.  This should normally succeed already at the
3657    // first loop cycle, so it's fast!
3658    for (match = compl_curr_match->cp_next;
3659         match != NULL && !is_first_match(match); match = match->cp_next) {
3660      if (match->cp_number != -1) {
3661        number = match->cp_number;
3662        break;
3663      }
3664    }
3665    if (match != NULL) {
3666      // go down and assign all numbers which are not assigned yet
3667      for (match = match->cp_prev;
3668           match && match->cp_number == -1;
3669           match = match->cp_prev) {
3670        match->cp_number = ++number;
3671      }
3672    }
3673  }
3674}
3675
3676/// Fill the dict of complete_info
3677static void fill_complete_info_dict(dict_T *di, compl_T *match, bool add_match)
3678{
3679  tv_dict_add_str_len(di, S_LEN("word"), match->cp_str.data, (int)match->cp_str.size);
3680  tv_dict_add_str(di, S_LEN("abbr"), match->cp_text[CPT_ABBR]);
3681  tv_dict_add_str(di, S_LEN("menu"), match->cp_text[CPT_MENU]);
3682  tv_dict_add_str(di, S_LEN("kind"), match->cp_text[CPT_KIND]);
3683  tv_dict_add_str(di, S_LEN("info"), match->cp_text[CPT_INFO]);
3684  tv_dict_add_str(di, S_LEN("abbr_hlgroup"), syn_id2name(match->cp_user_abbr_hl_id));
3685  tv_dict_add_str(di, S_LEN("kind_hlgroup"), syn_id2name(match->cp_user_kind_hl_id));
3686  if (add_match) {
3687    tv_dict_add_bool(di, S_LEN("match"), match->cp_in_match_array);
3688  }
3689  if (match->cp_flags & CP_EQUAL) {
3690    tv_dict_add_nr(di, S_LEN("equal"), 1);
3691  }
3692  if (match->cp_preselect) {
3693    tv_dict_add_nr(di, S_LEN("preselect"), 1);
3694  }
3695  if (match->cp_commit_chars != NULL) {
3696    tv_dict_add_str(di, S_LEN("commit_chars"), match->cp_commit_chars);
3697  }
3698  if (match->cp_user_data.v_type == VAR_UNKNOWN) {
3699    // Add an empty string for backwards compatibility
3700    tv_dict_add_str_len(di, S_LEN("user_data"), "", 0);
3701  } else {
3702    tv_dict_add_tv(di, S_LEN("user_data"), &match->cp_user_data);
3703  }
3704}
3705
3706/// Get complete information
3707static void get_complete_info(list_T *what_list, dict_T *retdict)
3708{
3709#define CI_WHAT_MODE                0x01
3710#define CI_WHAT_PUM_VISIBLE         0x02
3711#define CI_WHAT_ITEMS               0x04
3712#define CI_WHAT_SELECTED            0x08
3713#define CI_WHAT_COMPLETED           0x10
3714#define CI_WHAT_MATCHES             0x20
3715#define CI_WHAT_PREINSERTED_TEXT    0x40
3716#define CI_WHAT_AUTO                0x80
3717#define CI_WHAT_ALL                 0xff
3718  int what_flag;
3719
3720  if (what_list == NULL) {
3721    what_flag = CI_WHAT_ALL & ~(CI_WHAT_MATCHES|CI_WHAT_COMPLETED|CI_WHAT_AUTO);
3722  } else {
3723    what_flag = 0;
3724    for (listitem_T *item = tv_list_first(what_list)
3725         ; item != NULL
3726         ; item = TV_LIST_ITEM_NEXT(what_list, item)) {
3727      const char *what = tv_get_string(TV_LIST_ITEM_TV(item));
3728
3729      if (strcmp(what, "mode") == 0) {
3730        what_flag |= CI_WHAT_MODE;
3731      } else if (strcmp(what, "pum_visible") == 0) {
3732        what_flag |= CI_WHAT_PUM_VISIBLE;
3733      } else if (strcmp(what, "items") == 0) {
3734        what_flag |= CI_WHAT_ITEMS;
3735      } else if (strcmp(what, "selected") == 0) {
3736        what_flag |= CI_WHAT_SELECTED;
3737      } else if (strcmp(what, "completed") == 0) {
3738        what_flag |= CI_WHAT_COMPLETED;
3739      } else if (strcmp(what, "preinserted_text") == 0) {
3740        what_flag |= CI_WHAT_PREINSERTED_TEXT;
3741      } else if (strcmp(what, "matches") == 0) {
3742        what_flag |= CI_WHAT_MATCHES;
3743      } else if (strcmp(what, "auto") == 0) {
3744        what_flag |= CI_WHAT_AUTO;
3745      }
3746    }
3747  }
3748
3749  int ret = OK;
3750  if (what_flag & CI_WHAT_MODE) {
3751    String mode = ins_compl_mode();
3752    ret = tv_dict_add_str_len(retdict, S_LEN("mode"), mode.data, (int)mode.size);
3753  }
3754
3755  if (ret == OK && (what_flag & CI_WHAT_PUM_VISIBLE)) {
3756    ret = tv_dict_add_nr(retdict, S_LEN("pum_visible"), pum_visible());
3757  }
3758
3759  if (ret == OK && (what_flag & CI_WHAT_AUTO)) {
3760    ret = tv_dict_add_nr(retdict, S_LEN("auto"), compl_autostarted);
3761  }
3762
3763  if (ret == OK && (what_flag & CI_WHAT_PREINSERTED_TEXT)) {
3764    char *line = get_cursor_line_ptr();
3765    int len = compl_ins_end_col - curwin->w_cursor.col;
3766    ret = tv_dict_add_str_len(retdict, S_LEN("preinserted_text"),
3767                              len > 0 ? line + curwin->w_cursor.col : "", MAX(len, 0));
3768  }
3769
3770  if (ret == OK && (what_flag & (CI_WHAT_ITEMS|CI_WHAT_SELECTED
3771                                 |CI_WHAT_MATCHES|CI_WHAT_COMPLETED))) {
3772    list_T *li = NULL;
3773    int selected_idx = -1;
3774    bool has_items = what_flag & CI_WHAT_ITEMS;
3775    bool has_matches = what_flag & CI_WHAT_MATCHES;
3776    bool has_completed = what_flag & CI_WHAT_COMPLETED;
3777    if (has_items || has_matches) {
3778      li = tv_list_alloc(kListLenMayKnow);
3779      const char *key = (has_matches && !has_items) ? "matches" : "items";
3780      ret = tv_dict_add_list(retdict, key, strlen(key), li);
3781    }
3782    if (ret == OK && what_flag & CI_WHAT_SELECTED) {
3783      if (compl_curr_match != NULL && compl_curr_match->cp_number == -1) {
3784        ins_compl_update_sequence_numbers();
3785      }
3786    }
3787    if (ret == OK && compl_first_match != NULL) {
3788      int list_idx = 0;
3789      compl_T *match = compl_first_match;
3790      do {
3791        if (!match_at_original_text(match)) {
3792          if (has_items || (has_matches && match->cp_in_match_array)) {
3793            dict_T *di = tv_dict_alloc();
3794            tv_list_append_dict(li, di);
3795            fill_complete_info_dict(di, match, has_matches && has_items);
3796          }
3797          if (compl_curr_match != NULL
3798              && compl_curr_match->cp_number == match->cp_number) {
3799            selected_idx = list_idx;
3800          }
3801          if (!has_matches || match->cp_in_match_array) {
3802            list_idx++;
3803          }
3804        }
3805        match = match->cp_next;
3806      } while (match != NULL && !is_first_match(match));
3807    }
3808    if (ret == OK && (what_flag & CI_WHAT_SELECTED)) {
3809      ret = tv_dict_add_nr(retdict, S_LEN("selected"), selected_idx);
3810      win_T *wp = win_float_find(kWinInfo);
3811      if (wp != NULL) {
3812        tv_dict_add_nr(retdict, S_LEN("preview_winid"), wp->handle);
3813        tv_dict_add_nr(retdict, S_LEN("preview_bufnr"), wp->w_buffer->handle);
3814      }
3815    }
3816    if (ret == OK && selected_idx != -1 && has_completed) {
3817      dict_T *di = tv_dict_alloc();
3818      fill_complete_info_dict(di, compl_curr_match, false);
3819      ret = tv_dict_add_dict(retdict, S_LEN("completed"), di);
3820    }
3821  }
3822
3823  (void)ret;
3824}
3825
3826/// "complete_info()" function
3827void f_complete_info(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
3828{
3829  tv_dict_alloc_ret(rettv);
3830
3831  list_T *what_list = NULL;
3832
3833  if (argvars[0].v_type != VAR_UNKNOWN) {
3834    if (argvars[0].v_type != VAR_LIST) {
3835      emsg(_(e_listreq));
3836      return;
3837    }
3838    what_list = argvars[0].vval.v_list;
3839  }
3840  get_complete_info(what_list, rettv->vval.v_dict);
3841}
3842
3843/// Returns true when using a user-defined function for thesaurus completion.
3844static bool thesaurus_func_complete(int type)
3845{
3846  return type == CTRL_X_THESAURUS
3847         && (curbuf->b_p_tsrfu.type != kCallbackNone || p_tsrfu.type != kCallbackNone);
3848}
3849
3850/// Check if 'cpt' list index can be advanced to the next completion source.
3851static bool may_advance_cpt_index(const char *cpt)
3852{
3853  const char *p = cpt;
3854
3855  if (cpt_sources_index == -1) {
3856    return false;
3857  }
3858  while (*p == ',' || *p == ' ') {  // Skip delimiters
3859    p++;
3860  }
3861  return (*p != NUL);
3862}
3863
3864/// Return value of process_next_cpt_value()
3865enum {
3866  INS_COMPL_CPT_OK = 1,
3867  INS_COMPL_CPT_CONT,
3868  INS_COMPL_CPT_END,
3869};
3870
3871/// Process the next 'complete' option value in st->e_cpt.
3872///
3873/// If successful, the arguments are set as below:
3874///   st->cpt - pointer to the next option value in "st->cpt"
3875///   compl_type_arg - type of insert mode completion to use
3876///   st->found_all - all matches of this type are found
3877///   st->ins_buf - search for completions in this buffer
3878///   st->first_match_pos - position of the first completion match
3879///   st->last_match_pos - position of the last completion match
3880///   st->set_match_pos - true if the first match position should be saved to
3881///                       avoid loops after the search wraps around.
3882///   st->dict - name of the dictionary or thesaurus file to search
3883///   st->dict_f - flag specifying whether "dict" is an exact file name or not
3884///
3885/// @return  INS_COMPL_CPT_OK if the next value is processed successfully.
3886///          INS_COMPL_CPT_CONT to skip the current completion source matching
3887///          the "st->e_cpt" option value and process the next matching source.
3888///          INS_COMPL_CPT_END if all the values in "st->e_cpt" are processed.
3889static int process_next_cpt_value(ins_compl_next_state_T *st, int *compl_type_arg,
3890                                  pos_T *start_match_pos, bool fuzzy_collect, bool *advance_cpt_idx)
3891{
3892  int compl_type = -1;
3893  int status = INS_COMPL_CPT_OK;
3894  bool skip_source = compl_autocomplete && compl_from_nonkeyword;
3895
3896  st->found_all = false;
3897  *advance_cpt_idx = false;
3898
3899  while (*st->e_cpt == ',' || *st->e_cpt == ' ') {
3900    st->e_cpt++;
3901  }
3902
3903  if (*st->e_cpt == '.' && !curbuf->b_scanned && !skip_source
3904      && !compl_time_slice_expired) {
3905    st->ins_buf = curbuf;
3906    st->first_match_pos = *start_match_pos;
3907    // Move the cursor back one character so that ^N can match the
3908    // word immediately after the cursor.
3909    if (ctrl_x_mode_normal() && (!fuzzy_collect && dec(&st->first_match_pos) < 0)) {
3910      // Move the cursor to after the last character in the
3911      // buffer, so that word at start of buffer is found
3912      // correctly.
3913      st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count;
3914      st->first_match_pos.col = ml_get_len(st->first_match_pos.lnum);
3915    }
3916    st->last_match_pos = st->first_match_pos;
3917    compl_type = 0;
3918
3919    // Remember the first match so that the loop stops when we
3920    // wrap and come back there a second time.
3921    st->set_match_pos = true;
3922  } else if (!skip_source && !compl_time_slice_expired
3923             && vim_strchr("buwU", (uint8_t)(*st->e_cpt)) != NULL
3924             && (st->ins_buf = ins_compl_next_buf(st->ins_buf, *st->e_cpt)) != curbuf) {
3925    // Scan a buffer, but not the current one.
3926    if (st->ins_buf->b_ml.ml_mfp != NULL) {  // loaded buffer
3927      compl_started = true;
3928      st->first_match_pos.col = st->last_match_pos.col = 0;
3929      st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count + 1;
3930      st->last_match_pos.lnum = 0;
3931      compl_type = 0;
3932    } else {  // unloaded buffer, scan like dictionary
3933      st->found_all = true;
3934      if (st->ins_buf->b_fname == NULL) {
3935        status = INS_COMPL_CPT_CONT;
3936        goto done;
3937      }
3938      compl_type = CTRL_X_DICTIONARY;
3939      st->dict = st->ins_buf->b_fname;
3940      st->dict_f = DICT_EXACT;
3941    }
3942    if (!shortmess(kShmCompletionscan) && !compl_autocomplete) {
3943      vim_snprintf(IObuff, IOSIZE, _("Scanning: %s"),
3944                   st->ins_buf->b_fname == NULL
3945                   ? buf_spname(st->ins_buf)
3946                   : st->ins_buf->b_sfname == NULL
3947                   ? st->ins_buf->b_fname
3948                   : st->ins_buf->b_sfname);
3949      msg_progress(IObuff, "nvim.completion", "running", HLF_R, false, true, false);
3950    }
3951  } else if (*st->e_cpt == NUL) {
3952    status = INS_COMPL_CPT_END;
3953  } else {
3954    if (ctrl_x_mode_line_or_eval()) {
3955      // compl_type = -1;
3956    } else if (*st->e_cpt == 'F' || *st->e_cpt == 'o') {
3957      compl_type = CTRL_X_FUNCTION;
3958      st->func_cb = get_callback_if_cpt_func(st->e_cpt, cpt_sources_index);
3959      if (!st->func_cb) {
3960        compl_type = -1;
3961      }
3962    } else if (!skip_source) {
3963      if (*st->e_cpt == 'k' || *st->e_cpt == 's') {
3964        if (*st->e_cpt == 'k') {
3965          compl_type = CTRL_X_DICTIONARY;
3966        } else {
3967          compl_type = CTRL_X_THESAURUS;
3968        }
3969        if (*++st->e_cpt != ',' && *st->e_cpt != NUL) {
3970          st->dict = st->e_cpt;
3971          st->dict_f = DICT_FIRST;
3972        }
3973      } else if (*st->e_cpt == 'i') {
3974        compl_type = CTRL_X_PATH_PATTERNS;
3975      } else if (*st->e_cpt == 'd') {
3976        compl_type = CTRL_X_PATH_DEFINES;
3977      } else if (*st->e_cpt == 'f') {
3978        compl_type = CTRL_X_BUFNAMES;
3979      } else if (*st->e_cpt == ']' || *st->e_cpt == 't') {
3980        compl_type = CTRL_X_TAGS;
3981        if (!shortmess(kShmCompletionscan) && !compl_autocomplete) {
3982          vim_snprintf(IObuff, IOSIZE, "%s", _("Scanning tags."));
3983          msg_progress(IObuff, "nvim.completion", "running", HLF_R, false, true, false);
3984        }
3985      }
3986    }
3987
3988    // in any case e_cpt is advanced to the next entry
3989    copy_option_part(&st->e_cpt, IObuff, IOSIZE, ",");
3990    *advance_cpt_idx = may_advance_cpt_index(st->e_cpt);
3991
3992    st->found_all = true;
3993    if (compl_type == -1) {
3994      status = INS_COMPL_CPT_CONT;
3995    }
3996  }
3997
3998done:
3999  *compl_type_arg = compl_type;
4000  return status;
4001}
4002
4003/// Get the next set of identifiers or defines matching "compl_pattern" in
4004/// included files.
4005static void get_next_include_file_completion(int compl_type)
4006{
4007  find_pattern_in_path(compl_pattern.data, compl_direction,
4008                       compl_pattern.size, false, false,
4009                       ((compl_type == CTRL_X_PATH_DEFINES
4010                         && !(compl_cont_status & CONT_SOL))
4011                        ? FIND_DEFINE : FIND_ANY),
4012                       1, ACTION_EXPAND, 1, MAXLNUM, false, compl_autocomplete);
4013}
4014
4015/// Get the next set of words matching "compl_pattern" in dictionary or
4016/// thesaurus files.
4017static void get_next_dict_tsr_completion(int compl_type, char *dict, int dict_f)
4018{
4019  if (thesaurus_func_complete(compl_type)) {
4020    expand_by_function(compl_type, compl_pattern.data, NULL);
4021  } else {
4022    ins_compl_dictionaries(dict != NULL
4023                           ? dict
4024                           : (compl_type == CTRL_X_THESAURUS
4025                              ? (*curbuf->b_p_tsr == NUL ? p_tsr : curbuf->b_p_tsr)
4026                              : (*curbuf->b_p_dict == NUL ? p_dict : curbuf->b_p_dict)),
4027                           compl_pattern.data,
4028                           dict != NULL ? dict_f : 0,
4029                           compl_type == CTRL_X_THESAURUS);
4030  }
4031}
4032
4033/// Get the next set of tag names matching "compl_pattern".
4034static void get_next_tag_completion(void)
4035{
4036  // set p_ic according to p_ic, p_scs and pat for find_tags().
4037  const int save_p_ic = p_ic;
4038  p_ic = ignorecase(compl_pattern.data);
4039
4040  // Find up to TAG_MANY matches.  Avoids that an enormous number
4041  // of matches is found when compl_pattern is empty
4042  g_tag_at_cursor = true;
4043  char **matches;
4044  int num_matches;
4045  if (find_tags(compl_pattern.data, &num_matches, &matches,
4046                TAG_REGEXP | TAG_NAMES | TAG_NOIC | TAG_INS_COMP
4047                | (ctrl_x_mode_not_default() ? TAG_VERBOSE : 0),
4048                TAG_MANY, curbuf->b_ffname) == OK && num_matches > 0) {
4049    ins_compl_add_matches(num_matches, matches, p_ic);
4050  }
4051  g_tag_at_cursor = false;
4052  p_ic = save_p_ic;
4053}
4054
4055/// Compare function for qsort
4056static int compare_scores(const void *a, const void *b)
4057{
4058  int idx_a = *(const int *)a;
4059  int idx_b = *(const int *)b;
4060  int score_a = compl_fuzzy_scores[idx_a];
4061  int score_b = compl_fuzzy_scores[idx_b];
4062  return score_a == score_b ? (idx_a == idx_b ? 0 : (idx_a < idx_b ? -1 : 1))
4063                            : (score_a > score_b ? -1 : 1);
4064}
4065
4066/// insert prefix with redraw
4067static void ins_compl_longest_insert(char *prefix)
4068{
4069  ins_compl_delete(false);
4070  ins_compl_insert_bytes(prefix + get_compl_len(), -1);
4071  compl_longest_end_col = curwin->w_cursor.col;
4072  ins_redraw(false);
4073}
4074
4075/// Calculate the longest common prefix among the best fuzzy matches
4076/// stored in compl_best_matches, and insert it as the longest.
4077static void fuzzy_longest_match(void)
4078{
4079  if (compl_num_bests == 0) {
4080    return;
4081  }
4082
4083  compl_T *nn_compl = compl_first_match->cp_next->cp_next;
4084  bool more_candidates = nn_compl && nn_compl != compl_first_match;
4085
4086  compl_T *compl = ctrl_x_mode_whole_line() ? compl_first_match
4087                                            : compl_first_match->cp_next;
4088  if (compl_num_bests == 1) {
4089    // no more candidates insert the match str
4090    if (!more_candidates) {
4091      ins_compl_longest_insert(compl->cp_str.data);
4092      compl_num_bests = 0;
4093    }
4094    compl_num_bests = 0;
4095    return;
4096  }
4097
4098  if ((size_t)compl_num_bests > SIZE_MAX / sizeof(compl_T *)) {
4099    return;
4100  }
4101  compl_best_matches = (compl_T **)xmalloc((size_t)compl_num_bests * sizeof(compl_T *));
4102
4103  for (int i = 0; compl != NULL && i < compl_num_bests; i++) {
4104    compl_best_matches[i] = compl;
4105    compl = compl->cp_next;
4106  }
4107
4108  char *prefix = compl_best_matches[0]->cp_str.data;
4109  int prefix_len = (int)compl_best_matches[0]->cp_str.size;
4110
4111  for (int i = 1; i < compl_num_bests; i++) {
4112    char *match_str = compl_best_matches[i]->cp_str.data;
4113    char *prefix_ptr = prefix;
4114    char *match_ptr = match_str;
4115    int j = 0;
4116
4117    while (j < prefix_len && *match_ptr != NUL && *prefix_ptr != NUL) {
4118      if (strncmp(prefix_ptr, match_ptr, (size_t)utfc_ptr2len(prefix_ptr)) != 0) {
4119        break;
4120      }
4121
4122      MB_PTR_ADV(prefix_ptr);
4123      MB_PTR_ADV(match_ptr);
4124      j++;
4125    }
4126
4127    if (j > 0) {
4128      prefix_len = j;
4129    }
4130  }
4131
4132  char *leader = ins_compl_leader();
4133  size_t leader_len = ins_compl_leader_len();
4134
4135  // skip non-consecutive prefixes
4136  if (leader_len > 0 && strncmp(prefix, leader, leader_len) != 0) {
4137    goto end;
4138  }
4139
4140  prefix = xmemdupz(prefix, (size_t)prefix_len);
4141  ins_compl_longest_insert(prefix);
4142  xfree(prefix);
4143
4144end:
4145  xfree(compl_best_matches);
4146  compl_best_matches = NULL;
4147  compl_num_bests = 0;
4148}
4149
4150/// Get the next set of filename matching "compl_pattern".
4151static void get_next_filename_completion(void)
4152{
4153  char **matches;
4154  int num_matches;
4155  char *leader = ins_compl_leader();
4156  size_t leader_len = ins_compl_leader_len();
4157  bool in_fuzzy_collect = (cot_fuzzy() && leader_len > 0);
4158  bool need_collect_bests = in_fuzzy_collect && compl_get_longest;
4159  int max_score = 0;
4160  Direction dir = compl_direction;
4161
4162  if (in_fuzzy_collect) {
4163    TO_SLASH(leader);
4164    char *last_sep = strrchr(leader, PATHSEP);
4165    if (last_sep == NULL) {
4166      // No path separator or separator is the last character,
4167      // fuzzy match the whole leader
4168      API_CLEAR_STRING(compl_pattern);
4169      compl_pattern = cbuf_to_string("*", 1);
4170    } else if (*(last_sep + 1) == NUL) {
4171      in_fuzzy_collect = false;
4172    } else {
4173      // Split leader into path and file parts
4174      size_t path_len = (size_t)(last_sep - leader) + 1;
4175      char *path_with_wildcard = xmalloc(path_len + 2);
4176      vim_snprintf(path_with_wildcard, path_len + 2, "%*.*s*",
4177                   (int)path_len, (int)path_len, leader);
4178      API_CLEAR_STRING(compl_pattern);
4179      compl_pattern.data = path_with_wildcard;
4180      compl_pattern.size = path_len + 1;
4181
4182      // Move leader to the file part
4183      leader = last_sep + 1;
4184      leader_len -= path_len;
4185    }
4186  }
4187
4188  if (expand_wildcards(1, &compl_pattern.data, &num_matches, &matches,
4189                       EW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) != OK) {
4190    return;
4191  }
4192
4193  // May change home directory back to "~".
4194  tilde_replace(compl_pattern.data, num_matches, matches);
4195#ifdef BACKSLASH_IN_FILENAME
4196  if ((curbuf->b_p_csl[0] == NUL && !p_ssl) || curbuf->b_p_csl[0] == 'b') {
4197    for (int i = 0; i < num_matches; i++) {
4198      for (char *ptr = matches[i]; *ptr; ptr++) {
4199        if (*ptr == '/') {
4200          *ptr = '\\';
4201        }
4202      }
4203    }
4204  }
4205#endif
4206
4207  if (in_fuzzy_collect) {
4208    garray_T fuzzy_indices;
4209    ga_init(&fuzzy_indices, sizeof(int), 10);
4210    compl_fuzzy_scores = (int *)xmalloc(sizeof(int) * (size_t)num_matches);
4211
4212    for (int i = 0; i < num_matches; i++) {
4213      char *ptr = matches[i];
4214      int score = fuzzy_match_str(ptr, leader);
4215      if (score != FUZZY_SCORE_NONE) {
4216        GA_APPEND(int, &fuzzy_indices, i);
4217        compl_fuzzy_scores[i] = score;
4218      }
4219    }
4220
4221    // prevent qsort from deref NULL pointer
4222    if (fuzzy_indices.ga_len > 0) {
4223      int *fuzzy_indices_data = (int *)fuzzy_indices.ga_data;
4224      qsort(fuzzy_indices_data, (size_t)fuzzy_indices.ga_len, sizeof(int), compare_scores);
4225
4226      for (int i = 0; i < fuzzy_indices.ga_len; i++) {
4227        char *match = matches[fuzzy_indices_data[i]];
4228        int current_score = compl_fuzzy_scores[fuzzy_indices_data[i]];
4229        if (ins_compl_add(match, -1, NULL, NULL, false, NULL, dir,
4230                          CP_FAST | ((p_fic || p_wic) ? CP_ICASE : 0),
4231                          false, NULL, current_score, false, NULL) == OK) {
4232          dir = FORWARD;
4233        }
4234
4235        if (need_collect_bests) {
4236          if (i == 0 || current_score == max_score) {
4237            compl_num_bests++;
4238            max_score = current_score;
4239          }
4240        }
4241      }
4242
4243      FreeWild(num_matches, matches);
4244    } else if (leader_len > 0) {
4245      FreeWild(num_matches, matches);
4246      num_matches = 0;
4247    }
4248
4249    xfree(compl_fuzzy_scores);
4250    ga_clear(&fuzzy_indices);
4251
4252    if (compl_num_bests > 0 && compl_get_longest) {
4253      fuzzy_longest_match();
4254    }
4255    return;
4256  }
4257
4258  if (num_matches > 0) {
4259    ins_compl_add_matches(num_matches, matches, p_fic || p_wic);
4260  }
4261}
4262
4263/// Get the next set of command-line completions matching "compl_pattern".
4264static void get_next_cmdline_completion(void)
4265{
4266  char **matches;
4267  int num_matches;
4268  if (expand_cmdline(&compl_xp, compl_pattern.data,
4269                     (int)compl_pattern.size, &num_matches, &matches) == EXPAND_OK) {
4270    int add_r = OK;
4271    Direction dir = compl_direction;
4272
4273    for (int i = 0; i < num_matches && add_r != FAIL; i++) {
4274      char *(cptext[CPT_COUNT]) = { NULL, NULL, NULL, NULL };
4275
4276      if (compl_xp.xp_files_abbr != NULL) {
4277        cptext[CPT_ABBR] = compl_xp.xp_files_abbr[i];
4278      }
4279      if (compl_xp.xp_files_kind != NULL) {
4280        cptext[CPT_KIND] = compl_xp.xp_files_kind[i];
4281      }
4282      if (compl_xp.xp_files_menu != NULL) {
4283        cptext[CPT_MENU] = compl_xp.xp_files_menu[i];
4284      }
4285      if (compl_xp.xp_files_info != NULL) {
4286        cptext[CPT_INFO] = compl_xp.xp_files_info[i];
4287      }
4288
4289      add_r = ins_compl_add(matches[i], -1, NULL, cptext, false, NULL, dir,
4290                            CP_FAST, false, NULL, FUZZY_SCORE_NONE, false, NULL);
4291      if (add_r == OK) {
4292        // if dir was BACKWARD then honor it just once
4293        dir = FORWARD;
4294      }
4295    }
4296    FreeWild(num_matches, matches);
4297    free_xp_files_extra(&compl_xp, num_matches);
4298  }
4299}
4300
4301/// Get the next set of spell suggestions matching "compl_pattern".
4302static void get_next_spell_completion(linenr_T lnum)
4303{
4304  char **matches;
4305  int num_matches = expand_spelling(lnum, compl_pattern.data, &matches);
4306  if (num_matches > 0) {
4307    ins_compl_add_matches(num_matches, matches, p_ic);
4308  } else {
4309    xfree(matches);
4310  }
4311}
4312
4313/// Return the next word or line from buffer "ins_buf" at position
4314/// "cur_match_pos" for completion.  The length of the match is set in "len".
4315/// @param ins_buf        buffer being scanned
4316/// @param cur_match_pos  current match position
4317/// @param match_len
4318/// @param cont_s_ipos    next ^X<> will set initial_pos
4319static char *ins_compl_get_next_word_or_line(buf_T *ins_buf, pos_T *cur_match_pos, int *match_len,
4320                                             bool *cont_s_ipos)
4321{
4322  *match_len = 0;
4323  char *ptr = ml_get_buf(ins_buf, cur_match_pos->lnum) + cur_match_pos->col;
4324  int len = ml_get_buf_len(ins_buf, cur_match_pos->lnum) - cur_match_pos->col;
4325  if (ctrl_x_mode_line_or_eval()) {
4326    if (compl_status_adding()) {
4327      if (cur_match_pos->lnum >= ins_buf->b_ml.ml_line_count) {
4328        return NULL;
4329      }
4330      ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1);
4331      len = ml_get_buf_len(ins_buf, cur_match_pos->lnum + 1);
4332      if (!p_paste) {
4333        char *tmp_ptr = ptr;
4334        ptr = skipwhite(tmp_ptr);
4335        len -= (int)(ptr - tmp_ptr);
4336      }
4337    }
4338  } else {
4339    char *tmp_ptr = ptr;
4340
4341    if (compl_status_adding() && compl_length <= len) {
4342      tmp_ptr += compl_length;
4343      // Skip if already inside a word.
4344      if (vim_iswordp(tmp_ptr)) {
4345        return NULL;
4346      }
4347      // Find start of next word.
4348      tmp_ptr = find_word_start(tmp_ptr);
4349    }
4350    // Find end of this word.
4351    tmp_ptr = find_word_end(tmp_ptr);
4352    len = (int)(tmp_ptr - ptr);
4353
4354    if (compl_status_adding() && len == compl_length) {
4355      if (cur_match_pos->lnum < ins_buf->b_ml.ml_line_count) {
4356        // Try next line, if any. the new word will be "join" as if the
4357        // normal command "J" was used. IOSIZE is always greater than
4358        // compl_length, so the next strncpy always works -- Acevedo
4359        strncpy(IObuff, ptr, (size_t)len);  // NOLINT(runtime/printf)
4360        ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1);
4361        tmp_ptr = ptr = skipwhite(ptr);
4362        // Find start of next word.
4363        tmp_ptr = find_word_start(tmp_ptr);
4364        // Find end of next word.
4365        tmp_ptr = find_word_end(tmp_ptr);
4366        if (tmp_ptr > ptr) {
4367          if (*ptr != ')' && IObuff[len - 1] != TAB) {
4368            if (IObuff[len - 1] != ' ') {
4369              IObuff[len++] = ' ';
4370            }
4371            // IObuf =~ "\k.* ", thus len >= 2
4372            if (p_js
4373                && (IObuff[len - 2] == '.'
4374                    || IObuff[len - 2] == '?'
4375                    || IObuff[len - 2] == '!')) {
4376              IObuff[len++] = ' ';
4377            }
4378          }
4379          // copy as much as possible of the new word
4380          if (tmp_ptr - ptr >= IOSIZE - len) {
4381            tmp_ptr = ptr + IOSIZE - len - 1;
4382          }
4383          xstrlcpy(IObuff + len, ptr, (size_t)(IOSIZE - len));
4384          len += (int)(tmp_ptr - ptr);
4385          *cont_s_ipos = true;
4386        }
4387        IObuff[len] = NUL;
4388        ptr = IObuff;
4389      }
4390      if (len == compl_length) {
4391        return NULL;
4392      }
4393    }
4394  }
4395
4396  *match_len = len;
4397  return ptr;
4398}
4399
4400/// Get the next set of words matching "compl_pattern" for default completion(s)
4401/// (normal ^P/^N and ^X^L).
4402/// Search for "compl_pattern" in the buffer "st->ins_buf" starting from the
4403/// position "st->start_pos" in the "compl_direction" direction. If
4404/// "st->set_match_pos" is true, then set the "st->first_match_pos" and
4405/// "st->last_match_pos".
4406///
4407/// @return  OK if a new next match is found, otherwise FAIL.
4408static int get_next_default_completion(ins_compl_next_state_T *st, pos_T *start_pos)
4409{
4410  char *ptr = NULL;
4411  int len = 0;
4412  bool in_fuzzy_collect = !compl_status_adding() && cot_fuzzy() && compl_length > 0;
4413  char *leader = ins_compl_leader();
4414  int score = FUZZY_SCORE_NONE;
4415  const bool in_curbuf = st->ins_buf == curbuf;
4416
4417  // If 'infercase' is set, don't use 'smartcase' here
4418  const int save_p_scs = p_scs;
4419  assert(st->ins_buf);
4420  if (st->ins_buf->b_p_inf) {
4421    p_scs = false;
4422  }
4423
4424  // Buffers other than curbuf are scanned from the beginning or the
4425  // end but never from the middle, thus setting nowrapscan in this
4426  // buffers is a good idea, on the other hand, we always set
4427  // wrapscan for curbuf to avoid missing matches -- Acevedo,Webb
4428  const int save_p_ws = p_ws;
4429  if (!in_curbuf) {
4430    p_ws = false;
4431  } else if (*st->e_cpt == '.') {
4432    p_ws = true;
4433  }
4434  bool looped_around = false;
4435  int found_new_match = FAIL;
4436  while (true) {
4437    bool cont_s_ipos = false;
4438
4439    msg_silent++;  // Don't want messages for wrapscan.
4440
4441    if (in_fuzzy_collect) {
4442      found_new_match = search_for_fuzzy_match(st->ins_buf,
4443                                               st->cur_match_pos, leader, compl_direction,
4444                                               start_pos, &len, &ptr, &score);
4445      // ctrl_x_mode_line_or_eval() || word-wise search that
4446      // has added a word that was at the beginning of the line.
4447    } else if (ctrl_x_mode_whole_line() || ctrl_x_mode_eval()
4448               || (compl_cont_status & CONT_SOL)) {
4449      found_new_match = search_for_exact_line(st->ins_buf, st->cur_match_pos,
4450                                              compl_direction, compl_pattern.data);
4451    } else {
4452      found_new_match = searchit(NULL, st->ins_buf, st->cur_match_pos,
4453                                 NULL, compl_direction, compl_pattern.data,
4454                                 compl_pattern.size,
4455                                 1, SEARCH_KEEP + SEARCH_NFMSG, RE_LAST, p_magic, NULL);
4456    }
4457    msg_silent--;
4458    if (!compl_started || st->set_match_pos) {
4459      // set "compl_started" even on fail
4460      compl_started = true;
4461      st->first_match_pos = *st->cur_match_pos;
4462      st->last_match_pos = *st->cur_match_pos;
4463      st->set_match_pos = false;
4464    } else if (st->first_match_pos.lnum == st->last_match_pos.lnum
4465               && st->first_match_pos.col == st->last_match_pos.col) {
4466      found_new_match = FAIL;
4467    } else if (compl_dir_forward()
4468               && (st->prev_match_pos.lnum > st->cur_match_pos->lnum
4469                   || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
4470                       && st->prev_match_pos.col >= st->cur_match_pos->col))) {
4471      if (looped_around) {
4472        found_new_match = FAIL;
4473      } else {
4474        looped_around = true;
4475      }
4476    } else if (!compl_dir_forward()
4477               && (st->prev_match_pos.lnum < st->cur_match_pos->lnum
4478                   || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
4479                       && st->prev_match_pos.col <= st->cur_match_pos->col))) {
4480      if (looped_around) {
4481        found_new_match = FAIL;
4482      } else {
4483        looped_around = true;
4484      }
4485    }
4486    st->prev_match_pos = *st->cur_match_pos;
4487    if (found_new_match == FAIL) {
4488      break;
4489    }
4490
4491    // when ADDING, the text before the cursor matches, skip it
4492    if (compl_status_adding() && in_curbuf
4493        && start_pos->lnum == st->cur_match_pos->lnum
4494        && start_pos->col == st->cur_match_pos->col) {
4495      continue;
4496    }
4497
4498    if (!in_fuzzy_collect) {
4499      ptr = ins_compl_get_next_word_or_line(st->ins_buf,
4500                                            st->cur_match_pos, &len, &cont_s_ipos);
4501    }
4502    if (ptr == NULL || (ins_compl_has_preinsert()
4503                        && strcmp(ptr, ins_compl_leader()) == 0)) {
4504      continue;
4505    }
4506
4507    if (is_nearest_active() && in_curbuf) {
4508      score = st->cur_match_pos->lnum - curwin->w_cursor.lnum;
4509      if (score < 0) {
4510        score = -score;
4511      }
4512    }
4513
4514    if (ins_compl_add_infercase(ptr, len, p_ic,
4515                                in_curbuf ? NULL : st->ins_buf->b_sfname,
4516                                0, cont_s_ipos, score) != NOTDONE) {
4517      if (in_fuzzy_collect && score == compl_first_match->cp_next->cp_score) {
4518        compl_num_bests++;
4519      }
4520      found_new_match = OK;
4521      break;
4522    }
4523  }
4524  p_scs = save_p_scs;
4525  p_ws = save_p_ws;
4526
4527  return found_new_match;
4528}
4529
4530/// Get completion matches from register contents.
4531/// Extracts words from all available registers and adds them to the completion list.
4532static void get_register_completion(void)
4533{
4534  Direction dir = compl_direction;
4535  bool adding_mode = compl_status_adding();
4536
4537  for (int i = 0; i < NUM_REGISTERS; i++) {
4538    int regname = get_register_name(i);
4539    // Skip invalid or black hole register
4540    if (!valid_yank_reg(regname, false) || regname == '_') {
4541      continue;
4542    }
4543
4544    yankreg_T *reg = copy_register(regname);
4545
4546    if (reg->y_array == NULL || reg->y_size == 0) {
4547      free_register(reg);
4548      xfree(reg);
4549      continue;
4550    }
4551
4552    for (size_t j = 0; j < reg->y_size; j++) {
4553      char *str = reg->y_array[j].data;
4554      if (str == NULL) {
4555        continue;
4556      }
4557
4558      if (adding_mode) {
4559        int str_len = (int)strlen(str);
4560        if (str_len == 0) {
4561          continue;
4562        }
4563
4564        if (!compl_orig_text.data
4565            || (p_ic ? STRNICMP(str, compl_orig_text.data,
4566                                compl_orig_text.size) == 0
4567                     : strncmp(str, compl_orig_text.data,
4568                               compl_orig_text.size) == 0)) {
4569          if (ins_compl_add_infercase(str, str_len, p_ic, NULL,
4570                                      dir, false, FUZZY_SCORE_NONE) == OK) {
4571            dir = FORWARD;
4572          }
4573        }
4574      } else {
4575        // Calculate the safe end of string to avoid null byte issues
4576        char *str_end = str + strlen(str);
4577        char *p = str;
4578
4579        // Safely iterate through the string
4580        while (p < str_end && *p != NUL) {
4581          char *old_p = p;
4582          p = find_word_start(p);
4583          if (p >= str_end || *p == NUL) {
4584            break;
4585          }
4586
4587          char *word_end = find_word_end(p);
4588
4589          if (word_end <= p) {
4590            word_end = p + utfc_ptr2len(p);
4591          }
4592
4593          if (word_end > str_end) {
4594            word_end = str_end;
4595          }
4596
4597          int len = (int)(word_end - p);
4598          if (len > 0 && (!compl_orig_text.data
4599                          || (p_ic ? STRNICMP(p, compl_orig_text.data,
4600                                              compl_orig_text.size) == 0
4601                                   : strncmp(p, compl_orig_text.data,
4602                                             compl_orig_text.size) == 0))) {
4603            if (ins_compl_add_infercase(p, len, p_ic, NULL,
4604                                        dir, false, FUZZY_SCORE_NONE) == OK) {
4605              dir = FORWARD;
4606            }
4607          }
4608
4609          p = word_end;
4610
4611          if (p <= old_p) {
4612            p = old_p + utfc_ptr2len(old_p);
4613          }
4614        }
4615      }
4616    }
4617
4618    free_register(reg);
4619    xfree(reg);
4620  }
4621}
4622
4623/// Return the callback function associated with "p" if it refers to a
4624/// user-defined function in the 'complete' option.
4625/// The "idx" parameter is used for indexing callback entries.
4626static Callback *get_callback_if_cpt_func(char *p, int idx)
4627{
4628  if (*p == 'o') {
4629    return &curbuf->b_p_ofu;
4630  }
4631
4632  if (*p == 'F') {
4633    if (*++p != ',' && *p != NUL) {
4634      // 'F{func}' case
4635      if (curbuf->b_p_cpt_cb == NULL || idx < 0 || idx >= curbuf->b_p_cpt_count) {
4636        return NULL;
4637      }
4638      return curbuf->b_p_cpt_cb[idx].type != kCallbackNone
4639             ? &curbuf->b_p_cpt_cb[idx] : NULL;
4640    } else {
4641      return &curbuf->b_p_cfu;  // 'cfu'
4642    }
4643  }
4644
4645  return NULL;
4646}
4647
4648/// get the next set of completion matches for "type".
4649/// @return  true if a new match is found, otherwise false.
4650static bool get_next_completion_match(int type, ins_compl_next_state_T *st, pos_T *ini)
4651{
4652  int found_new_match = FAIL;
4653
4654  switch (type) {
4655  case -1:
4656    break;
4657  case CTRL_X_PATH_PATTERNS:
4658  case CTRL_X_PATH_DEFINES:
4659    get_next_include_file_completion(type);
4660    break;
4661
4662  case CTRL_X_DICTIONARY:
4663  case CTRL_X_THESAURUS:
4664    get_next_dict_tsr_completion(type, st->dict, st->dict_f);
4665    st->dict = NULL;
4666    break;
4667
4668  case CTRL_X_TAGS:
4669    get_next_tag_completion();
4670    break;
4671
4672  case CTRL_X_FILES:
4673    get_next_filename_completion();
4674    break;
4675
4676  case CTRL_X_CMDLINE:
4677  case CTRL_X_CMDLINE_CTRL_X:
4678    get_next_cmdline_completion();
4679    break;
4680
4681  case CTRL_X_FUNCTION:
4682    if (ctrl_x_mode_normal()) {  // Invoked by a func in 'cpt' option
4683      get_cpt_func_completion_matches(st->func_cb);
4684    } else {
4685      expand_by_function(type, compl_pattern.data, NULL);
4686    }
4687    break;
4688  case CTRL_X_OMNI:
4689    expand_by_function(type, compl_pattern.data, NULL);
4690    break;
4691
4692  case CTRL_X_SPELL:
4693    get_next_spell_completion(st->first_match_pos.lnum);
4694    break;
4695  case CTRL_X_BUFNAMES:
4696    get_next_bufname_token();
4697    break;
4698  case CTRL_X_REGISTER:
4699    get_register_completion();
4700    break;
4701
4702  default:            // normal ^P/^N and ^X^L
4703    found_new_match = get_next_default_completion(st, ini);
4704    if (found_new_match == FAIL && st->ins_buf == curbuf) {
4705      st->found_all = true;
4706    }
4707  }
4708
4709  // check if compl_curr_match has changed, (e.g. other type of
4710  // expansion added something)
4711  if (type != 0 && compl_curr_match != compl_old_match) {
4712    found_new_match = OK;
4713  }
4714
4715  return found_new_match;
4716}
4717
4718static void get_next_bufname_token(void)
4719{
4720  FOR_ALL_BUFFERS(b) {
4721    if (b->b_p_bl && b->b_sfname != NULL) {
4722      char *tail = path_tail(b->b_sfname);
4723      if (strncmp(tail, compl_orig_text.data, compl_orig_text.size) == 0) {
4724        ins_compl_add(tail, (int)strlen(tail), NULL, NULL, false, NULL, 0,
4725                      p_ic ? CP_ICASE : 0, false, NULL, FUZZY_SCORE_NONE, false, NULL);
4726      }
4727    }
4728  }
4729}
4730
4731/// Strips carets followed by numbers. This suffix typically represents the
4732/// max_matches setting.
4733static void strip_caret_numbers_in_place(char *str)
4734{
4735  char *read = str, *write = str, *p;
4736
4737  if (str == NULL) {
4738    return;
4739  }
4740
4741  while (*read) {
4742    if (*read == '^') {
4743      p = read + 1;
4744      while (ascii_isdigit(*p)) {
4745        p++;
4746      }
4747      if ((*p == ',' || *p == '\0') && p != read + 1) {
4748        read = p;
4749        continue;
4750      } else {
4751        *write++ = *read++;
4752      }
4753    } else {
4754      *write++ = *read++;
4755    }
4756  }
4757  *write = '\0';
4758}
4759
4760/// Call functions specified in the 'cpt' option with findstart=1,
4761/// and retrieve the startcol.
4762static void prepare_cpt_compl_funcs(void)
4763{
4764  // Make a copy of 'cpt' in case the buffer gets wiped out
4765  char *cpt = xstrdup(curbuf->b_p_cpt);
4766  strip_caret_numbers_in_place(cpt);
4767
4768  int idx = 0;
4769  for (char *p = cpt; *p;) {
4770    while (*p == ',' || *p == ' ') {  // Skip delimiters
4771      p++;
4772    }
4773    if (*p == NUL) {
4774      break;
4775    }
4776
4777    Callback *cb = get_callback_if_cpt_func(p, idx);
4778    if (cb) {
4779      int startcol;
4780      if (get_userdefined_compl_info(curwin->w_cursor.col, cb, &startcol) == FAIL) {
4781        if (startcol == -3) {
4782          cpt_sources_array[idx].cs_refresh_always = false;
4783        } else {
4784          startcol = -2;
4785        }
4786      } else if (startcol < 0 || startcol > curwin->w_cursor.col) {
4787        startcol = curwin->w_cursor.col;
4788      }
4789      cpt_sources_array[idx].cs_startcol = startcol;
4790    } else {
4791      cpt_sources_array[idx].cs_startcol = -3;
4792    }
4793
4794    (void)copy_option_part(&p, IObuff, IOSIZE, ",");  // Advance p
4795    idx++;
4796  }
4797
4798  xfree(cpt);
4799}
4800
4801/// Start the timer for the current completion source.
4802static void compl_source_start_timer(int source_idx)
4803{
4804  if (compl_autocomplete || p_cto > 0) {
4805    cpt_sources_array[source_idx].compl_start_tv = os_hrtime();
4806    compl_time_slice_expired = false;
4807  }
4808}
4809
4810/// Safely advance the cpt_sources_index by one.
4811static int advance_cpt_sources_index_safe(void)
4812{
4813  if (cpt_sources_index >= 0 && cpt_sources_index < cpt_sources_count - 1) {
4814    cpt_sources_index++;
4815    return OK;
4816  }
4817  semsg(_(e_list_index_out_of_range_nr), cpt_sources_index);
4818  return FAIL;
4819}
4820
4821/// Get the next expansion(s), using "compl_pattern".
4822/// The search starts at position "ini" in curbuf and in the direction
4823/// compl_direction.
4824/// When "compl_started" is false start at that position, otherwise continue
4825/// where we stopped searching before.
4826/// This may return before finding all the matches.
4827/// Return the total number of matches or -1 if still unknown -- Acevedo
4828static int ins_compl_get_exp(pos_T *ini)
4829{
4830  static ins_compl_next_state_T st;
4831  static bool st_cleared = false;
4832  int found_new_match;
4833  int type = ctrl_x_mode;
4834  bool may_advance_cpt_idx = false;
4835  pos_T start_pos = *ini;
4836
4837  assert(curbuf != NULL);
4838
4839  if (!compl_started) {
4840    FOR_ALL_BUFFERS(buf) {
4841      buf->b_scanned = false;
4842    }
4843    if (!st_cleared) {
4844      CLEAR_FIELD(st);
4845      st_cleared = true;
4846    }
4847    st.found_all = false;
4848    st.ins_buf = curbuf;
4849    xfree(st.e_cpt_copy);
4850    // Make a copy of 'complete', in case the buffer is wiped out.
4851    st.e_cpt_copy = xstrdup((compl_cont_status & CONT_LOCAL) ? "." : curbuf->b_p_cpt);
4852    strip_caret_numbers_in_place(st.e_cpt_copy);
4853    st.e_cpt = st.e_cpt_copy;
4854
4855    // In large buffers, timeout may miss nearby matches — search above cursor
4856#define LOOKBACK_LINE_COUNT     1000
4857    if (compl_autocomplete && is_nearest_active()) {
4858      start_pos.lnum = MAX(1, start_pos.lnum - LOOKBACK_LINE_COUNT);
4859      start_pos.col = 0;
4860    }
4861    st.last_match_pos = st.first_match_pos = start_pos;
4862  } else if (st.ins_buf != curbuf && !buf_valid(st.ins_buf)) {
4863    st.ins_buf = curbuf;  // In case the buffer was wiped out.
4864  }
4865  assert(st.ins_buf != NULL);
4866
4867  compl_old_match = compl_curr_match;   // remember the last current match
4868  st.cur_match_pos = compl_dir_forward() ? &st.last_match_pos : &st.first_match_pos;
4869
4870  bool normal_mode_strict = ctrl_x_mode_normal() && !ctrl_x_mode_line_or_eval()
4871                            && !(compl_cont_status & CONT_LOCAL)
4872                            && cpt_sources_array != NULL;
4873  if (normal_mode_strict) {
4874    cpt_sources_index = 0;
4875    if (compl_autocomplete || p_cto > 0) {
4876      compl_source_start_timer(0);
4877      compl_time_slice_expired = false;
4878      compl_timeout_ms = compl_autocomplete
4879                         ? (uint64_t)MAX(COMPL_INITIAL_TIMEOUT_MS, p_act)
4880                         : (uint64_t)p_cto;
4881    }
4882  }
4883
4884  // For ^N/^P loop over all the flags/windows/buffers in 'complete'
4885  while (true) {
4886    found_new_match = FAIL;
4887    st.set_match_pos = false;
4888
4889    // For ^N/^P pick a new entry from e_cpt if compl_started is off,
4890    // or if found_all says this entry is done.  For ^X^L only use the
4891    // entries from 'complete' that look in loaded buffers.
4892    if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
4893        && (!compl_started || st.found_all)) {
4894      int status = process_next_cpt_value(&st, &type, &start_pos,
4895                                          cot_fuzzy(), &may_advance_cpt_idx);
4896      if (status == INS_COMPL_CPT_END) {
4897        break;
4898      }
4899      if (status == INS_COMPL_CPT_CONT) {
4900        if (may_advance_cpt_idx) {
4901          if (!advance_cpt_sources_index_safe()) {
4902            break;
4903          }
4904          compl_source_start_timer(cpt_sources_index);
4905        }
4906        continue;
4907      }
4908    }
4909
4910    uint64_t compl_timeout_save = 0;
4911    if (normal_mode_strict && type == CTRL_X_FUNCTION
4912        && (compl_autocomplete || p_cto > 0)) {
4913      // LSP servers may sporadically take >1s to respond (e.g., while
4914      // loading modules), but other sources might already have matches.
4915      // To show results quickly use a short timeout for keyword
4916      // completion. Allow longer timeout for non-keyword completion
4917      // where only function based sources (e.g. LSP) are active.
4918      compl_timeout_save = compl_timeout_ms;
4919      compl_timeout_ms = compl_from_nonkeyword
4920                         ? COMPL_FUNC_TIMEOUT_NON_KW_MS : COMPL_FUNC_TIMEOUT_MS;
4921    }
4922
4923    // get the next set of completion matches
4924    found_new_match = get_next_completion_match(type, &st, &start_pos);
4925
4926    // If complete() was called then compl_pattern has been reset.
4927    // The following won't work then, bail out.
4928    if (compl_pattern.data == NULL) {
4929      break;
4930    }
4931
4932    if (may_advance_cpt_idx) {
4933      if (!advance_cpt_sources_index_safe()) {
4934        break;
4935      }
4936      compl_source_start_timer(cpt_sources_index);
4937    }
4938
4939    // break the loop for specialized modes (use 'complete' just for the
4940    // generic ctrl_x_mode == CTRL_X_NORMAL) or when we've found a new match
4941    if ((ctrl_x_mode_not_default() && !ctrl_x_mode_line_or_eval())
4942        || found_new_match != FAIL) {
4943      if (got_int) {
4944        break;
4945      }
4946      // Fill the popup menu as soon as possible.
4947      if (type != -1) {
4948        ins_compl_check_keys(0, false);
4949      }
4950
4951      if ((ctrl_x_mode_not_default() && !ctrl_x_mode_line_or_eval())
4952          || compl_interrupted) {
4953        break;
4954      }
4955      compl_started = !compl_time_slice_expired;
4956    } else {
4957      // Mark a buffer scanned when it has been scanned completely
4958      if (buf_valid(st.ins_buf) && (type == 0 || type == CTRL_X_PATH_PATTERNS)) {
4959        assert(st.ins_buf);
4960        st.ins_buf->b_scanned = true;
4961      }
4962
4963      compl_started = false;
4964    }
4965
4966    // Restore the timeout after collecting matches from function source
4967    if (normal_mode_strict && type == CTRL_X_FUNCTION
4968        && (compl_autocomplete || p_cto > 0)) {
4969      compl_timeout_ms = compl_timeout_save;
4970    }
4971
4972    // For `^P` completion, reset `compl_curr_match` to the head to avoid
4973    // mixing matches from different sources.
4974    if (!compl_dir_forward()) {
4975      while (compl_curr_match->cp_prev
4976             && !match_at_original_text(compl_curr_match->cp_prev)) {
4977        compl_curr_match = compl_curr_match->cp_prev;
4978      }
4979    }
4980  }
4981  cpt_sources_index = -1;
4982  compl_started = true;
4983
4984  if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
4985      && *st.e_cpt == NUL) {  // Got to end of 'complete'
4986    found_new_match = FAIL;
4987  }
4988
4989  int match_count = -1;  // total of matches, unknown
4990  if (found_new_match == FAIL
4991      || (ctrl_x_mode_not_default() && !ctrl_x_mode_line_or_eval())) {
4992    match_count = ins_compl_make_cyclic();
4993  }
4994
4995  if (cot_fuzzy() && compl_get_longest && compl_num_bests > 0) {
4996    fuzzy_longest_match();
4997  }
4998
4999  if (compl_old_match != NULL) {
5000    // If several matches were added (FORWARD) or the search failed and has
5001    // just been made cyclic then we have to move compl_curr_match to the
5002    // next or previous entry (if any) -- Acevedo
5003    compl_curr_match = compl_dir_forward()
5004                       ? compl_old_match->cp_next
5005                       : compl_old_match->cp_prev;
5006    if (compl_curr_match == NULL) {
5007      compl_curr_match = compl_old_match;
5008    }
5009  }
5010  may_trigger_modechanged();
5011
5012  if (match_count > 0 && !ctrl_x_mode_spell()) {
5013    if (is_nearest_active() && !ins_compl_has_preinsert()) {
5014      sort_compl_match_list(cp_compare_nearest);
5015    }
5016
5017    if (cot_fuzzy() && ins_compl_leader_len() > 0) {
5018      ins_compl_fuzzy_sort();
5019    }
5020  }
5021
5022  return match_count;
5023}
5024
5025/// Update "compl_shown_match" to the actually shown match, it may differ when
5026/// "compl_leader" is used to omit some of the matches.
5027static void ins_compl_update_shown_match(void)
5028{
5029  (void)get_leader_for_startcol(NULL, true);  // Clear the cache
5030  String *leader = get_leader_for_startcol(compl_shown_match, true);
5031
5032  while (!ins_compl_equal(compl_shown_match, leader->data, leader->size)
5033         && compl_shown_match->cp_next != NULL
5034         && !is_first_match(compl_shown_match->cp_next)) {
5035    compl_shown_match = compl_shown_match->cp_next;
5036    leader = get_leader_for_startcol(compl_shown_match, true);
5037  }
5038
5039  // If we didn't find it searching forward, and compl_shows_dir is
5040  // backward, find the last match.
5041  if (compl_shows_dir_backward()
5042      && !ins_compl_equal(compl_shown_match, leader->data, leader->size)
5043      && (compl_shown_match->cp_next == NULL
5044          || is_first_match(compl_shown_match->cp_next))) {
5045    while (!ins_compl_equal(compl_shown_match, leader->data, leader->size)
5046           && compl_shown_match->cp_prev != NULL
5047           && !is_first_match(compl_shown_match->cp_prev)) {
5048      compl_shown_match = compl_shown_match->cp_prev;
5049      leader = get_leader_for_startcol(compl_shown_match, true);
5050    }
5051  }
5052}
5053
5054/// Delete the old text being completed.
5055void ins_compl_delete(bool new_leader)
5056{
5057  // Avoid deleting text that will be reinserted when changing leader. This
5058  // allows marks present on the original text to shrink/grow appropriately.
5059  int orig_col = 0;
5060  if (new_leader) {
5061    char *orig = compl_orig_text.data;
5062    char *leader = ins_compl_leader();
5063    while (*orig != NUL && utf_ptr2char(orig) == utf_ptr2char(leader)) {
5064      leader += utf_ptr2len(leader);
5065      orig += utf_ptr2len(orig);
5066    }
5067    orig_col = (int)(orig - compl_orig_text.data);
5068  }
5069
5070  // In insert mode: Delete the typed part.
5071  // In replace mode: Put the old characters back, if any.
5072  int col = compl_col + (compl_status_adding() ? compl_length : orig_col);
5073
5074  if (ins_compl_preinsert_effect()) {
5075    col += (int)ins_compl_leader_len();
5076    curwin->w_cursor.col = compl_ins_end_col;
5077  }
5078
5079  String remaining = STRING_INIT;
5080  if (curwin->w_cursor.lnum > compl_lnum) {
5081    if (curwin->w_cursor.col < get_cursor_line_len()) {
5082      remaining = cbuf_to_string(get_cursor_pos_ptr(), (size_t)get_cursor_pos_len());
5083    }
5084
5085    while (curwin->w_cursor.lnum > compl_lnum) {
5086      if (ml_delete(curwin->w_cursor.lnum) == FAIL) {
5087        if (remaining.data) {
5088          xfree(remaining.data);
5089        }
5090        return;
5091      }
5092      deleted_lines_mark(curwin->w_cursor.lnum, 1);
5093      curwin->w_cursor.lnum--;
5094    }
5095    // move cursor to end of line
5096    curwin->w_cursor.col = get_cursor_line_len();
5097  }
5098
5099  if ((int)curwin->w_cursor.col > col) {
5100    if (stop_arrow() == FAIL) {
5101      if (remaining.data) {
5102        xfree(remaining.data);
5103      }
5104      return;
5105    }
5106    backspace_until_column(col);
5107    compl_ins_end_col = curwin->w_cursor.col;
5108  }
5109
5110  if (remaining.data != NULL) {
5111    orig_col = curwin->w_cursor.col;
5112    ins_str(remaining.data, remaining.size);
5113    curwin->w_cursor.col = orig_col;
5114    xfree(remaining.data);
5115  }
5116
5117  // TODO(vim): is this sufficient for redrawing?  Redrawing everything
5118  // causes flicker, thus we can't do that.
5119  changed_cline_bef_curs(curwin);
5120  // clear v:completed_item
5121  set_vim_var_dict(VV_COMPLETED_ITEM, tv_dict_alloc_lock(VAR_FIXED));
5122}
5123
5124/// Insert a completion string that contains newlines.
5125/// The string is split and inserted line by line.
5126static void ins_compl_expand_multiple(char *str)
5127{
5128  char *start = str;
5129  char *curr = str;
5130  int base_indent = get_indent();
5131  while (*curr != NUL) {
5132    if (*curr == '\n') {
5133      // Insert the text chunk before newline
5134      if (curr > start) {
5135        ins_char_bytes(start, (size_t)(curr - start));
5136      }
5137
5138      // Handle newline
5139      open_line(FORWARD, OPENLINE_KEEPTRAIL | OPENLINE_FORCE_INDENT, base_indent, NULL);
5140      start = curr + 1;
5141    }
5142    curr++;
5143  }
5144
5145  // Handle remaining text after last newline (if any)
5146  if (curr > start) {
5147    ins_char_bytes(start, (size_t)(curr - start));
5148  }
5149
5150  compl_ins_end_col = curwin->w_cursor.col;
5151}
5152
5153/// Find the longest common prefix among the current completion matches.
5154/// Returns a pointer to the first match string, with *prefix_len set to
5155/// the length of the common prefix.
5156/// If "curbuf_only" is true, restrict matches to the current buffer
5157/// ('.' source in 'complete').
5158static char *find_common_prefix(size_t *prefix_len, bool curbuf_only)
5159{
5160  bool is_cpt_completion = (cpt_sources_array != NULL);
5161
5162  if (!is_cpt_completion) {
5163    return NULL;
5164  }
5165
5166  int *match_count = xcalloc((size_t)cpt_sources_count, sizeof(int));
5167
5168  (void)get_leader_for_startcol(NULL, true);  // Clear the cache
5169
5170  compl_T *compl = compl_first_match;
5171  char *first = NULL;
5172  int len = -1;
5173  do {
5174    String *leader = get_leader_for_startcol(compl, true);
5175
5176    // Apply 'smartcase' behavior during normal mode
5177    if (ctrl_x_mode_normal() && !p_inf && compl_orig_text.data
5178        && !ignorecase(compl_orig_text.data)) {
5179      compl->cp_flags &= ~CP_ICASE;
5180    }
5181
5182    if (!match_at_original_text(compl)
5183        && (leader->data == NULL
5184            || ins_compl_equal_sc(compl, leader->data, leader->size))) {
5185      // Limit number of items from each source if max_items is set.
5186      bool match_limit_exceeded = false;
5187      int cur_source = compl->cp_cpt_source_idx;
5188
5189      if (cur_source != -1) {
5190        match_count[cur_source]++;
5191        int max_matches = cpt_sources_array[cur_source].cs_max_matches;
5192        if (max_matches > 0 && match_count[cur_source] > max_matches) {
5193          match_limit_exceeded = true;
5194        }
5195      }
5196
5197      if (!match_limit_exceeded
5198          && (!curbuf_only || (cur_source != -1
5199                               && cpt_sources_array[cur_source].cs_flag == '.'))) {
5200        if (first == NULL && strncmp(ins_compl_leader(), compl->cp_str.data,
5201                                     ins_compl_leader_len()) == 0) {
5202          first = compl->cp_str.data;
5203          len = (int)strlen(first);
5204        } else if (first != NULL) {
5205          int j = 0;  // count in bytes
5206          char *s1 = first;
5207          char *s2 = compl->cp_str.data;
5208
5209          while (j < len && *s1 != NUL && *s2 != NUL) {
5210            if (MB_BYTE2LEN((uint8_t)(*s1)) != MB_BYTE2LEN((uint8_t)(*s2))
5211                || memcmp(s1, s2, MB_BYTE2LEN((uint8_t)(*s1))) != 0) {
5212              break;
5213            }
5214
5215            j += MB_BYTE2LEN((uint8_t)(*s1));
5216            MB_PTR_ADV(s1);
5217            MB_PTR_ADV(s2);
5218          }
5219          len = j;
5220
5221          if (len == 0) {
5222            break;
5223          }
5224        }
5225      }
5226    }
5227    compl = compl->cp_next;
5228  } while (compl != NULL && !is_first_match(compl));
5229
5230  xfree(match_count);
5231
5232  if (len > (int)ins_compl_leader_len()) {
5233    assert(first != NULL);
5234    // Avoid inserting text that duplicates the text already present
5235    // after the cursor.
5236    if (len == (int)strlen(first)) {
5237      char *line = get_cursor_line_ptr();
5238      char *p = line + curwin->w_cursor.col;
5239      if (p && !ascii_iswhite_or_nul(*p)) {
5240        char *end = find_word_end(p);
5241        int text_len = (int)(end - p);
5242        if (text_len > 0 && text_len < (len - (int)ins_compl_leader_len())
5243            && strncmp(first + len - text_len, p, (size_t)text_len) == 0) {
5244          len -= text_len;
5245        }
5246      }
5247    }
5248    *prefix_len = (size_t)len;
5249    return first;
5250  }
5251  return NULL;
5252}
5253
5254/// Insert the new text being completed.
5255/// "move_cursor" is used when 'completeopt' includes "preinsert" and when true
5256/// cursor needs to move back from the inserted text to the compl_leader.
5257/// When "insert_prefix" is true the longest common prefix is inserted instead
5258/// of shown match.
5259void ins_compl_insert(bool move_cursor, bool insert_prefix)
5260{
5261  int compl_len = get_compl_len();
5262  bool preinsert = ins_compl_has_preinsert();
5263  char *cp_str = compl_shown_match->cp_str.data;
5264  size_t cp_str_len = compl_shown_match->cp_str.size;
5265  size_t leader_len = ins_compl_leader_len();
5266  char *has_multiple = strchr(cp_str, '\n');
5267
5268  if (insert_prefix) {
5269    cp_str = find_common_prefix(&cp_str_len, false);
5270    if (cp_str == NULL) {
5271      cp_str = find_common_prefix(&cp_str_len, true);
5272      if (cp_str == NULL) {
5273        cp_str = compl_shown_match->cp_str.data;
5274        cp_str_len = compl_shown_match->cp_str.size;
5275      }
5276    }
5277  } else if (cpt_sources_array != NULL) {
5278    // Since completion sources may provide matches with varying start
5279    // positions, insert only the portion of the match that corresponds to the
5280    // intended replacement range.
5281    int cpt_idx = compl_shown_match->cp_cpt_source_idx;
5282    if (cpt_idx >= 0 && compl_col >= 0) {
5283      int startcol = cpt_sources_array[cpt_idx].cs_startcol;
5284      if (startcol >= 0 && startcol < (int)compl_col) {
5285        int skip = (int)compl_col - startcol;
5286        if ((size_t)skip <= cp_str_len) {
5287          cp_str_len -= (size_t)skip;
5288          cp_str += skip;
5289        }
5290      }
5291    }
5292  }
5293
5294  // Make sure we don't go over the end of the string, this can happen with
5295  // illegal bytes.
5296  if (compl_len < (int)cp_str_len) {
5297    if (has_multiple) {
5298      ins_compl_expand_multiple(cp_str + compl_len);
5299    } else {
5300      ins_compl_insert_bytes(cp_str + compl_len,
5301                             insert_prefix ? (int)cp_str_len - compl_len : -1);
5302      if ((preinsert || insert_prefix) && move_cursor) {
5303        curwin->w_cursor.col -= (colnr_T)(cp_str_len - leader_len);
5304      }
5305    }
5306  }
5307  compl_used_match = !(match_at_original_text(compl_shown_match)
5308                       || (preinsert && !insert_prefix));
5309
5310  dict_T *dict = ins_compl_dict_alloc(compl_shown_match);
5311  set_vim_var_dict(VV_COMPLETED_ITEM, dict);
5312  compl_hi_on_autocompl_longest = insert_prefix && move_cursor;
5313}
5314
5315/// show the file name for the completion match (if any).  Truncate the file
5316/// name to avoid a wait for return.
5317static void ins_compl_show_filename(void)
5318{
5319  char *const lead = _("match in file");
5320
5321  // In the case of ext_messages, `sc_col` is obsolete. Fortunately, long messages are no longer
5322  // disruptive, so truncation could be skipped. But in this particular case, with default
5323  // configuration `showmode cmdheight=1`, a multi-line message is shown partially, and a message
5324  // that fits into one line is not shown at all. It's better to be consistent: it should not depend
5325  // on the exact length of the message whether it is displayed at all.
5326  int space = (ui_has(kUIMessages) ? Columns : sc_col) - vim_strsize(lead) - 2;
5327  if (space <= 0) {
5328    return;
5329  }
5330
5331  // We need the tail that fits.  With double-byte encoding going
5332  // back from the end is very slow, thus go from the start and keep
5333  // the text that fits in "space" between "s" and "e".
5334  char *s;
5335  char *e;
5336  for (s = e = compl_shown_match->cp_fname; *e != NUL; MB_PTR_ADV(e)) {
5337    space -= ptr2cells(e);
5338    while (space < 0) {
5339      space += ptr2cells(s);
5340      MB_PTR_ADV(s);
5341    }
5342  }
5343  if (!compl_autocomplete) {
5344    msg_hist_off = true;
5345    vim_snprintf(IObuff, IOSIZE, "%s %s%s", lead,
5346                 s > compl_shown_match->cp_fname ? "<" : "", s);
5347    msg(IObuff, 0);
5348    msg_hist_off = false;
5349    redraw_cmdline = false;  // don't overwrite!
5350  }
5351}
5352
5353/// Find the appropriate completion item when 'complete' ('cpt') includes
5354/// a 'max_matches' postfix. In this case, we search for a match where
5355/// 'cp_in_match_array' is set, indicating that the match is also present
5356/// in 'compl_match_array'.
5357static compl_T *find_next_match_in_menu(void)
5358{
5359  bool is_forward = compl_shows_dir_forward();
5360  compl_T *match = compl_shown_match;
5361
5362  do {
5363    match = is_forward ? match->cp_next : match->cp_prev;
5364  } while (match->cp_next && !match->cp_in_match_array
5365           && !match_at_original_text(match));
5366  return match;
5367}
5368
5369/// Find the next set of matches for completion. Repeat the completion "todo"
5370/// times.  The number of matches found is returned in 'num_matches'.
5371///
5372/// @param allow_get_expansion  If true, then ins_compl_get_exp() may be called to
5373///                             get more completions.
5374///                             If false, then do nothing when there are no more
5375///                             completions in the given direction.
5376/// @param todo  repeat completion this many times
5377/// @param advance  If true, then completion will move to the first match.
5378///                 Otherwise, the original text will be shown.
5379///
5380/// @return  OK on success and -1 if the number of matches are unknown.
5381static int find_next_completion_match(bool allow_get_expansion, int todo, bool advance,
5382                                      int *num_matches)
5383{
5384  bool found_end = false;
5385  compl_T *found_compl = NULL;
5386  unsigned cur_cot_flags = get_cot_flags();
5387  bool compl_no_select = (cur_cot_flags & kOptCotFlagNoselect) != 0
5388                         || (compl_autocomplete && !ins_compl_has_preinsert());
5389
5390  while (--todo >= 0) {
5391    if (compl_shows_dir_forward() && compl_shown_match->cp_next != NULL) {
5392      if (compl_match_array != NULL) {
5393        compl_shown_match = find_next_match_in_menu();
5394      } else {
5395        compl_shown_match = compl_shown_match->cp_next;
5396      }
5397      found_end = (compl_first_match != NULL
5398                   && (is_first_match(compl_shown_match->cp_next)
5399                       || is_first_match(compl_shown_match)));
5400    } else if (compl_shows_dir_backward()
5401               && compl_shown_match->cp_prev != NULL) {
5402      found_end = is_first_match(compl_shown_match);
5403      if (compl_match_array != NULL) {
5404        compl_shown_match = find_next_match_in_menu();
5405      } else {
5406        compl_shown_match = compl_shown_match->cp_prev;
5407      }
5408      found_end |= is_first_match(compl_shown_match);
5409    } else {
5410      if (!allow_get_expansion) {
5411        if (advance) {
5412          if (compl_shows_dir_backward()) {
5413            compl_pending -= todo + 1;
5414          } else {
5415            compl_pending += todo + 1;
5416          }
5417        }
5418        return -1;
5419      }
5420
5421      if (!compl_no_select && advance) {
5422        if (compl_shows_dir_backward()) {
5423          compl_pending--;
5424        } else {
5425          compl_pending++;
5426        }
5427      }
5428
5429      // Find matches.
5430      *num_matches = ins_compl_get_exp(&compl_startpos);
5431
5432      // handle any pending completions
5433      while (compl_pending != 0 && compl_direction == compl_shows_dir
5434             && advance) {
5435        if (compl_pending > 0 && compl_shown_match->cp_next != NULL) {
5436          compl_shown_match = compl_shown_match->cp_next;
5437          compl_pending--;
5438        } else if (compl_pending < 0 && compl_shown_match->cp_prev != NULL) {
5439          compl_shown_match = compl_shown_match->cp_prev;
5440          compl_pending++;
5441        } else {
5442          break;
5443        }
5444      }
5445      found_end = false;
5446    }
5447
5448    String *leader = get_leader_for_startcol(compl_shown_match, false);
5449
5450    if (!match_at_original_text(compl_shown_match)
5451        && leader->data != NULL
5452        && !ins_compl_equal(compl_shown_match, leader->data, leader->size)
5453        && !(cot_fuzzy() && compl_shown_match->cp_score != FUZZY_SCORE_NONE)) {
5454      todo++;
5455    } else {
5456      // Remember a matching item.
5457      found_compl = compl_shown_match;
5458    }
5459
5460    // Stop at the end of the list when we found a usable match.
5461    if (found_end) {
5462      if (found_compl != NULL) {
5463        compl_shown_match = found_compl;
5464        break;
5465      }
5466      todo = 1;             // use first usable match after wrapping around
5467    }
5468  }
5469
5470  return OK;
5471}
5472
5473/// Fill in the next completion in the current direction.
5474/// If "allow_get_expansion" is true, then we may call ins_compl_get_exp() to
5475/// get more completions.  If it is false, then we just do nothing when there
5476/// are no more completions in a given direction.  The latter case is used when
5477/// we are still in the middle of finding completions, to allow browsing
5478/// through the ones found so far.
5479/// @return  the total number of matches, or -1 if still unknown -- webb.
5480///
5481/// compl_curr_match is currently being used by ins_compl_get_exp(), so we use
5482/// compl_shown_match here.
5483///
5484/// Note that this function may be called recursively once only.  First with
5485/// "allow_get_expansion" true, which calls ins_compl_get_exp(), which in turn
5486/// calls this function with "allow_get_expansion" false.
5487///
5488/// @param count          Repeat completion this many times; should be at least 1
5489/// @param insert_match   Insert the newly selected match
5490static int ins_compl_next(bool allow_get_expansion, int count, bool insert_match)
5491{
5492  int num_matches = -1;
5493  int todo = count;
5494  const bool started = compl_started;
5495  buf_T *const orig_curbuf = curbuf;
5496  unsigned cur_cot_flags = get_cot_flags();
5497  bool compl_no_insert = (cur_cot_flags & kOptCotFlagNoinsert) != 0
5498                         || (compl_autocomplete && !ins_compl_has_preinsert());
5499  bool compl_preinsert = ins_compl_has_preinsert();
5500
5501  // When user complete function return -1 for findstart which is next
5502  // time of 'always', compl_shown_match become NULL.
5503  if (compl_shown_match == NULL) {
5504    return -1;
5505  }
5506
5507  if (compl_leader.data != NULL
5508      && !match_at_original_text(compl_shown_match)
5509      && !cot_fuzzy()) {
5510    // Update "compl_shown_match" to the actually shown match
5511    ins_compl_update_shown_match();
5512  }
5513
5514  if (allow_get_expansion && insert_match
5515      && (!compl_get_longest || compl_used_match)) {
5516    // Delete old text to be replaced
5517    ins_compl_delete(false);
5518  }
5519
5520  // When finding the longest common text we stick at the original text,
5521  // don't let CTRL-N or CTRL-P move to the first match.
5522  bool advance = count != 1 || !allow_get_expansion || !compl_get_longest;
5523
5524  // When restarting the search don't insert the first match either.
5525  if (compl_restarting) {
5526    advance = false;
5527    compl_restarting = false;
5528  }
5529
5530  // Repeat this for when <PageUp> or <PageDown> is typed.  But don't wrap
5531  // around.
5532  if (find_next_completion_match(allow_get_expansion, todo, advance,
5533                                 &num_matches) == -1) {
5534    return -1;
5535  }
5536
5537  if (curbuf != orig_curbuf) {
5538    // In case some completion function switched buffer, don't want to
5539    // insert the completion elsewhere.
5540    return -1;
5541  }
5542
5543  // Insert the text of the new completion, or the compl_leader.
5544  if (!started && ins_compl_preinsert_longest()) {
5545    ins_compl_insert(true, true);
5546  } else if (compl_no_insert && !started && !compl_preinsert) {
5547    ins_compl_insert_bytes(compl_orig_text.data + get_compl_len(), -1);
5548    compl_used_match = false;
5549    restore_orig_extmarks();
5550  } else if (insert_match) {
5551    if (!compl_get_longest || compl_used_match) {
5552      bool preinsert_longest = ins_compl_preinsert_longest()
5553                               && match_at_original_text(compl_shown_match);  // none selected
5554      ins_compl_insert(compl_preinsert || preinsert_longest, preinsert_longest);
5555    } else {
5556      assert(compl_leader.data != NULL);
5557      ins_compl_insert_bytes(compl_leader.data + get_compl_len(), -1);
5558    }
5559    if (strequal(compl_shown_match->cp_str.data, compl_orig_text.data)) {
5560      restore_orig_extmarks();
5561    }
5562  } else {
5563    compl_used_match = false;
5564  }
5565
5566  if (!allow_get_expansion) {
5567    // redraw to show the user what was inserted
5568    update_screen();  // TODO(bfredl): no!
5569
5570    // display the updated popup menu
5571    ins_compl_show_pum();
5572
5573    // Delete old text to be replaced, since we're still searching and
5574    // don't want to match ourselves!
5575    ins_compl_delete(false);
5576  }
5577
5578  // Enter will select a match when the match wasn't inserted and the popup
5579  // menu is visible.
5580  if (compl_no_insert && !started && !match_at_original_text(compl_shown_match)) {
5581    compl_enter_selects = true;
5582  } else {
5583    compl_enter_selects = !insert_match && compl_match_array != NULL;
5584  }
5585
5586  // Show the file name for the match (if any)
5587  if (compl_shown_match->cp_fname != NULL) {
5588    ins_compl_show_filename();
5589  }
5590
5591  return num_matches;
5592}
5593
5594/// Check if the current completion source exceeded its timeout. If so, stop
5595/// collecting, and halve the timeout.
5596static void check_elapsed_time(void)
5597{
5598  uint64_t start_tv = cpt_sources_array[cpt_sources_index].compl_start_tv;
5599  uint64_t elapsed_ms = (os_hrtime() - start_tv) / 1000000;
5600
5601  if (elapsed_ms > compl_timeout_ms) {
5602    compl_time_slice_expired = true;
5603    DECAY_COMPL_TIMEOUT();
5604  }
5605}
5606
5607/// Call this while finding completions, to check whether the user has hit a key
5608/// that should change the currently displayed completion, or exit completion
5609/// mode.  Also, when compl_pending is not zero, show a completion as soon as
5610/// possible. -- webb
5611///
5612/// @param frequency      specifies out of how many calls we actually check.
5613/// @param in_compl_func  true when called from complete_check(), don't set
5614///                       compl_curr_match.
5615void ins_compl_check_keys(int frequency, bool in_compl_func)
5616{
5617  static int count = 0;
5618
5619  // Don't check when reading keys from a script, :normal or feedkeys().
5620  // That would break the test scripts.  But do check for keys when called
5621  // from complete_check().
5622  if (!in_compl_func && (using_script() || ex_normal_busy)) {
5623    return;
5624  }
5625
5626  // Only do this at regular intervals
5627  if (++count < frequency) {
5628    return;
5629  }
5630  count = 0;
5631
5632  // Check for a typed key.  Do use mappings, otherwise vim_is_ctrl_x_key()
5633  // can't do its work correctly.
5634  int c = vpeekc_any();
5635  if (c != NUL && !test_disable_char_avail) {
5636    if (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R) {
5637      c = safe_vgetc();         // Eat the character
5638      compl_shows_dir = ins_compl_key2dir(c);
5639      ins_compl_next(false, ins_compl_key2count(c), c != K_UP && c != K_DOWN);
5640    } else {
5641      // Need to get the character to have KeyTyped set.  We'll put it
5642      // back with vungetc() below.  But skip K_IGNORE.
5643      c = safe_vgetc();
5644      if (c != K_IGNORE) {
5645        // Typed keys that get mapped lose KeyTyped. Still let
5646        // complete_check() interrupt, except during @r replay.
5647        if (c != Ctrl_R && (KeyTyped || (in_compl_func && reg_executing == 0))) {
5648          compl_interrupted = true;
5649        }
5650
5651        vungetc(c);
5652      }
5653    }
5654  } else {
5655    bool normal_mode_strict = ctrl_x_mode_normal() && !ctrl_x_mode_line_or_eval()
5656                              && !(compl_cont_status & CONT_LOCAL)
5657                              && cpt_sources_array != NULL && cpt_sources_index >= 0;
5658    if (normal_mode_strict && (compl_autocomplete || p_cto > 0)) {
5659      check_elapsed_time();
5660    }
5661  }
5662
5663  if (compl_pending
5664      && !got_int
5665      && !(cot_flags & (kOptCotFlagNoinsert | kOptCotFlagFuzzy))
5666      && (!compl_autocomplete || ins_compl_has_preinsert())) {
5667    // Insert the first match immediately and advance compl_shown_match,
5668    // before finding other matches.
5669    int todo = compl_pending > 0 ? compl_pending : -compl_pending;
5670
5671    compl_pending = 0;
5672    ins_compl_next(false, todo, true);
5673  }
5674}
5675
5676/// Decide the direction of Insert mode complete from the key typed.
5677/// Returns BACKWARD or FORWARD.
5678static int ins_compl_key2dir(int c)
5679{
5680  if (c == K_EVENT || c == K_COMMAND || c == K_LUA) {
5681    return pum_want.item < compl_selected_item ? BACKWARD : FORWARD;
5682  }
5683  if (c == Ctrl_P || c == Ctrl_L
5684      || c == K_PAGEUP || c == K_KPAGEUP
5685      || c == K_S_UP || c == K_UP) {
5686    return BACKWARD;
5687  }
5688  return FORWARD;
5689}
5690
5691/// Check that "c" is a valid completion key only while the popup menu is shown
5692///
5693/// @param  c  character to check
5694static bool ins_compl_pum_key(int c)
5695  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
5696{
5697  return pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP
5698                           || c == K_PAGEDOWN || c == K_KPAGEDOWN
5699                           || c == K_S_DOWN || c == K_UP || c == K_DOWN);
5700}
5701
5702/// Decide the number of completions to move forward.
5703/// Returns 1 for most keys, height of the popup menu for page-up/down keys.
5704static int ins_compl_key2count(int c)
5705{
5706  if (c == K_EVENT || c == K_COMMAND || c == K_LUA) {
5707    int offset = pum_want.item - compl_selected_item;
5708    return abs(offset);
5709  }
5710
5711  if (ins_compl_pum_key(c) && c != K_UP && c != K_DOWN) {
5712    int h = pum_get_height();
5713    if (h > 3) {
5714      h -= 2;       // keep some context
5715    }
5716    return h;
5717  }
5718  return 1;
5719}
5720
5721/// Check that completion with "c" should insert the match, false if only
5722/// to change the currently selected completion.
5723///
5724/// @param  c  character to check
5725static bool ins_compl_use_match(int c)
5726  FUNC_ATTR_CONST FUNC_ATTR_WARN_UNUSED_RESULT
5727{
5728  switch (c) {
5729  case K_UP:
5730  case K_DOWN:
5731  case K_PAGEDOWN:
5732  case K_KPAGEDOWN:
5733  case K_S_DOWN:
5734  case K_PAGEUP:
5735  case K_KPAGEUP:
5736  case K_S_UP:
5737    return false;
5738  case K_EVENT:
5739  case K_COMMAND:
5740  case K_LUA:
5741    return pum_want.active && pum_want.insert;
5742  }
5743  return true;
5744}
5745
5746/// Get the pattern, column and length for normal completion (CTRL-N CTRL-P
5747/// completion)
5748/// Sets the global variables: compl_col, compl_length and compl_pattern.
5749/// Uses the global variables: compl_cont_status and ctrl_x_mode
5750static int get_normal_compl_info(char *line, int startcol, colnr_T curs_col)
5751{
5752  if ((compl_cont_status & CONT_SOL) || ctrl_x_mode_path_defines()) {
5753    if (!compl_status_adding()) {
5754      while (--startcol >= 0 && vim_isIDc((uint8_t)line[startcol])) {}
5755      compl_col += ++startcol;
5756      compl_length = curs_col - startcol;
5757    }
5758    if (p_ic) {
5759      compl_pattern = cstr_as_string(str_foldcase(line + compl_col,
5760                                                  compl_length, NULL, 0));
5761    } else {
5762      compl_pattern = cbuf_to_string(line + compl_col, (size_t)compl_length);
5763    }
5764  } else if (compl_status_adding()) {
5765    char *prefix = "\\<";
5766    size_t prefixlen = STRLEN_LITERAL("\\<");
5767
5768    if (!vim_iswordp(line + compl_col)
5769        || (compl_col > 0
5770            && (vim_iswordp(mb_prevptr(line, line + compl_col))))) {
5771      prefix = "";
5772      prefixlen = 0;
5773    }
5774
5775    // we need up to 2 extra chars for the prefix
5776    size_t n = quote_meta(NULL, line + compl_col, compl_length) + prefixlen;
5777    compl_pattern.data = xmalloc(n);
5778    STRCPY(compl_pattern.data, prefix);
5779    quote_meta(compl_pattern.data + prefixlen, line + compl_col, compl_length);
5780    compl_pattern.size = n - 1;
5781  } else if (--startcol < 0
5782             || !vim_iswordp(mb_prevptr(line, line + startcol + 1))) {
5783    // Match any word of at least two chars
5784    compl_pattern = cbuf_to_string(S_LEN("\\<\\k\\k"));
5785    compl_col += curs_col;
5786    compl_length = 0;
5787    compl_from_nonkeyword = true;
5788  } else {
5789    // Search the point of change class of multibyte character
5790    // or not a word single byte character backward.
5791    startcol -= utf_head_off(line, line + startcol);
5792    int base_class = mb_get_class(line + startcol);
5793    while (--startcol >= 0) {
5794      int head_off = utf_head_off(line, line + startcol);
5795      if (base_class != mb_get_class(line + startcol - head_off)) {
5796        break;
5797      }
5798      startcol -= head_off;
5799    }
5800
5801    compl_col += ++startcol;
5802    compl_length = (int)curs_col - startcol;
5803    if (compl_length == 1) {
5804      // Only match word with at least two chars -- webb
5805      // there's no need to call quote_meta,
5806      // xmalloc(7) is enough  -- Acevedo
5807      compl_pattern.data = xmalloc(7);
5808      STRCPY(compl_pattern.data, "\\<");
5809      quote_meta(compl_pattern.data + 2, line + compl_col, 1);
5810      strcat(compl_pattern.data, "\\k");
5811      compl_pattern.size = strlen(compl_pattern.data);
5812    } else {
5813      size_t n = quote_meta(NULL, line + compl_col, compl_length) + 2;
5814      compl_pattern.data = xmalloc(n);
5815      STRCPY(compl_pattern.data, "\\<");
5816      quote_meta(compl_pattern.data + 2, line + compl_col, compl_length);
5817      compl_pattern.size = n - 1;
5818    }
5819  }
5820
5821  // Call functions in 'complete' with 'findstart=1'
5822  if (ctrl_x_mode_normal() && !(compl_cont_status & CONT_LOCAL)) {
5823    // ^N completion, not complete() or ^X^N
5824    setup_cpt_sources();
5825    prepare_cpt_compl_funcs();
5826  }
5827
5828  return OK;
5829}
5830
5831/// Get the pattern, column and length for whole line completion or for the
5832/// complete() function.
5833/// Sets the global variables: compl_col, compl_length and compl_pattern.
5834static int get_wholeline_compl_info(char *line, colnr_T curs_col)
5835{
5836  compl_col = (colnr_T)getwhitecols(line);
5837  compl_length = (int)curs_col - (int)compl_col;
5838  if (compl_length < 0) {  // cursor in indent: empty pattern
5839    compl_length = 0;
5840  }
5841  if (p_ic) {
5842    compl_pattern = cstr_as_string(str_foldcase(line + compl_col,
5843                                                compl_length, NULL, 0));
5844  } else {
5845    compl_pattern = cbuf_to_string(line + compl_col, (size_t)compl_length);
5846  }
5847
5848  return OK;
5849}
5850
5851/// Get the pattern, column and length for filename completion.
5852/// Sets the global variables: compl_col, compl_length and compl_pattern.
5853static int get_filename_compl_info(char *line, int startcol, colnr_T curs_col)
5854{
5855  // Go back to just before the first filename character.
5856  if (startcol > 0) {
5857    char *p = line + startcol;
5858
5859    MB_PTR_BACK(line, p);
5860    while (p > line && vim_isfilec(utf_ptr2char(p))) {
5861      MB_PTR_BACK(line, p);
5862    }
5863    bool p_is_filec = false;
5864#ifdef MSWIN
5865    // check for drive letters on mswin
5866    if (p > line && path_has_drive_letter(p - 1, line + startcol - (p - 1))) {
5867      p -= p == line + 1 ? 1 : 2;
5868      p_is_filec = true;
5869    }
5870#endif
5871    p_is_filec = p_is_filec || vim_isfilec(utf_ptr2char(p));
5872
5873    if (p == line && p_is_filec) {
5874      startcol = 0;
5875    } else {
5876      startcol = (int)(p - line) + 1;
5877    }
5878  }
5879
5880  compl_col += startcol;
5881  compl_length = (int)curs_col - startcol;
5882  compl_pattern = cstr_as_string(addstar(line + compl_col,
5883                                         (size_t)compl_length, EXPAND_FILES));
5884
5885  return OK;
5886}
5887
5888/// Get the pattern, column and length for command-line completion.
5889/// Sets the global variables: compl_col, compl_length and compl_pattern.
5890static int get_cmdline_compl_info(char *line, colnr_T curs_col)
5891{
5892  compl_pattern = cbuf_to_string(line, (size_t)curs_col);
5893  set_cmd_context(&compl_xp, compl_pattern.data,
5894                  (int)compl_pattern.size, curs_col, false);
5895  if (compl_xp.xp_context == EXPAND_LUA) {
5896    nlua_expand_pat(&compl_xp);
5897  }
5898  if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL
5899      || compl_xp.xp_context == EXPAND_NOTHING) {
5900    // No completion possible, use an empty pattern to get a
5901    // "pattern not found" message.
5902    compl_col = curs_col;
5903  } else {
5904    compl_col = (int)(compl_xp.xp_pattern - compl_pattern.data);
5905  }
5906  compl_length = curs_col - compl_col;
5907
5908  return OK;
5909}
5910
5911/// Set global variables related to completion:
5912/// compl_col, compl_length, compl_pattern, and cpt_compl_pattern.
5913static void set_compl_globals(int startcol, colnr_T curs_col, bool is_cpt_compl)
5914{
5915  if (is_cpt_compl) {
5916    API_CLEAR_STRING(cpt_compl_pattern);
5917    if (startcol < compl_col) {
5918      prepend_startcol_text(&cpt_compl_pattern, &compl_orig_text, startcol);
5919      return;
5920    } else {
5921      cpt_compl_pattern = copy_string(compl_orig_text, NULL);
5922    }
5923  } else {
5924    if (startcol < 0 || startcol > curs_col) {
5925      startcol = curs_col;
5926    }
5927
5928    // Re-obtain line in case it has changed
5929    char *line = ml_get(curwin->w_cursor.lnum);
5930    int len = curs_col - startcol;
5931
5932    compl_pattern = cbuf_to_string(line + startcol, (size_t)len);
5933    compl_col = startcol;
5934    compl_length = len;
5935  }
5936}
5937
5938/// Get the pattern, column and length for user defined completion ('omnifunc',
5939/// 'completefunc' and 'thesaurusfunc')
5940/// Uses the global variable: spell_bad_len
5941///
5942/// @param cb        set if triggered by a function in the 'cpt' option, otherwise NULL
5943/// @param startcol  when not NULL, contains the column returned by function.
5944static int get_userdefined_compl_info(colnr_T curs_col, Callback *cb, int *startcol)
5945{
5946  // Call user defined function 'completefunc' with "a:findstart"
5947  // set to 1 to obtain the length of text to use for completion.
5948  const int save_State = State;
5949
5950  const bool is_cpt_function = (cb != NULL);
5951  const bool use_sandbox = is_cpt_function && was_set_insecurely(curwin, kOptComplete, OPT_LOCAL);
5952  if (!is_cpt_function) {
5953    cb = get_insert_callback(ctrl_x_mode);
5954    if (cb->type == kCallbackNone) {
5955      semsg(_(e_notset), ctrl_x_mode_function() ? "completefunc" : "omnifunc");
5956      return FAIL;
5957    }
5958  }
5959
5960  typval_T args[3];
5961  args[0].v_type = VAR_NUMBER;
5962  args[1].v_type = VAR_STRING;
5963  args[2].v_type = VAR_UNKNOWN;
5964  args[0].vval.v_number = 1;
5965  args[1].vval.v_string = "";
5966
5967  pos_T pos = curwin->w_cursor;
5968  textlock++;
5969  if (use_sandbox) {
5970    sandbox++;
5971  }
5972  colnr_T col = (colnr_T)callback_call_retnr(cb, 2, args);
5973  if (use_sandbox) {
5974    sandbox--;
5975  }
5976  textlock--;
5977
5978  State = save_State;
5979  curwin->w_cursor = pos;  // restore the cursor position
5980  check_cursor(curwin);  // make sure cursor position is valid, just in case
5981  validate_cursor(curwin);
5982  if (!equalpos(curwin->w_cursor, pos)) {
5983    emsg(_(e_compldel));
5984    return FAIL;
5985  }
5986
5987  if (startcol != NULL) {
5988    *startcol = col;
5989  }
5990
5991  // Return value -2 means the user complete function wants to cancel the
5992  // complete without an error, do the same if the function did not execute
5993  // successfully.
5994  if (col == -2 || aborting()) {
5995    return FAIL;
5996  }
5997
5998  // Return value -3 does the same as -2 and leaves CTRL-X mode.
5999  if (col == -3) {
6000    if (is_cpt_function) {
6001      return FAIL;
6002    }
6003    ctrl_x_mode = CTRL_X_NORMAL;
6004    edit_submode = NULL;
6005    if (!shortmess(kShmCompletionmenu)) {
6006      msg_clr_cmdline();
6007    }
6008    return FAIL;
6009  }
6010
6011  // Reset extended parameters of completion, when starting new
6012  // completion.
6013  compl_opt_refresh_always = false;
6014
6015  if (!is_cpt_function) {
6016    set_compl_globals(col, curs_col, false);
6017  }
6018  return OK;
6019}
6020
6021/// Get the pattern, column and length for spell completion.
6022/// Sets the global variables: compl_col, compl_length and compl_pattern.
6023/// Uses the global variable: spell_bad_len
6024static int get_spell_compl_info(int startcol, colnr_T curs_col)
6025{
6026  if (spell_bad_len > 0) {
6027    assert(spell_bad_len <= INT_MAX);
6028    compl_col = curs_col - (int)spell_bad_len;
6029  } else {
6030    compl_col = spell_word_start(startcol);
6031  }
6032  if (compl_col >= (colnr_T)startcol) {
6033    compl_length = 0;
6034    compl_col = curs_col;
6035  } else {
6036    spell_expand_check_cap(compl_col);
6037    compl_length = (int)curs_col - compl_col;
6038  }
6039  // Need to obtain "line" again, it may have become invalid.
6040  char *line = ml_get(curwin->w_cursor.lnum);
6041  compl_pattern = cbuf_to_string(line + compl_col, (size_t)compl_length);
6042
6043  return OK;
6044}
6045
6046/// Get the completion pattern, column and length.
6047///
6048/// @param startcol  start column number of the completion pattern/text
6049/// @param cur_col   current cursor column
6050///
6051/// On return, "line_invalid" is set to true, if the current line may have
6052/// become invalid and needs to be fetched again.
6053///
6054/// @return  OK on success.
6055static int compl_get_info(char *line, int startcol, colnr_T curs_col, bool *line_invalid)
6056{
6057  if (ctrl_x_mode_normal() || ctrl_x_mode_register()
6058      || ((ctrl_x_mode & CTRL_X_WANT_IDENT)
6059          && !thesaurus_func_complete(ctrl_x_mode))) {
6060    if (get_normal_compl_info(line, startcol, curs_col) != OK) {
6061      return FAIL;
6062    }
6063    *line_invalid = true;  // 'cpt' func may have invalidated "line"
6064  } else if (ctrl_x_mode_line_or_eval()) {
6065    return get_wholeline_compl_info(line, curs_col);
6066  } else if (ctrl_x_mode_files()) {
6067    return get_filename_compl_info(line, startcol, curs_col);
6068  } else if (ctrl_x_mode == CTRL_X_CMDLINE) {
6069    return get_cmdline_compl_info(line, curs_col);
6070  } else if (ctrl_x_mode_function() || ctrl_x_mode_omni()
6071             || thesaurus_func_complete(ctrl_x_mode)) {
6072    if (get_userdefined_compl_info(curs_col, NULL, NULL) != OK) {
6073      return FAIL;
6074    }
6075    *line_invalid = true;  // "line" may have become invalid
6076  } else if (ctrl_x_mode_spell()) {
6077    if (get_spell_compl_info(startcol, curs_col) == FAIL) {
6078      return FAIL;
6079    }
6080    *line_invalid = true;  // "line" may have become invalid
6081  } else {
6082    internal_error("ins_complete()");
6083    return FAIL;
6084  }
6085
6086  return OK;
6087}
6088
6089/// Continue an interrupted completion mode search in "line".
6090///
6091/// If this same ctrl_x_mode has been interrupted use the text from
6092/// "compl_startpos" to the cursor as a pattern to add a new word instead of
6093/// expand the one before the cursor, in word-wise if "compl_startpos" is not in
6094/// the same line as the cursor then fix it (the line has been split because it
6095/// was longer than 'tw').  if SOL is set then skip the previous pattern, a word
6096/// at the beginning of the line has been inserted, we'll look for that.
6097static void ins_compl_continue_search(char *line)
6098{
6099  // it is a continued search
6100  compl_cont_status &= ~CONT_INTRPT;  // remove INTRPT
6101  if (ctrl_x_mode_normal()
6102      || ctrl_x_mode_path_patterns()
6103      || ctrl_x_mode_path_defines()) {
6104    if (compl_startpos.lnum != curwin->w_cursor.lnum) {
6105      // line (probably) wrapped, set compl_startpos to the
6106      // first non_blank in the line, if it is not a wordchar
6107      // include it to get a better pattern, but then we don't
6108      // want the "\\<" prefix, check it below.
6109      compl_col = (colnr_T)getwhitecols(line);
6110      compl_startpos.col = compl_col;
6111      compl_startpos.lnum = curwin->w_cursor.lnum;
6112      compl_cont_status &= ~CONT_SOL;  // clear SOL if present
6113    } else {
6114      // S_IPOS was set when we inserted a word that was at the
6115      // beginning of the line, which means that we'll go to SOL
6116      // mode but first we need to redefine compl_startpos
6117      if (compl_cont_status & CONT_S_IPOS) {
6118        compl_cont_status |= CONT_SOL;
6119        compl_startpos.col = (colnr_T)(skipwhite(line + compl_length + compl_startpos.col) - line);
6120      }
6121      compl_col = compl_startpos.col;
6122    }
6123    compl_length = curwin->w_cursor.col - (int)compl_col;
6124    // IObuff is used to add a "word from the next line" would we
6125    // have enough space?  just being paranoid
6126#define MIN_SPACE 75
6127    if (compl_length > (IOSIZE - MIN_SPACE)) {
6128      compl_cont_status &= ~CONT_SOL;
6129      compl_length = (IOSIZE - MIN_SPACE);
6130      compl_col = curwin->w_cursor.col - compl_length;
6131    }
6132    compl_cont_status |= CONT_ADDING | CONT_N_ADDS;
6133    if (compl_length < 1) {
6134      compl_cont_status &= CONT_LOCAL;
6135    }
6136  } else if (ctrl_x_mode_line_or_eval() || ctrl_x_mode_register()) {
6137    compl_cont_status = CONT_ADDING | CONT_N_ADDS;
6138  } else {
6139    compl_cont_status = 0;
6140  }
6141}
6142
6143/// start insert mode completion
6144static int ins_compl_start(void)
6145{
6146  const bool save_did_ai = Ins.did_ai;
6147
6148  // First time we hit ^N or ^P (in a row, I mean)
6149
6150  Ins.did_ai = false;
6151  Ins.did_si = false;
6152  Ins.can_si = false;
6153  Ins.can_si_back = false;
6154  if (stop_arrow() == FAIL) {
6155    Ins.did_ai = save_did_ai;
6156    return FAIL;
6157  }
6158
6159  char *line = ml_get(curwin->w_cursor.lnum);
6160  colnr_T curs_col = curwin->w_cursor.col;
6161  compl_pending = 0;
6162  compl_lnum = curwin->w_cursor.lnum;
6163
6164  if ((compl_cont_status & CONT_INTRPT) == CONT_INTRPT
6165      && compl_cont_mode == ctrl_x_mode) {
6166    // this same ctrl-x_mode was interrupted previously. Continue the
6167    // completion.
6168    ins_compl_continue_search(line);
6169  } else {
6170    compl_cont_status &= CONT_LOCAL;
6171  }
6172
6173  int startcol = 0;  // column where searched text starts
6174  if (!compl_status_adding()) {   // normal expansion
6175    compl_cont_mode = ctrl_x_mode;
6176    if (ctrl_x_mode_not_default()) {
6177      // Remove LOCAL if ctrl_x_mode != CTRL_X_NORMAL
6178      compl_cont_status = 0;
6179    }
6180    compl_cont_status |= CONT_N_ADDS;
6181    compl_startpos = curwin->w_cursor;
6182    startcol = (int)curs_col;
6183    compl_col = 0;
6184  }
6185
6186  // Work out completion pattern and original text -- webb
6187  bool line_invalid = false;
6188  if (compl_get_info(line, startcol, curs_col, &line_invalid) == FAIL) {
6189    if (ctrl_x_mode_function() || ctrl_x_mode_omni()
6190        || thesaurus_func_complete(ctrl_x_mode)) {
6191      // restore Ins.did_ai, so that adding comment leader works
6192      Ins.did_ai = save_did_ai;
6193    }
6194    return FAIL;
6195  }
6196  // If "line" was changed while getting completion info get it again.
6197  if (line_invalid) {
6198    line = ml_get(curwin->w_cursor.lnum);
6199  }
6200
6201  if (compl_status_adding()) {
6202    if (!shortmess(kShmCompletionmenu)) {
6203      edit_submode_pre = _(" Adding");
6204    }
6205    if (ctrl_x_mode_line_or_eval()) {
6206      // Insert a new line, keep indentation but ignore 'comments'.
6207      char *old = curbuf->b_p_com;
6208
6209      curbuf->b_p_com = "";
6210      compl_startpos.lnum = curwin->w_cursor.lnum;
6211      compl_startpos.col = compl_col;
6212      ins_eol('\r');
6213      curbuf->b_p_com = old;
6214      compl_length = 0;
6215      compl_col = curwin->w_cursor.col;
6216      compl_lnum = curwin->w_cursor.lnum;
6217    }
6218  } else {
6219    edit_submode_pre = NULL;
6220    compl_startpos.col = compl_col;
6221  }
6222
6223  if (!shortmess(kShmCompletionmenu) && !compl_autocomplete) {
6224    if (compl_cont_status & CONT_LOCAL) {
6225      edit_submode = _(ctrl_x_msgs[CTRL_X_LOCAL_MSG]);
6226    } else {
6227      edit_submode = _(CTRL_X_MSG(ctrl_x_mode));
6228    }
6229  }
6230
6231  // If any of the original typed text has been changed we need to fix
6232  // the redo buffer.
6233  ins_compl_fixRedoBufForLeader(NULL);
6234
6235  // Always add completion for the original text.
6236  API_CLEAR_STRING(compl_orig_text);
6237  kv_destroy(compl_orig_extmarks);
6238  compl_orig_text = cbuf_to_string(line + compl_col, (size_t)compl_length);
6239  save_orig_extmarks();
6240  int flags = CP_ORIGINAL_TEXT;
6241  if (p_ic) {
6242    flags |= CP_ICASE;
6243  }
6244  if (ins_compl_add(compl_orig_text.data, (int)compl_orig_text.size,
6245                    NULL, NULL, false, NULL, 0,
6246                    flags, false, NULL, FUZZY_SCORE_NONE, false, NULL) != OK) {
6247    API_CLEAR_STRING(compl_pattern);
6248    API_CLEAR_STRING(compl_orig_text);
6249    kv_destroy(compl_orig_extmarks);
6250    Ins.did_ai = save_did_ai;
6251    return FAIL;
6252  }
6253
6254  // showmode might reset the internal line pointers, so it must
6255  // be called before line = ml_get(), or when this address is no
6256  // longer needed.  -- Acevedo.
6257  if (!shortmess(kShmCompletionmenu) && !compl_autocomplete) {
6258    edit_submode_extra = _("-- Searching...");
6259    edit_submode_highl = HLF_COUNT;
6260    showmode();
6261    edit_submode_extra = NULL;
6262    ui_flush();
6263  }
6264
6265  Ins.did_ai = save_did_ai;
6266  return OK;
6267}
6268
6269/// display the completion status message
6270static void ins_compl_show_statusmsg(void)
6271{
6272  // we found no match if the list has only the "compl_orig_text"-entry
6273  if (is_first_match(compl_first_match->cp_next)) {
6274    edit_submode_extra = compl_status_adding() && compl_length > 1
6275                         ? _("Hit end of paragraph") : _("Pattern not found");
6276    edit_submode_highl = HLF_E;
6277  }
6278
6279  if (edit_submode_extra == NULL) {
6280    if (match_at_original_text(compl_curr_match)) {
6281      edit_submode_extra = _("Back at original");
6282      edit_submode_highl = HLF_W;
6283    } else if (compl_cont_status & CONT_S_IPOS) {
6284      edit_submode_extra = _("Word from other line");
6285      edit_submode_highl = HLF_COUNT;
6286    } else if (compl_curr_match->cp_next == compl_curr_match->cp_prev) {
6287      edit_submode_extra = _("The only match");
6288      edit_submode_highl = HLF_COUNT;
6289      compl_curr_match->cp_number = 1;
6290    } else {
6291      // Update completion sequence number when needed.
6292      if (compl_curr_match->cp_number == -1) {
6293        ins_compl_update_sequence_numbers();
6294      }
6295
6296      // The match should always have a sequence number now, this is
6297      // just a safety check.
6298      if (compl_curr_match->cp_number != -1) {
6299        // Space for 10 text chars. + 2x10-digit no.s = 31.
6300        // Translations may need more than twice that.
6301        static char match_ref[81];
6302
6303        if (compl_matches > 0) {
6304          vim_snprintf(match_ref, sizeof(match_ref),
6305                       _("match %d of %d"),
6306                       compl_curr_match->cp_number, compl_matches);
6307        } else {
6308          vim_snprintf(match_ref, sizeof(match_ref),
6309                       _("match %d"),
6310                       compl_curr_match->cp_number);
6311        }
6312        edit_submode_extra = match_ref;
6313        edit_submode_highl = HLF_R;
6314        if (dollar_vcol >= 0) {
6315          curs_columns(curwin, false);
6316        }
6317      }
6318    }
6319  }
6320
6321  // Show a message about what (completion) mode we're in.
6322  redraw_mode = true;
6323  if (!shortmess(kShmCompletionmenu)) {
6324    if (edit_submode_extra != NULL) {
6325      if (!p_smd) {
6326        msg_hist_off = true;
6327        msg_ext_set_kind("completion");
6328        msg(edit_submode_extra, (edit_submode_highl < HLF_COUNT
6329                                 ? (int)edit_submode_highl + 1 : 0));
6330        msg_hist_off = false;
6331      }
6332    } else {
6333      msg_clr_cmdline();  // necessary for "noshowmode"
6334    }
6335  }
6336}
6337
6338/// Do Insert mode completion.
6339/// Called when character "c" was typed, which has a meaning for completion.
6340/// Returns OK if completion was done, FAIL if something failed.
6341int ins_complete(int c, bool enable_pum)
6342{
6343  compl_direction = ins_compl_key2dir(c);
6344  int insert_match = ins_compl_use_match(c);
6345
6346  if (!compl_started) {
6347    // Only what the automatic trigger armed counts as started by Vim.
6348    compl_autostarted = compl_autostart_pending;
6349    compl_autostart_pending = false;
6350    if (ins_compl_start() == FAIL) {
6351      return FAIL;
6352    }
6353  } else if (insert_match && stop_arrow() == FAIL) {
6354    return FAIL;
6355  }
6356
6357  compl_curr_win = curwin;
6358  compl_curr_buf = curwin->w_buffer;
6359  compl_shown_match = compl_curr_match;
6360  compl_shows_dir = compl_direction;
6361  compl_num_bests = 0;
6362
6363  // Find next match (and following matches).
6364  int save_w_wrow = curwin->w_wrow;
6365  int save_w_leftcol = curwin->w_leftcol;
6366  int n = ins_compl_next(true, ins_compl_key2count(c), insert_match);
6367
6368  // Reset autocompletion timer expiry flag
6369  if (compl_autocomplete) {
6370    compl_time_slice_expired = false;
6371  }
6372
6373  if (n > 1) {          // all matches have been found
6374    compl_matches = n;
6375  }
6376  compl_curr_match = compl_shown_match;
6377  compl_direction = compl_shows_dir;
6378
6379  // Eat the ESC that vgetc() returns after a CTRL-C to avoid leaving Insert
6380  // mode.
6381  if (got_int && !global_busy) {
6382    vgetc();
6383    got_int = false;
6384  }
6385
6386  // we found no match if the list has only the "compl_orig_text"-entry
6387  bool no_matches_found = is_first_match(compl_first_match->cp_next);
6388  if (no_matches_found) {
6389    // remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,
6390    // because we couldn't expand anything at first place, but if we used
6391    // ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word
6392    // (such as M in M'exico) if not tried already.  -- Acevedo
6393    if (compl_length > 1
6394        || compl_status_adding()
6395        || (ctrl_x_mode_not_default()
6396            && !ctrl_x_mode_path_patterns()
6397            && !ctrl_x_mode_path_defines())) {
6398      compl_cont_status &= ~CONT_N_ADDS;
6399    }
6400  }
6401
6402  if (compl_curr_match->cp_flags & CP_CONT_S_IPOS) {
6403    compl_cont_status |= CONT_S_IPOS;
6404  } else {
6405    compl_cont_status &= ~CONT_S_IPOS;
6406  }
6407
6408  if (!shortmess(kShmCompletionmenu) && !compl_autocomplete) {
6409    ins_compl_show_statusmsg();
6410  }
6411
6412  if (!shortmess(kShmCompletionscan) && !compl_autocomplete) {
6413    // End the "Scanning..." progress-msg. ins_compl_show_statusmsg() already reported the result.
6414    msg_progress(NULL, "nvim.completion", "success", 0, false, false, false);
6415  }
6416
6417  // Show the popup menu, unless we got interrupted.
6418  if (enable_pum && !compl_interrupted) {
6419    show_pum(save_w_wrow, save_w_leftcol);
6420  }
6421  compl_was_interrupted = compl_interrupted;
6422  compl_interrupted = false;
6423
6424  return OK;
6425}
6426
6427/// Enable autocompletion
6428void ins_compl_enable_autocomplete(void)
6429{
6430  compl_autocomplete = true;
6431  compl_get_longest = false;
6432}
6433
6434/// Disable autocompletion
6435void ins_compl_disable_autocomplete(void)
6436{
6437  compl_autocomplete = false;
6438}
6439
6440/// Remember that Vim is about to start a completion by itself, rather than
6441/// because a key was typed to ask for one.
6442void ins_compl_arm_autostart(void)
6443{
6444  compl_autostart_pending = true;
6445}
6446
6447/// Forget what the automatic trigger armed, another key was typed since.
6448void ins_compl_disarm_autostart(void)
6449{
6450  compl_autostart_pending = false;
6451}
6452
6453/// Arm the 'autocompletedelay' timer when the delay is in effect.
6454/// Return true when the popup should be deferred, false to trigger it now.
6455bool ins_compl_arm_autocomplete_delay(void)
6456{
6457  if (p_acl > 0) {
6458    compl_autocomplete_start_tv = os_hrtime();
6459    compl_autocomplete_pending = true;
6460    return true;
6461  }
6462  return false;
6463}
6464
6465/// Clear the pending 'autocompletedelay' state.
6466void ins_compl_clear_autocomplete_delay(void)
6467{
6468  compl_autocomplete_pending = false;
6469}
6470
6471/// Return true while waiting for 'autocompletedelay' to expire.
6472bool ins_compl_autocomplete_pending(void)
6473{
6474  return compl_autocomplete_pending;
6475}
6476
6477/// Return the time in msec since the 'autocompletedelay' was armed.
6478int64_t ins_compl_autocomplete_elapsed(void)
6479{
6480  return (int64_t)((os_hrtime() - compl_autocomplete_start_tv) / 1000000);
6481}
6482
6483/// Remove (if needed) and show the popup menu
6484static void show_pum(int prev_w_wrow, int prev_w_leftcol)
6485{
6486  // RedrawingDisabled may be set when invoked through complete().
6487  int n = RedrawingDisabled;
6488  RedrawingDisabled = 0;
6489
6490  // If the cursor moved or the display scrolled we need to remove the pum
6491  // first.
6492  setcursor();
6493  if (prev_w_wrow != curwin->w_wrow || prev_w_leftcol != curwin->w_leftcol) {
6494    ins_compl_del_pum();
6495  }
6496
6497  ins_compl_show_pum();
6498  setcursor();
6499  RedrawingDisabled = n;
6500}
6501
6502// Looks in the first "len" chars. of "src" for search-metachars.
6503// If dest is not NULL the chars. are copied there quoting (with
6504// a backslash) the metachars, and dest would be NUL terminated.
6505// Returns the length (needed) of dest
6506static unsigned quote_meta(char *dest, char *src, int len)
6507{
6508  unsigned m = (unsigned)len + 1;       // one extra for the NUL
6509
6510  for (; --len >= 0; src++) {
6511    switch (*src) {
6512    case '.':
6513    case '*':
6514    case '[':
6515      if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus()) {
6516        break;
6517      }
6518      FALLTHROUGH;
6519    case '~':
6520      if (!p_magic) {  // quote these only if magic is set
6521        break;
6522      }
6523      FALLTHROUGH;
6524    case '\\':
6525      if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus()) {
6526        break;
6527      }
6528      FALLTHROUGH;
6529    case '^':                   // currently it's not needed.
6530    case '$':
6531      m++;
6532      if (dest != NULL) {
6533        *dest++ = '\\';
6534      }
6535      break;
6536    }
6537    if (dest != NULL) {
6538      *dest++ = *src;
6539    }
6540    // Copy remaining bytes of a multibyte character.
6541    const int mb_len = utfc_ptr2len(src) - 1;
6542    if (mb_len > 0 && len >= mb_len) {
6543      for (int i = 0; i < mb_len; i++) {
6544        len--;
6545        src++;
6546        if (dest != NULL) {
6547          *dest++ = *src;
6548        }
6549      }
6550    }
6551  }
6552  if (dest != NULL) {
6553    *dest = NUL;
6554  }
6555
6556  return m;
6557}
6558
6559#ifdef EXITFREE
6560void free_insexpand_stuff(void)
6561{
6562  API_CLEAR_STRING(compl_orig_text);
6563  kv_destroy(compl_orig_extmarks);
6564  callback_free(&p_cfu);
6565  callback_free(&p_ofu);
6566  callback_free(&p_tsrfu);
6567  clear_cpt_callbacks(&cpt_cb, cpt_cb_count);
6568}
6569#endif
6570
6571/// Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly
6572/// spelled word, if there is one.
6573static void spell_back_to_badword(void)
6574{
6575  pos_T tpos = curwin->w_cursor;
6576  spell_bad_len = spell_move_to(curwin, BACKWARD, SMT_ALL, true, NULL);
6577  if (curwin->w_cursor.col != tpos.col) {
6578    start_arrow(&tpos, true, NUL);
6579  }
6580}
6581
6582/// Reset the info associated with completion sources.
6583static void cpt_sources_clear(void)
6584{
6585  XFREE_CLEAR(cpt_sources_array);
6586  cpt_sources_index = -1;
6587  cpt_sources_count = 0;
6588}
6589
6590/// Setup completion sources.
6591static void setup_cpt_sources(void)
6592{
6593  cpt_sources_clear();
6594
6595  int count = get_cpt_sources_count(curbuf->b_p_cpt);
6596  if (count == 0) {
6597    return;
6598  }
6599
6600  cpt_sources_array = xcalloc((size_t)count, sizeof(cpt_source_T));
6601
6602  char buf[LSIZE];
6603  int idx = 0;
6604  for (char *p = curbuf->b_p_cpt; *p;) {
6605    while (*p == ',' || *p == ' ') {  // Skip delimiters
6606      p++;
6607    }
6608    if (*p) {  // If not end of string, count this segment
6609      cpt_sources_array[idx].cs_flag = *p;
6610      memset(buf, 0, LSIZE);
6611      size_t slen = copy_option_part(&p, buf, LSIZE, ",");  // Advance p
6612      if (slen > 0) {
6613        char *caret = vim_strchr(buf, '^');
6614        if (caret != NULL) {
6615          cpt_sources_array[idx].cs_max_matches = atoi(caret + 1);
6616        }
6617      }
6618      idx++;
6619    }
6620  }
6621
6622  cpt_sources_count = count;
6623}
6624
6625/// Return true if any of the completion sources have 'refresh' set to 'always'.
6626static bool is_cpt_func_refresh_always(void)
6627{
6628  for (int i = 0; i < cpt_sources_count; i++) {
6629    if (cpt_sources_array[i].cs_refresh_always) {
6630      return true;
6631    }
6632  }
6633  return false;
6634}
6635
6636/// Make the completion list non-cyclic.
6637static void ins_compl_make_linear(void)
6638{
6639  if (compl_first_match == NULL || compl_first_match->cp_prev == NULL) {
6640    return;
6641  }
6642  compl_T *m = compl_first_match->cp_prev;
6643  m->cp_next = NULL;
6644  compl_first_match->cp_prev = NULL;
6645}
6646
6647/// Remove the matches linked to the current completion source (as indicated by
6648/// cpt_sources_index) from the completion list.
6649static void remove_old_matches(void)
6650{
6651  bool shown_match_removed = false;
6652  bool forward = (compl_first_match->cp_cpt_source_idx < 0);
6653
6654  if (cpt_sources_index < 0) {
6655    return;
6656  }
6657
6658  compl_direction = forward ? FORWARD : BACKWARD;
6659  compl_shows_dir = compl_direction;
6660
6661  // When 'fuzzy' is enabled, items are not ordered by their original source
6662  // order (cpt_sources_index). So, remove items one by one.
6663  for (compl_T *current = compl_first_match; current != NULL;) {
6664    if (current->cp_cpt_source_idx == cpt_sources_index) {
6665      compl_T *to_delete = current;
6666
6667      if (!shown_match_removed && compl_shown_match == current) {
6668        shown_match_removed = true;
6669      }
6670
6671      // Avoid dangling pointer when preselect match is removed.
6672      if (to_delete == compl_preselect_match) {
6673        compl_preselect_match = NULL;
6674      }
6675
6676      current = current->cp_next;
6677
6678      if (to_delete == compl_first_match) {  // node to remove is at head
6679        compl_first_match = to_delete->cp_next;
6680        compl_first_match->cp_prev = NULL;
6681      } else if (to_delete->cp_next == NULL) {  // node to remove is at tail
6682        to_delete->cp_prev->cp_next = NULL;
6683      } else {          // node is in the moddle
6684        to_delete->cp_prev->cp_next = to_delete->cp_next;
6685        to_delete->cp_next->cp_prev = to_delete->cp_prev;
6686      }
6687      ins_compl_item_free(to_delete);
6688    } else {
6689      current = current->cp_next;
6690    }
6691  }
6692
6693  // Re-assign compl_shown_match if necessary
6694  if (shown_match_removed) {
6695    if (forward) {
6696      compl_shown_match = compl_first_match;
6697    } else {    // Last node will have the prefix that is being completed
6698      compl_T *current;
6699      for (current = compl_first_match; current->cp_next != NULL;
6700           current = current->cp_next) {}
6701      compl_shown_match = current;
6702    }
6703  }
6704
6705  // Re-assign compl_curr_match
6706  compl_curr_match = compl_first_match;
6707  for (compl_T *current = compl_first_match; current != NULL;) {
6708    if ((forward ? current->cp_cpt_source_idx < cpt_sources_index
6709                 : current->cp_cpt_source_idx > cpt_sources_index)) {
6710      compl_curr_match = forward ? current : current->cp_next;
6711      current = current->cp_next;
6712    } else {
6713      break;
6714    }
6715  }
6716}
6717
6718/// Retrieve completion matches using the callback function "cb" and store the
6719/// 'refresh:always' flag.
6720static void get_cpt_func_completion_matches(Callback *cb)
6721{
6722  cpt_source_T *cpt_src = &cpt_sources_array[cpt_sources_index];
6723  int startcol = cpt_src->cs_startcol;
6724
6725  if (startcol == -2 || startcol == -3) {
6726    return;
6727  }
6728
6729  set_compl_globals(startcol, curwin->w_cursor.col, true);
6730
6731  // Insert the leader string (previously removed) before expansion.
6732  // This prevents flicker when `func` (e.g. an LSP client) is slow and
6733  // calls 'sleep', which triggers ui_flush().
6734  if (!cpt_src->cs_refresh_always) {
6735    ins_compl_insert_bytes(ins_compl_leader(), -1);
6736  }
6737
6738  expand_by_function(0, cpt_compl_pattern.data, cb);
6739
6740  if (!cpt_src->cs_refresh_always) {
6741    ins_compl_delete(false);
6742  }
6743
6744  cpt_src->cs_refresh_always = compl_opt_refresh_always;
6745  compl_opt_refresh_always = false;
6746}
6747
6748/// Retrieve completion matches from functions in the 'cpt' option where the
6749/// 'refresh:always' flag is set.
6750static void cpt_compl_refresh(void)
6751{
6752  // Make the completion list linear (non-cyclic)
6753  ins_compl_make_linear();
6754  // Make a copy of 'cpt' in case the buffer gets wiped out
6755  char *cpt = xstrdup(curbuf->b_p_cpt);
6756  strip_caret_numbers_in_place(cpt);
6757
6758  cpt_sources_index = 0;
6759  for (char *p = cpt; *p;) {
6760    while (*p == ',' || *p == ' ') {  // Skip delimiters
6761      p++;
6762    }
6763    if (*p == NUL) {
6764      break;
6765    }
6766
6767    if (cpt_sources_array[cpt_sources_index].cs_refresh_always) {
6768      Callback *cb = get_callback_if_cpt_func(p, cpt_sources_index);
6769      if (cb) {
6770        remove_old_matches();
6771        int startcol;
6772        int ret = get_userdefined_compl_info(curwin->w_cursor.col, cb, &startcol);
6773        if (ret == FAIL) {
6774          if (startcol == -3) {
6775            cpt_sources_array[cpt_sources_index].cs_refresh_always = false;
6776          } else {
6777            startcol = -2;
6778          }
6779        } else if (startcol < 0 || startcol > curwin->w_cursor.col) {
6780          startcol = curwin->w_cursor.col;
6781        }
6782        cpt_sources_array[cpt_sources_index].cs_startcol = startcol;
6783        if (ret == OK) {
6784          compl_source_start_timer(cpt_sources_index);
6785          get_cpt_func_completion_matches(cb);
6786        }
6787      }
6788    }
6789
6790    (void)copy_option_part(&p, IObuff, IOSIZE, ",");  // Advance p
6791    if (may_advance_cpt_index(p)) {
6792      (void)advance_cpt_sources_index_safe();
6793    }
6794  }
6795  cpt_sources_index = -1;
6796
6797  xfree(cpt);
6798  // Make the list cyclic
6799  compl_matches = ins_compl_make_cyclic();
6800}
6801
6802/// "preinserted()" function
6803void f_preinserted(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
6804{
6805  if (ins_compl_preinsert_effect()) {
6806    rettv->vval.v_number = 1;
6807  }
6808}