blob: 889ea3611902ffeca20519a7a0e65df222183fdc [file] [log] [blame]
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001/* vi:set ts=8 sts=4 sw=4 noet:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * insexpand.c: functions for Insert mode completion
12 */
13
14#include "vim.h"
15
Bram Moolenaar7591bb32019-03-30 13:53:47 +010016/*
17 * Definitions used for CTRL-X submode.
18 * Note: If you change CTRL-X submode, you must also maintain ctrl_x_msgs[] and
19 * ctrl_x_mode_names[] below.
20 */
21# define CTRL_X_WANT_IDENT 0x100
22
Bram Moolenaaraa2f0ee2019-12-21 18:47:26 +010023# define CTRL_X_NORMAL 0 // CTRL-N CTRL-P completion, default
Bram Moolenaar7591bb32019-03-30 13:53:47 +010024# define CTRL_X_NOT_DEFINED_YET 1
25# define CTRL_X_SCROLL 2
26# define CTRL_X_WHOLE_LINE 3
27# define CTRL_X_FILES 4
28# define CTRL_X_TAGS (5 + CTRL_X_WANT_IDENT)
29# define CTRL_X_PATH_PATTERNS (6 + CTRL_X_WANT_IDENT)
30# define CTRL_X_PATH_DEFINES (7 + CTRL_X_WANT_IDENT)
31# define CTRL_X_FINISHED 8
32# define CTRL_X_DICTIONARY (9 + CTRL_X_WANT_IDENT)
33# define CTRL_X_THESAURUS (10 + CTRL_X_WANT_IDENT)
34# define CTRL_X_CMDLINE 11
Bram Moolenaar9810cfb2019-12-11 21:23:00 +010035# define CTRL_X_FUNCTION 12
Bram Moolenaar7591bb32019-03-30 13:53:47 +010036# define CTRL_X_OMNI 13
37# define CTRL_X_SPELL 14
Bram Moolenaaraa2f0ee2019-12-21 18:47:26 +010038# define CTRL_X_LOCAL_MSG 15 // only used in "ctrl_x_msgs"
39# define CTRL_X_EVAL 16 // for builtin function complete()
zeertzjqdca29d92021-08-31 19:12:51 +020040# define CTRL_X_CMDLINE_CTRL_X 17 // CTRL-X typed in CTRL_X_CMDLINE
glepnir05460682025-05-26 18:23:27 +020041# define CTRL_X_REGISTER 18 // complete words from registers
Bram Moolenaar7591bb32019-03-30 13:53:47 +010042
43# define CTRL_X_MSG(i) ctrl_x_msgs[(i) & ~CTRL_X_WANT_IDENT]
44
45// Message for CTRL-X mode, index is ctrl_x_mode.
46static char *ctrl_x_msgs[] =
47{
48 N_(" Keyword completion (^N^P)"), // CTRL_X_NORMAL, ^P/^N compl.
glepnir05460682025-05-26 18:23:27 +020049 N_(" ^X mode (^]^D^E^F^I^K^L^N^O^P^Rs^U^V^Y)"),
Bram Moolenaar7591bb32019-03-30 13:53:47 +010050 NULL, // CTRL_X_SCROLL: depends on state
51 N_(" Whole line completion (^L^N^P)"),
52 N_(" File name completion (^F^N^P)"),
53 N_(" Tag completion (^]^N^P)"),
54 N_(" Path pattern completion (^N^P)"),
55 N_(" Definition completion (^D^N^P)"),
56 NULL, // CTRL_X_FINISHED
57 N_(" Dictionary completion (^K^N^P)"),
58 N_(" Thesaurus completion (^T^N^P)"),
59 N_(" Command-line completion (^V^N^P)"),
60 N_(" User defined completion (^U^N^P)"),
61 N_(" Omni completion (^O^N^P)"),
zeertzjq7002c052024-06-21 07:55:07 +020062 N_(" Spelling suggestion (^S^N^P)"),
Bram Moolenaar7591bb32019-03-30 13:53:47 +010063 N_(" Keyword Local completion (^N^P)"),
64 NULL, // CTRL_X_EVAL doesn't use msg.
zeertzjqdca29d92021-08-31 19:12:51 +020065 N_(" Command-line completion (^V^N^P)"),
glepnir05460682025-05-26 18:23:27 +020066 N_(" Register completion (^N^P)"),
Bram Moolenaar7591bb32019-03-30 13:53:47 +010067};
68
Bram Moolenaar9cb698d2019-08-21 15:30:45 +020069#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +010070static char *ctrl_x_mode_names[] = {
Hirohito Higashi355db992025-04-28 18:07:02 +020071 "keyword",
72 "ctrl_x",
73 "scroll",
74 "whole_line",
75 "files",
76 "tags",
77 "path_patterns",
78 "path_defines",
79 "unknown", // CTRL_X_FINISHED
80 "dictionary",
81 "thesaurus",
82 "cmdline",
83 "function",
84 "omni",
85 "spell",
86 NULL, // CTRL_X_LOCAL_MSG only used in "ctrl_x_msgs"
87 "eval",
88 "cmdline",
glepnir05460682025-05-26 18:23:27 +020089 "register",
Bram Moolenaar7591bb32019-03-30 13:53:47 +010090};
Bram Moolenaar9cb698d2019-08-21 15:30:45 +020091#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +010092
93/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +010094 * Structure used to store one match for insert completion.
95 */
96typedef struct compl_S compl_T;
97struct compl_S
98{
99 compl_T *cp_next;
100 compl_T *cp_prev;
glepnir80b66202024-11-27 21:53:53 +0100101 compl_T *cp_match_next; // matched next compl_T
John Marriott5e6ea922024-11-23 14:01:57 +0100102 string_T cp_str; // matched text
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200103 char_u *(cp_text[CPT_COUNT]); // text for the menu
Bram Moolenaarab782c52020-01-04 19:00:11 +0100104#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +0100105 typval_T cp_user_data;
Bram Moolenaarab782c52020-01-04 19:00:11 +0100106#endif
glepnir0fe17f82024-10-08 22:26:44 +0200107 char_u *cp_fname; // file containing the match, allocated when
108 // cp_flags has CP_FREE_FNAME
109 int cp_flags; // CP_ values
110 int cp_number; // sequence number
Girish Palyab1565882025-04-15 20:16:00 +0200111 int cp_score; // fuzzy match score or proximity score
glepnird4088ed2024-12-31 10:55:22 +0100112 int cp_in_match_array; // collected by compl_match_array
glepnir7baa0142024-10-09 20:19:25 +0200113 int cp_user_abbr_hlattr; // highlight attribute for abbr
glepnir0fe17f82024-10-08 22:26:44 +0200114 int cp_user_kind_hlattr; // highlight attribute for kind
Girish Palya0ac1eb32025-04-16 20:18:33 +0200115 int cp_cpt_source_idx; // index of this match's source in 'cpt' option
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100116};
117
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200118// values for cp_flags
119# define CP_ORIGINAL_TEXT 1 // the original text when the expansion begun
120# define CP_FREE_FNAME 2 // cp_fname is allocated
121# define CP_CONT_S_IPOS 4 // use CONT_S_IPOS for compl_cont_status
122# define CP_EQUAL 8 // ins_compl_equal() always returns TRUE
123# define CP_ICASE 16 // ins_compl_equal() ignores case
Bram Moolenaar440cf092021-04-03 20:13:30 +0200124# define CP_FAST 32 // use fast_breakcheck instead of ui_breakcheck
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100125
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100126/*
127 * All the current matches are stored in a list.
128 * "compl_first_match" points to the start of the list.
129 * "compl_curr_match" points to the currently selected entry.
130 * "compl_shown_match" is different from compl_curr_match during
Girish Palyacbe53192025-04-14 22:13:15 +0200131 * ins_compl_get_exp(), when new matches are added to the list.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000132 * "compl_old_match" points to previous "compl_curr_match".
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100133 */
134static compl_T *compl_first_match = NULL;
135static compl_T *compl_curr_match = NULL;
136static compl_T *compl_shown_match = NULL;
137static compl_T *compl_old_match = NULL;
138
glepnirf31cfa22025-03-06 21:59:13 +0100139// list used to store the compl_T which have the max score
140// used for completefuzzycollect
141static compl_T **compl_best_matches = NULL;
142static int compl_num_bests = 0;
143// inserted a longest when completefuzzycollect enabled
144static int compl_cfc_longest_ins = FALSE;
145
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100146// After using a cursor key <Enter> selects a match in the popup menu,
147// otherwise it inserts a line break.
148static int compl_enter_selects = FALSE;
149
150// When "compl_leader" is not NULL only matches that start with this string
151// are used.
John Marriott5e6ea922024-11-23 14:01:57 +0100152static string_T compl_leader = {NULL, 0};
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100153
154static int compl_get_longest = FALSE; // put longest common string
155 // in compl_leader
156
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100157// Selected one of the matches. When FALSE the match was edited or using the
158// longest common string.
159static int compl_used_match;
160
161// didn't finish finding completions.
162static int compl_was_interrupted = FALSE;
163
164// Set when character typed while looking for matches and it means we should
165// stop looking for matches.
166static int compl_interrupted = FALSE;
167
168static int compl_restarting = FALSE; // don't insert match
169
170// When the first completion is done "compl_started" is set. When it's
171// FALSE the word to be completed must be located.
172static int compl_started = FALSE;
173
174// Which Ctrl-X mode are we in?
175static int ctrl_x_mode = CTRL_X_NORMAL;
176
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000177static int compl_matches = 0; // number of completion matches
Girish Palyacbe53192025-04-14 22:13:15 +0200178static string_T compl_pattern = {NULL, 0}; // search pattern for matching items
179#ifdef FEAT_COMPL_FUNC
180static string_T cpt_compl_pattern = {NULL, 0}; // pattern returned by func in 'cpt'
181#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100182static int compl_direction = FORWARD;
183static int compl_shows_dir = FORWARD;
184static int compl_pending = 0; // > 1 for postponed CTRL-N
185static pos_T compl_startpos;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000186// Length in bytes of the text being completed (this is deleted to be replaced
187// by the match.)
188static int compl_length = 0;
glepnir76bdb822025-02-08 19:04:51 +0100189static linenr_T compl_lnum = 0; // lnum where the completion start
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100190static colnr_T compl_col = 0; // column where the text starts
191 // that is being completed
glepnir6a38aff2024-12-16 21:56:16 +0100192static colnr_T compl_ins_end_col = 0;
John Marriott5e6ea922024-11-23 14:01:57 +0100193static string_T compl_orig_text = {NULL, 0}; // text as it was before
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100194 // completion started
195static int compl_cont_mode = 0;
196static expand_T compl_xp;
197
glepnircf7f0122025-04-15 19:02:00 +0200198static win_T *compl_curr_win = NULL; // win where completion is active
199static buf_T *compl_curr_buf = NULL; // buf where completion is active
200
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000201// List of flags for method of completion.
202static int compl_cont_status = 0;
203# define CONT_ADDING 1 // "normal" or "adding" expansion
204# define CONT_INTRPT (2 + 4) // a ^X interrupted the current expansion
205 // it's set only iff N_ADDS is set
206# define CONT_N_ADDS 4 // next ^X<> will add-new or expand-current
207# define CONT_S_IPOS 8 // next ^X<> will set initial_pos?
208 // if so, word-wise-expansion will set SOL
209# define CONT_SOL 16 // pattern includes start of line, just for
210 // word-wise expansion, not set for ^X^L
211# define CONT_LOCAL 32 // for ctrl_x_mode 0, ^X^P/^X^N do a local
212 // expansion, (eg use complete=.)
213
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100214static int compl_opt_refresh_always = FALSE;
215static int compl_opt_suppress_empty = FALSE;
216
glepnira218cc62024-06-03 19:32:39 +0200217static int compl_selected_item = -1;
218
glepnir8159fb12024-07-17 20:32:54 +0200219static int *compl_fuzzy_scores;
220
Girish Palya0ac1eb32025-04-16 20:18:33 +0200221// Define the structure for completion source (in 'cpt' option) information
222typedef struct cpt_source_T
223{
Girish Palya98c29db2025-06-01 19:40:00 +0200224 int cs_refresh_always; // Whether 'refresh:always' is set for func
225 int cs_startcol; // Start column returned by func
226 int cs_max_matches; // Max items to display from this source
Girish Palya0ac1eb32025-04-16 20:18:33 +0200227} cpt_source_T;
228
229static cpt_source_T *cpt_sources_array; // Pointer to the array of completion sources
230static int cpt_sources_count; // Total number of completion sources specified in the 'cpt' option
Girish Palya7c621052025-05-26 19:41:59 +0200231static int cpt_sources_index = -1; // Index of the current completion source being expanded
Girish Palyacbe53192025-04-14 22:13:15 +0200232
glepnir6a38aff2024-12-16 21:56:16 +0100233// "compl_match_array" points the currently displayed list of entries in the
234// popup menu. It is NULL when there is no popup menu.
235static pumitem_T *compl_match_array = NULL;
236static int compl_match_arraysize;
237
glepnirf31cfa22025-03-06 21:59:13 +0100238static int ins_compl_add(char_u *str, int len, char_u *fname, char_u **cptext, typval_T *user_data, int cdir, int flags, int adup, int *user_hl, int score);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100239static void ins_compl_longest_match(compl_T *match);
240static void ins_compl_del_pum(void);
241static void ins_compl_files(int count, char_u **files, int thesaurus, int flags, regmatch_T *regmatch, char_u *buf, int *dir);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100242static void ins_compl_free(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100243static int ins_compl_need_restart(void);
244static void ins_compl_new_leader(void);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000245static int get_compl_len(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100246static void ins_compl_restart(void);
John Marriott5e6ea922024-11-23 14:01:57 +0100247static void ins_compl_set_original_text(char_u *str, size_t len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100248static void ins_compl_fixRedoBufForLeader(char_u *ptr_arg);
249# if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
250static void ins_compl_add_list(list_T *list);
251static void ins_compl_add_dict(dict_T *dict);
Girish Palyacbe53192025-04-14 22:13:15 +0200252static int get_userdefined_compl_info(colnr_T curs_col, callback_T *cb, int *startcol);
Girish Palyacbe53192025-04-14 22:13:15 +0200253static void get_cpt_func_completion_matches(callback_T *cb);
Girish Palya98c29db2025-06-01 19:40:00 +0200254static callback_T *get_callback_if_cpt_func(char_u *p);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100255# endif
Girish Palya98c29db2025-06-01 19:40:00 +0200256static int setup_cpt_sources(void);
Girish Palyacbe53192025-04-14 22:13:15 +0200257static int is_cpt_func_refresh_always(void);
Girish Palya0ac1eb32025-04-16 20:18:33 +0200258static void cpt_sources_clear(void);
Girish Palyacbe53192025-04-14 22:13:15 +0200259static void cpt_compl_refresh(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100260static int ins_compl_key2dir(int c);
261static int ins_compl_pum_key(int c);
262static int ins_compl_key2count(int c);
263static void show_pum(int prev_w_wrow, int prev_w_leftcol);
264static unsigned quote_meta(char_u *dest, char_u *str, int len);
glepnir76bdb822025-02-08 19:04:51 +0100265static int ins_compl_has_multiple(void);
266static void ins_compl_expand_multiple(char_u *str);
glepnirf31cfa22025-03-06 21:59:13 +0100267static void ins_compl_longest_insert(char_u *prefix);
Girish Palya8cd42a52025-06-05 21:04:29 +0200268static void ins_compl_make_linear(void);
269static int ins_compl_make_cyclic(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100270
271#ifdef FEAT_SPELL
272static void spell_back_to_badword(void);
273static int spell_bad_len = 0; // length of located bad word
274#endif
275
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100276/*
277 * CTRL-X pressed in Insert mode.
278 */
279 void
280ins_ctrl_x(void)
281{
zeertzjqdca29d92021-08-31 19:12:51 +0200282 if (!ctrl_x_mode_cmdline())
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100283 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000284 // if the next ^X<> won't ADD nothing, then reset compl_cont_status
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100285 if (compl_cont_status & CONT_N_ADDS)
286 compl_cont_status |= CONT_INTRPT;
287 else
288 compl_cont_status = 0;
289 // We're not sure which CTRL-X mode it will be yet
290 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
291 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
292 edit_submode_pre = NULL;
293 showmode();
294 }
zeertzjqdca29d92021-08-31 19:12:51 +0200295 else
296 // CTRL-X in CTRL-X CTRL-V mode behaves differently to make CTRL-X
297 // CTRL-V look like CTRL-N
298 ctrl_x_mode = CTRL_X_CMDLINE_CTRL_X;
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +0100299
LemonBoy2bf52dd2022-04-09 18:17:34 +0100300 may_trigger_modechanged();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100301}
302
303/*
304 * Functions to check the current CTRL-X mode.
305 */
Bram Moolenaarebfec1c2023-01-22 21:14:53 +0000306int ctrl_x_mode_none(void)
307 { return ctrl_x_mode == 0; }
308int ctrl_x_mode_normal(void)
309 { return ctrl_x_mode == CTRL_X_NORMAL; }
310int ctrl_x_mode_scroll(void)
311 { return ctrl_x_mode == CTRL_X_SCROLL; }
312int ctrl_x_mode_whole_line(void)
313 { return ctrl_x_mode == CTRL_X_WHOLE_LINE; }
314int ctrl_x_mode_files(void)
315 { return ctrl_x_mode == CTRL_X_FILES; }
316int ctrl_x_mode_tags(void)
317 { return ctrl_x_mode == CTRL_X_TAGS; }
318int ctrl_x_mode_path_patterns(void)
319 { return ctrl_x_mode == CTRL_X_PATH_PATTERNS; }
320int ctrl_x_mode_path_defines(void)
321 { return ctrl_x_mode == CTRL_X_PATH_DEFINES; }
322int ctrl_x_mode_dictionary(void)
323 { return ctrl_x_mode == CTRL_X_DICTIONARY; }
324int ctrl_x_mode_thesaurus(void)
325 { return ctrl_x_mode == CTRL_X_THESAURUS; }
326int ctrl_x_mode_cmdline(void)
327 { return ctrl_x_mode == CTRL_X_CMDLINE
zeertzjqdca29d92021-08-31 19:12:51 +0200328 || ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X; }
Bram Moolenaarebfec1c2023-01-22 21:14:53 +0000329int ctrl_x_mode_function(void)
330 { return ctrl_x_mode == CTRL_X_FUNCTION; }
331int ctrl_x_mode_omni(void)
332 { return ctrl_x_mode == CTRL_X_OMNI; }
333int ctrl_x_mode_spell(void)
334 { return ctrl_x_mode == CTRL_X_SPELL; }
335static int ctrl_x_mode_eval(void)
336 { return ctrl_x_mode == CTRL_X_EVAL; }
337int ctrl_x_mode_line_or_eval(void)
338 { return ctrl_x_mode == CTRL_X_WHOLE_LINE || ctrl_x_mode == CTRL_X_EVAL; }
glepnir05460682025-05-26 18:23:27 +0200339int ctrl_x_mode_register(void)
340 { return ctrl_x_mode == CTRL_X_REGISTER; }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100341
342/*
343 * Whether other than default completion has been selected.
344 */
345 int
346ctrl_x_mode_not_default(void)
347{
348 return ctrl_x_mode != CTRL_X_NORMAL;
349}
350
351/*
zeertzjqdca29d92021-08-31 19:12:51 +0200352 * Whether CTRL-X was typed without a following character,
353 * not including when in CTRL-X CTRL-V mode.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100354 */
355 int
356ctrl_x_mode_not_defined_yet(void)
357{
358 return ctrl_x_mode == CTRL_X_NOT_DEFINED_YET;
359}
360
361/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000362 * Return TRUE if currently in "normal" or "adding" insert completion matches
363 * state
364 */
365 int
366compl_status_adding(void)
367{
368 return compl_cont_status & CONT_ADDING;
369}
370
371/*
372 * Return TRUE if the completion pattern includes start of line, just for
373 * word-wise expansion.
374 */
375 int
376compl_status_sol(void)
377{
378 return compl_cont_status & CONT_SOL;
379}
380
381/*
382 * Return TRUE if ^X^P/^X^N will do a local completion (i.e. use complete=.)
383 */
384 int
385compl_status_local(void)
386{
387 return compl_cont_status & CONT_LOCAL;
388}
389
390/*
391 * Clear the completion status flags
392 */
393 void
394compl_status_clear(void)
395{
396 compl_cont_status = 0;
397}
398
399/*
400 * Return TRUE if completion is using the forward direction matches
401 */
402 static int
403compl_dir_forward(void)
404{
405 return compl_direction == FORWARD;
406}
407
408/*
409 * Return TRUE if currently showing forward completion matches
410 */
411 static int
412compl_shows_dir_forward(void)
413{
414 return compl_shows_dir == FORWARD;
415}
416
417/*
418 * Return TRUE if currently showing backward completion matches
419 */
420 static int
421compl_shows_dir_backward(void)
422{
423 return compl_shows_dir == BACKWARD;
424}
425
426/*
427 * Return TRUE if the 'dictionary' or 'thesaurus' option can be used.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100428 */
429 int
430has_compl_option(int dict_opt)
431{
432 if (dict_opt ? (*curbuf->b_p_dict == NUL && *p_dict == NUL
Bram Moolenaare2c453d2019-08-21 14:37:09 +0200433#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100434 && !curwin->w_p_spell
Bram Moolenaare2c453d2019-08-21 14:37:09 +0200435#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100436 )
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +0100437 : (*curbuf->b_p_tsr == NUL && *p_tsr == NUL
438#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +0100439 && *curbuf->b_p_tsrfu == NUL && *p_tsrfu == NUL
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +0100440#endif
441 ))
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100442 {
443 ctrl_x_mode = CTRL_X_NORMAL;
444 edit_submode = NULL;
445 msg_attr(dict_opt ? _("'dictionary' option is empty")
446 : _("'thesaurus' option is empty"),
447 HL_ATTR(HLF_E));
Bram Moolenaar28ee8922020-10-28 20:20:00 +0100448 if (emsg_silent == 0 && !in_assert_fails)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100449 {
450 vim_beep(BO_COMPL);
451 setcursor();
452 out_flush();
453#ifdef FEAT_EVAL
454 if (!get_vim_var_nr(VV_TESTING))
455#endif
Bram Moolenaareda1da02019-11-17 17:06:33 +0100456 ui_delay(2004L, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100457 }
458 return FALSE;
459 }
460 return TRUE;
461}
462
463/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000464 * Is the character "c" a valid key to go to or keep us in CTRL-X mode?
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100465 * This depends on the current mode.
466 */
467 int
468vim_is_ctrl_x_key(int c)
469{
470 // Always allow ^R - let its results then be checked
glepnir05460682025-05-26 18:23:27 +0200471 if (c == Ctrl_R && ctrl_x_mode != CTRL_X_REGISTER)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100472 return TRUE;
473
474 // Accept <PageUp> and <PageDown> if the popup menu is visible.
475 if (ins_compl_pum_key(c))
476 return TRUE;
477
478 switch (ctrl_x_mode)
479 {
480 case 0: // Not in any CTRL-X mode
481 return (c == Ctrl_N || c == Ctrl_P || c == Ctrl_X);
482 case CTRL_X_NOT_DEFINED_YET:
zeertzjqdca29d92021-08-31 19:12:51 +0200483 case CTRL_X_CMDLINE_CTRL_X:
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100484 return ( c == Ctrl_X || c == Ctrl_Y || c == Ctrl_E
485 || c == Ctrl_L || c == Ctrl_F || c == Ctrl_RSB
486 || c == Ctrl_I || c == Ctrl_D || c == Ctrl_P
487 || c == Ctrl_N || c == Ctrl_T || c == Ctrl_V
488 || c == Ctrl_Q || c == Ctrl_U || c == Ctrl_O
zeertzjqdca29d92021-08-31 19:12:51 +0200489 || c == Ctrl_S || c == Ctrl_K || c == 's'
glepnir05460682025-05-26 18:23:27 +0200490 || c == Ctrl_Z || c == Ctrl_R);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100491 case CTRL_X_SCROLL:
492 return (c == Ctrl_Y || c == Ctrl_E);
493 case CTRL_X_WHOLE_LINE:
494 return (c == Ctrl_L || c == Ctrl_P || c == Ctrl_N);
495 case CTRL_X_FILES:
496 return (c == Ctrl_F || c == Ctrl_P || c == Ctrl_N);
497 case CTRL_X_DICTIONARY:
498 return (c == Ctrl_K || c == Ctrl_P || c == Ctrl_N);
499 case CTRL_X_THESAURUS:
500 return (c == Ctrl_T || c == Ctrl_P || c == Ctrl_N);
501 case CTRL_X_TAGS:
502 return (c == Ctrl_RSB || c == Ctrl_P || c == Ctrl_N);
503#ifdef FEAT_FIND_ID
504 case CTRL_X_PATH_PATTERNS:
505 return (c == Ctrl_P || c == Ctrl_N);
506 case CTRL_X_PATH_DEFINES:
507 return (c == Ctrl_D || c == Ctrl_P || c == Ctrl_N);
508#endif
509 case CTRL_X_CMDLINE:
510 return (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_P || c == Ctrl_N
511 || c == Ctrl_X);
512#ifdef FEAT_COMPL_FUNC
513 case CTRL_X_FUNCTION:
514 return (c == Ctrl_U || c == Ctrl_P || c == Ctrl_N);
515 case CTRL_X_OMNI:
516 return (c == Ctrl_O || c == Ctrl_P || c == Ctrl_N);
517#endif
518 case CTRL_X_SPELL:
519 return (c == Ctrl_S || c == Ctrl_P || c == Ctrl_N);
520 case CTRL_X_EVAL:
521 return (c == Ctrl_P || c == Ctrl_N);
glepnir05460682025-05-26 18:23:27 +0200522 case CTRL_X_REGISTER:
523 return (c == Ctrl_R || c == Ctrl_P || c == Ctrl_N);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100524 }
525 internal_error("vim_is_ctrl_x_key()");
526 return FALSE;
527}
528
529/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000530 * Return TRUE if "match" is the original text when the completion began.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000531 */
532 static int
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000533match_at_original_text(compl_T *match)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000534{
535 return match->cp_flags & CP_ORIGINAL_TEXT;
536}
537
538/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000539 * Returns TRUE if "match" is the first match in the completion list.
540 */
541 static int
542is_first_match(compl_T *match)
543{
544 return match == compl_first_match;
545}
546
547/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100548 * Return TRUE when character "c" is part of the item currently being
549 * completed. Used to decide whether to abandon complete mode when the menu
550 * is visible.
551 */
552 int
553ins_compl_accept_char(int c)
554{
555 if (ctrl_x_mode & CTRL_X_WANT_IDENT)
556 // When expanding an identifier only accept identifier chars.
557 return vim_isIDc(c);
558
559 switch (ctrl_x_mode)
560 {
561 case CTRL_X_FILES:
562 // When expanding file name only accept file name chars. But not
563 // path separators, so that "proto/<Tab>" expands files in
564 // "proto", not "proto/" as a whole
565 return vim_isfilec(c) && !vim_ispathsep(c);
566
567 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +0200568 case CTRL_X_CMDLINE_CTRL_X:
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100569 case CTRL_X_OMNI:
570 // Command line and Omni completion can work with just about any
571 // printable character, but do stop at white space.
572 return vim_isprintc(c) && !VIM_ISWHITE(c);
573
574 case CTRL_X_WHOLE_LINE:
575 // For while line completion a space can be part of the line.
576 return vim_isprintc(c);
577 }
578 return vim_iswordc(c);
579}
580
581/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000582 * Get the completed text by inferring the case of the originally typed text.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100583 * If the result is in allocated memory "tofree" is set to it.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000584 */
585 static char_u *
586ins_compl_infercase_gettext(
glepnir19e1dd62025-05-08 22:50:38 +0200587 char_u *str,
588 int char_len,
589 int compl_char_len,
590 int min_len,
591 char_u **tofree)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000592{
593 int *wca; // Wide character array.
594 char_u *p;
595 int i, c;
596 int has_lower = FALSE;
597 int was_letter = FALSE;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100598 garray_T gap;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000599
600 IObuff[0] = NUL;
601
602 // Allocate wide character array for the completion and fill it.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100603 wca = ALLOC_MULT(int, char_len);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000604 if (wca == NULL)
605 return IObuff;
606
607 p = str;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100608 for (i = 0; i < char_len; ++i)
glepnir6e199932024-12-14 21:13:27 +0100609 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000610 if (has_mbyte)
611 wca[i] = mb_ptr2char_adv(&p);
612 else
613 wca[i] = *(p++);
glepnir6e199932024-12-14 21:13:27 +0100614 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000615
616 // Rule 1: Were any chars converted to lower?
John Marriott5e6ea922024-11-23 14:01:57 +0100617 p = compl_orig_text.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000618 for (i = 0; i < min_len; ++i)
619 {
glepnir6e199932024-12-14 21:13:27 +0100620 c = has_mbyte ? mb_ptr2char_adv(&p) : *(p++);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000621 if (MB_ISLOWER(c))
622 {
623 has_lower = TRUE;
624 if (MB_ISUPPER(wca[i]))
625 {
626 // Rule 1 is satisfied.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100627 for (i = compl_char_len; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000628 wca[i] = MB_TOLOWER(wca[i]);
629 break;
630 }
631 }
632 }
633
634 // Rule 2: No lower case, 2nd consecutive letter converted to
635 // upper case.
636 if (!has_lower)
637 {
John Marriott5e6ea922024-11-23 14:01:57 +0100638 p = compl_orig_text.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000639 for (i = 0; i < min_len; ++i)
640 {
glepnir6e199932024-12-14 21:13:27 +0100641 c = has_mbyte ? mb_ptr2char_adv(&p) : *(p++);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000642 if (was_letter && MB_ISUPPER(c) && MB_ISLOWER(wca[i]))
643 {
644 // Rule 2 is satisfied.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100645 for (i = compl_char_len; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000646 wca[i] = MB_TOUPPER(wca[i]);
647 break;
648 }
649 was_letter = MB_ISLOWER(c) || MB_ISUPPER(c);
650 }
651 }
652
653 // Copy the original case of the part we typed.
John Marriott5e6ea922024-11-23 14:01:57 +0100654 p = compl_orig_text.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000655 for (i = 0; i < min_len; ++i)
656 {
glepnir6e199932024-12-14 21:13:27 +0100657 c = has_mbyte ? mb_ptr2char_adv(&p) : *(p++);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000658 if (MB_ISLOWER(c))
659 wca[i] = MB_TOLOWER(wca[i]);
660 else if (MB_ISUPPER(c))
661 wca[i] = MB_TOUPPER(wca[i]);
662 }
663
664 // Generate encoding specific output from wide character array.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000665 p = IObuff;
666 i = 0;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100667 ga_init2(&gap, 1, 500);
668 while (i < char_len)
669 {
670 if (gap.ga_data != NULL)
671 {
672 if (ga_grow(&gap, 10) == FAIL)
673 {
674 ga_clear(&gap);
675 return (char_u *)"[failed]";
676 }
677 p = (char_u *)gap.ga_data + gap.ga_len;
678 if (has_mbyte)
679 gap.ga_len += (*mb_char2bytes)(wca[i++], p);
680 else
681 {
682 *p = wca[i++];
683 ++gap.ga_len;
684 }
685 }
686 else if ((p - IObuff) + 6 >= IOSIZE)
687 {
688 // Multi-byte characters can occupy up to five bytes more than
689 // ASCII characters, and we also need one byte for NUL, so when
690 // getting to six bytes from the edge of IObuff switch to using a
691 // growarray. Add the character in the next round.
692 if (ga_grow(&gap, IOSIZE) == FAIL)
zeertzjq70e566b2024-03-21 07:11:58 +0100693 {
694 vim_free(wca);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100695 return (char_u *)"[failed]";
zeertzjq70e566b2024-03-21 07:11:58 +0100696 }
Bram Moolenaarb9e71732022-07-23 06:53:08 +0100697 *p = NUL;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100698 STRCPY(gap.ga_data, IObuff);
John Marriott5e6ea922024-11-23 14:01:57 +0100699 gap.ga_len = (int)(p - IObuff);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100700 }
701 else if (has_mbyte)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000702 p += (*mb_char2bytes)(wca[i++], p);
703 else
704 *(p++) = wca[i++];
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100705 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000706 vim_free(wca);
707
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100708 if (gap.ga_data != NULL)
709 {
710 *tofree = gap.ga_data;
711 return gap.ga_data;
712 }
713
714 *p = NUL;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000715 return IObuff;
716}
717
718/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100719 * This is like ins_compl_add(), but if 'ic' and 'inf' are set, then the
720 * case of the originally typed text is used, and the case of the completed
721 * text is inferred, ie this tries to work out what case you probably wanted
722 * the rest of the word to be in -- webb
723 */
724 int
725ins_compl_add_infercase(
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200726 char_u *str_arg,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100727 int len,
728 int icase,
729 char_u *fname,
730 int dir,
glepnirf31cfa22025-03-06 21:59:13 +0100731 int cont_s_ipos, // next ^X<> will set initial_pos
732 int score)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100733{
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200734 char_u *str = str_arg;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100735 char_u *p;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100736 int char_len; // count multi-byte characters
737 int compl_char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100738 int min_len;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200739 int flags = 0;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100740 int res;
741 char_u *tofree = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100742
743 if (p_ic && curbuf->b_p_inf && len > 0)
744 {
745 // Infer case of completed part.
746
747 // Find actual length of completion.
748 if (has_mbyte)
749 {
750 p = str;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100751 char_len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100752 while (*p != NUL)
753 {
754 MB_PTR_ADV(p);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100755 ++char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100756 }
757 }
758 else
glepnir6e199932024-12-14 21:13:27 +0100759 {
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100760 char_len = len;
glepnir6e199932024-12-14 21:13:27 +0100761 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100762
763 // Find actual length of original text.
764 if (has_mbyte)
765 {
John Marriott5e6ea922024-11-23 14:01:57 +0100766 p = compl_orig_text.string;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100767 compl_char_len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100768 while (*p != NUL)
769 {
770 MB_PTR_ADV(p);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100771 ++compl_char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100772 }
773 }
774 else
glepnir6e199932024-12-14 21:13:27 +0100775 {
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100776 compl_char_len = compl_length;
glepnir6e199932024-12-14 21:13:27 +0100777 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100778
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100779 // "char_len" may be smaller than "compl_char_len" when using
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100780 // thesaurus, only use the minimum when comparing.
glepnir6e199932024-12-14 21:13:27 +0100781 min_len = MIN(char_len, compl_char_len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100782
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100783 str = ins_compl_infercase_gettext(str, char_len,
784 compl_char_len, min_len, &tofree);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100785 }
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200786 if (cont_s_ipos)
787 flags |= CP_CONT_S_IPOS;
788 if (icase)
789 flags |= CP_ICASE;
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200790
glepnirf31cfa22025-03-06 21:59:13 +0100791 res = ins_compl_add(str, len, fname, NULL, NULL, dir, flags, FALSE, NULL, score);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100792 vim_free(tofree);
793 return res;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100794}
795
796/*
glepnirf31cfa22025-03-06 21:59:13 +0100797 * Check if ctrl_x_mode has been configured in 'completefuzzycollect'
798 */
799 static int
800cfc_has_mode(void)
801{
glepnir58760162025-03-13 21:39:51 +0100802 if (ctrl_x_mode_normal() || ctrl_x_mode_dictionary())
803 return (cfc_flags & CFC_KEYWORD) != 0;
804 else if (ctrl_x_mode_files())
805 return (cfc_flags & CFC_FILES) != 0;
806 else if (ctrl_x_mode_whole_line())
807 return (cfc_flags & CFC_WHOLELINE) != 0;
808 else
809 return FALSE;
glepnirf31cfa22025-03-06 21:59:13 +0100810}
811
812/*
Girish Palyab1565882025-04-15 20:16:00 +0200813 * Returns TRUE if matches should be sorted based on proximity to the cursor.
814 */
815 static int
816is_nearest_active(void)
817{
glepnirc3fbaa02025-05-08 23:05:10 +0200818 return (get_cot_flags() & (COT_NEAREST | COT_FUZZY)) == COT_NEAREST;
Girish Palyab1565882025-04-15 20:16:00 +0200819}
820
821/*
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000822 * Add a match to the list of matches. The arguments are:
823 * str - text of the match to add
824 * len - length of "str". If -1, then the length of "str" is
825 * computed.
826 * fname - file name to associate with this match.
827 * cptext - list of strings to use with this match (for abbr, menu, info
828 * and kind)
829 * user_data - user supplied data (any vim type) for this match
830 * cdir - match direction. If 0, use "compl_direction".
831 * flags_arg - match flags (cp_flags)
832 * adup - accept this match even if it is already present.
glepnir80b66202024-11-27 21:53:53 +0100833 * *user_hl - list of extra highlight attributes for abbr kind.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000834 * If "cdir" is FORWARD, then the match is added after the current match.
835 * Otherwise, it is added before the current match.
836 *
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100837 * If the given string is already in the list of completions, then return
838 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
839 * maybe because alloc() returns NULL, then FAIL is returned.
840 */
841 static int
842ins_compl_add(
843 char_u *str,
844 int len,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100845 char_u *fname,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100846 char_u **cptext, // extra text for popup menu or NULL
847 typval_T *user_data UNUSED, // "user_data" entry or NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100848 int cdir,
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200849 int flags_arg,
glepnir508e7852024-07-25 21:39:08 +0200850 int adup, // accept duplicate match
glepnirf31cfa22025-03-06 21:59:13 +0100851 int *user_hl, // user abbr/kind hlattr
852 int score)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100853{
glepnirf31cfa22025-03-06 21:59:13 +0100854 compl_T *match, *current, *prev;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100855 int dir = (cdir == 0 ? compl_direction : cdir);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200856 int flags = flags_arg;
glepnirf31cfa22025-03-06 21:59:13 +0100857 int inserted = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100858
Bram Moolenaarceb06192021-04-04 15:05:22 +0200859 if (flags & CP_FAST)
860 fast_breakcheck();
861 else
862 ui_breakcheck();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100863 if (got_int)
864 return FAIL;
865 if (len < 0)
866 len = (int)STRLEN(str);
867
868 // If the same match is already present, don't add it.
869 if (compl_first_match != NULL && !adup)
870 {
871 match = compl_first_match;
872 do
873 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000874 if (!match_at_original_text(match)
John Marriott5e6ea922024-11-23 14:01:57 +0100875 && STRNCMP(match->cp_str.string, str, len) == 0
876 && ((int)match->cp_str.length <= len
877 || match->cp_str.string[len] == NUL))
Girish Palyab1565882025-04-15 20:16:00 +0200878 {
879 if (is_nearest_active() && score > 0 && score < match->cp_score)
Girish Palyab1565882025-04-15 20:16:00 +0200880 match->cp_score = score;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100881 return NOTDONE;
Girish Palyab1565882025-04-15 20:16:00 +0200882 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100883 match = match->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000884 } while (match != NULL && !is_first_match(match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100885 }
886
887 // Remove any popup menu before changing the list of matches.
888 ins_compl_del_pum();
889
890 // Allocate a new match structure.
891 // Copy the values to the new match structure.
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200892 match = ALLOC_CLEAR_ONE(compl_T);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100893 if (match == NULL)
894 return FAIL;
glepnir40891ba2025-02-10 22:18:00 +0100895 match->cp_number = flags & CP_ORIGINAL_TEXT ? 0 : -1;
John Marriott5e6ea922024-11-23 14:01:57 +0100896 if ((match->cp_str.string = vim_strnsave(str, len)) == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100897 {
898 vim_free(match);
899 return FAIL;
900 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100901
John Marriott5e6ea922024-11-23 14:01:57 +0100902 match->cp_str.length = len;
903
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100904 // match-fname is:
905 // - compl_curr_match->cp_fname if it is a string equal to fname.
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200906 // - a copy of fname, CP_FREE_FNAME is set to free later THE allocated mem.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100907 // - NULL otherwise. --Acevedo
908 if (fname != NULL
909 && compl_curr_match != NULL
910 && compl_curr_match->cp_fname != NULL
911 && STRCMP(fname, compl_curr_match->cp_fname) == 0)
912 match->cp_fname = compl_curr_match->cp_fname;
913 else if (fname != NULL)
914 {
915 match->cp_fname = vim_strsave(fname);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200916 flags |= CP_FREE_FNAME;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100917 }
918 else
919 match->cp_fname = NULL;
920 match->cp_flags = flags;
glepnir80b66202024-11-27 21:53:53 +0100921 match->cp_user_abbr_hlattr = user_hl ? user_hl[0] : -1;
922 match->cp_user_kind_hlattr = user_hl ? user_hl[1] : -1;
glepnirf31cfa22025-03-06 21:59:13 +0100923 match->cp_score = score;
Girish Palya0ac1eb32025-04-16 20:18:33 +0200924 match->cp_cpt_source_idx = cpt_sources_index;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100925
926 if (cptext != NULL)
927 {
glepnir19e1dd62025-05-08 22:50:38 +0200928 for (int i = 0; i < CPT_COUNT; ++i)
glepnir6e199932024-12-14 21:13:27 +0100929 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100930 if (cptext[i] != NULL && *cptext[i] != NUL)
931 match->cp_text[i] = vim_strsave(cptext[i]);
glepnir6e199932024-12-14 21:13:27 +0100932 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100933 }
Bram Moolenaarab782c52020-01-04 19:00:11 +0100934#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +0100935 if (user_data != NULL)
936 match->cp_user_data = *user_data;
Bram Moolenaarab782c52020-01-04 19:00:11 +0100937#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100938
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000939 // Link the new match structure after (FORWARD) or before (BACKWARD) the
940 // current match in the list of matches .
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100941 if (compl_first_match == NULL)
942 match->cp_next = match->cp_prev = NULL;
glepnirf31cfa22025-03-06 21:59:13 +0100943 else if (cfc_has_mode() && score > 0 && compl_get_longest)
944 {
945 current = compl_first_match->cp_next;
946 prev = compl_first_match;
947 inserted = FALSE;
948 // The direction is ignored when using longest and
949 // completefuzzycollect, because matches are inserted
950 // and sorted by score.
951 while (current != NULL && current != compl_first_match)
952 {
953 if (current->cp_score < score)
954 {
Hirohito Higashi355db992025-04-28 18:07:02 +0200955 match->cp_next = current;
956 match->cp_prev = current->cp_prev;
957 if (current->cp_prev)
glepnirf31cfa22025-03-06 21:59:13 +0100958 current->cp_prev->cp_next = match;
Hirohito Higashi355db992025-04-28 18:07:02 +0200959 current->cp_prev = match;
960 inserted = TRUE;
961 break;
glepnirf31cfa22025-03-06 21:59:13 +0100962 }
963 prev = current;
964 current = current->cp_next;
965 }
966 if (!inserted)
967 {
968 prev->cp_next = match;
969 match->cp_prev = prev;
970 match->cp_next = compl_first_match;
971 compl_first_match->cp_prev = match;
972 }
973 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100974 else if (dir == FORWARD)
975 {
976 match->cp_next = compl_curr_match->cp_next;
977 match->cp_prev = compl_curr_match;
978 }
979 else // BACKWARD
980 {
981 match->cp_next = compl_curr_match;
982 match->cp_prev = compl_curr_match->cp_prev;
983 }
984 if (match->cp_next)
985 match->cp_next->cp_prev = match;
986 if (match->cp_prev)
987 match->cp_prev->cp_next = match;
988 else // if there's nothing before, it is the first match
989 compl_first_match = match;
990 compl_curr_match = match;
991
992 // Find the longest common string if still doing that.
glepnirf31cfa22025-03-06 21:59:13 +0100993 if (compl_get_longest && (flags & CP_ORIGINAL_TEXT) == 0 && !cfc_has_mode())
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100994 ins_compl_longest_match(match);
995
996 return OK;
997}
998
999/*
1000 * Return TRUE if "str[len]" matches with match->cp_str, considering
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001001 * match->cp_flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001002 */
1003 static int
1004ins_compl_equal(compl_T *match, char_u *str, int len)
1005{
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001006 if (match->cp_flags & CP_EQUAL)
Bram Moolenaar73655cf2019-04-06 13:45:55 +02001007 return TRUE;
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001008 if (match->cp_flags & CP_ICASE)
John Marriott5e6ea922024-11-23 14:01:57 +01001009 return STRNICMP(match->cp_str.string, str, (size_t)len) == 0;
1010 return STRNCMP(match->cp_str.string, str, (size_t)len) == 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001011}
1012
1013/*
glepnir6a38aff2024-12-16 21:56:16 +01001014 * when len is -1 mean use whole length of p otherwise part of p
1015 */
1016 static void
1017ins_compl_insert_bytes(char_u *p, int len)
1018{
1019 if (len == -1)
1020 len = (int)STRLEN(p);
1021 ins_bytes_len(p, len);
zeertzjqf25d8f92024-12-18 21:12:25 +01001022 compl_ins_end_col = curwin->w_cursor.col;
glepnir6a38aff2024-12-16 21:56:16 +01001023}
1024
1025/*
zeertzjqd32bf0a2024-12-17 20:55:13 +01001026 * Checks if the column is within the currently inserted completion text
1027 * column range. If it is, it returns a special highlight attribute.
glepnir76bdb822025-02-08 19:04:51 +01001028 * -1 means normal item.
glepnir6a38aff2024-12-16 21:56:16 +01001029 */
1030 int
glepnir76bdb822025-02-08 19:04:51 +01001031ins_compl_col_range_attr(linenr_T lnum, int col)
glepnir6a38aff2024-12-16 21:56:16 +01001032{
glepnir76bdb822025-02-08 19:04:51 +01001033 int start_col;
1034 int attr;
1035
1036 if ((get_cot_flags() & COT_FUZZY)
1037 || (attr = syn_name2attr((char_u *)"ComplMatchIns")) == 0)
glepnire8908872025-01-08 18:30:45 +01001038 return -1;
1039
glepnir76bdb822025-02-08 19:04:51 +01001040 start_col = compl_col + (int)ins_compl_leader_len();
1041 if (!ins_compl_has_multiple())
1042 return (col >= start_col && col < compl_ins_end_col) ? attr : -1;
1043
1044 // Multiple lines
1045 if ((lnum == compl_lnum && col >= start_col && col < MAXCOL) ||
1046 (lnum > compl_lnum && lnum < curwin->w_cursor.lnum) ||
1047 (lnum == curwin->w_cursor.lnum && col <= compl_ins_end_col))
1048 return attr;
glepnir6a38aff2024-12-16 21:56:16 +01001049
1050 return -1;
1051}
1052
1053/*
glepnir76bdb822025-02-08 19:04:51 +01001054 * Returns TRUE if the current completion string contains newline characters,
1055 * indicating it's a multi-line completion.
1056 */
1057 static int
1058ins_compl_has_multiple(void)
1059{
1060 return vim_strchr(compl_shown_match->cp_str.string, '\n') != NULL;
1061}
1062
1063/*
1064 * Returns TRUE if the given line number falls within the range of a multi-line
1065 * completion, i.e. between the starting line (compl_lnum) and current cursor
1066 * line. Always returns FALSE for single-line completions.
1067 */
1068 int
1069ins_compl_lnum_in_range(linenr_T lnum)
1070{
1071 if (!ins_compl_has_multiple())
1072 return FALSE;
1073 return lnum >= compl_lnum && lnum <= curwin->w_cursor.lnum;
1074}
1075
1076/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001077 * Reduce the longest common string for match "match".
1078 */
1079 static void
1080ins_compl_longest_match(compl_T *match)
1081{
1082 char_u *p, *s;
1083 int c1, c2;
1084 int had_match;
1085
John Marriott5e6ea922024-11-23 14:01:57 +01001086 if (compl_leader.string == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001087 {
1088 // First match, use it as a whole.
John Marriott5e6ea922024-11-23 14:01:57 +01001089 compl_leader.string = vim_strnsave(match->cp_str.string, match->cp_str.length);
1090 if (compl_leader.string == NULL)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001091 return;
1092
John Marriott5e6ea922024-11-23 14:01:57 +01001093 compl_leader.length = match->cp_str.length;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001094 had_match = (curwin->w_cursor.col > compl_col);
glepnirf31cfa22025-03-06 21:59:13 +01001095 ins_compl_longest_insert(compl_leader.string);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001096
1097 // When the match isn't there (to avoid matching itself) remove it
1098 // again after redrawing.
1099 if (!had_match)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001100 ins_compl_delete();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001101 compl_used_match = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001102
1103 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001104 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001105
1106 // Reduce the text if this match differs from compl_leader.
John Marriott5e6ea922024-11-23 14:01:57 +01001107 p = compl_leader.string;
1108 s = match->cp_str.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001109 while (*p != NUL)
1110 {
1111 if (has_mbyte)
1112 {
1113 c1 = mb_ptr2char(p);
1114 c2 = mb_ptr2char(s);
1115 }
1116 else
1117 {
1118 c1 = *p;
1119 c2 = *s;
1120 }
1121 if ((match->cp_flags & CP_ICASE)
1122 ? (MB_TOLOWER(c1) != MB_TOLOWER(c2)) : (c1 != c2))
1123 break;
1124 if (has_mbyte)
1125 {
1126 MB_PTR_ADV(p);
1127 MB_PTR_ADV(s);
1128 }
1129 else
1130 {
1131 ++p;
1132 ++s;
1133 }
1134 }
1135
1136 if (*p != NUL)
1137 {
1138 // Leader was shortened, need to change the inserted text.
1139 *p = NUL;
John Marriott5e6ea922024-11-23 14:01:57 +01001140 compl_leader.length = (size_t)(p - compl_leader.string);
1141
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001142 had_match = (curwin->w_cursor.col > compl_col);
glepnirf31cfa22025-03-06 21:59:13 +01001143 ins_compl_longest_insert(compl_leader.string);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001144
1145 // When the match isn't there (to avoid matching itself) remove it
1146 // again after redrawing.
1147 if (!had_match)
1148 ins_compl_delete();
1149 }
1150
1151 compl_used_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001152}
1153
1154/*
1155 * Add an array of matches to the list of matches.
1156 * Frees matches[].
1157 */
1158 static void
1159ins_compl_add_matches(
1160 int num_matches,
1161 char_u **matches,
1162 int icase)
1163{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001164 int add_r = OK;
1165 int dir = compl_direction;
1166
glepnir19e1dd62025-05-08 22:50:38 +02001167 for (int i = 0; i < num_matches && add_r != FAIL; i++)
glepnir6e199932024-12-14 21:13:27 +01001168 {
1169 add_r = ins_compl_add(matches[i], -1, NULL, NULL, NULL, dir,
glepnirf31cfa22025-03-06 21:59:13 +01001170 CP_FAST | (icase ? CP_ICASE : 0), FALSE, NULL, 0);
glepnir6e199932024-12-14 21:13:27 +01001171 if (add_r == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001172 // if dir was BACKWARD then honor it just once
1173 dir = FORWARD;
glepnir6e199932024-12-14 21:13:27 +01001174 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001175 FreeWild(num_matches, matches);
1176}
1177
1178/*
1179 * Make the completion list cyclic.
1180 * Return the number of matches (excluding the original).
1181 */
1182 static int
1183ins_compl_make_cyclic(void)
1184{
1185 compl_T *match;
1186 int count = 0;
1187
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001188 if (compl_first_match == NULL)
1189 return 0;
1190
1191 // Find the end of the list.
1192 match = compl_first_match;
1193 // there's always an entry for the compl_orig_text, it doesn't count.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001194 while (match->cp_next != NULL && !is_first_match(match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001195 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001196 match = match->cp_next;
1197 ++count;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001198 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001199 match->cp_next = compl_first_match;
1200 compl_first_match->cp_prev = match;
1201
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001202 return count;
1203}
1204
1205/*
1206 * Return whether there currently is a shown match.
1207 */
1208 int
1209ins_compl_has_shown_match(void)
1210{
1211 return compl_shown_match == NULL
1212 || compl_shown_match != compl_shown_match->cp_next;
1213}
1214
1215/*
1216 * Return whether the shown match is long enough.
1217 */
1218 int
1219ins_compl_long_shown_match(void)
1220{
John Marriott5e6ea922024-11-23 14:01:57 +01001221 return (int)compl_shown_match->cp_str.length
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001222 > curwin->w_cursor.col - compl_col;
1223}
1224
1225/*
zeertzjq529b9ad2024-06-05 20:27:06 +02001226 * Get the local or global value of 'completeopt' flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001227 */
zeertzjq529b9ad2024-06-05 20:27:06 +02001228 unsigned int
1229get_cot_flags(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001230{
zeertzjq529b9ad2024-06-05 20:27:06 +02001231 return curbuf->b_cot_flags != 0 ? curbuf->b_cot_flags : cot_flags;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001232}
1233
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001234/*
1235 * Update the screen and when there is any scrolling remove the popup menu.
1236 */
1237 static void
1238ins_compl_upd_pum(void)
1239{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001240 if (compl_match_array == NULL)
1241 return;
1242
glepnir19e1dd62025-05-08 22:50:38 +02001243 int h = curwin->w_cline_height;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001244 // Update the screen later, before drawing the popup menu over it.
1245 pum_call_update_screen();
1246 if (h != curwin->w_cline_height)
1247 ins_compl_del_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001248}
1249
1250/*
1251 * Remove any popup menu.
1252 */
1253 static void
1254ins_compl_del_pum(void)
1255{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001256 if (compl_match_array == NULL)
1257 return;
1258
1259 pum_undisplay();
1260 VIM_CLEAR(compl_match_array);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001261}
1262
1263/*
1264 * Return TRUE if the popup menu should be displayed.
1265 */
1266 int
1267pum_wanted(void)
1268{
1269 // 'completeopt' must contain "menu" or "menuone"
zeertzjq529b9ad2024-06-05 20:27:06 +02001270 if ((get_cot_flags() & COT_ANY_MENU) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001271 return FALSE;
1272
1273 // The display looks bad on a B&W display.
1274 if (t_colors < 8
1275#ifdef FEAT_GUI
1276 && !gui.in_use
1277#endif
1278 )
1279 return FALSE;
1280 return TRUE;
1281}
1282
1283/*
1284 * Return TRUE if there are two or more matches to be shown in the popup menu.
1285 * One if 'completopt' contains "menuone".
1286 */
1287 static int
1288pum_enough_matches(void)
1289{
1290 compl_T *compl;
glepnir6e199932024-12-14 21:13:27 +01001291 int i = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001292
1293 // Don't display the popup menu if there are no matches or there is only
1294 // one (ignoring the original text).
1295 compl = compl_first_match;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001296 do
1297 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001298 if (compl == NULL || (!match_at_original_text(compl) && ++i == 2))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001299 break;
1300 compl = compl->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001301 } while (!is_first_match(compl));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001302
zeertzjq529b9ad2024-06-05 20:27:06 +02001303 if (get_cot_flags() & COT_MENUONE)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001304 return (i >= 1);
1305 return (i >= 2);
1306}
1307
Bram Moolenaar3075a452021-11-17 15:51:52 +00001308#if defined(FEAT_EVAL) || defined(PROTO)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001309/*
1310 * Allocate Dict for the completed item.
1311 * { word, abbr, menu, kind, info }
1312 */
1313 static dict_T *
1314ins_compl_dict_alloc(compl_T *match)
1315{
1316 dict_T *dict = dict_alloc_lock(VAR_FIXED);
1317
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001318 if (dict == NULL)
1319 return NULL;
1320
John Marriott5e6ea922024-11-23 14:01:57 +01001321 dict_add_string(dict, "word", match->cp_str.string);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001322 dict_add_string(dict, "abbr", match->cp_text[CPT_ABBR]);
1323 dict_add_string(dict, "menu", match->cp_text[CPT_MENU]);
1324 dict_add_string(dict, "kind", match->cp_text[CPT_KIND]);
1325 dict_add_string(dict, "info", match->cp_text[CPT_INFO]);
1326 if (match->cp_user_data.v_type == VAR_UNKNOWN)
1327 dict_add_string(dict, "user_data", (char_u *)"");
1328 else
1329 dict_add_tv(dict, "user_data", &match->cp_user_data);
1330
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001331 return dict;
1332}
1333
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001334/*
1335 * Trigger the CompleteChanged autocmd event. Invoked each time the Insert mode
1336 * completion menu is changed.
1337 */
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001338 static void
1339trigger_complete_changed_event(int cur)
1340{
1341 dict_T *v_event;
1342 dict_T *item;
1343 static int recursive = FALSE;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001344 save_v_event_T save_v_event;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001345
1346 if (recursive)
1347 return;
1348
glepnir40891ba2025-02-10 22:18:00 +01001349 item = cur < 0 ? dict_alloc() : ins_compl_dict_alloc(compl_curr_match);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001350 if (item == NULL)
1351 return;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001352 v_event = get_v_event(&save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001353 dict_add_dict(v_event, "completed_item", item);
1354 pum_set_event_info(v_event);
1355 dict_set_items_ro(v_event);
1356
1357 recursive = TRUE;
zeertzjqcfe45652022-05-27 17:26:55 +01001358 textlock++;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001359 apply_autocmds(EVENT_COMPLETECHANGED, NULL, NULL, FALSE, curbuf);
zeertzjqcfe45652022-05-27 17:26:55 +01001360 textlock--;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001361 recursive = FALSE;
1362
Bram Moolenaar3075a452021-11-17 15:51:52 +00001363 restore_v_event(v_event, &save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001364}
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001365#endif
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001366
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001367/*
Girish Palya8cd42a52025-06-05 21:04:29 +02001368 * Helper functions for mergesort_list().
Girish Palya19ef6b02025-05-28 20:28:21 +02001369 */
Girish Palya8cd42a52025-06-05 21:04:29 +02001370 static void*
1371cp_get_next(void *node)
Girish Palya19ef6b02025-05-28 20:28:21 +02001372{
Girish Palya8cd42a52025-06-05 21:04:29 +02001373 return ((compl_T*)node)->cp_next;
Girish Palya19ef6b02025-05-28 20:28:21 +02001374}
1375
Girish Palya8cd42a52025-06-05 21:04:29 +02001376 static void
1377cp_set_next(void *node, void *next)
glepnira218cc62024-06-03 19:32:39 +02001378{
Girish Palya8cd42a52025-06-05 21:04:29 +02001379 ((compl_T*)node)->cp_next = (compl_T*)next;
1380}
1381
1382 static void*
1383cp_get_prev(void* node)
1384{
1385 return ((compl_T*)node)->cp_prev;
1386}
1387
1388 static void
1389cp_set_prev(void* node, void* prev)
1390{
1391 ((compl_T*)node)->cp_prev = (compl_T*)prev;
1392}
1393
1394 static int
1395cp_compare_fuzzy(const void* a, const void* b)
1396{
1397 int score_a = ((compl_T*)a)->cp_score;
1398 int score_b = ((compl_T*)b)->cp_score;
1399 return (score_b > score_a) ? 1 : (score_b < score_a) ? -1 : 0;
glepnira218cc62024-06-03 19:32:39 +02001400}
1401
Girish Palyab8ee1cf2025-06-08 16:20:06 +02001402 static int
1403cp_compare_nearest(const void* a, const void* b)
1404{
1405 int score_a = ((compl_T*)a)->cp_score;
1406 int score_b = ((compl_T*)b)->cp_score;
1407 if (score_a < 0 || score_b < 0)
1408 return 0;
1409 return (score_a > score_b) ? 1 : (score_a < score_b) ? -1 : 0;
1410}
1411
1412/*
1413 * Set fuzzy score.
1414 */
1415 static void
1416set_fuzzy_score(void)
1417{
Girish Palyab8ee1cf2025-06-08 16:20:06 +02001418 if (compl_leader.string != NULL && compl_leader.length > 0)
1419 {
zeertzjqde1c7ac2025-06-09 20:34:57 +02001420 compl_T *compl = compl_first_match;
1421
Girish Palyab8ee1cf2025-06-08 16:20:06 +02001422 do
1423 {
1424 compl->cp_score = fuzzy_match_str(compl->cp_str.string,
1425 compl_leader.string);
1426 compl = compl->cp_next;
1427 } while (compl != NULL && !is_first_match(compl));
1428 }
1429}
1430
1431/*
1432 * Sort completion matches, excluding the node that contains the leader.
1433 */
1434 static void
1435sort_compl_match_list(int (*compare)(const void *, const void *))
1436{
1437 compl_T *compl = compl_first_match->cp_prev;
1438
1439 if (!compl_first_match || is_first_match(compl_first_match->cp_next))
1440 return;
1441
1442 ins_compl_make_linear();
1443 if (compl_shows_dir_forward())
1444 {
1445 compl_first_match->cp_next->cp_prev = NULL;
1446 compl_first_match->cp_next = mergesort_list(compl_first_match->cp_next,
1447 cp_get_next, cp_set_next, cp_get_prev, cp_set_prev, compare);
1448 compl_first_match->cp_next->cp_prev = compl_first_match;
1449 }
1450 else
1451 {
1452 compl->cp_prev->cp_next = NULL;
1453 compl_first_match = mergesort_list(compl_first_match, cp_get_next,
1454 cp_set_next, cp_get_prev, cp_set_prev, compare);
1455 compl_T *tail = compl_first_match;
1456 while (tail->cp_next != NULL)
1457 tail = tail->cp_next;
1458 tail->cp_next = compl;
1459 compl->cp_prev = tail;
1460 }
1461 (void)ins_compl_make_cyclic();
1462}
1463
glepnira218cc62024-06-03 19:32:39 +02001464/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001465 * Build a popup menu to show the completion matches.
1466 * Returns the popup menu entry that should be selected. Returns -1 if nothing
1467 * should be selected.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001468 */
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001469 static int
1470ins_compl_build_pum(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001471{
1472 compl_T *compl;
1473 compl_T *shown_compl = NULL;
1474 int did_find_shown_match = FALSE;
1475 int shown_match_ok = FALSE;
glepnira49c0772024-11-30 10:56:30 +01001476 int i = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001477 int cur = -1;
zeertzjqaa925ee2024-06-09 18:24:05 +02001478 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02001479 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
zeertzjqd65aa1b2025-01-25 15:29:03 +01001480 int fuzzy_filter = (cur_cot_flags & COT_FUZZY) != 0;
glepnir80b66202024-11-27 21:53:53 +01001481 compl_T *match_head = NULL;
1482 compl_T *match_tail = NULL;
1483 compl_T *match_next = NULL;
Girish Palya8cd42a52025-06-05 21:04:29 +02001484 int *match_count = NULL;
Girish Palya19ef6b02025-05-28 20:28:21 +02001485 int is_forward = compl_shows_dir_forward();
Girish Palya8cd42a52025-06-05 21:04:29 +02001486 int is_cpt_completion = (cpt_sources_array != NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001487
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001488 // Need to build the popup menu list.
1489 compl_match_arraysize = 0;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001490
glepnira49c0772024-11-30 10:56:30 +01001491 // If the current match is the original text don't find the first
1492 // match after it, don't highlight anything.
1493 if (match_at_original_text(compl_shown_match))
1494 shown_match_ok = TRUE;
1495
1496 if (compl_leader.string != NULL
1497 && STRCMP(compl_leader.string, compl_orig_text.string) == 0
1498 && shown_match_ok == FALSE)
1499 compl_shown_match = compl_no_select ? compl_first_match
1500 : compl_first_match->cp_next;
1501
Girish Palya8cd42a52025-06-05 21:04:29 +02001502 if (is_cpt_completion)
1503 {
1504 match_count = ALLOC_CLEAR_MULT(int, cpt_sources_count);
1505 if (match_count == NULL)
1506 return -1;
1507 }
1508
1509 compl = compl_first_match;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001510 do
1511 {
glepnird4088ed2024-12-31 10:55:22 +01001512 compl->cp_in_match_array = FALSE;
Girish Palya0ac1eb32025-04-16 20:18:33 +02001513
Girish Palyadc314052025-05-08 23:28:52 +02001514 // Apply 'smartcase' behavior during normal mode
1515 if (ctrl_x_mode_normal() && !p_inf && compl_leader.string
1516 && !ignorecase(compl_leader.string) && !fuzzy_filter)
1517 compl->cp_flags &= ~CP_ICASE;
1518
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001519 if (!match_at_original_text(compl)
John Marriott5e6ea922024-11-23 14:01:57 +01001520 && (compl_leader.string == NULL
Girish Palyadc314052025-05-08 23:28:52 +02001521 || ins_compl_equal(compl, compl_leader.string,
1522 (int)compl_leader.length)
glepnirf400a0c2025-01-23 19:55:14 +01001523 || (fuzzy_filter && compl->cp_score > 0)))
glepnir80b66202024-11-27 21:53:53 +01001524 {
Girish Palya8cd42a52025-06-05 21:04:29 +02001525 // Limit number of items from each source if max_items is set.
1526 int match_limit_exceeded = FALSE;
1527 int cur_source = compl->cp_cpt_source_idx;
1528 if (is_forward && cur_source != -1 && is_cpt_completion)
glepnira49c0772024-11-30 10:56:30 +01001529 {
Girish Palya8cd42a52025-06-05 21:04:29 +02001530 match_count[cur_source]++;
1531 int max_matches = cpt_sources_array[cur_source].cs_max_matches;
1532 if (max_matches > 0 && match_count[cur_source] > max_matches)
1533 match_limit_exceeded = TRUE;
1534 }
1535
1536 if (!match_limit_exceeded)
1537 {
1538 ++compl_match_arraysize;
1539 compl->cp_in_match_array = TRUE;
1540 if (match_head == NULL)
1541 match_head = compl;
glepnira49c0772024-11-30 10:56:30 +01001542 else
Girish Palya8cd42a52025-06-05 21:04:29 +02001543 match_tail->cp_match_next = compl;
1544 match_tail = compl;
glepnira49c0772024-11-30 10:56:30 +01001545
Girish Palya8cd42a52025-06-05 21:04:29 +02001546 if (!shown_match_ok && !fuzzy_filter)
glepnira49c0772024-11-30 10:56:30 +01001547 {
Girish Palya8cd42a52025-06-05 21:04:29 +02001548 if (compl == compl_shown_match || did_find_shown_match)
1549 {
1550 // This item is the shown match or this is the
1551 // first displayed item after the shown match.
1552 compl_shown_match = compl;
1553 did_find_shown_match = TRUE;
1554 shown_match_ok = TRUE;
1555 }
1556 else
1557 // Remember this displayed match for when the
1558 // shown match is just below it.
1559 shown_compl = compl;
glepnira49c0772024-11-30 10:56:30 +01001560 cur = i;
glepnira49c0772024-11-30 10:56:30 +01001561 }
Girish Palya8cd42a52025-06-05 21:04:29 +02001562 else if (fuzzy_filter)
1563 {
1564 if (i == 0)
1565 shown_compl = compl;
1566
1567 if (!shown_match_ok && compl == compl_shown_match)
1568 {
1569 cur = i;
1570 shown_match_ok = TRUE;
1571 }
1572 }
1573 i++;
glepnira49c0772024-11-30 10:56:30 +01001574 }
glepnir80b66202024-11-27 21:53:53 +01001575 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001576
glepnirf400a0c2025-01-23 19:55:14 +01001577 if (compl == compl_shown_match && !fuzzy_filter)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001578 {
1579 did_find_shown_match = TRUE;
1580
1581 // When the original text is the shown match don't set
1582 // compl_shown_match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001583 if (match_at_original_text(compl))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001584 shown_match_ok = TRUE;
1585
1586 if (!shown_match_ok && shown_compl != NULL)
1587 {
1588 // The shown match isn't displayed, set it to the
1589 // previously displayed match.
1590 compl_shown_match = shown_compl;
1591 shown_match_ok = TRUE;
1592 }
1593 }
glepnira49c0772024-11-30 10:56:30 +01001594 compl = compl->cp_next;
1595 } while (compl != NULL && !is_first_match(compl));
1596
Girish Palya8cd42a52025-06-05 21:04:29 +02001597 vim_free(match_count);
1598
glepnira49c0772024-11-30 10:56:30 +01001599 if (compl_match_arraysize == 0)
1600 return -1;
1601
Girish Palya8cd42a52025-06-05 21:04:29 +02001602 if (fuzzy_filter && !compl_no_select && !shown_match_ok)
glepnirc0b7ca42025-02-13 20:27:44 +01001603 {
1604 compl_shown_match = shown_compl;
1605 shown_match_ok = TRUE;
1606 cur = 0;
1607 }
1608
glepnira49c0772024-11-30 10:56:30 +01001609 compl_match_array = ALLOC_CLEAR_MULT(pumitem_T, compl_match_arraysize);
1610 if (compl_match_array == NULL)
1611 return -1;
1612
1613 compl = match_head;
1614 i = 0;
1615 while (compl != NULL)
1616 {
glepnir6e199932024-12-14 21:13:27 +01001617 compl_match_array[i].pum_text = compl->cp_text[CPT_ABBR] != NULL
1618 ? compl->cp_text[CPT_ABBR] : compl->cp_str.string;
glepnira49c0772024-11-30 10:56:30 +01001619 compl_match_array[i].pum_kind = compl->cp_text[CPT_KIND];
1620 compl_match_array[i].pum_info = compl->cp_text[CPT_INFO];
Girish Palya19ef6b02025-05-28 20:28:21 +02001621 compl_match_array[i].pum_cpt_source_idx = compl->cp_cpt_source_idx;
glepnira49c0772024-11-30 10:56:30 +01001622 compl_match_array[i].pum_user_abbr_hlattr = compl->cp_user_abbr_hlattr;
1623 compl_match_array[i].pum_user_kind_hlattr = compl->cp_user_kind_hlattr;
glepnir6e199932024-12-14 21:13:27 +01001624 compl_match_array[i++].pum_extra = compl->cp_text[CPT_MENU] != NULL
1625 ? compl->cp_text[CPT_MENU] : compl->cp_fname;
glepnir80b66202024-11-27 21:53:53 +01001626 match_next = compl->cp_match_next;
1627 compl->cp_match_next = NULL;
1628 compl = match_next;
1629 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001630
1631 if (!shown_match_ok) // no displayed match at all
1632 cur = -1;
1633
1634 return cur;
1635}
1636
1637/*
1638 * Show the popup menu for the list of matches.
1639 * Also adjusts "compl_shown_match" to an entry that is actually displayed.
1640 */
1641 void
1642ins_compl_show_pum(void)
1643{
1644 int i;
1645 int cur = -1;
1646 colnr_T col;
1647
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001648 if (!pum_wanted() || !pum_enough_matches())
1649 return;
1650
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001651 // Update the screen later, before drawing the popup menu over it.
1652 pum_call_update_screen();
1653
1654 if (compl_match_array == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001655 // Need to build the popup menu list.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001656 cur = ins_compl_build_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001657 else
1658 {
1659 // popup menu already exists, only need to find the current item.
1660 for (i = 0; i < compl_match_arraysize; ++i)
glepnir19e1dd62025-05-08 22:50:38 +02001661 {
John Marriott5e6ea922024-11-23 14:01:57 +01001662 if (compl_match_array[i].pum_text == compl_shown_match->cp_str.string
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001663 || compl_match_array[i].pum_text
1664 == compl_shown_match->cp_text[CPT_ABBR])
1665 {
1666 cur = i;
1667 break;
1668 }
glepnir19e1dd62025-05-08 22:50:38 +02001669 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001670 }
1671
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001672 if (compl_match_array == NULL)
glepnir0d3c0a62024-02-11 17:52:40 +01001673 {
1674#ifdef FEAT_EVAL
1675 if (compl_started && has_completechanged())
1676 trigger_complete_changed_event(cur);
1677#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001678 return;
glepnir0d3c0a62024-02-11 17:52:40 +01001679 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001680
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001681 // In Replace mode when a $ is displayed at the end of the line only
1682 // part of the screen would be updated. We do need to redraw here.
1683 dollar_vcol = -1;
1684
1685 // Compute the screen column of the start of the completed text.
1686 // Use the cursor to get all wrapping and other settings right.
1687 col = curwin->w_cursor.col;
1688 curwin->w_cursor.col = compl_col;
glepnira218cc62024-06-03 19:32:39 +02001689 compl_selected_item = cur;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001690 pum_display(compl_match_array, compl_match_arraysize, cur);
1691 curwin->w_cursor.col = col;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001692
glepnircbb46b42024-02-03 18:11:13 +01001693 // After adding leader, set the current match to shown match.
1694 if (compl_started && compl_curr_match != compl_shown_match)
1695 compl_curr_match = compl_shown_match;
1696
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001697#ifdef FEAT_EVAL
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001698 if (has_completechanged())
1699 trigger_complete_changed_event(cur);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001700#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001701}
1702
1703#define DICT_FIRST (1) // use just first element in "dict"
1704#define DICT_EXACT (2) // "dict" is the exact name of a file
1705
1706/*
glepnir40c1c332024-06-11 19:37:04 +02001707 * Get current completion leader
1708 */
1709 char_u *
1710ins_compl_leader(void)
1711{
John Marriott5e6ea922024-11-23 14:01:57 +01001712 return compl_leader.string != NULL ? compl_leader.string : compl_orig_text.string;
1713}
1714
1715/*
1716 * Get current completion leader length
1717 */
1718 size_t
1719ins_compl_leader_len(void)
1720{
1721 return compl_leader.string != NULL ? compl_leader.length : compl_orig_text.length;
glepnir40c1c332024-06-11 19:37:04 +02001722}
1723
1724/*
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001725 * Add any identifiers that match the given pattern "pat" in the list of
1726 * dictionary files "dict_start" to the list of completions.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001727 */
1728 static void
1729ins_compl_dictionaries(
1730 char_u *dict_start,
1731 char_u *pat,
1732 int flags, // DICT_FIRST and/or DICT_EXACT
1733 int thesaurus) // Thesaurus completion
1734{
1735 char_u *dict = dict_start;
1736 char_u *ptr;
1737 char_u *buf;
1738 regmatch_T regmatch;
1739 char_u **files;
1740 int count;
1741 int save_p_scs;
1742 int dir = compl_direction;
1743
1744 if (*dict == NUL)
1745 {
1746#ifdef FEAT_SPELL
1747 // When 'dictionary' is empty and spell checking is enabled use
1748 // "spell".
1749 if (!thesaurus && curwin->w_p_spell)
1750 dict = (char_u *)"spell";
1751 else
1752#endif
1753 return;
1754 }
1755
1756 buf = alloc(LSIZE);
1757 if (buf == NULL)
1758 return;
1759 regmatch.regprog = NULL; // so that we can goto theend
1760
1761 // If 'infercase' is set, don't use 'smartcase' here
1762 save_p_scs = p_scs;
1763 if (curbuf->b_p_inf)
1764 p_scs = FALSE;
1765
1766 // When invoked to match whole lines for CTRL-X CTRL-L adjust the pattern
1767 // to only match at the start of a line. Otherwise just match the
1768 // pattern. Also need to double backslashes.
1769 if (ctrl_x_mode_line_or_eval())
1770 {
1771 char_u *pat_esc = vim_strsave_escaped(pat, (char_u *)"\\");
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001772
1773 if (pat_esc == NULL)
1774 goto theend;
glepnir19e1dd62025-05-08 22:50:38 +02001775 size_t len = STRLEN(pat_esc) + 10;
Bram Moolenaar964b3742019-05-24 18:54:09 +02001776 ptr = alloc(len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001777 if (ptr == NULL)
1778 {
1779 vim_free(pat_esc);
1780 goto theend;
1781 }
1782 vim_snprintf((char *)ptr, len, "^\\s*\\zs\\V%s", pat_esc);
1783 regmatch.regprog = vim_regcomp(ptr, RE_MAGIC);
1784 vim_free(pat_esc);
1785 vim_free(ptr);
1786 }
1787 else
1788 {
Bram Moolenaarf4e20992020-12-21 19:59:08 +01001789 regmatch.regprog = vim_regcomp(pat, magic_isset() ? RE_MAGIC : 0);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001790 if (regmatch.regprog == NULL)
1791 goto theend;
1792 }
1793
1794 // ignore case depends on 'ignorecase', 'smartcase' and "pat"
1795 regmatch.rm_ic = ignorecase(pat);
1796 while (*dict != NUL && !got_int && !compl_interrupted)
1797 {
1798 // copy one dictionary file name into buf
1799 if (flags == DICT_EXACT)
1800 {
1801 count = 1;
1802 files = &dict;
1803 }
1804 else
1805 {
1806 // Expand wildcards in the dictionary name, but do not allow
1807 // backticks (for security, the 'dict' option may have been set in
1808 // a modeline).
1809 copy_option_part(&dict, buf, LSIZE, ",");
1810# ifdef FEAT_SPELL
1811 if (!thesaurus && STRCMP(buf, "spell") == 0)
1812 count = -1;
1813 else
1814# endif
1815 if (vim_strchr(buf, '`') != NULL
1816 || expand_wildcards(1, &buf, &count, &files,
1817 EW_FILE|EW_SILENT) != OK)
1818 count = 0;
1819 }
1820
1821# ifdef FEAT_SPELL
1822 if (count == -1)
1823 {
1824 // Complete from active spelling. Skip "\<" in the pattern, we
1825 // don't use it as a RE.
1826 if (pat[0] == '\\' && pat[1] == '<')
1827 ptr = pat + 2;
1828 else
1829 ptr = pat;
1830 spell_dump_compl(ptr, regmatch.rm_ic, &dir, 0);
1831 }
1832 else
1833# endif
1834 if (count > 0) // avoid warning for using "files" uninit
1835 {
1836 ins_compl_files(count, files, thesaurus, flags,
glepnirf31cfa22025-03-06 21:59:13 +01001837 (cfc_has_mode() ? NULL : &regmatch), buf, &dir);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001838 if (flags != DICT_EXACT)
1839 FreeWild(count, files);
1840 }
1841 if (flags != 0)
1842 break;
1843 }
1844
1845theend:
1846 p_scs = save_p_scs;
1847 vim_regfree(regmatch.regprog);
1848 vim_free(buf);
1849}
1850
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001851/*
1852 * Add all the words in the line "*buf_arg" from the thesaurus file "fname"
1853 * skipping the word at 'skip_word'. Returns OK on success.
1854 */
1855 static int
zeertzjq5fb3aab2022-08-24 16:48:23 +01001856thesaurus_add_words_in_line(
glepnir19e1dd62025-05-08 22:50:38 +02001857 char_u *fname,
1858 char_u **buf_arg,
1859 int dir,
1860 char_u *skip_word)
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001861{
1862 int status = OK;
1863 char_u *ptr;
1864 char_u *wstart;
1865
1866 // Add the other matches on the line
1867 ptr = *buf_arg;
1868 while (!got_int)
1869 {
1870 // Find start of the next word. Skip white
1871 // space and punctuation.
1872 ptr = find_word_start(ptr);
1873 if (*ptr == NUL || *ptr == NL)
1874 break;
1875 wstart = ptr;
1876
1877 // Find end of the word.
1878 if (has_mbyte)
1879 // Japanese words may have characters in
1880 // different classes, only separate words
1881 // with single-byte non-word characters.
1882 while (*ptr != NUL)
1883 {
1884 int l = (*mb_ptr2len)(ptr);
1885
1886 if (l < 2 && !vim_iswordc(*ptr))
1887 break;
1888 ptr += l;
1889 }
1890 else
1891 ptr = find_word_end(ptr);
1892
1893 // Add the word. Skip the regexp match.
1894 if (wstart != skip_word)
1895 {
1896 status = ins_compl_add_infercase(wstart, (int)(ptr - wstart), p_ic,
glepnirf31cfa22025-03-06 21:59:13 +01001897 fname, dir, FALSE, 0);
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001898 if (status == FAIL)
1899 break;
1900 }
1901 }
1902
1903 *buf_arg = ptr;
1904 return status;
1905}
1906
1907/*
1908 * Process "count" dictionary/thesaurus "files" and add the text matching
1909 * "regmatch".
1910 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001911 static void
1912ins_compl_files(
1913 int count,
1914 char_u **files,
1915 int thesaurus,
1916 int flags,
1917 regmatch_T *regmatch,
1918 char_u *buf,
1919 int *dir)
1920{
1921 char_u *ptr;
1922 int i;
1923 FILE *fp;
1924 int add_r;
glepnirf31cfa22025-03-06 21:59:13 +01001925 char_u *leader = NULL;
1926 int leader_len = 0;
glepnir58760162025-03-13 21:39:51 +01001927 int in_fuzzy_collect = cfc_has_mode();
glepnirf31cfa22025-03-06 21:59:13 +01001928 int score = 0;
1929 int len = 0;
1930 char_u *line_end = NULL;
1931
1932 if (in_fuzzy_collect)
1933 {
1934 leader = ins_compl_leader();
Yegappan Lakshmanan7b6add02025-04-01 20:38:37 +02001935 leader_len = (int)ins_compl_leader_len();
glepnirf31cfa22025-03-06 21:59:13 +01001936 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001937
1938 for (i = 0; i < count && !got_int && !compl_interrupted; i++)
1939 {
1940 fp = mch_fopen((char *)files[i], "r"); // open dictionary file
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01001941 if (flags != DICT_EXACT && !shortmess(SHM_COMPLETIONSCAN))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001942 {
Bram Moolenaarcc233582020-12-12 13:32:07 +01001943 msg_hist_off = TRUE; // reset in msg_trunc_attr()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001944 vim_snprintf((char *)IObuff, IOSIZE,
1945 _("Scanning dictionary: %s"), (char *)files[i]);
1946 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
1947 }
1948
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001949 if (fp == NULL)
1950 continue;
1951
1952 // Read dictionary file line by line.
1953 // Check each line for a match.
1954 while (!got_int && !compl_interrupted && !vim_fgets(buf, LSIZE, fp))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001955 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001956 ptr = buf;
glepnirf31cfa22025-03-06 21:59:13 +01001957 if (regmatch != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001958 {
glepnirf31cfa22025-03-06 21:59:13 +01001959 while (vim_regexec(regmatch, buf, (colnr_T)(ptr - buf)))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001960 {
glepnirf31cfa22025-03-06 21:59:13 +01001961 ptr = regmatch->startp[0];
1962 ptr = ctrl_x_mode_line_or_eval() ? find_line_end(ptr)
1963 : find_word_end(ptr);
1964 add_r = ins_compl_add_infercase(regmatch->startp[0],
1965 (int)(ptr - regmatch->startp[0]),
1966 p_ic, files[i], *dir, FALSE, 0);
1967 if (thesaurus)
1968 {
1969 // For a thesaurus, add all the words in the line
1970 ptr = buf;
1971 add_r = thesaurus_add_words_in_line(files[i], &ptr, *dir,
1972 regmatch->startp[0]);
1973 }
1974 if (add_r == OK)
1975 // if dir was BACKWARD then honor it just once
1976 *dir = FORWARD;
1977 else if (add_r == FAIL)
1978 break;
1979 // avoid expensive call to vim_regexec() when at end
1980 // of line
1981 if (*ptr == '\n' || got_int)
1982 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001983 }
glepnirf31cfa22025-03-06 21:59:13 +01001984 }
1985 else if (in_fuzzy_collect && leader_len > 0)
1986 {
1987 line_end = find_line_end(ptr);
1988 while (ptr < line_end)
1989 {
1990 if (fuzzy_match_str_in_line(&ptr, leader, &len, NULL, &score))
1991 {
1992 char_u *end_ptr = ctrl_x_mode_line_or_eval()
1993 ? find_line_end(ptr) : find_word_end(ptr);
1994 add_r = ins_compl_add_infercase(ptr, (int)(end_ptr - ptr),
1995 p_ic, files[i], *dir, FALSE, score);
1996 if (add_r == FAIL)
1997 break;
1998 ptr = end_ptr; // start from next word
1999 if (compl_get_longest && ctrl_x_mode_normal()
2000 && compl_first_match->cp_next
2001 && score == compl_first_match->cp_next->cp_score)
2002 compl_num_bests++;
2003 }
glepnirf31cfa22025-03-06 21:59:13 +01002004 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002005 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002006 line_breakcheck();
2007 ins_compl_check_keys(50, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002008 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002009 fclose(fp);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002010 }
2011}
2012
2013/*
2014 * Find the start of the next word.
2015 * Returns a pointer to the first char of the word. Also stops at a NUL.
2016 */
2017 char_u *
2018find_word_start(char_u *ptr)
2019{
2020 if (has_mbyte)
glepnir19e1dd62025-05-08 22:50:38 +02002021 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002022 while (*ptr != NUL && *ptr != '\n' && mb_get_class(ptr) <= 1)
2023 ptr += (*mb_ptr2len)(ptr);
glepnir19e1dd62025-05-08 22:50:38 +02002024 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002025 else
glepnir19e1dd62025-05-08 22:50:38 +02002026 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002027 while (*ptr != NUL && *ptr != '\n' && !vim_iswordc(*ptr))
2028 ++ptr;
glepnir19e1dd62025-05-08 22:50:38 +02002029 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002030 return ptr;
2031}
2032
2033/*
2034 * Find the end of the word. Assumes it starts inside a word.
2035 * Returns a pointer to just after the word.
2036 */
2037 char_u *
2038find_word_end(char_u *ptr)
2039{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002040 if (has_mbyte)
2041 {
glepnir19e1dd62025-05-08 22:50:38 +02002042 int start_class = mb_get_class(ptr);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002043 if (start_class > 1)
2044 while (*ptr != NUL)
2045 {
2046 ptr += (*mb_ptr2len)(ptr);
2047 if (mb_get_class(ptr) != start_class)
2048 break;
2049 }
2050 }
2051 else
2052 while (vim_iswordc(*ptr))
2053 ++ptr;
2054 return ptr;
2055}
2056
2057/*
2058 * Find the end of the line, omitting CR and NL at the end.
2059 * Returns a pointer to just after the line.
2060 */
glepnirdd42b052025-03-08 16:52:55 +01002061 char_u *
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002062find_line_end(char_u *ptr)
2063{
glepnir19e1dd62025-05-08 22:50:38 +02002064 char_u *s = ptr + STRLEN(ptr);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002065 while (s > ptr && (s[-1] == CAR || s[-1] == NL))
2066 --s;
2067 return s;
2068}
2069
2070/*
Girish Palyacbe53192025-04-14 22:13:15 +02002071 * Free a completion item in the list
2072 */
2073 static void
2074ins_compl_item_free(compl_T *match)
2075{
Girish Palyacbe53192025-04-14 22:13:15 +02002076 VIM_CLEAR_STRING(match->cp_str);
2077 // several entries may use the same fname, free it just once.
2078 if (match->cp_flags & CP_FREE_FNAME)
2079 vim_free(match->cp_fname);
glepnir19e1dd62025-05-08 22:50:38 +02002080 for (int i = 0; i < CPT_COUNT; ++i)
Girish Palyacbe53192025-04-14 22:13:15 +02002081 vim_free(match->cp_text[i]);
2082#ifdef FEAT_EVAL
2083 clear_tv(&match->cp_user_data);
2084#endif
2085 vim_free(match);
2086}
2087
2088/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002089 * Free the list of completions
2090 */
2091 static void
2092ins_compl_free(void)
2093{
2094 compl_T *match;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002095
John Marriott5e6ea922024-11-23 14:01:57 +01002096 VIM_CLEAR_STRING(compl_pattern);
2097 VIM_CLEAR_STRING(compl_leader);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002098
2099 if (compl_first_match == NULL)
2100 return;
2101
2102 ins_compl_del_pum();
2103 pum_clear();
2104
2105 compl_curr_match = compl_first_match;
2106 do
2107 {
2108 match = compl_curr_match;
2109 compl_curr_match = compl_curr_match->cp_next;
Girish Palyacbe53192025-04-14 22:13:15 +02002110 ins_compl_item_free(match);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002111 } while (compl_curr_match != NULL && !is_first_match(compl_curr_match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002112 compl_first_match = compl_curr_match = NULL;
2113 compl_shown_match = NULL;
2114 compl_old_match = NULL;
2115}
2116
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002117/*
2118 * Reset/clear the completion state.
2119 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002120 void
2121ins_compl_clear(void)
2122{
2123 compl_cont_status = 0;
2124 compl_started = FALSE;
glepnirf31cfa22025-03-06 21:59:13 +01002125 compl_cfc_longest_ins = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002126 compl_matches = 0;
glepnir07f0dbe2025-02-18 20:27:30 +01002127 compl_selected_item = -1;
glepnir6a38aff2024-12-16 21:56:16 +01002128 compl_ins_end_col = 0;
glepnircf7f0122025-04-15 19:02:00 +02002129 compl_curr_win = NULL;
2130 compl_curr_buf = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002131 VIM_CLEAR_STRING(compl_pattern);
2132 VIM_CLEAR_STRING(compl_leader);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002133 edit_submode_extra = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002134 VIM_CLEAR_STRING(compl_orig_text);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002135 compl_enter_selects = FALSE;
Girish Palya0ac1eb32025-04-16 20:18:33 +02002136 cpt_sources_clear();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002137#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002138 // clear v:completed_item
2139 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002140#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002141}
2142
2143/*
2144 * Return TRUE when Insert completion is active.
2145 */
2146 int
2147ins_compl_active(void)
2148{
2149 return compl_started;
2150}
2151
2152/*
glepnir8d0bb6d2024-12-24 09:44:35 +01002153 * Return True when wp is the actual completion window
2154 */
2155 int
glepnircf7f0122025-04-15 19:02:00 +02002156ins_compl_win_active(win_T *wp)
glepnir8d0bb6d2024-12-24 09:44:35 +01002157{
glepnircf7f0122025-04-15 19:02:00 +02002158 return ins_compl_active() && wp == compl_curr_win
2159 && wp->w_buffer == compl_curr_buf;
glepnir8d0bb6d2024-12-24 09:44:35 +01002160}
2161
2162/*
Girish Palyacbe53192025-04-14 22:13:15 +02002163 * Selected one of the matches. When FALSE, the match was either edited or
2164 * using the longest common string.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002165 */
2166 int
2167ins_compl_used_match(void)
2168{
2169 return compl_used_match;
2170}
2171
2172/*
2173 * Initialize get longest common string.
2174 */
2175 void
2176ins_compl_init_get_longest(void)
2177{
2178 compl_get_longest = FALSE;
2179}
2180
2181/*
2182 * Returns TRUE when insert completion is interrupted.
2183 */
2184 int
2185ins_compl_interrupted(void)
2186{
2187 return compl_interrupted;
2188}
2189
2190/*
2191 * Returns TRUE if the <Enter> key selects a match in the completion popup
2192 * menu.
2193 */
2194 int
2195ins_compl_enter_selects(void)
2196{
2197 return compl_enter_selects;
2198}
2199
2200/*
2201 * Return the column where the text starts that is being completed
2202 */
2203 colnr_T
2204ins_compl_col(void)
2205{
2206 return compl_col;
2207}
2208
2209/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002210 * Return the length in bytes of the text being completed
2211 */
2212 int
2213ins_compl_len(void)
2214{
2215 return compl_length;
2216}
2217
2218/*
glepnir94a045e2025-03-01 16:12:23 +01002219 * Return TRUE when the 'completeopt' "preinsert" flag is in effect,
2220 * otherwise return FALSE.
glepniredd4ac32025-01-29 18:53:51 +01002221 */
2222 static int
2223ins_compl_has_preinsert(void)
2224{
glepnira2c55592025-02-28 17:43:42 +01002225 int cur_cot_flags = get_cot_flags();
glepnir94a045e2025-03-01 16:12:23 +01002226 return (cur_cot_flags & (COT_PREINSERT | COT_FUZZY | COT_MENUONE))
2227 == (COT_PREINSERT | COT_MENUONE);
glepniredd4ac32025-01-29 18:53:51 +01002228}
2229
2230/*
2231 * Returns TRUE if the pre-insert effect is valid and the cursor is within
2232 * the `compl_ins_end_col` range.
2233 */
2234 int
2235ins_compl_preinsert_effect(void)
2236{
2237 if (!ins_compl_has_preinsert())
2238 return FALSE;
2239
2240 return curwin->w_cursor.col < compl_ins_end_col;
2241}
2242
2243/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002244 * Delete one character before the cursor and show the subset of the matches
2245 * that match the word that is now before the cursor.
2246 * Returns the character to be used, NUL if the work is done and another char
2247 * to be got from the user.
2248 */
2249 int
2250ins_compl_bs(void)
2251{
2252 char_u *line;
2253 char_u *p;
2254
glepniredd4ac32025-01-29 18:53:51 +01002255 if (ins_compl_preinsert_effect())
2256 ins_compl_delete();
2257
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002258 line = ml_get_curline();
2259 p = line + curwin->w_cursor.col;
2260 MB_PTR_BACK(line, p);
2261
2262 // Stop completion when the whole word was deleted. For Omni completion
2263 // allow the word to be deleted, we won't match everything.
2264 // Respect the 'backspace' option.
2265 if ((int)(p - line) - (int)compl_col < 0
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002266 || ((int)(p - line) - (int)compl_col == 0 && !ctrl_x_mode_omni())
2267 || ctrl_x_mode_eval()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002268 || (!can_bs(BS_START) && (int)(p - line) - (int)compl_col
2269 - compl_length < 0))
2270 return K_BS;
2271
2272 // Deleted more than what was used to find matches or didn't finish
2273 // finding all matches: need to look for matches all over again.
2274 if (curwin->w_cursor.col <= compl_col + compl_length
2275 || ins_compl_need_restart())
2276 ins_compl_restart();
2277
John Marriott5e6ea922024-11-23 14:01:57 +01002278 VIM_CLEAR_STRING(compl_leader);
2279 compl_leader.length = (size_t)((p - line) - compl_col);
2280 compl_leader.string = vim_strnsave(line + compl_col, compl_leader.length);
2281 if (compl_leader.string == NULL)
2282 {
2283 compl_leader.length = 0;
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00002284 return K_BS;
John Marriott5e6ea922024-11-23 14:01:57 +01002285 }
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00002286
2287 ins_compl_new_leader();
2288 if (compl_shown_match != NULL)
2289 // Make sure current match is not a hidden item.
2290 compl_curr_match = compl_shown_match;
2291 return NUL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002292}
2293
2294/*
2295 * Return TRUE when we need to find matches again, ins_compl_restart() is to
2296 * be called.
2297 */
2298 static int
2299ins_compl_need_restart(void)
2300{
2301 // Return TRUE if we didn't complete finding matches or when the
2302 // 'completefunc' returned "always" in the "refresh" dictionary item.
2303 return compl_was_interrupted
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002304 || ((ctrl_x_mode_function() || ctrl_x_mode_omni())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002305 && compl_opt_refresh_always);
2306}
2307
2308/*
2309 * Called after changing "compl_leader".
2310 * Show the popup menu with a different set of matches.
2311 * May also search for matches again if the previous search was interrupted.
2312 */
2313 static void
2314ins_compl_new_leader(void)
2315{
2316 ins_compl_del_pum();
2317 ins_compl_delete();
glepnir6a38aff2024-12-16 21:56:16 +01002318 ins_compl_insert_bytes(compl_leader.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002319 compl_used_match = FALSE;
2320
2321 if (compl_started)
Girish Palyacbe53192025-04-14 22:13:15 +02002322 {
John Marriott5e6ea922024-11-23 14:01:57 +01002323 ins_compl_set_original_text(compl_leader.string, compl_leader.length);
Girish Palyacbe53192025-04-14 22:13:15 +02002324 if (is_cpt_func_refresh_always())
2325 cpt_compl_refresh();
2326 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002327 else
2328 {
2329#ifdef FEAT_SPELL
2330 spell_bad_len = 0; // need to redetect bad word
2331#endif
Bram Moolenaar32aa1022019-11-02 22:54:41 +01002332 // Matches were cleared, need to search for them now. Before drawing
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002333 // the popup menu display the changed text before the cursor. Set
2334 // "compl_restarting" to avoid that the first match is inserted.
2335 pum_call_update_screen();
2336#ifdef FEAT_GUI
2337 if (gui.in_use)
2338 {
2339 // Show the cursor after the match, not after the redrawn text.
2340 setcursor();
2341 out_flush_cursor(FALSE, FALSE);
2342 }
2343#endif
2344 compl_restarting = TRUE;
2345 if (ins_complete(Ctrl_N, TRUE) == FAIL)
2346 compl_cont_status = 0;
2347 compl_restarting = FALSE;
2348 }
2349
Girish Palyab8ee1cf2025-06-08 16:20:06 +02002350 // When 'cot' contains "fuzzy" set the cp_score
2351 if (get_cot_flags() & COT_FUZZY)
2352 set_fuzzy_score();
2353 // Sort the matches linked list based on fuzzy score
2354 int cur_cot_flags = get_cot_flags();
2355 if ((cur_cot_flags & COT_FUZZY) && !(cur_cot_flags & COT_NOSORT))
2356 {
2357 sort_compl_match_list(cp_compare_fuzzy);
2358 if ((cur_cot_flags & COT_NOINSERT) && !(cur_cot_flags & COT_NOSELECT)
2359 && compl_first_match)
2360 {
2361 compl_shown_match = compl_first_match;
2362 if (compl_shows_dir_forward())
2363 compl_shown_match = compl_first_match->cp_next;
2364 }
2365 }
2366
glepnir44180412025-02-20 22:09:48 +01002367 compl_enter_selects = !compl_used_match && compl_selected_item != -1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002368
2369 // Show the popup menu with a different set of matches.
2370 ins_compl_show_pum();
2371
2372 // Don't let Enter select the original text when there is no popup menu.
2373 if (compl_match_array == NULL)
2374 compl_enter_selects = FALSE;
glepniredd4ac32025-01-29 18:53:51 +01002375 else if (ins_compl_has_preinsert() && compl_leader.length > 0)
2376 ins_compl_insert(FALSE, TRUE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002377}
2378
2379/*
2380 * Return the length of the completion, from the completion start column to
2381 * the cursor column. Making sure it never goes below zero.
2382 */
2383 static int
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002384get_compl_len(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002385{
2386 int off = (int)curwin->w_cursor.col - (int)compl_col;
glepnir40891ba2025-02-10 22:18:00 +01002387 return MAX(0, off);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002388}
2389
2390/*
2391 * Append one character to the match leader. May reduce the number of
2392 * matches.
2393 */
2394 void
2395ins_compl_addleader(int c)
2396{
glepnir19e1dd62025-05-08 22:50:38 +02002397 int cc;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002398
glepniredd4ac32025-01-29 18:53:51 +01002399 if (ins_compl_preinsert_effect())
2400 ins_compl_delete();
2401
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002402 if (stop_arrow() == FAIL)
2403 return;
2404 if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)
2405 {
2406 char_u buf[MB_MAXBYTES + 1];
2407
2408 (*mb_char2bytes)(c, buf);
2409 buf[cc] = NUL;
2410 ins_char_bytes(buf, cc);
2411 if (compl_opt_refresh_always)
2412 AppendToRedobuff(buf);
2413 }
2414 else
2415 {
2416 ins_char(c);
2417 if (compl_opt_refresh_always)
2418 AppendCharToRedobuff(c);
2419 }
2420
2421 // If we didn't complete finding matches we must search again.
2422 if (ins_compl_need_restart())
2423 ins_compl_restart();
2424
2425 // When 'always' is set, don't reset compl_leader. While completing,
2426 // cursor doesn't point original position, changing compl_leader would
2427 // break redo.
2428 if (!compl_opt_refresh_always)
2429 {
John Marriott5e6ea922024-11-23 14:01:57 +01002430 VIM_CLEAR_STRING(compl_leader);
2431 compl_leader.length = (size_t)(curwin->w_cursor.col - compl_col);
2432 compl_leader.string = vim_strnsave(ml_get_curline() + compl_col,
2433 compl_leader.length);
2434 if (compl_leader.string == NULL)
2435 {
2436 compl_leader.length = 0;
2437 return;
2438 }
2439
2440 ins_compl_new_leader();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002441 }
2442}
2443
2444/*
2445 * Setup for finding completions again without leaving CTRL-X mode. Used when
2446 * BS or a key was typed while still searching for matches.
2447 */
2448 static void
2449ins_compl_restart(void)
2450{
2451 ins_compl_free();
2452 compl_started = FALSE;
2453 compl_matches = 0;
2454 compl_cont_status = 0;
2455 compl_cont_mode = 0;
Girish Palya0ac1eb32025-04-16 20:18:33 +02002456 cpt_sources_clear();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002457}
2458
2459/*
2460 * Set the first match, the original text.
2461 */
2462 static void
John Marriott5e6ea922024-11-23 14:01:57 +01002463ins_compl_set_original_text(char_u *str, size_t len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002464{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002465 // Replace the original text entry.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002466 // The CP_ORIGINAL_TEXT flag is either at the first item or might possibly
2467 // be at the last item for backward completion
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002468 if (match_at_original_text(compl_first_match)) // safety check
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002469 {
John Marriott5e6ea922024-11-23 14:01:57 +01002470 char_u *p = vim_strnsave(str, len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002471 if (p != NULL)
2472 {
John Marriott5e6ea922024-11-23 14:01:57 +01002473 VIM_CLEAR_STRING(compl_first_match->cp_str);
2474 compl_first_match->cp_str.string = p;
2475 compl_first_match->cp_str.length = len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002476 }
2477 }
2478 else if (compl_first_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002479 && match_at_original_text(compl_first_match->cp_prev))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002480 {
John Marriott5e6ea922024-11-23 14:01:57 +01002481 char_u *p = vim_strnsave(str, len);
2482 if (p != NULL)
2483 {
2484 VIM_CLEAR_STRING(compl_first_match->cp_prev->cp_str);
2485 compl_first_match->cp_prev->cp_str.string = p;
2486 compl_first_match->cp_prev->cp_str.length = len;
2487 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002488 }
2489}
2490
2491/*
2492 * Append one character to the match leader. May reduce the number of
2493 * matches.
2494 */
2495 void
2496ins_compl_addfrommatch(void)
2497{
2498 char_u *p;
2499 int len = (int)curwin->w_cursor.col - (int)compl_col;
2500 int c;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002501
John Marriott5e6ea922024-11-23 14:01:57 +01002502 p = compl_shown_match->cp_str.string;
2503 if ((int)compl_shown_match->cp_str.length <= len) // the match is too short
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002504 {
John Marriott5e6ea922024-11-23 14:01:57 +01002505 size_t plen;
2506 compl_T *cp;
2507
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002508 // When still at the original match use the first entry that matches
2509 // the leader.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002510 if (!match_at_original_text(compl_shown_match))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002511 return;
2512
2513 p = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002514 plen = 0;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002515 for (cp = compl_shown_match->cp_next; cp != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002516 && !is_first_match(cp); cp = cp->cp_next)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002517 {
John Marriott5e6ea922024-11-23 14:01:57 +01002518 if (compl_leader.string == NULL
2519 || ins_compl_equal(cp, compl_leader.string,
2520 (int)compl_leader.length))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002521 {
John Marriott5e6ea922024-11-23 14:01:57 +01002522 p = cp->cp_str.string;
2523 plen = cp->cp_str.length;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002524 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002525 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002526 }
John Marriott5e6ea922024-11-23 14:01:57 +01002527 if (p == NULL || (int)plen <= len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002528 return;
2529 }
2530 p += len;
2531 c = PTR2CHAR(p);
2532 ins_compl_addleader(c);
2533}
2534
2535/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002536 * Set the CTRL-X completion mode based on the key "c" typed after a CTRL-X.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002537 * Uses the global variables: ctrl_x_mode, edit_submode, edit_submode_pre,
2538 * compl_cont_mode and compl_cont_status.
2539 * Returns TRUE when the character is not to be inserted.
2540 */
2541 static int
2542set_ctrl_x_mode(int c)
2543{
glepnir05460682025-05-26 18:23:27 +02002544 int retval = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002545
2546 switch (c)
2547 {
2548 case Ctrl_E:
2549 case Ctrl_Y:
2550 // scroll the window one line up or down
2551 ctrl_x_mode = CTRL_X_SCROLL;
2552 if (!(State & REPLACE_FLAG))
2553 edit_submode = (char_u *)_(" (insert) Scroll (^E/^Y)");
2554 else
2555 edit_submode = (char_u *)_(" (replace) Scroll (^E/^Y)");
2556 edit_submode_pre = NULL;
2557 showmode();
2558 break;
2559 case Ctrl_L:
2560 // complete whole line
2561 ctrl_x_mode = CTRL_X_WHOLE_LINE;
2562 break;
2563 case Ctrl_F:
2564 // complete filenames
2565 ctrl_x_mode = CTRL_X_FILES;
2566 break;
2567 case Ctrl_K:
zeertzjq5fb3aab2022-08-24 16:48:23 +01002568 // complete words from a dictionary
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002569 ctrl_x_mode = CTRL_X_DICTIONARY;
2570 break;
2571 case Ctrl_R:
glepnir05460682025-05-26 18:23:27 +02002572 // When CTRL-R is followed by '=', don't trigger register completion
2573 // This allows expressions like <C-R>=func()<CR> to work normally
2574 if (vpeekc() == '=')
2575 break;
2576 ctrl_x_mode = CTRL_X_REGISTER;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002577 break;
2578 case Ctrl_T:
2579 // complete words from a thesaurus
2580 ctrl_x_mode = CTRL_X_THESAURUS;
2581 break;
2582#ifdef FEAT_COMPL_FUNC
2583 case Ctrl_U:
2584 // user defined completion
2585 ctrl_x_mode = CTRL_X_FUNCTION;
2586 break;
2587 case Ctrl_O:
2588 // omni completion
2589 ctrl_x_mode = CTRL_X_OMNI;
2590 break;
2591#endif
2592 case 's':
2593 case Ctrl_S:
2594 // complete spelling suggestions
2595 ctrl_x_mode = CTRL_X_SPELL;
2596#ifdef FEAT_SPELL
2597 ++emsg_off; // Avoid getting the E756 error twice.
2598 spell_back_to_badword();
2599 --emsg_off;
2600#endif
2601 break;
2602 case Ctrl_RSB:
2603 // complete tag names
2604 ctrl_x_mode = CTRL_X_TAGS;
2605 break;
2606#ifdef FEAT_FIND_ID
2607 case Ctrl_I:
2608 case K_S_TAB:
2609 // complete keywords from included files
2610 ctrl_x_mode = CTRL_X_PATH_PATTERNS;
2611 break;
2612 case Ctrl_D:
2613 // complete definitions from included files
2614 ctrl_x_mode = CTRL_X_PATH_DEFINES;
2615 break;
2616#endif
2617 case Ctrl_V:
2618 case Ctrl_Q:
2619 // complete vim commands
2620 ctrl_x_mode = CTRL_X_CMDLINE;
2621 break;
2622 case Ctrl_Z:
2623 // stop completion
2624 ctrl_x_mode = CTRL_X_NORMAL;
2625 edit_submode = NULL;
2626 showmode();
2627 retval = TRUE;
2628 break;
2629 case Ctrl_P:
2630 case Ctrl_N:
2631 // ^X^P means LOCAL expansion if nothing interrupted (eg we
2632 // just started ^X mode, or there were enough ^X's to cancel
2633 // the previous mode, say ^X^F^X^X^P or ^P^X^X^X^P, see below)
2634 // do normal expansion when interrupting a different mode (say
2635 // ^X^F^X^P or ^P^X^X^P, see below)
2636 // nothing changes if interrupting mode 0, (eg, the flag
2637 // doesn't change when going to ADDING mode -- Acevedo
2638 if (!(compl_cont_status & CONT_INTRPT))
2639 compl_cont_status |= CONT_LOCAL;
2640 else if (compl_cont_mode != 0)
2641 compl_cont_status &= ~CONT_LOCAL;
2642 // FALLTHROUGH
2643 default:
2644 // If we have typed at least 2 ^X's... for modes != 0, we set
2645 // compl_cont_status = 0 (eg, as if we had just started ^X
2646 // mode).
2647 // For mode 0, we set "compl_cont_mode" to an impossible
2648 // value, in both cases ^X^X can be used to restart the same
2649 // mode (avoiding ADDING mode).
2650 // Undocumented feature: In a mode != 0 ^X^P and ^X^X^P start
2651 // 'complete' and local ^P expansions respectively.
2652 // In mode 0 an extra ^X is needed since ^X^P goes to ADDING
2653 // mode -- Acevedo
2654 if (c == Ctrl_X)
2655 {
2656 if (compl_cont_mode != 0)
2657 compl_cont_status = 0;
2658 else
2659 compl_cont_mode = CTRL_X_NOT_DEFINED_YET;
2660 }
2661 ctrl_x_mode = CTRL_X_NORMAL;
2662 edit_submode = NULL;
2663 showmode();
2664 break;
2665 }
2666
2667 return retval;
2668}
2669
2670/*
glepnir1c5a1202024-12-04 20:27:34 +01002671 * Trigger CompleteDone event and adds relevant information to v:event
2672 */
2673 static void
2674trigger_complete_done_event(int mode UNUSED, char_u *word UNUSED)
2675{
2676#if defined(FEAT_EVAL)
2677 save_v_event_T save_v_event;
2678 dict_T *v_event = get_v_event(&save_v_event);
2679 char_u *mode_str = NULL;
2680
2681 mode = mode & ~CTRL_X_WANT_IDENT;
2682 if (ctrl_x_mode_names[mode])
2683 mode_str = (char_u *)ctrl_x_mode_names[mode];
2684
2685 (void)dict_add_string(v_event, "complete_word",
2686 word == NULL ? (char_u *)"" : word);
2687 (void)dict_add_string(v_event, "complete_type",
2688 mode_str != NULL ? mode_str : (char_u *)"");
2689
2690 dict_set_items_ro(v_event);
2691#endif
2692 ins_apply_autocmds(EVENT_COMPLETEDONE);
2693
2694#if defined(FEAT_EVAL)
2695 restore_v_event(v_event, &save_v_event);
2696#endif
2697}
2698
2699/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002700 * Stop insert completion mode
2701 */
2702 static int
2703ins_compl_stop(int c, int prev_mode, int retval)
2704{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002705 int want_cindent;
glepnir1c5a1202024-12-04 20:27:34 +01002706 char_u *word = NULL;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002707
glepnir84a75032025-03-15 09:59:22 +01002708 // Remove pre-inserted text when present.
zeertzjq13436812025-04-23 20:46:35 +02002709 if (ins_compl_preinsert_effect() && ins_compl_win_active(curwin))
glepnir84a75032025-03-15 09:59:22 +01002710 ins_compl_delete();
2711
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002712 // Get here when we have finished typing a sequence of ^N and
2713 // ^P or other completion characters in CTRL-X mode. Free up
2714 // memory that was used, and make sure we can redo the insert.
John Marriott5e6ea922024-11-23 14:01:57 +01002715 if (compl_curr_match != NULL || compl_leader.string != NULL || c == Ctrl_E)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002716 {
glepnir40891ba2025-02-10 22:18:00 +01002717 char_u *ptr = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002718
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002719 // If any of the original typed text has been changed, eg when
2720 // ignorecase is set, we must add back-spaces to the redo
2721 // buffer. We add as few as necessary to delete just the part
2722 // of the original text that has changed.
2723 // When using the longest match, edited the match or used
2724 // CTRL-E then don't use the current match.
2725 if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E)
John Marriott5e6ea922024-11-23 14:01:57 +01002726 ptr = compl_curr_match->cp_str.string;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002727 ins_compl_fixRedoBufForLeader(ptr);
2728 }
2729
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002730 want_cindent = (get_can_cindent() && cindent_on());
Bram Moolenaar8e145b82022-05-21 20:17:31 +01002731
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002732 // When completing whole lines: fix indent for 'cindent'.
2733 // Otherwise, break line if it's too long.
2734 if (compl_cont_mode == CTRL_X_WHOLE_LINE)
2735 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002736 // re-indent the current line
2737 if (want_cindent)
2738 {
2739 do_c_expr_indent();
2740 want_cindent = FALSE; // don't do it again
2741 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002742 }
2743 else
2744 {
2745 int prev_col = curwin->w_cursor.col;
2746
2747 // put the cursor on the last char, for 'tw' formatting
2748 if (prev_col > 0)
2749 dec_cursor();
2750 // only format when something was inserted
2751 if (!arrow_used && !ins_need_undo_get() && c != Ctrl_E)
2752 insertchar(NUL, 0, -1);
2753 if (prev_col > 0
2754 && ml_get_curline()[curwin->w_cursor.col] != NUL)
2755 inc_cursor();
2756 }
2757
2758 // If the popup menu is displayed pressing CTRL-Y means accepting
2759 // the selection without inserting anything. When
2760 // compl_enter_selects is set the Enter key does the same.
2761 if ((c == Ctrl_Y || (compl_enter_selects
2762 && (c == CAR || c == K_KENTER || c == NL)))
2763 && pum_visible())
glepnir1c5a1202024-12-04 20:27:34 +01002764 {
2765 word = vim_strsave(compl_shown_match->cp_str.string);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002766 retval = TRUE;
glepnir1c5a1202024-12-04 20:27:34 +01002767 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002768
2769 // CTRL-E means completion is Ended, go back to the typed text.
2770 // but only do this, if the Popup is still visible
2771 if (c == Ctrl_E)
2772 {
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002773 char_u *p = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002774 size_t plen = 0;
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002775
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002776 ins_compl_delete();
John Marriott5e6ea922024-11-23 14:01:57 +01002777 if (compl_leader.string != NULL)
2778 {
2779 p = compl_leader.string;
2780 plen = compl_leader.length;
2781 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002782 else if (compl_first_match != NULL)
John Marriott5e6ea922024-11-23 14:01:57 +01002783 {
2784 p = compl_orig_text.string;
2785 plen = compl_orig_text.length;
2786 }
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002787 if (p != NULL)
2788 {
2789 int compl_len = get_compl_len();
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002790
John Marriott5e6ea922024-11-23 14:01:57 +01002791 if ((int)plen > compl_len)
zeertzjqf25d8f92024-12-18 21:12:25 +01002792 ins_compl_insert_bytes(p + compl_len, (int)plen - compl_len);
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002793 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002794 retval = TRUE;
2795 }
2796
2797 auto_format(FALSE, TRUE);
2798
2799 // Trigger the CompleteDonePre event to give scripts a chance to
2800 // act upon the completion before clearing the info, and restore
2801 // ctrl_x_mode, so that complete_info() can be used.
2802 ctrl_x_mode = prev_mode;
2803 ins_apply_autocmds(EVENT_COMPLETEDONEPRE);
2804
2805 ins_compl_free();
2806 compl_started = FALSE;
2807 compl_matches = 0;
2808 if (!shortmess(SHM_COMPLETIONMENU))
2809 msg_clr_cmdline(); // necessary for "noshowmode"
2810 ctrl_x_mode = CTRL_X_NORMAL;
2811 compl_enter_selects = FALSE;
2812 if (edit_submode != NULL)
2813 {
2814 edit_submode = NULL;
2815 showmode();
2816 }
2817
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002818 if (c == Ctrl_C && cmdwin_type != 0)
2819 // Avoid the popup menu remains displayed when leaving the
2820 // command line window.
2821 update_screen(0);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002822 // Indent now if a key was typed that is in 'cinkeys'.
2823 if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0)))
2824 do_c_expr_indent();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002825 // Trigger the CompleteDone event to give scripts a chance to act
2826 // upon the end of completion.
glepnir1c5a1202024-12-04 20:27:34 +01002827 trigger_complete_done_event(prev_mode, word);
2828 vim_free(word);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002829
2830 return retval;
2831}
2832
2833/*
glepnircf7f0122025-04-15 19:02:00 +02002834 * Cancel completion.
2835 */
2836 int
2837ins_compl_cancel(void)
2838{
2839 return ins_compl_stop(' ', ctrl_x_mode, TRUE);
2840}
2841
2842/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002843 * Prepare for Insert mode completion, or stop it.
2844 * Called just after typing a character in Insert mode.
2845 * Returns TRUE when the character is not to be inserted;
2846 */
2847 int
2848ins_compl_prep(int c)
2849{
glepnir19e1dd62025-05-08 22:50:38 +02002850 int retval = FALSE;
2851 int prev_mode = ctrl_x_mode;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002852
2853 // Forget any previous 'special' messages if this is actually
2854 // a ^X mode key - bar ^R, in which case we wait to see what it gives us.
2855 if (c != Ctrl_R && vim_is_ctrl_x_key(c))
2856 edit_submode_extra = NULL;
2857
zeertzjq440d4cb2023-03-02 17:51:32 +00002858 // Ignore end of Select mode mapping and mouse scroll/movement.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002859 if (c == K_SELECT || c == K_MOUSEDOWN || c == K_MOUSEUP
zeertzjq440d4cb2023-03-02 17:51:32 +00002860 || c == K_MOUSELEFT || c == K_MOUSERIGHT || c == K_MOUSEMOVE
Bram Moolenaare32c3c42022-01-15 18:26:04 +00002861 || c == K_COMMAND || c == K_SCRIPT_COMMAND)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002862 return retval;
2863
Bram Moolenaar05ad5ff2019-11-30 22:48:27 +01002864#ifdef FEAT_PROP_POPUP
Bram Moolenaarf0bc15c2019-08-18 19:23:45 +02002865 // Ignore mouse events in a popup window
2866 if (is_mouse_key(c))
2867 {
2868 // Ignore drag and release events, the position does not need to be in
2869 // the popup and it may have just closed.
2870 if (c == K_LEFTRELEASE
2871 || c == K_LEFTRELEASE_NM
2872 || c == K_MIDDLERELEASE
2873 || c == K_RIGHTRELEASE
2874 || c == K_X1RELEASE
2875 || c == K_X2RELEASE
2876 || c == K_LEFTDRAG
2877 || c == K_MIDDLEDRAG
2878 || c == K_RIGHTDRAG
2879 || c == K_X1DRAG
2880 || c == K_X2DRAG)
2881 return retval;
2882 if (popup_visible)
2883 {
2884 int row = mouse_row;
2885 int col = mouse_col;
2886 win_T *wp = mouse_find_win(&row, &col, FIND_POPUP);
2887
2888 if (wp != NULL && WIN_IS_POPUP(wp))
2889 return retval;
2890 }
2891 }
2892#endif
2893
zeertzjqdca29d92021-08-31 19:12:51 +02002894 if (ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X && c != Ctrl_X)
2895 {
2896 if (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_Z || ins_compl_pum_key(c)
2897 || !vim_is_ctrl_x_key(c))
2898 {
2899 // Not starting another completion mode.
2900 ctrl_x_mode = CTRL_X_CMDLINE;
2901
2902 // CTRL-X CTRL-Z should stop completion without inserting anything
2903 if (c == Ctrl_Z)
2904 retval = TRUE;
2905 }
2906 else
2907 {
2908 ctrl_x_mode = CTRL_X_CMDLINE;
2909
2910 // Other CTRL-X keys first stop completion, then start another
2911 // completion mode.
2912 ins_compl_prep(' ');
2913 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
2914 }
2915 }
2916
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002917 // Set "compl_get_longest" when finding the first matches.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002918 if (ctrl_x_mode_not_defined_yet()
2919 || (ctrl_x_mode_normal() && !compl_started))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002920 {
zeertzjq529b9ad2024-06-05 20:27:06 +02002921 compl_get_longest = (get_cot_flags() & COT_LONGEST) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002922 compl_used_match = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002923 }
2924
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002925 if (ctrl_x_mode_not_defined_yet())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002926 // We have just typed CTRL-X and aren't quite sure which CTRL-X mode
2927 // it will be yet. Now we decide.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002928 retval = set_ctrl_x_mode(c);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002929 else if (ctrl_x_mode_not_default())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002930 {
2931 // We're already in CTRL-X mode, do we stay in it?
2932 if (!vim_is_ctrl_x_key(c))
2933 {
glepnir40891ba2025-02-10 22:18:00 +01002934 ctrl_x_mode = ctrl_x_mode_scroll() ? CTRL_X_NORMAL : CTRL_X_FINISHED;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002935 edit_submode = NULL;
2936 }
2937 showmode();
2938 }
2939
2940 if (compl_started || ctrl_x_mode == CTRL_X_FINISHED)
2941 {
2942 // Show error message from attempted keyword completion (probably
2943 // 'Pattern not found') until another key is hit, then go back to
2944 // showing what mode we are in.
2945 showmode();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002946 if ((ctrl_x_mode_normal() && c != Ctrl_N && c != Ctrl_P
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002947 && c != Ctrl_R && !ins_compl_pum_key(c))
2948 || ctrl_x_mode == CTRL_X_FINISHED)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002949 retval = ins_compl_stop(c, prev_mode, retval);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002950 }
2951 else if (ctrl_x_mode == CTRL_X_LOCAL_MSG)
2952 // Trigger the CompleteDone event to give scripts a chance to act
2953 // upon the (possibly failed) completion.
glepnir1c5a1202024-12-04 20:27:34 +01002954 trigger_complete_done_event(ctrl_x_mode, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002955
LemonBoy2bf52dd2022-04-09 18:17:34 +01002956 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01002957
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002958 // reset continue_* if we left expansion-mode, if we stay they'll be
2959 // (re)set properly in ins_complete()
2960 if (!vim_is_ctrl_x_key(c))
2961 {
2962 compl_cont_status = 0;
2963 compl_cont_mode = 0;
2964 }
2965
2966 return retval;
2967}
2968
2969/*
2970 * Fix the redo buffer for the completion leader replacing some of the typed
2971 * text. This inserts backspaces and appends the changed text.
2972 * "ptr" is the known leader text or NUL.
2973 */
2974 static void
2975ins_compl_fixRedoBufForLeader(char_u *ptr_arg)
2976{
John Marriott5e6ea922024-11-23 14:01:57 +01002977 int len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002978 char_u *p;
2979 char_u *ptr = ptr_arg;
2980
2981 if (ptr == NULL)
2982 {
John Marriott5e6ea922024-11-23 14:01:57 +01002983 if (compl_leader.string != NULL)
2984 ptr = compl_leader.string;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002985 else
2986 return; // nothing to do
2987 }
John Marriott5e6ea922024-11-23 14:01:57 +01002988 if (compl_orig_text.string != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002989 {
John Marriott5e6ea922024-11-23 14:01:57 +01002990 p = compl_orig_text.string;
glepnir40891ba2025-02-10 22:18:00 +01002991 // Find length of common prefix between original text and new completion
2992 while (p[len] != NUL && p[len] == ptr[len])
2993 len++;
2994 // Adjust length to not break inside a multi-byte character
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002995 if (len > 0)
2996 len -= (*mb_head_off)(p, p + len);
glepnir40891ba2025-02-10 22:18:00 +01002997 // Add backspace characters for each remaining character in
2998 // original text
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002999 for (p += len; *p != NUL; MB_PTR_ADV(p))
3000 AppendCharToRedobuff(K_BS);
3001 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003002 if (ptr != NULL)
3003 AppendToRedobuffLit(ptr + len, -1);
3004}
3005
3006/*
3007 * Loops through the list of windows, loaded-buffers or non-loaded-buffers
3008 * (depending on flag) starting from buf and looking for a non-scanned
3009 * buffer (other than curbuf). curbuf is special, if it is called with
3010 * buf=curbuf then it has to be the first call for a given flag/expansion.
3011 *
3012 * Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo
3013 */
3014 static buf_T *
3015ins_compl_next_buf(buf_T *buf, int flag)
3016{
glepnir19e1dd62025-05-08 22:50:38 +02003017 static win_T *wp = NULL;
3018 int skip_buffer;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003019
3020 if (flag == 'w') // just windows
3021 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003022 if (buf == curbuf || !win_valid(wp))
3023 // first call for this flag/expansion or window was closed
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003024 wp = curwin;
glepnir40891ba2025-02-10 22:18:00 +01003025
3026 while (TRUE)
3027 {
Hirohito Higashi355db992025-04-28 18:07:02 +02003028 // Move to next window (wrap to first window if at the end)
3029 wp = (wp->w_next != NULL) ? wp->w_next : firstwin;
3030 // Break if we're back at start or found an unscanned buffer
3031 if (wp == curwin || !wp->w_buffer->b_scanned)
3032 break;
glepnir40891ba2025-02-10 22:18:00 +01003033 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003034 buf = wp->w_buffer;
3035 }
3036 else
glepnir40891ba2025-02-10 22:18:00 +01003037 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003038 // 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U'
3039 // (unlisted buffers)
3040 // When completing whole lines skip unloaded buffers.
glepnir40891ba2025-02-10 22:18:00 +01003041 while (TRUE)
3042 {
3043 // Move to next buffer (wrap to first buffer if at the end)
3044 buf = (buf->b_next != NULL) ? buf->b_next : firstbuf;
3045 // Break if we're back at start buffer
3046 if (buf == curbuf)
3047 break;
3048
3049 // Check buffer conditions based on flag
3050 if (flag == 'U')
3051 skip_buffer = buf->b_p_bl;
3052 else
3053 skip_buffer = !buf->b_p_bl ||
3054 (buf->b_ml.ml_mfp == NULL) != (flag == 'u');
3055
3056 // Break if we found a buffer that matches our criteria
3057 if (!skip_buffer && !buf->b_scanned)
3058 break;
3059 }
3060 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003061 return buf;
3062}
3063
3064#ifdef FEAT_COMPL_FUNC
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003065
3066# ifdef FEAT_EVAL
3067static callback_T cfu_cb; // 'completefunc' callback function
3068static callback_T ofu_cb; // 'omnifunc' callback function
3069static callback_T tsrfu_cb; // 'thesaurusfunc' callback function
3070# endif
3071
3072/*
3073 * Copy a global callback function to a buffer local callback.
3074 */
3075 static void
3076copy_global_to_buflocal_cb(callback_T *globcb, callback_T *bufcb)
3077{
3078 free_callback(bufcb);
3079 if (globcb->cb_name != NULL && *globcb->cb_name != NUL)
3080 copy_callback(bufcb, globcb);
3081}
3082
3083/*
3084 * Parse the 'completefunc' option value and set the callback function.
3085 * Invoked when the 'completefunc' option is set. The option value can be a
3086 * name of a function (string), or function(<name>) or funcref(<name>) or a
3087 * lambda expression.
3088 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003089 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00003090did_set_completefunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003091{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003092 if (option_set_callback_func(curbuf->b_p_cfu, &cfu_cb) == FAIL)
3093 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003094
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003095 set_buflocal_cfu_callback(curbuf);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003096
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003097 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003098}
3099
3100/*
3101 * Copy the global 'completefunc' callback function to the buffer-local
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003102 * 'completefunc' callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003103 */
3104 void
3105set_buflocal_cfu_callback(buf_T *buf UNUSED)
3106{
3107# ifdef FEAT_EVAL
3108 copy_global_to_buflocal_cb(&cfu_cb, &buf->b_cfu_cb);
3109# endif
3110}
3111
3112/*
3113 * Parse the 'omnifunc' option value and set the callback function.
3114 * Invoked when the 'omnifunc' option is set. The option value can be a
3115 * name of a function (string), or function(<name>) or funcref(<name>) or a
3116 * lambda expression.
3117 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003118 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00003119did_set_omnifunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003120{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003121 if (option_set_callback_func(curbuf->b_p_ofu, &ofu_cb) == FAIL)
3122 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003123
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003124 set_buflocal_ofu_callback(curbuf);
3125 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003126}
3127
3128/*
3129 * Copy the global 'omnifunc' callback function to the buffer-local 'omnifunc'
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003130 * callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003131 */
3132 void
3133set_buflocal_ofu_callback(buf_T *buf UNUSED)
3134{
3135# ifdef FEAT_EVAL
3136 copy_global_to_buflocal_cb(&ofu_cb, &buf->b_ofu_cb);
3137# endif
3138}
3139
3140/*
3141 * Parse the 'thesaurusfunc' option value and set the callback function.
3142 * Invoked when the 'thesaurusfunc' option is set. The option value can be a
3143 * name of a function (string), or function(<name>) or funcref(<name>) or a
3144 * lambda expression.
3145 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003146 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00003147did_set_thesaurusfunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003148{
3149 int retval;
3150
zeertzjq6eda2692024-11-03 09:23:33 +01003151 if (args->os_flags & OPT_LOCAL)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003152 // buffer-local option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003153 retval = option_set_callback_func(curbuf->b_p_tsrfu,
3154 &curbuf->b_tsrfu_cb);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003155 else
3156 {
3157 // global option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003158 retval = option_set_callback_func(p_tsrfu, &tsrfu_cb);
zeertzjq6eda2692024-11-03 09:23:33 +01003159 // when using :set, free the local callback
3160 if (!(args->os_flags & OPT_GLOBAL))
3161 free_callback(&curbuf->b_tsrfu_cb);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003162 }
3163
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003164 return retval == FAIL ? e_invalid_argument : NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003165}
3166
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00003167/*
3168 * Mark the global 'completefunc' 'omnifunc' and 'thesaurusfunc' callbacks with
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003169 * "copyID" so that they are not garbage collected.
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00003170 */
3171 int
3172set_ref_in_insexpand_funcs(int copyID)
3173{
glepnir19e1dd62025-05-08 22:50:38 +02003174 int abort = set_ref_in_callback(&cfu_cb, copyID);
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00003175 abort = abort || set_ref_in_callback(&ofu_cb, copyID);
3176 abort = abort || set_ref_in_callback(&tsrfu_cb, copyID);
3177
3178 return abort;
3179}
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003180
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003181/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003182 * Get the user-defined completion function name for completion "type"
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003183 */
3184 static char_u *
3185get_complete_funcname(int type)
3186{
3187 switch (type)
3188 {
3189 case CTRL_X_FUNCTION:
3190 return curbuf->b_p_cfu;
3191 case CTRL_X_OMNI:
3192 return curbuf->b_p_ofu;
3193 case CTRL_X_THESAURUS:
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01003194 return *curbuf->b_p_tsrfu == NUL ? p_tsrfu : curbuf->b_p_tsrfu;
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003195 default:
3196 return (char_u *)"";
3197 }
3198}
3199
3200/*
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003201 * Get the callback to use for insert mode completion.
3202 */
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003203 static callback_T *
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003204get_insert_callback(int type)
3205{
3206 if (type == CTRL_X_FUNCTION)
3207 return &curbuf->b_cfu_cb;
3208 if (type == CTRL_X_OMNI)
3209 return &curbuf->b_ofu_cb;
3210 // CTRL_X_THESAURUS
3211 return (*curbuf->b_p_tsrfu != NUL) ? &curbuf->b_tsrfu_cb : &tsrfu_cb;
3212}
3213
3214/*
Yegappan Lakshmanan05e59e32021-12-01 10:30:07 +00003215 * Execute user defined complete function 'completefunc', 'omnifunc' or
3216 * 'thesaurusfunc', and get matches in "matches".
Girish Palyacbe53192025-04-14 22:13:15 +02003217 * "type" can be one of CTRL_X_OMNI, CTRL_X_FUNCTION, or CTRL_X_THESAURUS.
3218 * Callback function "cb" is set if triggered by a function in the 'cpt'
3219 * option; otherwise, it is NULL.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003220 */
3221 static void
Girish Palyacbe53192025-04-14 22:13:15 +02003222expand_by_function(int type, char_u *base, callback_T *cb)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003223{
3224 list_T *matchlist = NULL;
3225 dict_T *matchdict = NULL;
3226 typval_T args[3];
3227 char_u *funcname;
3228 pos_T pos;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003229 typval_T rettv;
3230 int save_State = State;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003231 int retval;
Girish Palyacbe53192025-04-14 22:13:15 +02003232 int is_cpt_function = (cb != NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003233
Girish Palyacbe53192025-04-14 22:13:15 +02003234 if (!is_cpt_function)
3235 {
3236 funcname = get_complete_funcname(type);
3237 if (*funcname == NUL)
3238 return;
3239 cb = get_insert_callback(type);
3240 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003241
3242 // Call 'completefunc' to obtain the list of matches.
3243 args[0].v_type = VAR_NUMBER;
3244 args[0].vval.v_number = 0;
3245 args[1].v_type = VAR_STRING;
3246 args[1].vval.v_string = base != NULL ? base : (char_u *)"";
3247 args[2].v_type = VAR_UNKNOWN;
3248
3249 pos = curwin->w_cursor;
Bram Moolenaar28976e22021-01-29 21:07:07 +01003250 // Lock the text to avoid weird things from happening. Also disallow
3251 // switching to another window, it should not be needed and may end up in
3252 // Insert mode in another buffer.
zeertzjqcfe45652022-05-27 17:26:55 +01003253 ++textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003254
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003255 retval = call_callback(cb, 0, &rettv, 2, args);
3256
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003257 // Call a function, which returns a list or dict.
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003258 if (retval == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003259 {
3260 switch (rettv.v_type)
3261 {
3262 case VAR_LIST:
3263 matchlist = rettv.vval.v_list;
3264 break;
3265 case VAR_DICT:
3266 matchdict = rettv.vval.v_dict;
3267 break;
3268 case VAR_SPECIAL:
3269 if (rettv.vval.v_number == VVAL_NONE)
3270 compl_opt_suppress_empty = TRUE;
3271 // FALLTHROUGH
3272 default:
3273 // TODO: Give error message?
3274 clear_tv(&rettv);
3275 break;
3276 }
3277 }
zeertzjqcfe45652022-05-27 17:26:55 +01003278 --textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003279
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003280 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02003281 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003282 validate_cursor();
3283 if (!EQUAL_POS(curwin->w_cursor, pos))
3284 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00003285 emsg(_(e_complete_function_deleted_text));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003286 goto theend;
3287 }
3288
3289 if (matchlist != NULL)
3290 ins_compl_add_list(matchlist);
3291 else if (matchdict != NULL)
3292 ins_compl_add_dict(matchdict);
3293
3294theend:
3295 // Restore State, it might have been changed.
3296 State = save_State;
3297
3298 if (matchdict != NULL)
3299 dict_unref(matchdict);
3300 if (matchlist != NULL)
3301 list_unref(matchlist);
3302}
3303#endif // FEAT_COMPL_FUNC
3304
3305#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL) || defined(PROTO)
glepnir38f99a12024-08-23 18:31:06 +02003306
3307 static inline int
3308get_user_highlight_attr(char_u *hlname)
3309{
3310 if (hlname != NULL && *hlname != NUL)
Hirohito Higashi355db992025-04-28 18:07:02 +02003311 return syn_name2attr(hlname);
glepnir38f99a12024-08-23 18:31:06 +02003312 return -1;
3313}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003314/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003315 * Add a match to the list of matches from a typeval_T.
3316 * If the given string is already in the list of completions, then return
3317 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
3318 * maybe because alloc() returns NULL, then FAIL is returned.
Bram Moolenaar440cf092021-04-03 20:13:30 +02003319 * When "fast" is TRUE use fast_breakcheck() instead of ui_breakcheck().
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003320 */
3321 static int
Bram Moolenaar440cf092021-04-03 20:13:30 +02003322ins_compl_add_tv(typval_T *tv, int dir, int fast)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003323{
3324 char_u *word;
3325 int dup = FALSE;
3326 int empty = FALSE;
Bram Moolenaar440cf092021-04-03 20:13:30 +02003327 int flags = fast ? CP_FAST : 0;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003328 char_u *(cptext[CPT_COUNT]);
Bram Moolenaar08928322020-01-04 14:32:48 +01003329 typval_T user_data;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003330 int status;
glepnir0fe17f82024-10-08 22:26:44 +02003331 char_u *user_abbr_hlname;
glepnir38f99a12024-08-23 18:31:06 +02003332 char_u *user_kind_hlname;
glepnir80b66202024-11-27 21:53:53 +01003333 int user_hl[2] = { -1, -1 };
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003334
Bram Moolenaar08928322020-01-04 14:32:48 +01003335 user_data.v_type = VAR_UNKNOWN;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003336 if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL)
3337 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01003338 word = dict_get_string(tv->vval.v_dict, "word", FALSE);
3339 cptext[CPT_ABBR] = dict_get_string(tv->vval.v_dict, "abbr", FALSE);
3340 cptext[CPT_MENU] = dict_get_string(tv->vval.v_dict, "menu", FALSE);
3341 cptext[CPT_KIND] = dict_get_string(tv->vval.v_dict, "kind", FALSE);
3342 cptext[CPT_INFO] = dict_get_string(tv->vval.v_dict, "info", FALSE);
glepnir38f99a12024-08-23 18:31:06 +02003343
glepnir0fe17f82024-10-08 22:26:44 +02003344 user_abbr_hlname = dict_get_string(tv->vval.v_dict, "abbr_hlgroup", FALSE);
glepnir80b66202024-11-27 21:53:53 +01003345 user_hl[0] = get_user_highlight_attr(user_abbr_hlname);
glepnir38f99a12024-08-23 18:31:06 +02003346
3347 user_kind_hlname = dict_get_string(tv->vval.v_dict, "kind_hlgroup", FALSE);
glepnir80b66202024-11-27 21:53:53 +01003348 user_hl[1] = get_user_highlight_attr(user_kind_hlname);
glepnir508e7852024-07-25 21:39:08 +02003349
Bram Moolenaard61efa52022-07-23 09:52:04 +01003350 dict_get_tv(tv->vval.v_dict, "user_data", &user_data);
3351 if (dict_get_string(tv->vval.v_dict, "icase", FALSE) != NULL
3352 && dict_get_number(tv->vval.v_dict, "icase"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003353 flags |= CP_ICASE;
Bram Moolenaard61efa52022-07-23 09:52:04 +01003354 if (dict_get_string(tv->vval.v_dict, "dup", FALSE) != NULL)
3355 dup = dict_get_number(tv->vval.v_dict, "dup");
3356 if (dict_get_string(tv->vval.v_dict, "empty", FALSE) != NULL)
3357 empty = dict_get_number(tv->vval.v_dict, "empty");
3358 if (dict_get_string(tv->vval.v_dict, "equal", FALSE) != NULL
3359 && dict_get_number(tv->vval.v_dict, "equal"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003360 flags |= CP_EQUAL;
3361 }
3362 else
3363 {
3364 word = tv_get_string_chk(tv);
Bram Moolenaara80faa82020-04-12 19:37:17 +02003365 CLEAR_FIELD(cptext);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003366 }
3367 if (word == NULL || (!empty && *word == NUL))
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003368 {
3369 clear_tv(&user_data);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003370 return FAIL;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003371 }
glepnir508e7852024-07-25 21:39:08 +02003372 status = ins_compl_add(word, -1, NULL, cptext,
glepnirf31cfa22025-03-06 21:59:13 +01003373 &user_data, dir, flags, dup, user_hl, 0);
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003374 if (status != OK)
3375 clear_tv(&user_data);
3376 return status;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003377}
3378
3379/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003380 * Add completions from a list.
3381 */
3382 static void
3383ins_compl_add_list(list_T *list)
3384{
3385 listitem_T *li;
3386 int dir = compl_direction;
3387
3388 // Go through the List with matches and add each of them.
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003389 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003390 FOR_ALL_LIST_ITEMS(list, li)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003391 {
Bram Moolenaar440cf092021-04-03 20:13:30 +02003392 if (ins_compl_add_tv(&li->li_tv, dir, TRUE) == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003393 // if dir was BACKWARD then honor it just once
3394 dir = FORWARD;
3395 else if (did_emsg)
3396 break;
3397 }
3398}
3399
3400/*
3401 * Add completions from a dict.
3402 */
3403 static void
3404ins_compl_add_dict(dict_T *dict)
3405{
3406 dictitem_T *di_refresh;
3407 dictitem_T *di_words;
3408
3409 // Check for optional "refresh" item.
3410 compl_opt_refresh_always = FALSE;
3411 di_refresh = dict_find(dict, (char_u *)"refresh", 7);
3412 if (di_refresh != NULL && di_refresh->di_tv.v_type == VAR_STRING)
3413 {
3414 char_u *v = di_refresh->di_tv.vval.v_string;
3415
3416 if (v != NULL && STRCMP(v, (char_u *)"always") == 0)
3417 compl_opt_refresh_always = TRUE;
3418 }
3419
3420 // Add completions from a "words" list.
3421 di_words = dict_find(dict, (char_u *)"words", 5);
3422 if (di_words != NULL && di_words->di_tv.v_type == VAR_LIST)
3423 ins_compl_add_list(di_words->di_tv.vval.v_list);
3424}
3425
3426/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003427 * Start completion for the complete() function.
3428 * "startcol" is where the matched text starts (1 is first column).
3429 * "list" is the list of matches.
3430 */
3431 static void
3432set_completion(colnr_T startcol, list_T *list)
3433{
3434 int save_w_wrow = curwin->w_wrow;
3435 int save_w_leftcol = curwin->w_leftcol;
3436 int flags = CP_ORIGINAL_TEXT;
zeertzjqaa925ee2024-06-09 18:24:05 +02003437 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02003438 int compl_longest = (cur_cot_flags & COT_LONGEST) != 0;
3439 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
3440 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003441
3442 // If already doing completions stop it.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003443 if (ctrl_x_mode_not_default())
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003444 ins_compl_prep(' ');
3445 ins_compl_clear();
3446 ins_compl_free();
bfredl87af60c2022-09-24 11:17:51 +01003447 compl_get_longest = compl_longest;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003448
3449 compl_direction = FORWARD;
3450 if (startcol > curwin->w_cursor.col)
3451 startcol = curwin->w_cursor.col;
3452 compl_col = startcol;
glepnir76bdb822025-02-08 19:04:51 +01003453 compl_lnum = curwin->w_cursor.lnum;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003454 compl_length = (int)curwin->w_cursor.col - (int)startcol;
3455 // compl_pattern doesn't need to be set
glepniredd4ac32025-01-29 18:53:51 +01003456 compl_orig_text.string = vim_strnsave(ml_get_curline() + compl_col,
3457 (size_t)compl_length);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003458 if (p_ic)
3459 flags |= CP_ICASE;
John Marriott5e6ea922024-11-23 14:01:57 +01003460 if (compl_orig_text.string == NULL)
3461 {
3462 compl_orig_text.length = 0;
3463 return;
3464 }
3465 compl_orig_text.length = (size_t)compl_length;
3466 if (ins_compl_add(compl_orig_text.string,
Hirohito Higashi355db992025-04-28 18:07:02 +02003467 (int)compl_orig_text.length, NULL, NULL, NULL, 0,
3468 flags | CP_FAST, FALSE, NULL, 0) != OK)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003469 return;
3470
3471 ctrl_x_mode = CTRL_X_EVAL;
3472
3473 ins_compl_add_list(list);
3474 compl_matches = ins_compl_make_cyclic();
3475 compl_started = TRUE;
3476 compl_used_match = TRUE;
3477 compl_cont_status = 0;
3478
3479 compl_curr_match = compl_first_match;
bfredl87af60c2022-09-24 11:17:51 +01003480 int no_select = compl_no_select || compl_longest;
3481 if (compl_no_insert || no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003482 {
3483 ins_complete(K_DOWN, FALSE);
bfredl87af60c2022-09-24 11:17:51 +01003484 if (no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003485 // Down/Up has no real effect.
3486 ins_complete(K_UP, FALSE);
3487 }
3488 else
3489 ins_complete(Ctrl_N, FALSE);
3490 compl_enter_selects = compl_no_insert;
3491
3492 // Lazily show the popup menu, unless we got interrupted.
3493 if (!compl_interrupted)
3494 show_pum(save_w_wrow, save_w_leftcol);
LemonBoy2bf52dd2022-04-09 18:17:34 +01003495 may_trigger_modechanged();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003496 out_flush();
3497}
3498
3499/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003500 * "complete()" function
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003501 */
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003502 void
3503f_complete(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003504{
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003505 if (in_vim9script()
3506 && (check_for_number_arg(argvars, 0) == FAIL
3507 || check_for_list_arg(argvars, 1) == FAIL))
3508 return;
3509
Bram Moolenaar24959102022-05-07 20:01:16 +01003510 if ((State & MODE_INSERT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003511 {
Bram Moolenaar677658a2022-01-05 16:09:06 +00003512 emsg(_(e_complete_can_only_be_used_in_insert_mode));
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003513 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003514 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003515
3516 // Check for undo allowed here, because if something was already inserted
3517 // the line was already saved for undo and this check isn't done.
3518 if (!undo_allowed())
3519 return;
3520
Bram Moolenaard83392a2022-09-01 12:22:46 +01003521 if (check_for_nonnull_list_arg(argvars, 1) != FAIL)
Bram Moolenaarff06f282020-04-21 22:01:14 +02003522 {
glepnir19e1dd62025-05-08 22:50:38 +02003523 int startcol = (int)tv_get_number_chk(&argvars[0], NULL);
Bram Moolenaarff06f282020-04-21 22:01:14 +02003524 if (startcol > 0)
3525 set_completion(startcol - 1, argvars[1].vval.v_list);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003526 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003527}
3528
3529/*
3530 * "complete_add()" function
3531 */
3532 void
3533f_complete_add(typval_T *argvars, typval_T *rettv)
3534{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003535 if (in_vim9script() && check_for_string_or_dict_arg(argvars, 0) == FAIL)
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003536 return;
3537
Bram Moolenaar440cf092021-04-03 20:13:30 +02003538 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0, FALSE);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003539}
3540
3541/*
3542 * "complete_check()" function
3543 */
3544 void
3545f_complete_check(typval_T *argvars UNUSED, typval_T *rettv)
3546{
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003547 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003548 RedrawingDisabled = 0;
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003549
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003550 ins_compl_check_keys(0, TRUE);
3551 rettv->vval.v_number = ins_compl_interrupted();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003552
3553 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003554}
3555
3556/*
glepnirbcd59952025-04-24 21:48:35 +02003557 * Add match item to the return list.
3558 * Returns FAIL if out of memory, OK otherwise.
3559 */
3560 static int
3561add_match_to_list(
3562 typval_T *rettv,
3563 char_u *str,
3564 int len,
3565 int pos)
3566{
3567 list_T *match;
3568 int ret;
3569
3570 match = list_alloc();
3571 if (match == NULL)
Hirohito Higashi355db992025-04-28 18:07:02 +02003572 return FAIL;
glepnirbcd59952025-04-24 21:48:35 +02003573
3574 if ((ret = list_append_number(match, pos + 1)) == FAIL
3575 || (ret = list_append_string(match, str, len)) == FAIL
3576 || (ret = list_append_list(rettv->vval.v_list, match)) == FAIL)
3577 {
Hirohito Higashi355db992025-04-28 18:07:02 +02003578 vim_free(match);
3579 return FAIL;
glepnirbcd59952025-04-24 21:48:35 +02003580 }
3581
3582 return OK;
3583}
3584
3585/*
3586 * "complete_match()" function
3587 */
3588 void
3589f_complete_match(typval_T *argvars, typval_T *rettv)
3590{
3591 linenr_T lnum;
3592 colnr_T col;
3593 char_u *line = NULL;
3594 char_u *ise = NULL;
3595 regmatch_T regmatch;
3596 char_u *before_cursor = NULL;
3597 char_u *cur_end = NULL;
glepnirbcd59952025-04-24 21:48:35 +02003598 int bytepos = 0;
3599 char_u part[MAXPATHL];
3600 int ret;
3601
3602 if (rettv_list_alloc(rettv) == FAIL)
3603 return;
3604
3605 ise = curbuf->b_p_ise[0] != NUL ? curbuf->b_p_ise : p_ise;
3606
3607 if (argvars[0].v_type == VAR_UNKNOWN)
3608 {
3609 lnum = curwin->w_cursor.lnum;
3610 col = curwin->w_cursor.col;
3611 }
3612 else if (argvars[1].v_type == VAR_UNKNOWN)
3613 {
3614 emsg(_(e_invalid_argument));
3615 return;
3616 }
3617 else
3618 {
3619 lnum = (linenr_T)tv_get_number(&argvars[0]);
3620 col = (colnr_T)tv_get_number(&argvars[1]);
3621 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
3622 {
3623 semsg(_(e_invalid_line_number_nr), lnum);
3624 return;
3625 }
3626 if (col < 1 || col > ml_get_buf_len(curbuf, lnum))
3627 {
3628 semsg(_(e_invalid_column_number_nr), col + 1);
3629 return;
3630 }
3631 }
3632
3633 line = ml_get_buf(curbuf, lnum, FALSE);
3634 if (line == NULL)
3635 return;
3636
3637 before_cursor = vim_strnsave(line, col);
3638 if (before_cursor == NULL)
3639 return;
3640
3641 if (ise == NULL || *ise == NUL)
3642 {
3643 regmatch.regprog = vim_regcomp((char_u *)"\\k\\+$", RE_MAGIC);
3644 if (regmatch.regprog != NULL)
3645 {
3646 if (vim_regexec_nl(&regmatch, before_cursor, (colnr_T)0))
3647 {
Christian Brabandt3accf042025-04-25 19:01:06 +02003648 char_u *trig = vim_strnsave(regmatch.startp[0],
glepnirbcd59952025-04-24 21:48:35 +02003649 regmatch.endp[0] - regmatch.startp[0]);
3650 if (trig == NULL)
3651 {
3652 vim_free(before_cursor);
Christian Brabandt3accf042025-04-25 19:01:06 +02003653 vim_regfree(regmatch.regprog);
glepnirbcd59952025-04-24 21:48:35 +02003654 return;
3655 }
3656
Christian Brabandt3accf042025-04-25 19:01:06 +02003657 bytepos = (int)(regmatch.startp[0] - before_cursor);
glepnirbcd59952025-04-24 21:48:35 +02003658 ret = add_match_to_list(rettv, trig, -1, bytepos);
3659 vim_free(trig);
3660 if (ret == FAIL)
3661 {
Christian Brabandt3accf042025-04-25 19:01:06 +02003662 vim_free(before_cursor);
glepnirbcd59952025-04-24 21:48:35 +02003663 vim_regfree(regmatch.regprog);
3664 return;
3665 }
3666 }
3667 vim_regfree(regmatch.regprog);
3668 }
3669 }
3670 else
3671 {
glepnir08db2f42025-05-14 20:26:19 +02003672 char_u *p = ise;
3673 char_u *p_space = NULL;
3674
glepnirbcd59952025-04-24 21:48:35 +02003675 cur_end = before_cursor + (int)STRLEN(before_cursor);
3676
3677 while (*p != NUL)
3678 {
glepnir8d0e42b2025-05-12 20:28:28 +02003679 int len = 0;
glepnir08db2f42025-05-14 20:26:19 +02003680 if (p_space)
glepnir8d0e42b2025-05-12 20:28:28 +02003681 {
glepnir08db2f42025-05-14 20:26:19 +02003682 len = p - p_space - 1;
3683 memcpy(part, p_space + 1, len);
3684 p_space = NULL;
glepnir8d0e42b2025-05-12 20:28:28 +02003685 }
3686 else
glepnir08db2f42025-05-14 20:26:19 +02003687 {
3688 char_u *next_comma = vim_strchr((*p == ',') ? p + 1 : p, ',');
3689 if (next_comma && *(next_comma + 1) == ' ')
3690 p_space = next_comma;
3691
glepnir8d0e42b2025-05-12 20:28:28 +02003692 len = copy_option_part(&p, part, MAXPATHL, ",");
glepnir08db2f42025-05-14 20:26:19 +02003693 }
glepnirbcd59952025-04-24 21:48:35 +02003694
3695 if (len > 0 && len <= col)
3696 {
3697 if (STRNCMP(cur_end - len, part, len) == 0)
3698 {
3699 bytepos = col - len;
3700 if (add_match_to_list(rettv, part, len, bytepos) == FAIL)
3701 {
3702 vim_free(before_cursor);
3703 return;
3704 }
3705 }
3706 }
3707 }
3708 }
3709
3710 vim_free(before_cursor);
3711}
3712
3713/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003714 * Return Insert completion mode name string
3715 */
3716 static char_u *
3717ins_compl_mode(void)
3718{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003719 if (ctrl_x_mode_not_defined_yet() || ctrl_x_mode_scroll() || compl_started)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003720 return (char_u *)ctrl_x_mode_names[ctrl_x_mode & ~CTRL_X_WANT_IDENT];
3721
3722 return (char_u *)"";
3723}
3724
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00003725/*
3726 * Assign the sequence number to all the completion matches which don't have
3727 * one assigned yet.
3728 */
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003729 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003730ins_compl_update_sequence_numbers(void)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003731{
3732 int number = 0;
3733 compl_T *match;
3734
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003735 if (compl_dir_forward())
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003736 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003737 // Search backwards for the first valid (!= -1) number.
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003738 // This should normally succeed already at the first loop
3739 // cycle, so it's fast!
3740 for (match = compl_curr_match->cp_prev; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003741 && !is_first_match(match); match = match->cp_prev)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003742 if (match->cp_number != -1)
3743 {
3744 number = match->cp_number;
3745 break;
3746 }
3747 if (match != NULL)
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003748 // go up and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003749 for (match = match->cp_next;
3750 match != NULL && match->cp_number == -1;
3751 match = match->cp_next)
3752 match->cp_number = ++number;
3753 }
3754 else // BACKWARD
3755 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003756 // Search forwards (upwards) for the first valid (!= -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003757 // number. This should normally succeed already at the
3758 // first loop cycle, so it's fast!
3759 for (match = compl_curr_match->cp_next; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003760 && !is_first_match(match); match = match->cp_next)
glepnir40891ba2025-02-10 22:18:00 +01003761 {
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003762 if (match->cp_number != -1)
3763 {
3764 number = match->cp_number;
3765 break;
3766 }
glepnir40891ba2025-02-10 22:18:00 +01003767 }
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003768 if (match != NULL)
glepnir40891ba2025-02-10 22:18:00 +01003769 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003770 // go down and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003771 for (match = match->cp_prev; match
3772 && match->cp_number == -1;
3773 match = match->cp_prev)
3774 match->cp_number = ++number;
glepnir40891ba2025-02-10 22:18:00 +01003775 }
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003776 }
3777}
3778
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003779/*
glepnir037b0282025-01-16 14:37:44 +01003780 * Fill the dict of complete_info
3781 */
3782 static void
3783fill_complete_info_dict(dict_T *di, compl_T *match, int add_match)
3784{
3785 dict_add_string(di, "word", match->cp_str.string);
3786 dict_add_string(di, "abbr", match->cp_text[CPT_ABBR]);
3787 dict_add_string(di, "menu", match->cp_text[CPT_MENU]);
3788 dict_add_string(di, "kind", match->cp_text[CPT_KIND]);
3789 dict_add_string(di, "info", match->cp_text[CPT_INFO]);
3790 if (add_match)
Hirohito Higashi355db992025-04-28 18:07:02 +02003791 dict_add_bool(di, "match", match->cp_in_match_array);
glepnir037b0282025-01-16 14:37:44 +01003792 if (match->cp_user_data.v_type == VAR_UNKNOWN)
Hirohito Higashi355db992025-04-28 18:07:02 +02003793 // Add an empty string for backwards compatibility
3794 dict_add_string(di, "user_data", (char_u *)"");
glepnir037b0282025-01-16 14:37:44 +01003795 else
Hirohito Higashi355db992025-04-28 18:07:02 +02003796 dict_add_tv(di, "user_data", &match->cp_user_data);
glepnir037b0282025-01-16 14:37:44 +01003797}
3798
3799/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003800 * Get complete information
3801 */
3802 static void
3803get_complete_info(list_T *what_list, dict_T *retdict)
3804{
3805 int ret = OK;
3806 listitem_T *item;
3807#define CI_WHAT_MODE 0x01
3808#define CI_WHAT_PUM_VISIBLE 0x02
3809#define CI_WHAT_ITEMS 0x04
3810#define CI_WHAT_SELECTED 0x08
glepnir037b0282025-01-16 14:37:44 +01003811#define CI_WHAT_COMPLETED 0x10
glepnird4088ed2024-12-31 10:55:22 +01003812#define CI_WHAT_MATCHES 0x20
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003813#define CI_WHAT_ALL 0xff
3814 int what_flag;
3815
3816 if (what_list == NULL)
glepnir037b0282025-01-16 14:37:44 +01003817 what_flag = CI_WHAT_ALL & ~(CI_WHAT_MATCHES | CI_WHAT_COMPLETED);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003818 else
3819 {
3820 what_flag = 0;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003821 CHECK_LIST_MATERIALIZE(what_list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003822 FOR_ALL_LIST_ITEMS(what_list, item)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003823 {
3824 char_u *what = tv_get_string(&item->li_tv);
3825
3826 if (STRCMP(what, "mode") == 0)
3827 what_flag |= CI_WHAT_MODE;
3828 else if (STRCMP(what, "pum_visible") == 0)
3829 what_flag |= CI_WHAT_PUM_VISIBLE;
3830 else if (STRCMP(what, "items") == 0)
3831 what_flag |= CI_WHAT_ITEMS;
3832 else if (STRCMP(what, "selected") == 0)
3833 what_flag |= CI_WHAT_SELECTED;
glepnir037b0282025-01-16 14:37:44 +01003834 else if (STRCMP(what, "completed") == 0)
3835 what_flag |= CI_WHAT_COMPLETED;
glepnird4088ed2024-12-31 10:55:22 +01003836 else if (STRCMP(what, "matches") == 0)
3837 what_flag |= CI_WHAT_MATCHES;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003838 }
3839 }
3840
3841 if (ret == OK && (what_flag & CI_WHAT_MODE))
3842 ret = dict_add_string(retdict, "mode", ins_compl_mode());
3843
3844 if (ret == OK && (what_flag & CI_WHAT_PUM_VISIBLE))
3845 ret = dict_add_number(retdict, "pum_visible", pum_visible());
3846
glepnir037b0282025-01-16 14:37:44 +01003847 if (ret == OK && (what_flag & (CI_WHAT_ITEMS | CI_WHAT_SELECTED
3848 | CI_WHAT_MATCHES | CI_WHAT_COMPLETED)))
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003849 {
Christian Brabandt9eb236f2024-03-21 20:12:59 +01003850 list_T *li = NULL;
Girish Palya8950bf72024-03-20 20:07:29 +01003851 dict_T *di;
3852 compl_T *match;
3853 int selected_idx = -1;
glepnird4088ed2024-12-31 10:55:22 +01003854 int has_items = what_flag & CI_WHAT_ITEMS;
3855 int has_matches = what_flag & CI_WHAT_MATCHES;
glepnir037b0282025-01-16 14:37:44 +01003856 int has_completed = what_flag & CI_WHAT_COMPLETED;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003857
glepnird4088ed2024-12-31 10:55:22 +01003858 if (has_items || has_matches)
Girish Palya8950bf72024-03-20 20:07:29 +01003859 {
3860 li = list_alloc();
3861 if (li == NULL)
3862 return;
glepnird4088ed2024-12-31 10:55:22 +01003863 ret = dict_add_list(retdict, (has_matches && !has_items)
3864 ? "matches" : "items", li);
Girish Palya8950bf72024-03-20 20:07:29 +01003865 }
3866 if (ret == OK && what_flag & CI_WHAT_SELECTED)
3867 if (compl_curr_match != NULL && compl_curr_match->cp_number == -1)
3868 ins_compl_update_sequence_numbers();
3869 if (ret == OK && compl_first_match != NULL)
3870 {
3871 int list_idx = 0;
3872 match = compl_first_match;
3873 do
3874 {
3875 if (!match_at_original_text(match))
3876 {
glepnird4088ed2024-12-31 10:55:22 +01003877 if (has_items
3878 || (has_matches && match->cp_in_match_array))
Girish Palya8950bf72024-03-20 20:07:29 +01003879 {
3880 di = dict_alloc();
3881 if (di == NULL)
3882 return;
3883 ret = list_append_dict(li, di);
3884 if (ret != OK)
3885 return;
glepnir037b0282025-01-16 14:37:44 +01003886 fill_complete_info_dict(di, match, has_matches && has_items);
Girish Palya8950bf72024-03-20 20:07:29 +01003887 }
glepnird4088ed2024-12-31 10:55:22 +01003888 if (compl_curr_match != NULL
3889 && compl_curr_match->cp_number == match->cp_number)
Girish Palya8950bf72024-03-20 20:07:29 +01003890 selected_idx = list_idx;
Girish Palya8cd42a52025-06-05 21:04:29 +02003891 if (match->cp_in_match_array)
Girish Palya0ac1eb32025-04-16 20:18:33 +02003892 list_idx += 1;
Girish Palya8950bf72024-03-20 20:07:29 +01003893 }
3894 match = match->cp_next;
3895 }
3896 while (match != NULL && !is_first_match(match));
3897 }
3898 if (ret == OK && (what_flag & CI_WHAT_SELECTED))
3899 ret = dict_add_number(retdict, "selected", selected_idx);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003900
glepnir037b0282025-01-16 14:37:44 +01003901 if (ret == OK && selected_idx != -1 && has_completed)
3902 {
3903 di = dict_alloc();
3904 if (di == NULL)
3905 return;
3906 fill_complete_info_dict(di, compl_curr_match, FALSE);
3907 ret = dict_add_dict(retdict, "completed", di);
3908 }
Yegappan Lakshmanan6b085b92022-09-04 12:47:21 +01003909 }
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003910}
3911
3912/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003913 * "complete_info()" function
3914 */
3915 void
3916f_complete_info(typval_T *argvars, typval_T *rettv)
3917{
3918 list_T *what_list = NULL;
3919
Bram Moolenaar93a10962022-06-16 11:42:09 +01003920 if (rettv_dict_alloc(rettv) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003921 return;
3922
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003923 if (in_vim9script() && check_for_opt_list_arg(argvars, 0) == FAIL)
3924 return;
3925
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003926 if (argvars[0].v_type != VAR_UNKNOWN)
3927 {
Bram Moolenaard83392a2022-09-01 12:22:46 +01003928 if (check_for_list_arg(argvars, 0) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003929 return;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003930 what_list = argvars[0].vval.v_list;
3931 }
3932 get_complete_info(what_list, rettv->vval.v_dict);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003933}
3934#endif
3935
3936/*
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003937 * Returns TRUE when using a user-defined function for thesaurus completion.
3938 */
3939 static int
3940thesaurus_func_complete(int type UNUSED)
3941{
3942#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01003943 return type == CTRL_X_THESAURUS
3944 && (*curbuf->b_p_tsrfu != NUL || *p_tsrfu != NUL);
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003945#else
3946 return FALSE;
3947#endif
3948}
3949
3950/*
Girish Palya7c621052025-05-26 19:41:59 +02003951 * Check if 'cpt' list index can be advanced to the next completion source.
3952 */
3953 static int
3954may_advance_cpt_index(char_u *cpt)
3955{
3956 char_u *p = cpt;
3957
Girish Palya98c29db2025-06-01 19:40:00 +02003958 if (cpt_sources_index == -1)
3959 return FALSE;
Girish Palya7c621052025-05-26 19:41:59 +02003960 while (*p == ',' || *p == ' ') // Skip delimiters
3961 p++;
3962 return (*p != NUL);
3963}
3964
3965/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003966 * Return value of process_next_cpt_value()
3967 */
3968enum
3969{
3970 INS_COMPL_CPT_OK = 1,
3971 INS_COMPL_CPT_CONT,
3972 INS_COMPL_CPT_END
3973};
3974
3975/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003976 * state information used for getting the next set of insert completion
3977 * matches.
3978 */
3979typedef struct
3980{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003981 char_u *e_cpt_copy; // copy of 'complete'
3982 char_u *e_cpt; // current entry in "e_cpt_copy"
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003983 buf_T *ins_buf; // buffer being scanned
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003984 pos_T *cur_match_pos; // current match position
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003985 pos_T prev_match_pos; // previous match position
3986 int set_match_pos; // save first_match_pos/last_match_pos
3987 pos_T first_match_pos; // first match position
3988 pos_T last_match_pos; // last match position
3989 int found_all; // found all matches of a certain type.
3990 char_u *dict; // dictionary file to search
3991 int dict_f; // "dict" is an exact file name or not
Girish Palyacbe53192025-04-14 22:13:15 +02003992 callback_T *func_cb; // callback of function in 'cpt' option
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003993} ins_compl_next_state_T;
3994
3995/*
3996 * Process the next 'complete' option value in st->e_cpt.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003997 *
3998 * If successful, the arguments are set as below:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003999 * st->cpt - pointer to the next option value in "st->cpt"
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004000 * compl_type_arg - type of insert mode completion to use
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004001 * st->found_all - all matches of this type are found
4002 * st->ins_buf - search for completions in this buffer
4003 * st->first_match_pos - position of the first completion match
4004 * st->last_match_pos - position of the last completion match
4005 * st->set_match_pos - TRUE if the first match position should be saved to
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01004006 * avoid loops after the search wraps around.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004007 * st->dict - name of the dictionary or thesaurus file to search
4008 * st->dict_f - flag specifying whether "dict" is an exact file name or not
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004009 *
4010 * Returns INS_COMPL_CPT_OK if the next value is processed successfully.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00004011 * Returns INS_COMPL_CPT_CONT to skip the current completion source matching
4012 * the "st->e_cpt" option value and process the next matching source.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004013 * Returns INS_COMPL_CPT_END if all the values in "st->e_cpt" are processed.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004014 */
4015 static int
4016process_next_cpt_value(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004017 ins_compl_next_state_T *st,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004018 int *compl_type_arg,
glepnir8159fb12024-07-17 20:32:54 +02004019 pos_T *start_match_pos,
Girish Palya7c621052025-05-26 19:41:59 +02004020 int fuzzy_collect,
4021 int *advance_cpt_idx)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004022{
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004023 int compl_type = -1;
4024 int status = INS_COMPL_CPT_OK;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004025
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004026 st->found_all = FALSE;
Girish Palya7c621052025-05-26 19:41:59 +02004027 *advance_cpt_idx = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004028
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004029 while (*st->e_cpt == ',' || *st->e_cpt == ' ')
4030 st->e_cpt++;
4031
4032 if (*st->e_cpt == '.' && !curbuf->b_scanned)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004033 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004034 st->ins_buf = curbuf;
4035 st->first_match_pos = *start_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004036 // Move the cursor back one character so that ^N can match the
4037 // word immediately after the cursor.
glepnir53b14572025-03-12 21:28:39 +01004038 if (ctrl_x_mode_normal() && (!fuzzy_collect && dec(&st->first_match_pos) < 0))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004039 {
4040 // Move the cursor to after the last character in the
4041 // buffer, so that word at start of buffer is found
4042 // correctly.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004043 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count;
zeertzjq94b7c322024-03-12 21:50:32 +01004044 st->first_match_pos.col = ml_get_len(st->first_match_pos.lnum);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004045 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004046 st->last_match_pos = st->first_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004047 compl_type = 0;
4048
4049 // Remember the first match so that the loop stops when we
4050 // wrap and come back there a second time.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004051 st->set_match_pos = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004052 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004053 else if (vim_strchr((char_u *)"buwU", *st->e_cpt) != NULL
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004054 && (st->ins_buf = ins_compl_next_buf(
4055 st->ins_buf, *st->e_cpt)) != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004056 {
4057 // Scan a buffer, but not the current one.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004058 if (st->ins_buf->b_ml.ml_mfp != NULL) // loaded buffer
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004059 {
4060 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004061 st->first_match_pos.col = st->last_match_pos.col = 0;
4062 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count + 1;
4063 st->last_match_pos.lnum = 0;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004064 compl_type = 0;
4065 }
4066 else // unloaded buffer, scan like dictionary
4067 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004068 st->found_all = TRUE;
4069 if (st->ins_buf->b_fname == NULL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004070 {
4071 status = INS_COMPL_CPT_CONT;
4072 goto done;
4073 }
4074 compl_type = CTRL_X_DICTIONARY;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004075 st->dict = st->ins_buf->b_fname;
4076 st->dict_f = DICT_EXACT;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004077 }
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01004078 if (!shortmess(SHM_COMPLETIONSCAN))
4079 {
4080 msg_hist_off = TRUE; // reset in msg_trunc_attr()
4081 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning: %s"),
4082 st->ins_buf->b_fname == NULL
4083 ? buf_spname(st->ins_buf)
4084 : st->ins_buf->b_sfname == NULL
4085 ? st->ins_buf->b_fname
4086 : st->ins_buf->b_sfname);
4087 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
4088 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004089 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004090 else if (*st->e_cpt == NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004091 status = INS_COMPL_CPT_END;
4092 else
4093 {
4094 if (ctrl_x_mode_line_or_eval())
4095 compl_type = -1;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004096 else if (*st->e_cpt == 'k' || *st->e_cpt == 's')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004097 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004098 if (*st->e_cpt == 'k')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004099 compl_type = CTRL_X_DICTIONARY;
4100 else
4101 compl_type = CTRL_X_THESAURUS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004102 if (*++st->e_cpt != ',' && *st->e_cpt != NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004103 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004104 st->dict = st->e_cpt;
4105 st->dict_f = DICT_FIRST;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004106 }
4107 }
Girish Palyacbe53192025-04-14 22:13:15 +02004108#ifdef FEAT_COMPL_FUNC
Girish Palya14f6da52025-05-26 19:04:25 +02004109 else if (*st->e_cpt == 'F' || *st->e_cpt == 'o')
Girish Palyacbe53192025-04-14 22:13:15 +02004110 {
4111 compl_type = CTRL_X_FUNCTION;
Girish Palya98c29db2025-06-01 19:40:00 +02004112 st->func_cb = get_callback_if_cpt_func(st->e_cpt);
Girish Palyacbe53192025-04-14 22:13:15 +02004113 if (!st->func_cb)
4114 compl_type = -1;
4115 }
4116#endif
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004117#ifdef FEAT_FIND_ID
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004118 else if (*st->e_cpt == 'i')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004119 compl_type = CTRL_X_PATH_PATTERNS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004120 else if (*st->e_cpt == 'd')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004121 compl_type = CTRL_X_PATH_DEFINES;
4122#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004123 else if (*st->e_cpt == ']' || *st->e_cpt == 't')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004124 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004125 compl_type = CTRL_X_TAGS;
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01004126 if (!shortmess(SHM_COMPLETIONSCAN))
4127 {
4128 msg_hist_off = TRUE; // reset in msg_trunc_attr()
4129 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning tags."));
4130 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
4131 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004132 }
4133 else
4134 compl_type = -1;
4135
4136 // in any case e_cpt is advanced to the next entry
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004137 (void)copy_option_part(&st->e_cpt, IObuff, IOSIZE, ",");
Girish Palya7c621052025-05-26 19:41:59 +02004138 *advance_cpt_idx = may_advance_cpt_index(st->e_cpt);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004139
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004140 st->found_all = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004141 if (compl_type == -1)
4142 status = INS_COMPL_CPT_CONT;
4143 }
4144
4145done:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004146 *compl_type_arg = compl_type;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004147 return status;
4148}
4149
4150#ifdef FEAT_FIND_ID
4151/*
4152 * Get the next set of identifiers or defines matching "compl_pattern" in
4153 * included files.
4154 */
4155 static void
4156get_next_include_file_completion(int compl_type)
4157{
John Marriott5e6ea922024-11-23 14:01:57 +01004158 find_pattern_in_path(compl_pattern.string, compl_direction,
4159 (int)compl_pattern.length, FALSE, FALSE,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004160 (compl_type == CTRL_X_PATH_DEFINES
4161 && !(compl_cont_status & CONT_SOL))
4162 ? FIND_DEFINE : FIND_ANY, 1L, ACTION_EXPAND,
Colin Kennedy21570352024-03-03 16:16:47 +01004163 (linenr_T)1, (linenr_T)MAXLNUM, FALSE);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004164}
4165#endif
4166
4167/*
4168 * Get the next set of words matching "compl_pattern" in dictionary or
4169 * thesaurus files.
4170 */
4171 static void
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004172get_next_dict_tsr_completion(int compl_type, char_u *dict, int dict_f)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004173{
4174#ifdef FEAT_COMPL_FUNC
4175 if (thesaurus_func_complete(compl_type))
Girish Palyacbe53192025-04-14 22:13:15 +02004176 expand_by_function(compl_type, compl_pattern.string, NULL);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004177 else
4178#endif
4179 ins_compl_dictionaries(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004180 dict != NULL ? dict
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004181 : (compl_type == CTRL_X_THESAURUS
4182 ? (*curbuf->b_p_tsr == NUL ? p_tsr : curbuf->b_p_tsr)
4183 : (*curbuf->b_p_dict == NUL ? p_dict : curbuf->b_p_dict)),
John Marriott5e6ea922024-11-23 14:01:57 +01004184 compl_pattern.string,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004185 dict != NULL ? dict_f : 0,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004186 compl_type == CTRL_X_THESAURUS);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004187}
4188
4189/*
4190 * Get the next set of tag names matching "compl_pattern".
4191 */
4192 static void
4193get_next_tag_completion(void)
4194{
4195 int save_p_ic;
4196 char_u **matches;
4197 int num_matches;
4198
4199 // set p_ic according to p_ic, p_scs and pat for find_tags().
4200 save_p_ic = p_ic;
John Marriott5e6ea922024-11-23 14:01:57 +01004201 p_ic = ignorecase(compl_pattern.string);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004202
4203 // Find up to TAG_MANY matches. Avoids that an enormous number
4204 // of matches is found when compl_pattern is empty
4205 g_tag_at_cursor = TRUE;
John Marriott5e6ea922024-11-23 14:01:57 +01004206 if (find_tags(compl_pattern.string, &num_matches, &matches,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004207 TAG_REGEXP | TAG_NAMES | TAG_NOIC | TAG_INS_COMP
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004208 | (ctrl_x_mode_not_default() ? TAG_VERBOSE : 0),
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004209 TAG_MANY, curbuf->b_ffname) == OK && num_matches > 0)
4210 ins_compl_add_matches(num_matches, matches, p_ic);
4211 g_tag_at_cursor = FALSE;
4212 p_ic = save_p_ic;
4213}
4214
4215/*
glepnir8159fb12024-07-17 20:32:54 +02004216 * Compare function for qsort
4217 */
glepnirf31cfa22025-03-06 21:59:13 +01004218 static int
4219compare_scores(const void *a, const void *b)
glepnir8159fb12024-07-17 20:32:54 +02004220{
4221 int idx_a = *(const int *)a;
4222 int idx_b = *(const int *)b;
4223 int score_a = compl_fuzzy_scores[idx_a];
4224 int score_b = compl_fuzzy_scores[idx_b];
zeertzjq58d70522024-08-31 17:05:39 +02004225 return score_a == score_b ? (idx_a == idx_b ? 0 : (idx_a < idx_b ? -1 : 1))
4226 : (score_a > score_b ? -1 : 1);
glepnir8159fb12024-07-17 20:32:54 +02004227}
4228
4229/*
glepnirf31cfa22025-03-06 21:59:13 +01004230 * insert prefix with redraw
4231 */
4232 static void
4233ins_compl_longest_insert(char_u *prefix)
4234{
4235 ins_compl_delete();
4236 ins_compl_insert_bytes(prefix + get_compl_len(), -1);
4237 ins_redraw(FALSE);
4238}
4239
4240/*
4241 * Calculate the longest common prefix among the best fuzzy matches
4242 * stored in compl_best_matches, and insert it as the longest.
4243 */
4244 static void
4245fuzzy_longest_match(void)
4246{
4247 char_u *prefix = NULL;
4248 int prefix_len = 0;
4249 int i = 0;
4250 int j = 0;
4251 char_u *match_str = NULL;
4252 char_u *prefix_ptr = NULL;
4253 char_u *match_ptr = NULL;
4254 char_u *leader = NULL;
4255 size_t leader_len = 0;
4256 compl_T *compl = NULL;
4257 int more_candidates = FALSE;
4258 compl_T *nn_compl = NULL;
4259
4260 if (compl_num_bests == 0)
Hirohito Higashi355db992025-04-28 18:07:02 +02004261 return;
glepnirf31cfa22025-03-06 21:59:13 +01004262
4263 nn_compl = compl_first_match->cp_next->cp_next;
4264 if (nn_compl && nn_compl != compl_first_match)
4265 more_candidates = TRUE;
4266
4267 compl = ctrl_x_mode_whole_line() ? compl_first_match
4268 : compl_first_match->cp_next;
4269 if (compl_num_bests == 1)
4270 {
4271 // no more candidates insert the match str
4272 if (!more_candidates)
4273 {
4274 ins_compl_longest_insert(compl->cp_str.string);
4275 compl_num_bests = 0;
4276 }
4277 compl_num_bests = 0;
4278 return;
4279 }
4280
4281 compl_best_matches = (compl_T **)alloc(compl_num_bests * sizeof(compl_T *));
4282 if (compl_best_matches == NULL)
Hirohito Higashi355db992025-04-28 18:07:02 +02004283 return;
glepnirf31cfa22025-03-06 21:59:13 +01004284 while (compl != NULL && i < compl_num_bests)
4285 {
Hirohito Higashi355db992025-04-28 18:07:02 +02004286 compl_best_matches[i] = compl;
4287 compl = compl->cp_next;
4288 i++;
glepnirf31cfa22025-03-06 21:59:13 +01004289 }
4290
4291 prefix = compl_best_matches[0]->cp_str.string;
zeertzjq4422de62025-03-07 19:06:02 +01004292 prefix_len = (int)compl_best_matches[0]->cp_str.length;
glepnirf31cfa22025-03-06 21:59:13 +01004293
4294 for (i = 1; i < compl_num_bests; i++)
4295 {
4296 match_str = compl_best_matches[i]->cp_str.string;
Hirohito Higashi355db992025-04-28 18:07:02 +02004297 prefix_ptr = prefix;
4298 match_ptr = match_str;
4299 j = 0;
glepnirf31cfa22025-03-06 21:59:13 +01004300
4301 while (j < prefix_len && *match_ptr != NUL && *prefix_ptr != NUL)
4302 {
4303 if (STRNCMP(prefix_ptr, match_ptr, mb_ptr2len(prefix_ptr)) != 0)
4304 break;
4305
4306 MB_PTR_ADV(prefix_ptr);
4307 MB_PTR_ADV(match_ptr);
4308 j++;
4309 }
4310
4311 if (j > 0)
4312 prefix_len = j;
4313 }
4314
4315 leader = ins_compl_leader();
zeertzjq4422de62025-03-07 19:06:02 +01004316 leader_len = ins_compl_leader_len();
glepnirf31cfa22025-03-06 21:59:13 +01004317
4318 // skip non-consecutive prefixes
zeertzjq4422de62025-03-07 19:06:02 +01004319 if (leader_len > 0 && STRNCMP(prefix, leader, leader_len) != 0)
glepnirf31cfa22025-03-06 21:59:13 +01004320 goto end;
4321
zeertzjq4422de62025-03-07 19:06:02 +01004322 prefix = vim_strnsave(prefix, prefix_len);
glepnirf31cfa22025-03-06 21:59:13 +01004323 if (prefix != NULL)
4324 {
4325 ins_compl_longest_insert(prefix);
4326 compl_cfc_longest_ins = TRUE;
4327 vim_free(prefix);
4328 }
4329
4330end:
4331 vim_free(compl_best_matches);
4332 compl_best_matches = NULL;
4333 compl_num_bests = 0;
4334}
4335
4336/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004337 * Get the next set of filename matching "compl_pattern".
4338 */
4339 static void
4340get_next_filename_completion(void)
4341{
4342 char_u **matches;
4343 int num_matches;
glepnir8159fb12024-07-17 20:32:54 +02004344 char_u *ptr;
4345 garray_T fuzzy_indices;
4346 int i;
4347 int score;
4348 char_u *leader = ins_compl_leader();
John Marriott5e6ea922024-11-23 14:01:57 +01004349 size_t leader_len = ins_compl_leader_len();;
glepnirf31cfa22025-03-06 21:59:13 +01004350 int in_fuzzy_collect = (cfc_has_mode() && leader_len > 0);
glepnir8159fb12024-07-17 20:32:54 +02004351 int *fuzzy_indices_data;
glepnir0be03e12024-07-19 16:45:05 +02004352 char_u *last_sep = NULL;
glepnirf31cfa22025-03-06 21:59:13 +01004353 int need_collect_bests = in_fuzzy_collect && compl_get_longest;
4354 int max_score = 0;
4355 int current_score = 0;
4356 int dir = compl_direction;
glepnir8159fb12024-07-17 20:32:54 +02004357
glepnirb9de1a02024-08-02 19:14:38 +02004358#ifdef BACKSLASH_IN_FILENAME
4359 char pathsep = (curbuf->b_p_csl[0] == 's') ?
4360 '/' : (curbuf->b_p_csl[0] == 'b') ? '\\' : PATHSEP;
4361#else
4362 char pathsep = PATHSEP;
4363#endif
4364
glepnirf31cfa22025-03-06 21:59:13 +01004365 if (in_fuzzy_collect)
glepnir8159fb12024-07-17 20:32:54 +02004366 {
glepnirb9de1a02024-08-02 19:14:38 +02004367#ifdef BACKSLASH_IN_FILENAME
4368 if (curbuf->b_p_csl[0] == 's')
4369 {
John Marriott5e6ea922024-11-23 14:01:57 +01004370 for (i = 0; i < (int)leader_len; i++)
glepnirb9de1a02024-08-02 19:14:38 +02004371 {
4372 if (leader[i] == '\\')
4373 leader[i] = '/';
4374 }
4375 }
4376 else if (curbuf->b_p_csl[0] == 'b')
4377 {
John Marriott5e6ea922024-11-23 14:01:57 +01004378 for (i = 0; i < (int)leader_len; i++)
glepnirb9de1a02024-08-02 19:14:38 +02004379 {
4380 if (leader[i] == '/')
4381 leader[i] = '\\';
4382 }
4383 }
4384#endif
4385 last_sep = vim_strrchr(leader, pathsep);
glepnir0be03e12024-07-19 16:45:05 +02004386 if (last_sep == NULL)
4387 {
4388 // No path separator or separator is the last character,
4389 // fuzzy match the whole leader
John Marriott5e6ea922024-11-23 14:01:57 +01004390 VIM_CLEAR_STRING(compl_pattern);
4391 compl_pattern.string = vim_strnsave((char_u *)"*", 1);
4392 if (compl_pattern.string == NULL)
4393 return;
4394 compl_pattern.length = 1;
glepnir0be03e12024-07-19 16:45:05 +02004395 }
4396 else if (*(last_sep + 1) == '\0')
glepnirf31cfa22025-03-06 21:59:13 +01004397 in_fuzzy_collect = FALSE;
glepnir0be03e12024-07-19 16:45:05 +02004398 else
4399 {
4400 // Split leader into path and file parts
4401 int path_len = last_sep - leader + 1;
John Marriott5e6ea922024-11-23 14:01:57 +01004402 char_u *path_with_wildcard;
4403
4404 path_with_wildcard = alloc(path_len + 2);
glepnir0be03e12024-07-19 16:45:05 +02004405 if (path_with_wildcard != NULL)
4406 {
John Marriott5e6ea922024-11-23 14:01:57 +01004407 vim_snprintf((char *)path_with_wildcard, path_len + 2, "%*.*s*", path_len, path_len, leader);
4408 VIM_CLEAR_STRING(compl_pattern);
4409 compl_pattern.string = path_with_wildcard;
4410 compl_pattern.length = path_len + 1;
glepnir0be03e12024-07-19 16:45:05 +02004411
4412 // Move leader to the file part
4413 leader = last_sep + 1;
John Marriott5e6ea922024-11-23 14:01:57 +01004414 leader_len -= path_len;
glepnir0be03e12024-07-19 16:45:05 +02004415 }
4416 }
glepnir8159fb12024-07-17 20:32:54 +02004417 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004418
John Marriott5e6ea922024-11-23 14:01:57 +01004419 if (expand_wildcards(1, &compl_pattern.string, &num_matches, &matches,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004420 EW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) != OK)
4421 return;
4422
4423 // May change home directory back to "~".
John Marriott5e6ea922024-11-23 14:01:57 +01004424 tilde_replace(compl_pattern.string, num_matches, matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004425#ifdef BACKSLASH_IN_FILENAME
4426 if (curbuf->b_p_csl[0] != NUL)
4427 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004428 for (i = 0; i < num_matches; ++i)
4429 {
glepnir8159fb12024-07-17 20:32:54 +02004430 ptr = matches[i];
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004431 while (*ptr != NUL)
4432 {
4433 if (curbuf->b_p_csl[0] == 's' && *ptr == '\\')
4434 *ptr = '/';
4435 else if (curbuf->b_p_csl[0] == 'b' && *ptr == '/')
4436 *ptr = '\\';
4437 ptr += (*mb_ptr2len)(ptr);
4438 }
4439 }
4440 }
4441#endif
glepnir8159fb12024-07-17 20:32:54 +02004442
glepnirf31cfa22025-03-06 21:59:13 +01004443 if (in_fuzzy_collect)
glepnir8159fb12024-07-17 20:32:54 +02004444 {
4445 ga_init2(&fuzzy_indices, sizeof(int), 10);
4446 compl_fuzzy_scores = (int *)alloc(sizeof(int) * num_matches);
4447
4448 for (i = 0; i < num_matches; i++)
4449 {
4450 ptr = matches[i];
4451 score = fuzzy_match_str(ptr, leader);
4452 if (score > 0)
4453 {
4454 if (ga_grow(&fuzzy_indices, 1) == OK)
4455 {
4456 ((int *)fuzzy_indices.ga_data)[fuzzy_indices.ga_len] = i;
4457 compl_fuzzy_scores[i] = score;
4458 fuzzy_indices.ga_len++;
4459 }
4460 }
4461 }
4462
Christian Brabandt220474d2024-07-20 13:26:44 +02004463 // prevent qsort from deref NULL pointer
4464 if (fuzzy_indices.ga_len > 0)
4465 {
glepnirf31cfa22025-03-06 21:59:13 +01004466 char_u *match = NULL;
Christian Brabandt220474d2024-07-20 13:26:44 +02004467 fuzzy_indices_data = (int *)fuzzy_indices.ga_data;
4468 qsort(fuzzy_indices_data, fuzzy_indices.ga_len, sizeof(int), compare_scores);
glepnir8159fb12024-07-17 20:32:54 +02004469
Christian Brabandt220474d2024-07-20 13:26:44 +02004470 for (i = 0; i < fuzzy_indices.ga_len; ++i)
glepnirf31cfa22025-03-06 21:59:13 +01004471 {
Hirohito Higashi355db992025-04-28 18:07:02 +02004472 match = matches[fuzzy_indices_data[i]];
glepnirf31cfa22025-03-06 21:59:13 +01004473 current_score = compl_fuzzy_scores[fuzzy_indices_data[i]];
4474 if (ins_compl_add(match, -1, NULL, NULL, NULL, dir,
Hirohito Higashi355db992025-04-28 18:07:02 +02004475 CP_FAST | ((p_fic || p_wic) ? CP_ICASE : 0),
4476 FALSE, NULL, current_score) == OK)
glepnirf31cfa22025-03-06 21:59:13 +01004477 dir = FORWARD;
4478
4479 if (need_collect_bests)
4480 {
4481 if (i == 0 || current_score == max_score)
4482 {
4483 compl_num_bests++;
4484 max_score = current_score;
4485 }
4486 }
4487 }
glepnir8159fb12024-07-17 20:32:54 +02004488
Christian Brabandt220474d2024-07-20 13:26:44 +02004489 FreeWild(num_matches, matches);
Christian Brabandt220474d2024-07-20 13:26:44 +02004490 }
glepnir6b6280c2024-07-27 16:25:45 +02004491 else if (leader_len > 0)
4492 {
4493 FreeWild(num_matches, matches);
4494 num_matches = 0;
4495 }
Christian Brabandt220474d2024-07-20 13:26:44 +02004496
glepnir8159fb12024-07-17 20:32:54 +02004497 vim_free(compl_fuzzy_scores);
4498 ga_clear(&fuzzy_indices);
glepnirf31cfa22025-03-06 21:59:13 +01004499
4500 if (compl_num_bests > 0 && compl_get_longest)
4501 fuzzy_longest_match();
4502 return;
glepnir8159fb12024-07-17 20:32:54 +02004503 }
4504
glepnir6b6280c2024-07-27 16:25:45 +02004505 if (num_matches > 0)
4506 ins_compl_add_matches(num_matches, matches, p_fic || p_wic);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004507}
4508
4509/*
4510 * Get the next set of command-line completions matching "compl_pattern".
4511 */
4512 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00004513get_next_cmdline_completion(void)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004514{
4515 char_u **matches;
4516 int num_matches;
4517
John Marriott5e6ea922024-11-23 14:01:57 +01004518 if (expand_cmdline(&compl_xp, compl_pattern.string,
4519 (int)compl_pattern.length, &num_matches, &matches) == EXPAND_OK)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004520 ins_compl_add_matches(num_matches, matches, FALSE);
4521}
4522
4523/*
4524 * Get the next set of spell suggestions matching "compl_pattern".
4525 */
4526 static void
4527get_next_spell_completion(linenr_T lnum UNUSED)
4528{
4529#ifdef FEAT_SPELL
4530 char_u **matches;
4531 int num_matches;
4532
John Marriott5e6ea922024-11-23 14:01:57 +01004533 num_matches = expand_spelling(lnum, compl_pattern.string, &matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004534 if (num_matches > 0)
4535 ins_compl_add_matches(num_matches, matches, p_ic);
Bram Moolenaar8e7cc6b2021-12-30 10:32:25 +00004536 else
4537 vim_free(matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004538#endif
4539}
4540
4541/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004542 * Return the next word or line from buffer "ins_buf" at position
4543 * "cur_match_pos" for completion. The length of the match is set in "len".
4544 */
4545 static char_u *
zeertzjq440d4cb2023-03-02 17:51:32 +00004546ins_compl_get_next_word_or_line(
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004547 buf_T *ins_buf, // buffer being scanned
4548 pos_T *cur_match_pos, // current match position
4549 int *match_len,
4550 int *cont_s_ipos) // next ^X<> will set initial_pos
4551{
4552 char_u *ptr;
4553 int len;
4554
4555 *match_len = 0;
4556 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum, FALSE) +
4557 cur_match_pos->col;
John Marriott5e6ea922024-11-23 14:01:57 +01004558 len = (int)ml_get_buf_len(ins_buf, cur_match_pos->lnum) - cur_match_pos->col;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004559 if (ctrl_x_mode_line_or_eval())
4560 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004561 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004562 {
4563 if (cur_match_pos->lnum >= ins_buf->b_ml.ml_line_count)
4564 return NULL;
4565 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
John Marriott5e6ea922024-11-23 14:01:57 +01004566 len = ml_get_buf_len(ins_buf, cur_match_pos->lnum + 1);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004567 if (!p_paste)
John Marriott5e6ea922024-11-23 14:01:57 +01004568 {
4569 char_u *tmp_ptr = ptr;
4570
4571 ptr = skipwhite(tmp_ptr);
4572 len -= (int)(ptr - tmp_ptr);
4573 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004574 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004575 }
4576 else
4577 {
4578 char_u *tmp_ptr = ptr;
4579
John Marriott5e6ea922024-11-23 14:01:57 +01004580 if (compl_status_adding() && compl_length <= len)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004581 {
4582 tmp_ptr += compl_length;
4583 // Skip if already inside a word.
4584 if (vim_iswordp(tmp_ptr))
4585 return NULL;
4586 // Find start of next word.
4587 tmp_ptr = find_word_start(tmp_ptr);
4588 }
4589 // Find end of this word.
4590 tmp_ptr = find_word_end(tmp_ptr);
4591 len = (int)(tmp_ptr - ptr);
4592
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004593 if (compl_status_adding() && len == compl_length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004594 {
4595 if (cur_match_pos->lnum < ins_buf->b_ml.ml_line_count)
4596 {
4597 // Try next line, if any. the new word will be
4598 // "join" as if the normal command "J" was used.
4599 // IOSIZE is always greater than
4600 // compl_length, so the next STRNCPY always
4601 // works -- Acevedo
4602 STRNCPY(IObuff, ptr, len);
4603 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
4604 tmp_ptr = ptr = skipwhite(ptr);
4605 // Find start of next word.
4606 tmp_ptr = find_word_start(tmp_ptr);
4607 // Find end of next word.
4608 tmp_ptr = find_word_end(tmp_ptr);
4609 if (tmp_ptr > ptr)
4610 {
4611 if (*ptr != ')' && IObuff[len - 1] != TAB)
4612 {
4613 if (IObuff[len - 1] != ' ')
4614 IObuff[len++] = ' ';
4615 // IObuf =~ "\k.* ", thus len >= 2
4616 if (p_js
4617 && (IObuff[len - 2] == '.'
4618 || (vim_strchr(p_cpo, CPO_JOINSP)
4619 == NULL
4620 && (IObuff[len - 2] == '?'
4621 || IObuff[len - 2] == '!'))))
4622 IObuff[len++] = ' ';
4623 }
4624 // copy as much as possible of the new word
4625 if (tmp_ptr - ptr >= IOSIZE - len)
4626 tmp_ptr = ptr + IOSIZE - len - 1;
4627 STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);
4628 len += (int)(tmp_ptr - ptr);
4629 *cont_s_ipos = TRUE;
4630 }
4631 IObuff[len] = NUL;
4632 ptr = IObuff;
4633 }
4634 if (len == compl_length)
4635 return NULL;
4636 }
4637 }
4638
4639 *match_len = len;
4640 return ptr;
4641}
4642
4643/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004644 * Get the next set of words matching "compl_pattern" for default completion(s)
4645 * (normal ^P/^N and ^X^L).
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004646 * Search for "compl_pattern" in the buffer "st->ins_buf" starting from the
4647 * position "st->start_pos" in the "compl_direction" direction. If
4648 * "st->set_match_pos" is TRUE, then set the "st->first_match_pos" and
4649 * "st->last_match_pos".
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004650 * Returns OK if a new next match is found, otherwise returns FAIL.
4651 */
4652 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004653get_next_default_completion(ins_compl_next_state_T *st, pos_T *start_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004654{
4655 int found_new_match = FAIL;
4656 int save_p_scs;
4657 int save_p_ws;
4658 int looped_around = FALSE;
glepnir8159fb12024-07-17 20:32:54 +02004659 char_u *ptr = NULL;
4660 int len = 0;
glepnirf31cfa22025-03-06 21:59:13 +01004661 int in_collect = (cfc_has_mode() && compl_length > 0);
glepnir8159fb12024-07-17 20:32:54 +02004662 char_u *leader = ins_compl_leader();
glepnirf31cfa22025-03-06 21:59:13 +01004663 int score = 0;
Girish Palyab1565882025-04-15 20:16:00 +02004664 int in_curbuf = st->ins_buf == curbuf;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004665
4666 // If 'infercase' is set, don't use 'smartcase' here
4667 save_p_scs = p_scs;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004668 if (st->ins_buf->b_p_inf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004669 p_scs = FALSE;
4670
4671 // Buffers other than curbuf are scanned from the beginning or the
4672 // end but never from the middle, thus setting nowrapscan in this
4673 // buffer is a good idea, on the other hand, we always set
4674 // wrapscan for curbuf to avoid missing matches -- Acevedo,Webb
4675 save_p_ws = p_ws;
Girish Palyab1565882025-04-15 20:16:00 +02004676 if (!in_curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004677 p_ws = FALSE;
glepnirf31cfa22025-03-06 21:59:13 +01004678 else if (*st->e_cpt == '.')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004679 p_ws = TRUE;
4680 looped_around = FALSE;
4681 for (;;)
4682 {
4683 int cont_s_ipos = FALSE;
4684
4685 ++msg_silent; // Don't want messages for wrapscan.
4686
glepnirf31cfa22025-03-06 21:59:13 +01004687 if (in_collect)
4688 {
Hirohito Higashi355db992025-04-28 18:07:02 +02004689 found_new_match = search_for_fuzzy_match(st->ins_buf,
glepnir8159fb12024-07-17 20:32:54 +02004690 st->cur_match_pos, leader, compl_direction,
glepnirf31cfa22025-03-06 21:59:13 +01004691 start_pos, &len, &ptr, &score);
4692 }
4693 // ctrl_x_mode_line_or_eval() || word-wise search that
4694 // has added a word that was at the beginning of the line
4695 else if (ctrl_x_mode_whole_line() || ctrl_x_mode_eval() || (compl_cont_status & CONT_SOL))
4696 found_new_match = search_for_exact_line(st->ins_buf,
4697 st->cur_match_pos, compl_direction, compl_pattern.string);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004698 else
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004699 found_new_match = searchit(NULL, st->ins_buf, st->cur_match_pos,
John Marriott5e6ea922024-11-23 14:01:57 +01004700 NULL, compl_direction, compl_pattern.string, (int)compl_pattern.length,
John Marriott8c85a2a2024-05-20 19:18:26 +02004701 1L, SEARCH_KEEP + SEARCH_NFMSG, RE_LAST, NULL);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004702 --msg_silent;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004703 if (!compl_started || st->set_match_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004704 {
4705 // set "compl_started" even on fail
4706 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004707 st->first_match_pos = *st->cur_match_pos;
4708 st->last_match_pos = *st->cur_match_pos;
4709 st->set_match_pos = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004710 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004711 else if (st->first_match_pos.lnum == st->last_match_pos.lnum
4712 && st->first_match_pos.col == st->last_match_pos.col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004713 {
4714 found_new_match = FAIL;
4715 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004716 else if (compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004717 && (st->prev_match_pos.lnum > st->cur_match_pos->lnum
4718 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
4719 && st->prev_match_pos.col >= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004720 {
4721 if (looped_around)
4722 found_new_match = FAIL;
4723 else
4724 looped_around = TRUE;
4725 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004726 else if (!compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004727 && (st->prev_match_pos.lnum < st->cur_match_pos->lnum
4728 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
4729 && st->prev_match_pos.col <= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004730 {
4731 if (looped_around)
4732 found_new_match = FAIL;
4733 else
4734 looped_around = TRUE;
4735 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004736 st->prev_match_pos = *st->cur_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004737 if (found_new_match == FAIL)
4738 break;
4739
4740 // when ADDING, the text before the cursor matches, skip it
Girish Palyab1565882025-04-15 20:16:00 +02004741 if (compl_status_adding() && in_curbuf
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004742 && start_pos->lnum == st->cur_match_pos->lnum
4743 && start_pos->col == st->cur_match_pos->col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004744 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004745
glepnirf31cfa22025-03-06 21:59:13 +01004746 if (!in_collect)
glepnir8159fb12024-07-17 20:32:54 +02004747 ptr = ins_compl_get_next_word_or_line(st->ins_buf, st->cur_match_pos,
4748 &len, &cont_s_ipos);
glepnirbfb4eea2025-01-31 15:28:29 +01004749 if (ptr == NULL || (ins_compl_has_preinsert() && STRCMP(ptr, compl_pattern.string) == 0))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004750 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004751
Girish Palyab1565882025-04-15 20:16:00 +02004752 if (is_nearest_active() && in_curbuf)
4753 {
4754 score = st->cur_match_pos->lnum - curwin->w_cursor.lnum;
4755 if (score < 0)
4756 score = -score;
4757 score++;
4758 }
4759
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004760 if (ins_compl_add_infercase(ptr, len, p_ic,
Girish Palyab1565882025-04-15 20:16:00 +02004761 in_curbuf ? NULL : st->ins_buf->b_sfname,
glepnirf31cfa22025-03-06 21:59:13 +01004762 0, cont_s_ipos, score) != NOTDONE)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004763 {
glepnirf31cfa22025-03-06 21:59:13 +01004764 if (in_collect && score == compl_first_match->cp_next->cp_score)
4765 compl_num_bests++;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004766 found_new_match = OK;
4767 break;
4768 }
4769 }
4770 p_scs = save_p_scs;
4771 p_ws = save_p_ws;
4772
4773 return found_new_match;
4774}
4775
Girish Palyacbe53192025-04-14 22:13:15 +02004776#ifdef FEAT_COMPL_FUNC
Girish Palya98c29db2025-06-01 19:40:00 +02004777/*
4778 * Return the callback function associated with "p" if it points to a
4779 * userfunc.
4780 */
Girish Palyacbe53192025-04-14 22:13:15 +02004781 static callback_T *
Girish Palya98c29db2025-06-01 19:40:00 +02004782get_callback_if_cpt_func(char_u *p)
Girish Palyacbe53192025-04-14 22:13:15 +02004783{
4784 static callback_T cb;
4785 char_u buf[LSIZE];
4786 int slen;
4787
Girish Palya98c29db2025-06-01 19:40:00 +02004788 if (*p == 'o')
4789 return &curbuf->b_ofu_cb;
4790 if (*p == 'F')
4791 {
4792 if (*++p != ',' && *p != NUL)
4793 {
4794 free_callback(&cb);
4795 slen = copy_option_part(&p, buf, LSIZE, ",");
4796 if (slen > 0 && option_set_callback_func(buf, &cb))
4797 return &cb;
4798 return NULL;
4799 }
4800 else
4801 return &curbuf->b_cfu_cb;
4802 }
Girish Palyacbe53192025-04-14 22:13:15 +02004803 return NULL;
4804}
4805
4806/*
4807 * Retrieve new completion matches by invoking callback "cb".
4808 */
4809 static void
4810expand_cpt_function(callback_T *cb)
4811{
4812 // Re-insert the text removed by ins_compl_delete().
4813 ins_compl_insert_bytes(compl_orig_text.string + get_compl_len(), -1);
4814 // Get matches
4815 get_cpt_func_completion_matches(cb);
4816 // Undo insertion
4817 ins_compl_delete();
4818}
4819#endif
4820
4821/*
glepnir05460682025-05-26 18:23:27 +02004822 * Get completion matches from register contents.
4823 * Extracts words from all available registers and adds them to the completion list.
4824 */
4825 static void
4826get_register_completion(void)
4827{
4828 int dir = compl_direction;
4829 yankreg_T *reg = NULL;
4830 void *reg_ptr = NULL;
glepnir86d46a72025-06-03 21:04:44 +02004831 int adding_mode = compl_status_adding();
glepnir05460682025-05-26 18:23:27 +02004832
4833 for (int i = 0; i < NUM_REGISTERS; i++)
4834 {
4835 int regname = 0;
glepnir05460682025-05-26 18:23:27 +02004836 if (i == 0)
4837 regname = '"'; // unnamed register
4838 else if (i < 10)
4839 regname = '0' + i;
4840 else if (i == DELETION_REGISTER)
4841 regname = '-';
4842#ifdef FEAT_CLIPBOARD
4843 else if (i == STAR_REGISTER)
4844 regname = '*';
4845 else if (i == PLUS_REGISTER)
4846 regname = '+';
4847#endif
4848 else
4849 regname = 'a' + i - 10;
4850
4851 // Skip invalid or black hole register
4852 if (!valid_yank_reg(regname, FALSE) || regname == '_')
4853 continue;
4854
4855 reg_ptr = get_register(regname, FALSE);
4856 if (reg_ptr == NULL)
4857 continue;
4858
4859 reg = (yankreg_T *)reg_ptr;
4860
glepnir86d46a72025-06-03 21:04:44 +02004861 for (int j = 0; j < reg->y_size; j++)
glepnir05460682025-05-26 18:23:27 +02004862 {
glepnir86d46a72025-06-03 21:04:44 +02004863 char_u *str = reg->y_array[j].string;
4864 if (str == NULL)
4865 continue;
glepnir05460682025-05-26 18:23:27 +02004866
glepnir86d46a72025-06-03 21:04:44 +02004867 if (adding_mode)
4868 {
glepnird5fdfa52025-06-02 19:45:41 +02004869 int str_len = (int)STRLEN(str);
4870 if (str_len == 0)
4871 continue;
glepnir05460682025-05-26 18:23:27 +02004872
glepnird5fdfa52025-06-02 19:45:41 +02004873 if (!compl_orig_text.string
4874 || (p_ic ? STRNICMP(str, compl_orig_text.string,
4875 compl_orig_text.length) == 0
4876 : STRNCMP(str, compl_orig_text.string,
4877 compl_orig_text.length) == 0))
glepnir05460682025-05-26 18:23:27 +02004878 {
glepnir86d46a72025-06-03 21:04:44 +02004879 if (ins_compl_add_infercase(str, str_len, p_ic, NULL,
4880 dir, FALSE, 0) == OK)
glepnir05460682025-05-26 18:23:27 +02004881 dir = FORWARD;
4882 }
glepnird5fdfa52025-06-02 19:45:41 +02004883 }
glepnir86d46a72025-06-03 21:04:44 +02004884 else
glepnird5fdfa52025-06-02 19:45:41 +02004885 {
glepnird5fdfa52025-06-02 19:45:41 +02004886 // Calculate the safe end of string to avoid null byte issues
4887 char_u *str_end = str + STRLEN(str);
4888 char_u *p = str;
4889
4890 // Safely iterate through the string
4891 while (p < str_end && *p != NUL)
4892 {
4893 char_u *old_p = p;
4894 p = find_word_start(p);
4895 if (p >= str_end || *p == NUL)
4896 break;
4897
4898 char_u *word_end = find_word_end(p);
4899
4900 if (word_end <= p)
4901 {
4902 if (has_mbyte)
4903 word_end = p + (*mb_ptr2len)(p);
4904 else
4905 word_end = p + 1;
4906 }
4907
4908 if (word_end > str_end)
4909 word_end = str_end;
4910
4911 int len = (int)(word_end - p);
4912 if (len > 0 && (!compl_orig_text.string
4913 || (p_ic ? STRNICMP(p, compl_orig_text.string,
4914 compl_orig_text.length) == 0
4915 : STRNCMP(p, compl_orig_text.string,
4916 compl_orig_text.length) == 0)))
4917 {
4918 if (ins_compl_add_infercase(p, len, p_ic, NULL,
4919 dir, FALSE, 0) == OK)
4920 dir = FORWARD;
4921 }
4922
4923 p = word_end;
4924
4925 if (p <= old_p)
4926 {
4927 p = old_p + 1;
4928 if (has_mbyte && p < str_end)
4929 p = old_p + (*mb_ptr2len)(old_p);
4930 }
4931 }
glepnir05460682025-05-26 18:23:27 +02004932 }
4933 }
4934
4935 // Free the register copy
4936 put_register(regname, reg_ptr);
4937 }
4938}
4939
4940/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004941 * get the next set of completion matches for "type".
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004942 * Returns TRUE if a new match is found. Otherwise returns FALSE.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004943 */
4944 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004945get_next_completion_match(int type, ins_compl_next_state_T *st, pos_T *ini)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004946{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004947 int found_new_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004948
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004949 switch (type)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004950 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004951 case -1:
4952 break;
4953#ifdef FEAT_FIND_ID
4954 case CTRL_X_PATH_PATTERNS:
4955 case CTRL_X_PATH_DEFINES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004956 get_next_include_file_completion(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004957 break;
4958#endif
4959
4960 case CTRL_X_DICTIONARY:
4961 case CTRL_X_THESAURUS:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004962 get_next_dict_tsr_completion(type, st->dict, st->dict_f);
4963 st->dict = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004964 break;
4965
4966 case CTRL_X_TAGS:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004967 get_next_tag_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004968 break;
4969
4970 case CTRL_X_FILES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004971 get_next_filename_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004972 break;
4973
4974 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +02004975 case CTRL_X_CMDLINE_CTRL_X:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004976 get_next_cmdline_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004977 break;
4978
4979#ifdef FEAT_COMPL_FUNC
4980 case CTRL_X_FUNCTION:
Girish Palyacbe53192025-04-14 22:13:15 +02004981 if (ctrl_x_mode_normal()) // Invoked by a func in 'cpt' option
4982 expand_cpt_function(st->func_cb);
4983 else
4984 expand_by_function(type, compl_pattern.string, NULL);
4985 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004986 case CTRL_X_OMNI:
Girish Palyacbe53192025-04-14 22:13:15 +02004987 expand_by_function(type, compl_pattern.string, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004988 break;
4989#endif
4990
4991 case CTRL_X_SPELL:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004992 get_next_spell_completion(st->first_match_pos.lnum);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004993 break;
4994
glepnir05460682025-05-26 18:23:27 +02004995 case CTRL_X_REGISTER:
4996 get_register_completion();
4997 break;
4998
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004999 default: // normal ^P/^N and ^X^L
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005000 found_new_match = get_next_default_completion(st, ini);
5001 if (found_new_match == FAIL && st->ins_buf == curbuf)
5002 st->found_all = TRUE;
5003 }
5004
5005 // check if compl_curr_match has changed, (e.g. other type of
5006 // expansion added something)
5007 if (type != 0 && compl_curr_match != compl_old_match)
5008 found_new_match = OK;
5009
5010 return found_new_match;
5011}
5012
5013/*
Girish Palya0ac1eb32025-04-16 20:18:33 +02005014 * Strips carets followed by numbers. This suffix typically represents the
5015 * max_matches setting.
5016 */
5017 static void
5018strip_caret_numbers_in_place(char_u *str)
5019{
5020 char_u *read = str, *write = str, *p;
5021
5022 if (str == NULL)
5023 return;
5024
5025 while (*read)
5026 {
5027 if (*read == '^')
5028 {
5029 p = read + 1;
5030 while (vim_isdigit(*p))
5031 p++;
5032 if ((*p == ',' || *p == '\0') && p != read + 1)
5033 {
5034 read = p;
5035 continue;
5036 }
5037 else
5038 *write++ = *read++;
5039 }
5040 else
5041 *write++ = *read++;
5042 }
5043 *write = '\0';
5044}
5045
5046/*
Girish Palya98c29db2025-06-01 19:40:00 +02005047 * Call functions specified in the 'cpt' option with findstart=1,
5048 * and retrieve the startcol.
5049 */
5050 static void
5051prepare_cpt_compl_funcs(void)
5052{
5053#ifdef FEAT_COMPL_FUNC
5054 char_u *cpt;
5055 char_u *p;
5056 callback_T *cb = NULL;
5057 int idx = 0;
5058 int startcol;
5059
5060 // Make a copy of 'cpt' in case the buffer gets wiped out
5061 cpt = vim_strsave(curbuf->b_p_cpt);
5062 strip_caret_numbers_in_place(cpt);
5063
5064 // Re-insert the text removed by ins_compl_delete().
5065 ins_compl_insert_bytes(compl_orig_text.string + get_compl_len(), -1);
5066
5067 for (p = cpt; *p;)
5068 {
5069 while (*p == ',' || *p == ' ') // Skip delimiters
5070 p++;
5071 cb = get_callback_if_cpt_func(p);
5072 if (cb)
5073 {
5074 if (get_userdefined_compl_info(curwin->w_cursor.col, cb, &startcol)
5075 == FAIL)
5076 {
5077 if (startcol == -3)
5078 cpt_sources_array[idx].cs_refresh_always = FALSE;
5079 else
5080 startcol = -2;
5081 }
5082 cpt_sources_array[idx].cs_startcol = startcol;
5083 }
5084 (void)copy_option_part(&p, IObuff, IOSIZE, ","); // Advance p
5085 idx++;
5086 }
5087
5088 // Undo insertion
5089 ins_compl_delete();
5090
5091 vim_free(cpt);
5092#endif
5093}
5094
5095/*
Girish Palya7c621052025-05-26 19:41:59 +02005096 * Safely advance the cpt_sources_index by one.
5097 */
5098 static int
5099advance_cpt_sources_index_safe(void)
5100{
5101 if (cpt_sources_index < cpt_sources_count - 1)
5102 {
5103 cpt_sources_index++;
5104 return OK;
5105 }
5106#ifdef FEAT_EVAL
5107 semsg(_(e_list_index_out_of_range_nr), cpt_sources_index + 1);
5108#endif
5109 return FAIL;
5110}
5111
5112/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005113 * Get the next expansion(s), using "compl_pattern".
5114 * The search starts at position "ini" in curbuf and in the direction
5115 * compl_direction.
5116 * When "compl_started" is FALSE start at that position, otherwise continue
5117 * where we stopped searching before.
5118 * This may return before finding all the matches.
5119 * Return the total number of matches or -1 if still unknown -- Acevedo
5120 */
5121 static int
5122ins_compl_get_exp(pos_T *ini)
5123{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005124 static ins_compl_next_state_T st;
5125 static int st_cleared = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005126 int i;
5127 int found_new_match;
5128 int type = ctrl_x_mode;
Girish Palya7c621052025-05-26 19:41:59 +02005129 int may_advance_cpt_idx = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005130
5131 if (!compl_started)
5132 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005133 buf_T *buf;
5134
5135 FOR_ALL_BUFFERS(buf)
5136 buf->b_scanned = 0;
5137 if (!st_cleared)
5138 {
5139 CLEAR_FIELD(st);
5140 st_cleared = TRUE;
5141 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005142 st.found_all = FALSE;
5143 st.ins_buf = curbuf;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005144 vim_free(st.e_cpt_copy);
Christian Brabandtee17b6f2023-09-09 11:23:50 +02005145 // Make a copy of 'complete', in case the buffer is wiped out.
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005146 st.e_cpt_copy = vim_strsave((compl_cont_status & CONT_LOCAL)
5147 ? (char_u *)"." : curbuf->b_p_cpt);
Girish Palya0ac1eb32025-04-16 20:18:33 +02005148 strip_caret_numbers_in_place(st.e_cpt_copy);
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005149 st.e_cpt = st.e_cpt_copy == NULL ? (char_u *)"" : st.e_cpt_copy;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005150 st.last_match_pos = st.first_match_pos = *ini;
5151 }
5152 else if (st.ins_buf != curbuf && !buf_valid(st.ins_buf))
5153 st.ins_buf = curbuf; // In case the buffer was wiped out.
5154
5155 compl_old_match = compl_curr_match; // remember the last current match
Christian Brabandt13032a42024-07-28 21:16:48 +02005156 st.cur_match_pos = (compl_dir_forward())
glepnir8159fb12024-07-17 20:32:54 +02005157 ? &st.last_match_pos : &st.first_match_pos;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005158
Girish Palya98c29db2025-06-01 19:40:00 +02005159 if (ctrl_x_mode_normal() && !ctrl_x_mode_line_or_eval() &&
5160 !(compl_cont_status & CONT_LOCAL))
5161 {
5162 // ^N completion, not ^X^L or complete() or ^X^N
5163 if (!compl_started) // Before showing menu the first time
5164 {
5165 if (setup_cpt_sources() == FAIL)
5166 return FAIL;
5167 }
5168 prepare_cpt_compl_funcs();
5169 cpt_sources_index = 0;
5170 }
5171
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005172 // For ^N/^P loop over all the flags/windows/buffers in 'complete'.
Girish Palya7c621052025-05-26 19:41:59 +02005173 for (;;)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005174 {
5175 found_new_match = FAIL;
5176 st.set_match_pos = FALSE;
5177
5178 // For ^N/^P pick a new entry from e_cpt if compl_started is off,
5179 // or if found_all says this entry is done. For ^X^L only use the
5180 // entries from 'complete' that look in loaded buffers.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005181 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005182 && (!compl_started || st.found_all))
5183 {
Girish Palya7c621052025-05-26 19:41:59 +02005184 int status = process_next_cpt_value(&st, &type, ini,
5185 cfc_has_mode(), &may_advance_cpt_idx);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005186
5187 if (status == INS_COMPL_CPT_END)
5188 break;
5189 if (status == INS_COMPL_CPT_CONT)
Girish Palyacbe53192025-04-14 22:13:15 +02005190 {
Girish Palya7c621052025-05-26 19:41:59 +02005191 if (may_advance_cpt_idx && !advance_cpt_sources_index_safe())
5192 break;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005193 continue;
Girish Palyacbe53192025-04-14 22:13:15 +02005194 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005195 }
5196
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005197 // If complete() was called then compl_pattern has been reset. The
5198 // following won't work then, bail out.
John Marriott5e6ea922024-11-23 14:01:57 +01005199 if (compl_pattern.string == NULL)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005200 break;
5201
5202 // get the next set of completion matches
5203 found_new_match = get_next_completion_match(type, &st, ini);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005204
Girish Palya7c621052025-05-26 19:41:59 +02005205 if (may_advance_cpt_idx && !advance_cpt_sources_index_safe())
5206 break;
Girish Palyacbe53192025-04-14 22:13:15 +02005207
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005208 // break the loop for specialized modes (use 'complete' just for the
5209 // generic ctrl_x_mode == CTRL_X_NORMAL) or when we've found a new
5210 // match
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005211 if ((ctrl_x_mode_not_default() && !ctrl_x_mode_line_or_eval())
5212 || found_new_match != FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005213 {
5214 if (got_int)
5215 break;
5216 // Fill the popup menu as soon as possible.
5217 if (type != -1)
5218 ins_compl_check_keys(0, FALSE);
5219
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005220 if ((ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005221 && !ctrl_x_mode_line_or_eval()) || compl_interrupted)
5222 break;
5223 compl_started = TRUE;
5224 }
5225 else
5226 {
5227 // Mark a buffer scanned when it has been scanned completely
Christian Brabandtee9166e2023-09-03 21:24:33 +02005228 if (buf_valid(st.ins_buf) && (type == 0 || type == CTRL_X_PATH_PATTERNS))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005229 st.ins_buf->b_scanned = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005230
5231 compl_started = FALSE;
5232 }
5233 }
Girish Palya0ac1eb32025-04-16 20:18:33 +02005234 cpt_sources_index = -1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005235 compl_started = TRUE;
5236
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005237 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005238 && *st.e_cpt == NUL) // Got to end of 'complete'
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005239 found_new_match = FAIL;
5240
5241 i = -1; // total of matches, unknown
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005242 if (found_new_match == FAIL || (ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005243 && !ctrl_x_mode_line_or_eval()))
5244 i = ins_compl_make_cyclic();
5245
glepnirf31cfa22025-03-06 21:59:13 +01005246 if (cfc_has_mode() && compl_get_longest && compl_num_bests > 0)
5247 fuzzy_longest_match();
5248
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005249 if (compl_old_match != NULL)
5250 {
5251 // If several matches were added (FORWARD) or the search failed and has
5252 // just been made cyclic then we have to move compl_curr_match to the
5253 // next or previous entry (if any) -- Acevedo
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005254 compl_curr_match = compl_dir_forward() ? compl_old_match->cp_next
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005255 : compl_old_match->cp_prev;
5256 if (compl_curr_match == NULL)
5257 compl_curr_match = compl_old_match;
5258 }
LemonBoy2bf52dd2022-04-09 18:17:34 +01005259 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01005260
Girish Palyab8ee1cf2025-06-08 16:20:06 +02005261 if (is_nearest_active())
5262 sort_compl_match_list(cp_compare_nearest);
5263
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005264 return i;
5265}
5266
5267/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005268 * Update "compl_shown_match" to the actually shown match, it may differ when
5269 * "compl_leader" is used to omit some of the matches.
5270 */
5271 static void
5272ins_compl_update_shown_match(void)
5273{
5274 while (!ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01005275 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005276 && compl_shown_match->cp_next != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005277 && !is_first_match(compl_shown_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005278 compl_shown_match = compl_shown_match->cp_next;
5279
5280 // If we didn't find it searching forward, and compl_shows_dir is
5281 // backward, find the last match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005282 if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005283 && !ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01005284 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005285 && (compl_shown_match->cp_next == NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005286 || is_first_match(compl_shown_match->cp_next)))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005287 {
5288 while (!ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01005289 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005290 && compl_shown_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005291 && !is_first_match(compl_shown_match->cp_prev))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005292 compl_shown_match = compl_shown_match->cp_prev;
5293 }
5294}
5295
5296/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005297 * Delete the old text being completed.
5298 */
5299 void
5300ins_compl_delete(void)
5301{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005302 // In insert mode: Delete the typed part.
5303 // In replace mode: Put the old characters back, if any.
glepniredd4ac32025-01-29 18:53:51 +01005304 int col = compl_col + (compl_status_adding() ? compl_length : 0);
John Marriottf4b36412025-02-23 09:09:59 +01005305 string_T remaining = {NULL, 0};
glepnir76bdb822025-02-08 19:04:51 +01005306 int orig_col;
glepniredd4ac32025-01-29 18:53:51 +01005307 int has_preinsert = ins_compl_preinsert_effect();
5308 if (has_preinsert)
5309 {
Yegappan Lakshmanan7b6add02025-04-01 20:38:37 +02005310 col += (int)ins_compl_leader_len();
glepniredd4ac32025-01-29 18:53:51 +01005311 curwin->w_cursor.col = compl_ins_end_col;
5312 }
5313
glepnir76bdb822025-02-08 19:04:51 +01005314 if (curwin->w_cursor.lnum > compl_lnum)
5315 {
5316 if (curwin->w_cursor.col < ml_get_curline_len())
5317 {
John Marriottf4b36412025-02-23 09:09:59 +01005318 char_u *line = ml_get_cursor();
5319 remaining.length = ml_get_cursor_len();
5320 remaining.string = vim_strnsave(line, remaining.length);
5321 if (remaining.string == NULL)
glepnir76bdb822025-02-08 19:04:51 +01005322 return;
5323 }
5324 while (curwin->w_cursor.lnum > compl_lnum)
5325 {
5326 if (ml_delete(curwin->w_cursor.lnum) == FAIL)
5327 {
John Marriottf4b36412025-02-23 09:09:59 +01005328 if (remaining.string)
5329 vim_free(remaining.string);
glepnir76bdb822025-02-08 19:04:51 +01005330 return;
5331 }
zeertzjq060e6552025-02-21 20:06:26 +01005332 deleted_lines_mark(curwin->w_cursor.lnum, 1L);
glepnir76bdb822025-02-08 19:04:51 +01005333 curwin->w_cursor.lnum--;
5334 }
5335 // move cursor to end of line
5336 curwin->w_cursor.col = ml_get_curline_len();
5337 }
5338
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005339 if ((int)curwin->w_cursor.col > col)
5340 {
5341 if (stop_arrow() == FAIL)
glepnire3647c82025-02-10 21:16:32 +01005342 {
John Marriottf4b36412025-02-23 09:09:59 +01005343 if (remaining.string)
5344 vim_free(remaining.string);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005345 return;
glepnire3647c82025-02-10 21:16:32 +01005346 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005347 backspace_until_column(col);
zeertzjqf25d8f92024-12-18 21:12:25 +01005348 compl_ins_end_col = curwin->w_cursor.col;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005349 }
5350
John Marriottf4b36412025-02-23 09:09:59 +01005351 if (remaining.string != NULL)
glepnir76bdb822025-02-08 19:04:51 +01005352 {
5353 orig_col = curwin->w_cursor.col;
John Marriottf4b36412025-02-23 09:09:59 +01005354 ins_str(remaining.string, remaining.length);
glepnir76bdb822025-02-08 19:04:51 +01005355 curwin->w_cursor.col = orig_col;
John Marriottf4b36412025-02-23 09:09:59 +01005356 vim_free(remaining.string);
glepnir76bdb822025-02-08 19:04:51 +01005357 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005358 // TODO: is this sufficient for redrawing? Redrawing everything causes
5359 // flicker, thus we can't do that.
5360 changed_cline_bef_curs();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02005361#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005362 // clear v:completed_item
5363 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02005364#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005365}
5366
5367/*
glepnir76bdb822025-02-08 19:04:51 +01005368 * Insert a completion string that contains newlines.
5369 * The string is split and inserted line by line.
5370 */
5371 static void
5372ins_compl_expand_multiple(char_u *str)
5373{
5374 char_u *start = str;
5375 char_u *curr = str;
glepnir5090a1f2025-02-24 19:10:37 +01005376 int base_indent = get_indent();
glepnir76bdb822025-02-08 19:04:51 +01005377
5378 while (*curr != NUL)
5379 {
5380 if (*curr == '\n')
5381 {
5382 // Insert the text chunk before newline
5383 if (curr > start)
5384 ins_char_bytes(start, (int)(curr - start));
5385
5386 // Handle newline
glepnir5090a1f2025-02-24 19:10:37 +01005387 open_line(FORWARD, OPENLINE_KEEPTRAIL | OPENLINE_FORCE_INDENT, base_indent, NULL);
glepnir76bdb822025-02-08 19:04:51 +01005388 start = curr + 1;
5389 }
5390 curr++;
5391 }
5392
5393 // Handle remaining text after last newline (if any)
5394 if (curr > start)
5395 ins_char_bytes(start, (int)(curr - start));
5396
5397 compl_ins_end_col = curwin->w_cursor.col;
5398}
5399
5400/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005401 * Insert the new text being completed.
5402 * "in_compl_func" is TRUE when called from complete_check().
glepniredd4ac32025-01-29 18:53:51 +01005403 * "move_cursor" is used when 'completeopt' includes "preinsert" and when TRUE
5404 * cursor needs to move back from the inserted text to the compl_leader.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005405 */
5406 void
glepniredd4ac32025-01-29 18:53:51 +01005407ins_compl_insert(int in_compl_func, int move_cursor)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005408{
glepnir76bdb822025-02-08 19:04:51 +01005409 int compl_len = get_compl_len();
5410 int preinsert = ins_compl_has_preinsert();
5411 char_u *cp_str = compl_shown_match->cp_str.string;
5412 size_t cp_str_len = compl_shown_match->cp_str.length;
5413 size_t leader_len = ins_compl_leader_len();
5414 char_u *has_multiple = vim_strchr(cp_str, '\n');
Bram Moolenaar4b28ba32021-12-27 19:28:37 +00005415
5416 // Make sure we don't go over the end of the string, this can happen with
5417 // illegal bytes.
zeertzjq8297e2c2025-01-30 11:04:47 +01005418 if (compl_len < (int)cp_str_len)
glepniredd4ac32025-01-29 18:53:51 +01005419 {
glepnir76bdb822025-02-08 19:04:51 +01005420 if (has_multiple)
5421 ins_compl_expand_multiple(cp_str + compl_len);
5422 else
5423 {
5424 ins_compl_insert_bytes(cp_str + compl_len, -1);
5425 if (preinsert && move_cursor)
5426 curwin->w_cursor.col -= (colnr_T)(cp_str_len - leader_len);
5427 }
glepniredd4ac32025-01-29 18:53:51 +01005428 }
5429 if (match_at_original_text(compl_shown_match) || preinsert)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005430 compl_used_match = FALSE;
5431 else
5432 compl_used_match = TRUE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02005433#ifdef FEAT_EVAL
5434 {
5435 dict_T *dict = ins_compl_dict_alloc(compl_shown_match);
5436
5437 set_vim_var_dict(VV_COMPLETED_ITEM, dict);
5438 }
5439#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005440 if (!in_compl_func)
5441 compl_curr_match = compl_shown_match;
5442}
5443
5444/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005445 * show the file name for the completion match (if any). Truncate the file
5446 * name to avoid a wait for return.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005447 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005448 static void
5449ins_compl_show_filename(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005450{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005451 char *lead = _("match in file");
5452 int space = sc_col - vim_strsize((char_u *)lead) - 2;
5453 char_u *s;
5454 char_u *e;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005455
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005456 if (space <= 0)
5457 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005458
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005459 // We need the tail that fits. With double-byte encoding going
5460 // back from the end is very slow, thus go from the start and keep
5461 // the text that fits in "space" between "s" and "e".
5462 for (s = e = compl_shown_match->cp_fname; *e != NUL; MB_PTR_ADV(e))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005463 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005464 space -= ptr2cells(e);
5465 while (space < 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005466 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005467 space += ptr2cells(s);
5468 MB_PTR_ADV(s);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005469 }
5470 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005471 msg_hist_off = TRUE;
5472 vim_snprintf((char *)IObuff, IOSIZE, "%s %s%s", lead,
5473 s > compl_shown_match->cp_fname ? "<" : "", s);
5474 msg((char *)IObuff);
5475 msg_hist_off = FALSE;
5476 redraw_cmdline = FALSE; // don't overwrite!
5477}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005478
glepnirdca57fb2024-06-04 22:01:21 +02005479/*
Girish Palya0ac1eb32025-04-16 20:18:33 +02005480 * Find the appropriate completion item when 'complete' ('cpt') includes
5481 * a 'max_matches' postfix. In this case, we search for a match where
5482 * 'cp_in_match_array' is set, indicating that the match is also present
5483 * in 'compl_match_array'.
5484 */
5485 static compl_T *
Girish Palyab8ee1cf2025-06-08 16:20:06 +02005486find_next_match_in_menu(void)
Girish Palya0ac1eb32025-04-16 20:18:33 +02005487{
5488 int is_forward = compl_shows_dir_forward();
5489 compl_T *match = compl_shown_match;
5490
5491 do
5492 match = is_forward ? match->cp_next : match->cp_prev;
5493 while (match->cp_next && !match->cp_in_match_array
5494 && !match_at_original_text(match));
5495 return match;
5496}
5497
5498/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005499 * Find the next set of matches for completion. Repeat the completion "todo"
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005500 * times. The number of matches found is returned in 'num_matches'.
5501 *
5502 * If "allow_get_expansion" is TRUE, then ins_compl_get_exp() may be called to
5503 * get more completions. If it is FALSE, then do nothing when there are no more
5504 * completions in the given direction.
5505 *
5506 * If "advance" is TRUE, then completion will move to the first match.
5507 * Otherwise, the original text will be shown.
5508 *
5509 * Returns OK on success and -1 if the number of matches are unknown.
5510 */
5511 static int
5512find_next_completion_match(
5513 int allow_get_expansion,
5514 int todo, // repeat completion this many times
5515 int advance,
5516 int *num_matches)
5517{
5518 int found_end = FALSE;
5519 compl_T *found_compl = NULL;
zeertzjqaa925ee2024-06-09 18:24:05 +02005520 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02005521 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
5522 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005523
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005524 while (--todo >= 0)
5525 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005526 if (compl_shows_dir_forward() && compl_shown_match->cp_next != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005527 {
Girish Palyab8ee1cf2025-06-08 16:20:06 +02005528 if (compl_match_array != NULL)
5529 compl_shown_match = find_next_match_in_menu();
Girish Palya0ac1eb32025-04-16 20:18:33 +02005530 else
5531 compl_shown_match = compl_shown_match->cp_next;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005532 found_end = (compl_first_match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005533 && (is_first_match(compl_shown_match->cp_next)
5534 || is_first_match(compl_shown_match)));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005535 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005536 else if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005537 && compl_shown_match->cp_prev != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005538 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005539 found_end = is_first_match(compl_shown_match);
Girish Palyab8ee1cf2025-06-08 16:20:06 +02005540 if (compl_match_array != NULL)
5541 compl_shown_match = find_next_match_in_menu();
Girish Palya0ac1eb32025-04-16 20:18:33 +02005542 else
5543 compl_shown_match = compl_shown_match->cp_prev;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005544 found_end |= is_first_match(compl_shown_match);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005545 }
5546 else
5547 {
5548 if (!allow_get_expansion)
5549 {
5550 if (advance)
5551 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005552 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005553 compl_pending -= todo + 1;
5554 else
5555 compl_pending += todo + 1;
5556 }
5557 return -1;
5558 }
5559
5560 if (!compl_no_select && advance)
5561 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005562 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005563 --compl_pending;
5564 else
5565 ++compl_pending;
5566 }
5567
5568 // Find matches.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005569 *num_matches = ins_compl_get_exp(&compl_startpos);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005570
5571 // handle any pending completions
5572 while (compl_pending != 0 && compl_direction == compl_shows_dir
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005573 && advance)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005574 {
5575 if (compl_pending > 0 && compl_shown_match->cp_next != NULL)
5576 {
5577 compl_shown_match = compl_shown_match->cp_next;
5578 --compl_pending;
5579 }
5580 if (compl_pending < 0 && compl_shown_match->cp_prev != NULL)
5581 {
5582 compl_shown_match = compl_shown_match->cp_prev;
5583 ++compl_pending;
5584 }
5585 else
5586 break;
5587 }
5588 found_end = FALSE;
5589 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005590 if (!match_at_original_text(compl_shown_match)
John Marriott5e6ea922024-11-23 14:01:57 +01005591 && compl_leader.string != NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005592 && !ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01005593 compl_leader.string, (int)compl_leader.length)
glepnira218cc62024-06-03 19:32:39 +02005594 && !(compl_fuzzy_match && compl_shown_match->cp_score > 0))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005595 ++todo;
5596 else
5597 // Remember a matching item.
5598 found_compl = compl_shown_match;
5599
5600 // Stop at the end of the list when we found a usable match.
5601 if (found_end)
5602 {
5603 if (found_compl != NULL)
5604 {
5605 compl_shown_match = found_compl;
5606 break;
5607 }
5608 todo = 1; // use first usable match after wrapping around
5609 }
5610 }
5611
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005612 return OK;
5613}
5614
5615/*
5616 * Fill in the next completion in the current direction.
5617 * If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to
5618 * get more completions. If it is FALSE, then we just do nothing when there
5619 * are no more completions in a given direction. The latter case is used when
5620 * we are still in the middle of finding completions, to allow browsing
5621 * through the ones found so far.
5622 * Return the total number of matches, or -1 if still unknown -- webb.
5623 *
5624 * compl_curr_match is currently being used by ins_compl_get_exp(), so we use
5625 * compl_shown_match here.
5626 *
5627 * Note that this function may be called recursively once only. First with
5628 * "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn
5629 * calls this function with "allow_get_expansion" FALSE.
5630 */
5631 static int
5632ins_compl_next(
5633 int allow_get_expansion,
5634 int count, // repeat completion this many times; should
5635 // be at least 1
5636 int insert_match, // Insert the newly selected match
5637 int in_compl_func) // called from complete_check()
5638{
5639 int num_matches = -1;
5640 int todo = count;
5641 int advance;
5642 int started = compl_started;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005643 buf_T *orig_curbuf = curbuf;
zeertzjqaa925ee2024-06-09 18:24:05 +02005644 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02005645 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
5646 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
glepniredd4ac32025-01-29 18:53:51 +01005647 int compl_preinsert = ins_compl_has_preinsert();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005648
5649 // When user complete function return -1 for findstart which is next
5650 // time of 'always', compl_shown_match become NULL.
5651 if (compl_shown_match == NULL)
5652 return -1;
5653
John Marriott5e6ea922024-11-23 14:01:57 +01005654 if (compl_leader.string != NULL
glepnira218cc62024-06-03 19:32:39 +02005655 && !match_at_original_text(compl_shown_match)
5656 && !compl_fuzzy_match)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005657 // Update "compl_shown_match" to the actually shown match
5658 ins_compl_update_shown_match();
5659
5660 if (allow_get_expansion && insert_match
nwounkn2e3cd522023-10-17 11:05:38 +02005661 && (!compl_get_longest || compl_used_match))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005662 // Delete old text to be replaced
5663 ins_compl_delete();
5664
5665 // When finding the longest common text we stick at the original text,
5666 // don't let CTRL-N or CTRL-P move to the first match.
5667 advance = count != 1 || !allow_get_expansion || !compl_get_longest;
5668
5669 // When restarting the search don't insert the first match either.
5670 if (compl_restarting)
5671 {
5672 advance = FALSE;
5673 compl_restarting = FALSE;
5674 }
5675
5676 // Repeat this for when <PageUp> or <PageDown> is typed. But don't wrap
5677 // around.
5678 if (find_next_completion_match(allow_get_expansion, todo, advance,
5679 &num_matches) == -1)
5680 return -1;
5681
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005682 if (curbuf != orig_curbuf)
5683 {
5684 // In case some completion function switched buffer, don't want to
5685 // insert the completion elsewhere.
5686 return -1;
5687 }
5688
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005689 // Insert the text of the new completion, or the compl_leader.
glepniredd4ac32025-01-29 18:53:51 +01005690 if (compl_no_insert && !started && !compl_preinsert)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005691 {
glepnir6a38aff2024-12-16 21:56:16 +01005692 ins_compl_insert_bytes(compl_orig_text.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005693 compl_used_match = FALSE;
5694 }
5695 else if (insert_match)
5696 {
5697 if (!compl_get_longest || compl_used_match)
glepniredd4ac32025-01-29 18:53:51 +01005698 ins_compl_insert(in_compl_func, TRUE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005699 else
glepnir6a38aff2024-12-16 21:56:16 +01005700 ins_compl_insert_bytes(compl_leader.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005701 }
5702 else
5703 compl_used_match = FALSE;
5704
5705 if (!allow_get_expansion)
5706 {
5707 // may undisplay the popup menu first
5708 ins_compl_upd_pum();
5709
5710 if (pum_enough_matches())
5711 // Will display the popup menu, don't redraw yet to avoid flicker.
5712 pum_call_update_screen();
5713 else
5714 // Not showing the popup menu yet, redraw to show the user what was
5715 // inserted.
5716 update_screen(0);
5717
5718 // display the updated popup menu
5719 ins_compl_show_pum();
5720#ifdef FEAT_GUI
5721 if (gui.in_use)
5722 {
5723 // Show the cursor after the match, not after the redrawn text.
5724 setcursor();
5725 out_flush_cursor(FALSE, FALSE);
5726 }
5727#endif
5728
5729 // Delete old text to be replaced, since we're still searching and
5730 // don't want to match ourselves!
5731 ins_compl_delete();
5732 }
5733
5734 // Enter will select a match when the match wasn't inserted and the popup
5735 // menu is visible.
5736 if (compl_no_insert && !started)
5737 compl_enter_selects = TRUE;
5738 else
5739 compl_enter_selects = !insert_match && compl_match_array != NULL;
5740
5741 // Show the file name for the match (if any)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005742 if (compl_shown_match->cp_fname != NULL)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005743 ins_compl_show_filename();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005744
5745 return num_matches;
5746}
5747
5748/*
5749 * Call this while finding completions, to check whether the user has hit a key
5750 * that should change the currently displayed completion, or exit completion
5751 * mode. Also, when compl_pending is not zero, show a completion as soon as
5752 * possible. -- webb
5753 * "frequency" specifies out of how many calls we actually check.
5754 * "in_compl_func" is TRUE when called from complete_check(), don't set
5755 * compl_curr_match.
5756 */
5757 void
5758ins_compl_check_keys(int frequency, int in_compl_func)
5759{
5760 static int count = 0;
5761 int c;
5762
5763 // Don't check when reading keys from a script, :normal or feedkeys().
5764 // That would break the test scripts. But do check for keys when called
5765 // from complete_check().
5766 if (!in_compl_func && (using_script() || ex_normal_busy))
5767 return;
5768
5769 // Only do this at regular intervals
5770 if (++count < frequency)
5771 return;
5772 count = 0;
5773
5774 // Check for a typed key. Do use mappings, otherwise vim_is_ctrl_x_key()
5775 // can't do its work correctly.
5776 c = vpeekc_any();
5777 if (c != NUL)
5778 {
5779 if (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R)
5780 {
5781 c = safe_vgetc(); // Eat the character
5782 compl_shows_dir = ins_compl_key2dir(c);
5783 (void)ins_compl_next(FALSE, ins_compl_key2count(c),
5784 c != K_UP && c != K_DOWN, in_compl_func);
5785 }
5786 else
5787 {
5788 // Need to get the character to have KeyTyped set. We'll put it
5789 // back with vungetc() below. But skip K_IGNORE.
5790 c = safe_vgetc();
5791 if (c != K_IGNORE)
5792 {
5793 // Don't interrupt completion when the character wasn't typed,
5794 // e.g., when doing @q to replay keys.
5795 if (c != Ctrl_R && KeyTyped)
5796 compl_interrupted = TRUE;
5797
5798 vungetc(c);
5799 }
5800 }
5801 }
zeertzjq529b9ad2024-06-05 20:27:06 +02005802 if (compl_pending != 0 && !got_int && !(cot_flags & COT_NOINSERT))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005803 {
5804 int todo = compl_pending > 0 ? compl_pending : -compl_pending;
5805
5806 compl_pending = 0;
5807 (void)ins_compl_next(FALSE, todo, TRUE, in_compl_func);
5808 }
5809}
5810
5811/*
5812 * Decide the direction of Insert mode complete from the key typed.
5813 * Returns BACKWARD or FORWARD.
5814 */
5815 static int
5816ins_compl_key2dir(int c)
5817{
5818 if (c == Ctrl_P || c == Ctrl_L
5819 || c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP || c == K_UP)
5820 return BACKWARD;
5821 return FORWARD;
5822}
5823
5824/*
5825 * Return TRUE for keys that are used for completion only when the popup menu
5826 * is visible.
5827 */
5828 static int
5829ins_compl_pum_key(int c)
5830{
5831 return pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP
5832 || c == K_PAGEDOWN || c == K_KPAGEDOWN || c == K_S_DOWN
5833 || c == K_UP || c == K_DOWN);
5834}
5835
5836/*
5837 * Decide the number of completions to move forward.
5838 * Returns 1 for most keys, height of the popup menu for page-up/down keys.
5839 */
5840 static int
5841ins_compl_key2count(int c)
5842{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005843 if (ins_compl_pum_key(c) && c != K_UP && c != K_DOWN)
5844 {
glepnir19e1dd62025-05-08 22:50:38 +02005845 int h = pum_get_height();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005846 if (h > 3)
5847 h -= 2; // keep some context
5848 return h;
5849 }
5850 return 1;
5851}
5852
5853/*
5854 * Return TRUE if completion with "c" should insert the match, FALSE if only
5855 * to change the currently selected completion.
5856 */
5857 static int
5858ins_compl_use_match(int c)
5859{
5860 switch (c)
5861 {
5862 case K_UP:
5863 case K_DOWN:
5864 case K_PAGEDOWN:
5865 case K_KPAGEDOWN:
5866 case K_S_DOWN:
5867 case K_PAGEUP:
5868 case K_KPAGEUP:
5869 case K_S_UP:
5870 return FALSE;
5871 }
5872 return TRUE;
5873}
5874
5875/*
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005876 * Get the pattern, column and length for normal completion (CTRL-N CTRL-P
5877 * completion)
John Marriott5e6ea922024-11-23 14:01:57 +01005878 * Sets the global variables: compl_col, compl_length and compl_pattern.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005879 * Uses the global variables: compl_cont_status and ctrl_x_mode
5880 */
5881 static int
5882get_normal_compl_info(char_u *line, int startcol, colnr_T curs_col)
5883{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005884 if ((compl_cont_status & CONT_SOL) || ctrl_x_mode_path_defines())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005885 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005886 if (!compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005887 {
5888 while (--startcol >= 0 && vim_isIDc(line[startcol]))
5889 ;
5890 compl_col += ++startcol;
5891 compl_length = curs_col - startcol;
5892 }
5893 if (p_ic)
John Marriott8c85a2a2024-05-20 19:18:26 +02005894 {
John Marriott5e6ea922024-11-23 14:01:57 +01005895 compl_pattern.string = str_foldcase(line + compl_col,
5896 compl_length, NULL, 0);
5897 if (compl_pattern.string == NULL)
5898 {
5899 compl_pattern.length = 0;
5900 return FAIL;
5901 }
5902 compl_pattern.length = STRLEN(compl_pattern.string);
5903 }
5904 else
5905 {
5906 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5907 if (compl_pattern.string == NULL)
5908 {
5909 compl_pattern.length = 0;
5910 return FAIL;
5911 }
5912 compl_pattern.length = (size_t)compl_length;
John Marriott8c85a2a2024-05-20 19:18:26 +02005913 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005914 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005915 else if (compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005916 {
5917 char_u *prefix = (char_u *)"\\<";
John Marriott8c85a2a2024-05-20 19:18:26 +02005918 size_t prefixlen = STRLEN_LITERAL("\\<");
John Marriott5e6ea922024-11-23 14:01:57 +01005919 size_t n;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005920
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005921 if (!vim_iswordp(line + compl_col)
5922 || (compl_col > 0
5923 && (vim_iswordp(mb_prevptr(line, line + compl_col)))))
John Marriott8c85a2a2024-05-20 19:18:26 +02005924 {
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005925 prefix = (char_u *)"";
John Marriott8c85a2a2024-05-20 19:18:26 +02005926 prefixlen = 0;
5927 }
John Marriott5e6ea922024-11-23 14:01:57 +01005928
5929 // we need up to 2 extra chars for the prefix
5930 n = quote_meta(NULL, line + compl_col, compl_length) + prefixlen;
5931 compl_pattern.string = alloc(n);
5932 if (compl_pattern.string == NULL)
5933 {
5934 compl_pattern.length = 0;
5935 return FAIL;
5936 }
5937 STRCPY((char *)compl_pattern.string, prefix);
5938 (void)quote_meta(compl_pattern.string + prefixlen,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005939 line + compl_col, compl_length);
John Marriott5e6ea922024-11-23 14:01:57 +01005940 compl_pattern.length = n - 1;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005941 }
5942 else if (--startcol < 0
5943 || !vim_iswordp(mb_prevptr(line, line + startcol + 1)))
5944 {
John Marriott5e6ea922024-11-23 14:01:57 +01005945 size_t len = STRLEN_LITERAL("\\<\\k\\k");
5946
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005947 // Match any word of at least two chars
John Marriott5e6ea922024-11-23 14:01:57 +01005948 compl_pattern.string = vim_strnsave((char_u *)"\\<\\k\\k", len);
5949 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005950 {
John Marriott5e6ea922024-11-23 14:01:57 +01005951 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005952 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005953 }
John Marriott5e6ea922024-11-23 14:01:57 +01005954 compl_pattern.length = len;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005955 compl_col += curs_col;
5956 compl_length = 0;
5957 }
5958 else
5959 {
5960 // Search the point of change class of multibyte character
5961 // or not a word single byte character backward.
5962 if (has_mbyte)
5963 {
5964 int base_class;
5965 int head_off;
5966
5967 startcol -= (*mb_head_off)(line, line + startcol);
5968 base_class = mb_get_class(line + startcol);
5969 while (--startcol >= 0)
5970 {
5971 head_off = (*mb_head_off)(line, line + startcol);
5972 if (base_class != mb_get_class(line + startcol
5973 - head_off))
5974 break;
5975 startcol -= head_off;
5976 }
5977 }
5978 else
glepnir19e1dd62025-05-08 22:50:38 +02005979 {
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005980 while (--startcol >= 0 && vim_iswordc(line[startcol]))
5981 ;
glepnir19e1dd62025-05-08 22:50:38 +02005982 }
5983
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005984 compl_col += ++startcol;
5985 compl_length = (int)curs_col - startcol;
5986 if (compl_length == 1)
5987 {
5988 // Only match word with at least two chars -- webb
5989 // there's no need to call quote_meta,
5990 // alloc(7) is enough -- Acevedo
John Marriott5e6ea922024-11-23 14:01:57 +01005991 compl_pattern.string = alloc(7);
5992 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005993 {
John Marriott5e6ea922024-11-23 14:01:57 +01005994 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005995 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005996 }
John Marriott5e6ea922024-11-23 14:01:57 +01005997 STRCPY((char *)compl_pattern.string, "\\<");
5998 (void)quote_meta(compl_pattern.string + 2, line + compl_col, 1);
5999 STRCAT((char *)compl_pattern.string, "\\k");
6000 compl_pattern.length = STRLEN(compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006001 }
6002 else
6003 {
John Marriott5e6ea922024-11-23 14:01:57 +01006004 size_t n = quote_meta(NULL, line + compl_col, compl_length) + 2;
6005
6006 compl_pattern.string = alloc(n);
6007 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02006008 {
John Marriott5e6ea922024-11-23 14:01:57 +01006009 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006010 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02006011 }
John Marriott5e6ea922024-11-23 14:01:57 +01006012 STRCPY((char *)compl_pattern.string, "\\<");
6013 (void)quote_meta(compl_pattern.string + 2, line + compl_col,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006014 compl_length);
John Marriott5e6ea922024-11-23 14:01:57 +01006015 compl_pattern.length = n - 1;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006016 }
6017 }
6018
6019 return OK;
6020}
6021
6022/*
6023 * Get the pattern, column and length for whole line completion or for the
6024 * complete() function.
6025 * Sets the global variables: compl_col, compl_length and compl_pattern.
6026 */
6027 static int
6028get_wholeline_compl_info(char_u *line, colnr_T curs_col)
6029{
6030 compl_col = (colnr_T)getwhitecols(line);
6031 compl_length = (int)curs_col - (int)compl_col;
6032 if (compl_length < 0) // cursor in indent: empty pattern
6033 compl_length = 0;
6034 if (p_ic)
John Marriott8c85a2a2024-05-20 19:18:26 +02006035 {
John Marriott5e6ea922024-11-23 14:01:57 +01006036 compl_pattern.string = str_foldcase(line + compl_col, compl_length,
6037 NULL, 0);
6038 if (compl_pattern.string == NULL)
6039 {
6040 compl_pattern.length = 0;
6041 return FAIL;
6042 }
6043 compl_pattern.length = STRLEN(compl_pattern.string);
John Marriott8c85a2a2024-05-20 19:18:26 +02006044 }
John Marriott5e6ea922024-11-23 14:01:57 +01006045 else
6046 {
6047 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
6048 if (compl_pattern.string == NULL)
6049 {
6050 compl_pattern.length = 0;
6051 return FAIL;
6052 }
6053 compl_pattern.length = (size_t)compl_length;
6054 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006055
6056 return OK;
6057}
6058
6059/*
6060 * Get the pattern, column and length for filename completion.
6061 * Sets the global variables: compl_col, compl_length and compl_pattern.
6062 */
6063 static int
6064get_filename_compl_info(char_u *line, int startcol, colnr_T curs_col)
6065{
6066 // Go back to just before the first filename character.
6067 if (startcol > 0)
6068 {
6069 char_u *p = line + startcol;
6070
6071 MB_PTR_BACK(line, p);
6072 while (p > line && vim_isfilec(PTR2CHAR(p)))
6073 MB_PTR_BACK(line, p);
6074 if (p == line && vim_isfilec(PTR2CHAR(p)))
6075 startcol = 0;
6076 else
6077 startcol = (int)(p - line) + 1;
6078 }
6079
6080 compl_col += startcol;
6081 compl_length = (int)curs_col - startcol;
John Marriott5e6ea922024-11-23 14:01:57 +01006082 compl_pattern.string = addstar(line + compl_col, compl_length, EXPAND_FILES);
6083 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02006084 {
John Marriott5e6ea922024-11-23 14:01:57 +01006085 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006086 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02006087 }
6088
John Marriott5e6ea922024-11-23 14:01:57 +01006089 compl_pattern.length = STRLEN(compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006090
6091 return OK;
6092}
6093
6094/*
6095 * Get the pattern, column and length for command-line completion.
6096 * Sets the global variables: compl_col, compl_length and compl_pattern.
6097 */
6098 static int
6099get_cmdline_compl_info(char_u *line, colnr_T curs_col)
6100{
John Marriott5e6ea922024-11-23 14:01:57 +01006101 compl_pattern.string = vim_strnsave(line, curs_col);
6102 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02006103 {
John Marriott5e6ea922024-11-23 14:01:57 +01006104 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006105 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02006106 }
John Marriott5e6ea922024-11-23 14:01:57 +01006107 compl_pattern.length = curs_col;
6108 set_cmd_context(&compl_xp, compl_pattern.string,
6109 (int)compl_pattern.length, curs_col, FALSE);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006110 if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL
6111 || compl_xp.xp_context == EXPAND_NOTHING)
6112 // No completion possible, use an empty pattern to get a
6113 // "pattern not found" message.
6114 compl_col = curs_col;
6115 else
John Marriott5e6ea922024-11-23 14:01:57 +01006116 compl_col = (int)(compl_xp.xp_pattern - compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006117 compl_length = curs_col - compl_col;
6118
6119 return OK;
6120}
6121
Girish Palya98c29db2025-06-01 19:40:00 +02006122#ifdef FEAT_COMPL_FUNC
6123/*
6124 * Set global variables related to completion:
6125 * compl_col, compl_length, compl_pattern, and cpt_compl_pattern.
6126 */
6127 static int
6128set_compl_globals(
6129 int startcol UNUSED,
6130 colnr_T curs_col UNUSED,
6131 int is_cpt_compl UNUSED)
6132{
6133 char_u *line = NULL;
6134 string_T *pattern = NULL;
6135 int len;
6136
6137 if (startcol < 0 || startcol > curs_col)
6138 startcol = curs_col;
6139 len = curs_col - startcol;
6140
6141 // Re-obtain line in case it has changed
6142 line = ml_get(curwin->w_cursor.lnum);
6143
6144 pattern = is_cpt_compl ? &cpt_compl_pattern : &compl_pattern;
6145 pattern->string = vim_strnsave(line + startcol, (size_t)len);
6146 if (pattern->string == NULL)
6147 {
6148 pattern->length = 0;
6149 return FAIL;
6150 }
6151 pattern->length = (size_t)len;
6152 if (!is_cpt_compl)
6153 {
6154 compl_col = startcol;
6155 compl_length = len;
6156 }
6157 return OK;
6158}
6159#endif
6160
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006161/*
6162 * Get the pattern, column and length for user defined completion ('omnifunc',
6163 * 'completefunc' and 'thesaurusfunc')
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006164 * Uses the global variable: spell_bad_len
Girish Palyacbe53192025-04-14 22:13:15 +02006165 * Callback function "cb" is set if triggered by a function in the 'cpt'
6166 * option; otherwise, it is NULL.
6167 * "startcol", when not NULL, contains the column returned by function.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006168 */
6169 static int
glepnir19e1dd62025-05-08 22:50:38 +02006170get_userdefined_compl_info(
6171 colnr_T curs_col UNUSED,
6172 callback_T *cb UNUSED,
6173 int *startcol UNUSED)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006174{
6175 int ret = FAIL;
6176
6177#ifdef FEAT_COMPL_FUNC
6178 // Call user defined function 'completefunc' with "a:findstart"
6179 // set to 1 to obtain the length of text to use for completion.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006180 typval_T args[3];
6181 int col;
glepnir19e1dd62025-05-08 22:50:38 +02006182 char_u *funcname = NULL;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006183 pos_T pos;
6184 int save_State = State;
Girish Palyacbe53192025-04-14 22:13:15 +02006185 int is_cpt_function = (cb != NULL);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006186
Girish Palyacbe53192025-04-14 22:13:15 +02006187 if (!is_cpt_function)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006188 {
Girish Palyacbe53192025-04-14 22:13:15 +02006189 // Call 'completefunc' or 'omnifunc' or 'thesaurusfunc' and get pattern
6190 // length as a string
6191 funcname = get_complete_funcname(ctrl_x_mode);
6192 if (*funcname == NUL)
6193 {
6194 semsg(_(e_option_str_is_not_set), ctrl_x_mode_function()
6195 ? "completefunc" : "omnifunc");
6196 return FAIL;
6197 }
6198 cb = get_insert_callback(ctrl_x_mode);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006199 }
6200
6201 args[0].v_type = VAR_NUMBER;
6202 args[0].vval.v_number = 1;
6203 args[1].v_type = VAR_STRING;
6204 args[1].vval.v_string = (char_u *)"";
6205 args[2].v_type = VAR_UNKNOWN;
6206 pos = curwin->w_cursor;
zeertzjqcfe45652022-05-27 17:26:55 +01006207 ++textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006208 col = call_callback_retnr(cb, 2, args);
zeertzjqcfe45652022-05-27 17:26:55 +01006209 --textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006210
6211 State = save_State;
6212 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02006213 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006214 validate_cursor();
6215 if (!EQUAL_POS(curwin->w_cursor, pos))
6216 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00006217 emsg(_(e_complete_function_deleted_text));
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006218 return FAIL;
6219 }
6220
Girish Palyacbe53192025-04-14 22:13:15 +02006221 if (startcol != NULL)
6222 *startcol = col;
6223
LemonBoy9bcb9ca2022-05-26 15:23:26 +01006224 // Return value -2 means the user complete function wants to cancel the
6225 // complete without an error, do the same if the function did not execute
6226 // successfully.
6227 if (col == -2 || aborting())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006228 return FAIL;
glepnir19e1dd62025-05-08 22:50:38 +02006229
LemonBoy9bcb9ca2022-05-26 15:23:26 +01006230 // Return value -3 does the same as -2 and leaves CTRL-X mode.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006231 if (col == -3)
6232 {
Girish Palyacbe53192025-04-14 22:13:15 +02006233 if (is_cpt_function)
6234 return FAIL;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006235 ctrl_x_mode = CTRL_X_NORMAL;
6236 edit_submode = NULL;
6237 if (!shortmess(SHM_COMPLETIONMENU))
6238 msg_clr_cmdline();
6239 return FAIL;
6240 }
6241
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00006242 // Reset extended parameters of completion, when starting new
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006243 // completion.
6244 compl_opt_refresh_always = FALSE;
6245 compl_opt_suppress_empty = FALSE;
6246
Girish Palya98c29db2025-06-01 19:40:00 +02006247 ret = !is_cpt_function ? set_compl_globals(col, curs_col, FALSE) : OK;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006248#endif
6249
6250 return ret;
6251}
6252
6253/*
6254 * Get the pattern, column and length for spell completion.
6255 * Sets the global variables: compl_col, compl_length and compl_pattern.
6256 * Uses the global variable: spell_bad_len
6257 */
6258 static int
6259get_spell_compl_info(int startcol UNUSED, colnr_T curs_col UNUSED)
6260{
6261 int ret = FAIL;
6262#ifdef FEAT_SPELL
glepnir19e1dd62025-05-08 22:50:38 +02006263 char_u *line = NULL;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006264
6265 if (spell_bad_len > 0)
6266 compl_col = curs_col - spell_bad_len;
6267 else
6268 compl_col = spell_word_start(startcol);
glepnir19e1dd62025-05-08 22:50:38 +02006269
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006270 if (compl_col >= (colnr_T)startcol)
6271 {
6272 compl_length = 0;
6273 compl_col = curs_col;
6274 }
6275 else
6276 {
6277 spell_expand_check_cap(compl_col);
6278 compl_length = (int)curs_col - compl_col;
6279 }
6280 // Need to obtain "line" again, it may have become invalid.
6281 line = ml_get(curwin->w_cursor.lnum);
John Marriott5e6ea922024-11-23 14:01:57 +01006282 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
6283 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02006284 {
John Marriott5e6ea922024-11-23 14:01:57 +01006285 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006286 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02006287 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006288
John Marriott5e6ea922024-11-23 14:01:57 +01006289 compl_pattern.length = (size_t)compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006290 ret = OK;
6291#endif
6292
6293 return ret;
6294}
6295
6296/*
6297 * Get the completion pattern, column and length.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006298 * "startcol" - start column number of the completion pattern/text
6299 * "cur_col" - current cursor column
6300 * On return, "line_invalid" is set to TRUE, if the current line may have
6301 * become invalid and needs to be fetched again.
6302 * Returns OK on success.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006303 */
6304 static int
6305compl_get_info(char_u *line, int startcol, colnr_T curs_col, int *line_invalid)
6306{
glepnird5fdfa52025-06-02 19:45:41 +02006307 if (ctrl_x_mode_normal() || ctrl_x_mode_register()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006308 || (ctrl_x_mode & CTRL_X_WANT_IDENT
6309 && !thesaurus_func_complete(ctrl_x_mode)))
6310 {
6311 return get_normal_compl_info(line, startcol, curs_col);
6312 }
6313 else if (ctrl_x_mode_line_or_eval())
6314 {
6315 return get_wholeline_compl_info(line, curs_col);
6316 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006317 else if (ctrl_x_mode_files())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006318 {
6319 return get_filename_compl_info(line, startcol, curs_col);
6320 }
6321 else if (ctrl_x_mode == CTRL_X_CMDLINE)
6322 {
6323 return get_cmdline_compl_info(line, curs_col);
6324 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006325 else if (ctrl_x_mode_function() || ctrl_x_mode_omni()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006326 || thesaurus_func_complete(ctrl_x_mode))
6327 {
Girish Palyacbe53192025-04-14 22:13:15 +02006328 if (get_userdefined_compl_info(curs_col, NULL, NULL) != OK)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006329 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006330 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006331 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006332 else if (ctrl_x_mode_spell())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006333 {
6334 if (get_spell_compl_info(startcol, curs_col) == FAIL)
6335 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006336 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006337 }
6338 else
6339 {
6340 internal_error("ins_complete()");
6341 return FAIL;
6342 }
6343
6344 return OK;
6345}
6346
6347/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006348 * Continue an interrupted completion mode search in "line".
6349 *
6350 * If this same ctrl_x_mode has been interrupted use the text from
6351 * "compl_startpos" to the cursor as a pattern to add a new word instead of
6352 * expand the one before the cursor, in word-wise if "compl_startpos" is not in
6353 * the same line as the cursor then fix it (the line has been split because it
6354 * was longer than 'tw'). if SOL is set then skip the previous pattern, a word
6355 * at the beginning of the line has been inserted, we'll look for that.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006356 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006357 static void
6358ins_compl_continue_search(char_u *line)
6359{
6360 // it is a continued search
6361 compl_cont_status &= ~CONT_INTRPT; // remove INTRPT
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006362 if (ctrl_x_mode_normal() || ctrl_x_mode_path_patterns()
6363 || ctrl_x_mode_path_defines())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006364 {
6365 if (compl_startpos.lnum != curwin->w_cursor.lnum)
6366 {
6367 // line (probably) wrapped, set compl_startpos to the
6368 // first non_blank in the line, if it is not a wordchar
6369 // include it to get a better pattern, but then we don't
6370 // want the "\\<" prefix, check it below
6371 compl_col = (colnr_T)getwhitecols(line);
6372 compl_startpos.col = compl_col;
6373 compl_startpos.lnum = curwin->w_cursor.lnum;
6374 compl_cont_status &= ~CONT_SOL; // clear SOL if present
6375 }
6376 else
6377 {
6378 // S_IPOS was set when we inserted a word that was at the
6379 // beginning of the line, which means that we'll go to SOL
6380 // mode but first we need to redefine compl_startpos
6381 if (compl_cont_status & CONT_S_IPOS)
6382 {
6383 compl_cont_status |= CONT_SOL;
6384 compl_startpos.col = (colnr_T)(skipwhite(
6385 line + compl_length
6386 + compl_startpos.col) - line);
6387 }
6388 compl_col = compl_startpos.col;
6389 }
6390 compl_length = curwin->w_cursor.col - (int)compl_col;
6391 // IObuff is used to add a "word from the next line" would we
6392 // have enough space? just being paranoid
6393#define MIN_SPACE 75
6394 if (compl_length > (IOSIZE - MIN_SPACE))
6395 {
6396 compl_cont_status &= ~CONT_SOL;
6397 compl_length = (IOSIZE - MIN_SPACE);
6398 compl_col = curwin->w_cursor.col - compl_length;
6399 }
6400 compl_cont_status |= CONT_ADDING | CONT_N_ADDS;
6401 if (compl_length < 1)
6402 compl_cont_status &= CONT_LOCAL;
6403 }
glepnird5fdfa52025-06-02 19:45:41 +02006404 else if (ctrl_x_mode_line_or_eval() || ctrl_x_mode_register())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006405 compl_cont_status = CONT_ADDING | CONT_N_ADDS;
6406 else
6407 compl_cont_status = 0;
6408}
6409
6410/*
6411 * start insert mode completion
6412 */
6413 static int
6414ins_compl_start(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006415{
glepnir19e1dd62025-05-08 22:50:38 +02006416 char_u *line = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006417 int startcol = 0; // column where searched text starts
6418 colnr_T curs_col; // cursor column
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006419 int line_invalid = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006420 int save_did_ai = did_ai;
Bram Moolenaard9eefe32019-04-06 14:22:21 +02006421 int flags = CP_ORIGINAL_TEXT;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006422
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006423 // First time we hit ^N or ^P (in a row, I mean)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006424 did_ai = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006425 did_si = FALSE;
6426 can_si = FALSE;
6427 can_si_back = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006428 if (stop_arrow() == FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006429 return FAIL;
6430
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006431 line = ml_get(curwin->w_cursor.lnum);
6432 curs_col = curwin->w_cursor.col;
6433 compl_pending = 0;
glepnir76bdb822025-02-08 19:04:51 +01006434 compl_lnum = curwin->w_cursor.lnum;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006435
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006436 if ((compl_cont_status & CONT_INTRPT) == CONT_INTRPT
6437 && compl_cont_mode == ctrl_x_mode)
6438 // this same ctrl-x_mode was interrupted previously. Continue the
6439 // completion.
6440 ins_compl_continue_search(line);
6441 else
6442 compl_cont_status &= CONT_LOCAL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006443
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006444 if (!compl_status_adding()) // normal expansion
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006445 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006446 compl_cont_mode = ctrl_x_mode;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006447 if (ctrl_x_mode_not_default())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006448 // Remove LOCAL if ctrl_x_mode != CTRL_X_NORMAL
6449 compl_cont_status = 0;
6450 compl_cont_status |= CONT_N_ADDS;
6451 compl_startpos = curwin->w_cursor;
6452 startcol = (int)curs_col;
6453 compl_col = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006454 }
6455
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006456 // Work out completion pattern and original text -- webb
6457 if (compl_get_info(line, startcol, curs_col, &line_invalid) == FAIL)
6458 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006459 if (ctrl_x_mode_function() || ctrl_x_mode_omni()
6460 || thesaurus_func_complete(ctrl_x_mode))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006461 // restore did_ai, so that adding comment leader works
6462 did_ai = save_did_ai;
6463 return FAIL;
6464 }
6465 // If "line" was changed while getting completion info get it again.
6466 if (line_invalid)
6467 line = ml_get(curwin->w_cursor.lnum);
6468
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006469 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006470 {
6471 edit_submode_pre = (char_u *)_(" Adding");
6472 if (ctrl_x_mode_line_or_eval())
6473 {
6474 // Insert a new line, keep indentation but ignore 'comments'.
6475 char_u *old = curbuf->b_p_com;
6476
6477 curbuf->b_p_com = (char_u *)"";
6478 compl_startpos.lnum = curwin->w_cursor.lnum;
6479 compl_startpos.col = compl_col;
6480 ins_eol('\r');
6481 curbuf->b_p_com = old;
6482 compl_length = 0;
6483 compl_col = curwin->w_cursor.col;
glepnir76bdb822025-02-08 19:04:51 +01006484 compl_lnum = curwin->w_cursor.lnum;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006485 }
glepnircfe502c2025-04-17 20:17:53 +02006486 else if (ctrl_x_mode_normal() && cfc_has_mode())
glepnir7cfe6932024-09-15 20:06:28 +02006487 {
6488 compl_startpos = curwin->w_cursor;
6489 compl_cont_status &= CONT_S_IPOS;
6490 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006491 }
6492 else
6493 {
6494 edit_submode_pre = NULL;
6495 compl_startpos.col = compl_col;
6496 }
6497
6498 if (compl_cont_status & CONT_LOCAL)
6499 edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]);
6500 else
6501 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
6502
6503 // If any of the original typed text has been changed we need to fix
6504 // the redo buffer.
6505 ins_compl_fixRedoBufForLeader(NULL);
6506
6507 // Always add completion for the original text.
John Marriott5e6ea922024-11-23 14:01:57 +01006508 VIM_CLEAR_STRING(compl_orig_text);
6509 compl_orig_text.length = (size_t)compl_length;
6510 compl_orig_text.string = vim_strnsave(line + compl_col, (size_t)compl_length);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006511 if (p_ic)
6512 flags |= CP_ICASE;
zeertzjq4422de62025-03-07 19:06:02 +01006513 if (compl_orig_text.string == NULL
6514 || ins_compl_add(compl_orig_text.string,
6515 (int)compl_orig_text.length,
6516 NULL, NULL, NULL, 0, flags, FALSE, NULL, 0) != OK)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006517 {
John Marriott5e6ea922024-11-23 14:01:57 +01006518 VIM_CLEAR_STRING(compl_pattern);
6519 VIM_CLEAR_STRING(compl_orig_text);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006520 return FAIL;
6521 }
6522
6523 // showmode might reset the internal line pointers, so it must
6524 // be called before line = ml_get(), or when this address is no
6525 // longer needed. -- Acevedo.
6526 edit_submode_extra = (char_u *)_("-- Searching...");
6527 edit_submode_highl = HLF_COUNT;
6528 showmode();
6529 edit_submode_extra = NULL;
6530 out_flush();
6531
6532 return OK;
6533}
6534
6535/*
6536 * display the completion status message
6537 */
6538 static void
6539ins_compl_show_statusmsg(void)
6540{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006541 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006542 if (is_first_match(compl_first_match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006543 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006544 edit_submode_extra = compl_status_adding() && compl_length > 1
Bram Moolenaarb53a1902022-11-15 13:57:38 +00006545 ? (char_u *)_("Hit end of paragraph")
6546 : (char_u *)_("Pattern not found");
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006547 edit_submode_highl = HLF_E;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006548 }
6549
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006550 if (edit_submode_extra == NULL)
6551 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006552 if (match_at_original_text(compl_curr_match))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006553 {
6554 edit_submode_extra = (char_u *)_("Back at original");
6555 edit_submode_highl = HLF_W;
6556 }
6557 else if (compl_cont_status & CONT_S_IPOS)
6558 {
6559 edit_submode_extra = (char_u *)_("Word from other line");
6560 edit_submode_highl = HLF_COUNT;
6561 }
6562 else if (compl_curr_match->cp_next == compl_curr_match->cp_prev)
6563 {
6564 edit_submode_extra = (char_u *)_("The only match");
6565 edit_submode_highl = HLF_COUNT;
Bram Moolenaarf9d51352020-10-26 19:22:42 +01006566 compl_curr_match->cp_number = 1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006567 }
6568 else
6569 {
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01006570#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006571 // Update completion sequence number when needed.
6572 if (compl_curr_match->cp_number == -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01006573 ins_compl_update_sequence_numbers();
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01006574#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006575 // The match should always have a sequence number now, this is
6576 // just a safety check.
6577 if (compl_curr_match->cp_number != -1)
6578 {
6579 // Space for 10 text chars. + 2x10-digit no.s = 31.
6580 // Translations may need more than twice that.
6581 static char_u match_ref[81];
6582
6583 if (compl_matches > 0)
6584 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006585 _("match %d of %d"),
6586 compl_curr_match->cp_number, compl_matches);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006587 else
6588 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006589 _("match %d"),
6590 compl_curr_match->cp_number);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006591 edit_submode_extra = match_ref;
6592 edit_submode_highl = HLF_R;
6593 if (dollar_vcol >= 0)
6594 curs_columns(FALSE);
6595 }
6596 }
6597 }
6598
6599 // Show a message about what (completion) mode we're in.
6600 if (!compl_opt_suppress_empty)
6601 {
6602 showmode();
6603 if (!shortmess(SHM_COMPLETIONMENU))
6604 {
6605 if (edit_submode_extra != NULL)
6606 {
6607 if (!p_smd)
Bram Moolenaarcc233582020-12-12 13:32:07 +01006608 {
6609 msg_hist_off = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006610 msg_attr((char *)edit_submode_extra,
6611 edit_submode_highl < HLF_COUNT
6612 ? HL_ATTR(edit_submode_highl) : 0);
Bram Moolenaarcc233582020-12-12 13:32:07 +01006613 msg_hist_off = FALSE;
6614 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006615 }
6616 else
6617 msg_clr_cmdline(); // necessary for "noshowmode"
6618 }
6619 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006620}
6621
6622/*
6623 * Do Insert mode completion.
6624 * Called when character "c" was typed, which has a meaning for completion.
6625 * Returns OK if completion was done, FAIL if something failed (out of mem).
6626 */
6627 int
6628ins_complete(int c, int enable_pum)
6629{
6630 int n;
6631 int save_w_wrow;
6632 int save_w_leftcol;
6633 int insert_match;
6634
6635 compl_direction = ins_compl_key2dir(c);
6636 insert_match = ins_compl_use_match(c);
6637
6638 if (!compl_started)
6639 {
6640 if (ins_compl_start() == FAIL)
6641 return FAIL;
6642 }
6643 else if (insert_match && stop_arrow() == FAIL)
6644 return FAIL;
6645
glepnircf7f0122025-04-15 19:02:00 +02006646 compl_curr_win = curwin;
6647 compl_curr_buf = curwin->w_buffer;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006648 compl_shown_match = compl_curr_match;
6649 compl_shows_dir = compl_direction;
6650
6651 // Find next match (and following matches).
6652 save_w_wrow = curwin->w_wrow;
6653 save_w_leftcol = curwin->w_leftcol;
6654 n = ins_compl_next(TRUE, ins_compl_key2count(c), insert_match, FALSE);
6655
6656 // may undisplay the popup menu
6657 ins_compl_upd_pum();
6658
6659 if (n > 1) // all matches have been found
6660 compl_matches = n;
6661 compl_curr_match = compl_shown_match;
6662 compl_direction = compl_shows_dir;
6663
6664 // Eat the ESC that vgetc() returns after a CTRL-C to avoid leaving Insert
6665 // mode.
6666 if (got_int && !global_busy)
6667 {
6668 (void)vgetc();
6669 got_int = FALSE;
6670 }
6671
6672 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006673 if (is_first_match(compl_first_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006674 {
6675 // remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,
6676 // because we couldn't expand anything at first place, but if we used
6677 // ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word
6678 // (such as M in M'exico) if not tried already. -- Acevedo
6679 if (compl_length > 1
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006680 || compl_status_adding()
6681 || (ctrl_x_mode_not_default()
6682 && !ctrl_x_mode_path_patterns()
6683 && !ctrl_x_mode_path_defines()))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006684 compl_cont_status &= ~CONT_N_ADDS;
6685 }
6686
6687 if (compl_curr_match->cp_flags & CP_CONT_S_IPOS)
6688 compl_cont_status |= CONT_S_IPOS;
6689 else
6690 compl_cont_status &= ~CONT_S_IPOS;
6691
6692 ins_compl_show_statusmsg();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006693
6694 // Show the popup menu, unless we got interrupted.
6695 if (enable_pum && !compl_interrupted)
6696 show_pum(save_w_wrow, save_w_leftcol);
6697
6698 compl_was_interrupted = compl_interrupted;
6699 compl_interrupted = FALSE;
6700
6701 return OK;
6702}
6703
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00006704/*
6705 * Remove (if needed) and show the popup menu
6706 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006707 static void
6708show_pum(int prev_w_wrow, int prev_w_leftcol)
6709{
6710 // RedrawingDisabled may be set when invoked through complete().
Bram Moolenaar79cdf022023-05-20 14:07:00 +01006711 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006712 RedrawingDisabled = 0;
6713
6714 // If the cursor moved or the display scrolled we need to remove the pum
6715 // first.
6716 setcursor();
6717 if (prev_w_wrow != curwin->w_wrow || prev_w_leftcol != curwin->w_leftcol)
6718 ins_compl_del_pum();
6719
6720 ins_compl_show_pum();
6721 setcursor();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01006722
6723 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006724}
6725
6726/*
6727 * Looks in the first "len" chars. of "src" for search-metachars.
6728 * If dest is not NULL the chars. are copied there quoting (with
6729 * a backslash) the metachars, and dest would be NUL terminated.
6730 * Returns the length (needed) of dest
6731 */
6732 static unsigned
6733quote_meta(char_u *dest, char_u *src, int len)
6734{
6735 unsigned m = (unsigned)len + 1; // one extra for the NUL
6736
6737 for ( ; --len >= 0; src++)
6738 {
6739 switch (*src)
6740 {
6741 case '.':
6742 case '*':
6743 case '[':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006744 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006745 break;
6746 // FALLTHROUGH
6747 case '~':
Bram Moolenaarf4e20992020-12-21 19:59:08 +01006748 if (!magic_isset()) // quote these only if magic is set
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006749 break;
6750 // FALLTHROUGH
6751 case '\\':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006752 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006753 break;
6754 // FALLTHROUGH
6755 case '^': // currently it's not needed.
6756 case '$':
6757 m++;
6758 if (dest != NULL)
6759 *dest++ = '\\';
6760 break;
6761 }
6762 if (dest != NULL)
6763 *dest++ = *src;
6764 // Copy remaining bytes of a multibyte character.
6765 if (has_mbyte)
6766 {
glepnir19e1dd62025-05-08 22:50:38 +02006767 int mb_len = (*mb_ptr2len)(src) - 1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006768 if (mb_len > 0 && len >= mb_len)
glepnir19e1dd62025-05-08 22:50:38 +02006769 for (int i = 0; i < mb_len; ++i)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006770 {
6771 --len;
6772 ++src;
6773 if (dest != NULL)
6774 *dest++ = *src;
6775 }
6776 }
6777 }
6778 if (dest != NULL)
6779 *dest = NUL;
6780
6781 return m;
6782}
6783
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006784#if defined(EXITFREE) || defined(PROTO)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006785 void
6786free_insexpand_stuff(void)
6787{
John Marriott5e6ea922024-11-23 14:01:57 +01006788 VIM_CLEAR_STRING(compl_orig_text);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00006789# ifdef FEAT_EVAL
6790 free_callback(&cfu_cb);
6791 free_callback(&ofu_cb);
6792 free_callback(&tsrfu_cb);
6793# endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006794}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006795#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006796
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006797#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006798/*
6799 * Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly
6800 * spelled word, if there is one.
6801 */
6802 static void
6803spell_back_to_badword(void)
6804{
6805 pos_T tpos = curwin->w_cursor;
6806
Christ van Willegen - van Noort8e4c4c72024-05-17 18:49:27 +02006807 spell_bad_len = spell_move_to(curwin, BACKWARD, SMT_ALL, TRUE, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006808 if (curwin->w_cursor.col != tpos.col)
6809 start_arrow(&tpos);
6810}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006811#endif
Girish Palyacbe53192025-04-14 22:13:15 +02006812
6813/*
6814 * Reset the info associated with completion sources.
6815 */
6816 static void
Girish Palya0ac1eb32025-04-16 20:18:33 +02006817cpt_sources_clear(void)
Girish Palyacbe53192025-04-14 22:13:15 +02006818{
Girish Palya0ac1eb32025-04-16 20:18:33 +02006819 VIM_CLEAR(cpt_sources_array);
6820 cpt_sources_index = -1;
6821 cpt_sources_count = 0;
Girish Palyacbe53192025-04-14 22:13:15 +02006822}
6823
6824/*
Girish Palya98c29db2025-06-01 19:40:00 +02006825 * Setup completion sources.
Girish Palyacbe53192025-04-14 22:13:15 +02006826 */
6827 static int
Girish Palya98c29db2025-06-01 19:40:00 +02006828setup_cpt_sources(void)
Girish Palyacbe53192025-04-14 22:13:15 +02006829{
Girish Palya0ac1eb32025-04-16 20:18:33 +02006830 char_u buf[LSIZE];
6831 int slen;
Girish Palya98c29db2025-06-01 19:40:00 +02006832 int count = 0, idx = 0;
Girish Palya0ac1eb32025-04-16 20:18:33 +02006833 char_u *p;
Girish Palyacbe53192025-04-14 22:13:15 +02006834
Girish Palya0ac1eb32025-04-16 20:18:33 +02006835 for (p = curbuf->b_p_cpt; *p;)
Girish Palyacbe53192025-04-14 22:13:15 +02006836 {
6837 while (*p == ',' || *p == ' ') // Skip delimiters
6838 p++;
6839 if (*p) // If not end of string, count this segment
6840 {
Girish Palya0ac1eb32025-04-16 20:18:33 +02006841 (void)copy_option_part(&p, buf, LSIZE, ","); // Advance p
Girish Palyacbe53192025-04-14 22:13:15 +02006842 count++;
Girish Palyacbe53192025-04-14 22:13:15 +02006843 }
6844 }
Girish Palya98c29db2025-06-01 19:40:00 +02006845 if (count == 0)
6846 return OK;
6847
Girish Palya0ac1eb32025-04-16 20:18:33 +02006848 cpt_sources_clear();
6849 cpt_sources_count = count;
Girish Palya98c29db2025-06-01 19:40:00 +02006850 cpt_sources_array = ALLOC_CLEAR_MULT(cpt_source_T, count);
6851 if (cpt_sources_array == NULL)
Girish Palyacbe53192025-04-14 22:13:15 +02006852 {
Girish Palya98c29db2025-06-01 19:40:00 +02006853 cpt_sources_count = 0;
6854 return FAIL;
6855 }
Girish Palya0ac1eb32025-04-16 20:18:33 +02006856
Girish Palya98c29db2025-06-01 19:40:00 +02006857 for (p = curbuf->b_p_cpt; *p;)
6858 {
6859 while (*p == ',' || *p == ' ') // Skip delimiters
6860 p++;
6861 if (*p) // If not end of string, count this segment
6862 {
6863 char_u *t;
6864
6865 vim_memset(buf, 0, LSIZE);
6866 slen = copy_option_part(&p, buf, LSIZE, ","); // Advance p
6867 if (slen > 0 && (t = vim_strchr(buf, '^')) != NULL)
6868 cpt_sources_array[idx].cs_max_matches = atoi((char *)t + 1);
6869 idx++;
Girish Palya0ac1eb32025-04-16 20:18:33 +02006870 }
Girish Palyacbe53192025-04-14 22:13:15 +02006871 }
6872 return OK;
6873}
6874
6875/*
6876 * Return TRUE if any of the completion sources have 'refresh' set to 'always'.
6877 */
6878 static int
6879is_cpt_func_refresh_always(void)
6880{
6881#ifdef FEAT_COMPL_FUNC
glepnir19e1dd62025-05-08 22:50:38 +02006882 for (int i = 0; i < cpt_sources_count; i++)
Girish Palya98c29db2025-06-01 19:40:00 +02006883 if (cpt_sources_array[i].cs_refresh_always)
Girish Palyacbe53192025-04-14 22:13:15 +02006884 return TRUE;
6885#endif
6886 return FALSE;
6887}
6888
6889/*
6890 * Make the completion list non-cyclic.
6891 */
Girish Palyacbe53192025-04-14 22:13:15 +02006892 static void
6893ins_compl_make_linear(void)
6894{
6895 compl_T *m;
6896
6897 if (compl_first_match == NULL || compl_first_match->cp_prev == NULL)
6898 return;
6899 m = compl_first_match->cp_prev;
6900 m->cp_next = NULL;
6901 compl_first_match->cp_prev = NULL;
6902}
Girish Palyacbe53192025-04-14 22:13:15 +02006903
6904/*
6905 * Remove the matches linked to the current completion source (as indicated by
Girish Palya0ac1eb32025-04-16 20:18:33 +02006906 * cpt_sources_index) from the completion list.
Girish Palyacbe53192025-04-14 22:13:15 +02006907 */
6908#ifdef FEAT_COMPL_FUNC
6909 static compl_T *
6910remove_old_matches(void)
6911{
6912 compl_T *sublist_start = NULL, *sublist_end = NULL, *insert_at = NULL;
6913 compl_T *current, *next;
Girish Palya0ac1eb32025-04-16 20:18:33 +02006914 int compl_shown_removed = FALSE;
6915 int forward = (compl_first_match->cp_cpt_source_idx < 0);
6916
6917 compl_direction = forward ? FORWARD : BACKWARD;
6918 compl_shows_dir = compl_direction;
Girish Palyacbe53192025-04-14 22:13:15 +02006919
6920 // Identify the sublist of old matches that needs removal
6921 for (current = compl_first_match; current != NULL; current = current->cp_next)
6922 {
Girish Palya0ac1eb32025-04-16 20:18:33 +02006923 if (current->cp_cpt_source_idx < cpt_sources_index &&
6924 (forward || (!forward && !insert_at)))
Girish Palyacbe53192025-04-14 22:13:15 +02006925 insert_at = current;
6926
Girish Palya0ac1eb32025-04-16 20:18:33 +02006927 if (current->cp_cpt_source_idx == cpt_sources_index)
Girish Palyacbe53192025-04-14 22:13:15 +02006928 {
6929 if (!sublist_start)
6930 sublist_start = current;
6931 sublist_end = current;
6932 if (!compl_shown_removed && compl_shown_match == current)
6933 compl_shown_removed = TRUE;
6934 }
6935
Girish Palya0ac1eb32025-04-16 20:18:33 +02006936 if ((forward && current->cp_cpt_source_idx > cpt_sources_index)
6937 || (!forward && insert_at))
Girish Palyacbe53192025-04-14 22:13:15 +02006938 break;
6939 }
6940
6941 // Re-assign compl_shown_match if necessary
6942 if (compl_shown_removed)
6943 {
6944 if (forward)
6945 compl_shown_match = compl_first_match;
6946 else
6947 { // Last node will have the prefix that is being completed
Girish Palya0ac1eb32025-04-16 20:18:33 +02006948 for (current = compl_first_match; current->cp_next != NULL;
6949 current = current->cp_next)
Girish Palyacbe53192025-04-14 22:13:15 +02006950 ;
6951 compl_shown_match = current;
6952 }
6953 }
6954
6955 if (!sublist_start) // No nodes to remove
6956 return insert_at;
6957
6958 // Update links to remove sublist
6959 if (sublist_start->cp_prev)
6960 sublist_start->cp_prev->cp_next = sublist_end->cp_next;
6961 else
6962 compl_first_match = sublist_end->cp_next;
6963
6964 if (sublist_end->cp_next)
6965 sublist_end->cp_next->cp_prev = sublist_start->cp_prev;
6966
6967 // Free all nodes in the sublist
6968 sublist_end->cp_next = NULL;
6969 for (current = sublist_start; current != NULL; current = next)
6970 {
6971 next = current->cp_next;
6972 ins_compl_item_free(current);
6973 }
6974
6975 return insert_at;
6976}
6977#endif
6978
6979/*
6980 * Retrieve completion matches using the callback function "cb" and store the
6981 * 'refresh:always' flag.
6982 */
6983#ifdef FEAT_COMPL_FUNC
6984 static void
6985get_cpt_func_completion_matches(callback_T *cb UNUSED)
6986{
Girish Palya98c29db2025-06-01 19:40:00 +02006987 int startcol = cpt_sources_array[cpt_sources_index].cs_startcol;
Girish Palyacbe53192025-04-14 22:13:15 +02006988
6989 VIM_CLEAR_STRING(cpt_compl_pattern);
Girish Palya98c29db2025-06-01 19:40:00 +02006990
6991 if (startcol == -2 || startcol == -3)
6992 return;
6993
6994 if (set_compl_globals(startcol, curwin->w_cursor.col, TRUE) == OK)
Girish Palyacbe53192025-04-14 22:13:15 +02006995 {
6996 expand_by_function(0, cpt_compl_pattern.string, cb);
Girish Palya98c29db2025-06-01 19:40:00 +02006997 cpt_sources_array[cpt_sources_index].cs_refresh_always =
Girish Palya0ac1eb32025-04-16 20:18:33 +02006998 compl_opt_refresh_always;
Girish Palyacbe53192025-04-14 22:13:15 +02006999 compl_opt_refresh_always = FALSE;
7000 }
7001}
7002#endif
7003
7004/*
7005 * Retrieve completion matches from functions in the 'cpt' option where the
7006 * 'refresh:always' flag is set.
7007 */
7008 static void
7009cpt_compl_refresh(void)
7010{
7011#ifdef FEAT_COMPL_FUNC
7012 char_u *cpt;
7013 char_u *p;
Christian Brabandtd2079cf2025-04-15 18:10:26 +02007014 callback_T *cb = NULL;
Girish Palya98c29db2025-06-01 19:40:00 +02007015 int startcol, ret;
Girish Palyacbe53192025-04-14 22:13:15 +02007016
7017 // Make the completion list linear (non-cyclic)
7018 ins_compl_make_linear();
7019 // Make a copy of 'cpt' in case the buffer gets wiped out
7020 cpt = vim_strsave(curbuf->b_p_cpt);
Girish Palya0ac1eb32025-04-16 20:18:33 +02007021 strip_caret_numbers_in_place(cpt);
Girish Palyacbe53192025-04-14 22:13:15 +02007022
Girish Palya0ac1eb32025-04-16 20:18:33 +02007023 cpt_sources_index = 0;
Girish Palya7c621052025-05-26 19:41:59 +02007024 for (p = cpt; *p;)
Girish Palyacbe53192025-04-14 22:13:15 +02007025 {
7026 while (*p == ',' || *p == ' ') // Skip delimiters
7027 p++;
7028
Girish Palya98c29db2025-06-01 19:40:00 +02007029 if (cpt_sources_array[cpt_sources_index].cs_refresh_always)
Girish Palyacbe53192025-04-14 22:13:15 +02007030 {
Girish Palya98c29db2025-06-01 19:40:00 +02007031 cb = get_callback_if_cpt_func(p);
Girish Palyacbe53192025-04-14 22:13:15 +02007032 if (cb)
7033 {
7034 compl_curr_match = remove_old_matches();
Girish Palya98c29db2025-06-01 19:40:00 +02007035 ret = get_userdefined_compl_info(curwin->w_cursor.col, cb,
7036 &startcol);
7037 if (ret == FAIL)
7038 {
7039 if (startcol == -3)
7040 cpt_sources_array[cpt_sources_index].cs_refresh_always
7041 = FALSE;
7042 else
7043 startcol = -2;
7044 }
7045 cpt_sources_array[cpt_sources_index].cs_startcol = startcol;
7046 if (ret == OK)
7047 get_cpt_func_completion_matches(cb);
Girish Palyacbe53192025-04-14 22:13:15 +02007048 }
7049 }
7050
Girish Palya7c621052025-05-26 19:41:59 +02007051 (void)copy_option_part(&p, IObuff, IOSIZE, ","); // Advance p
7052 if (may_advance_cpt_index(p))
7053 (void)advance_cpt_sources_index_safe();
Girish Palyacbe53192025-04-14 22:13:15 +02007054 }
Girish Palya0ac1eb32025-04-16 20:18:33 +02007055 cpt_sources_index = -1;
Girish Palyacbe53192025-04-14 22:13:15 +02007056
7057 vim_free(cpt);
7058 // Make the list cyclic
7059 compl_matches = ins_compl_make_cyclic();
7060#endif
7061}