blob: ade7bb772bc8324c012d877a6f8605373841fb90 [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
Bram Moolenaar7591bb32019-03-30 13:53:47 +010041
42# define CTRL_X_MSG(i) ctrl_x_msgs[(i) & ~CTRL_X_WANT_IDENT]
43
44// Message for CTRL-X mode, index is ctrl_x_mode.
45static char *ctrl_x_msgs[] =
46{
47 N_(" Keyword completion (^N^P)"), // CTRL_X_NORMAL, ^P/^N compl.
48 N_(" ^X mode (^]^D^E^F^I^K^L^N^O^Ps^U^V^Y)"),
49 NULL, // CTRL_X_SCROLL: depends on state
50 N_(" Whole line completion (^L^N^P)"),
51 N_(" File name completion (^F^N^P)"),
52 N_(" Tag completion (^]^N^P)"),
53 N_(" Path pattern completion (^N^P)"),
54 N_(" Definition completion (^D^N^P)"),
55 NULL, // CTRL_X_FINISHED
56 N_(" Dictionary completion (^K^N^P)"),
57 N_(" Thesaurus completion (^T^N^P)"),
58 N_(" Command-line completion (^V^N^P)"),
59 N_(" User defined completion (^U^N^P)"),
60 N_(" Omni completion (^O^N^P)"),
zeertzjq7002c052024-06-21 07:55:07 +020061 N_(" Spelling suggestion (^S^N^P)"),
Bram Moolenaar7591bb32019-03-30 13:53:47 +010062 N_(" Keyword Local completion (^N^P)"),
63 NULL, // CTRL_X_EVAL doesn't use msg.
zeertzjqdca29d92021-08-31 19:12:51 +020064 N_(" Command-line completion (^V^N^P)"),
Bram Moolenaar7591bb32019-03-30 13:53:47 +010065};
66
Bram Moolenaar9cb698d2019-08-21 15:30:45 +020067#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +010068static char *ctrl_x_mode_names[] = {
Hirohito Higashi355db992025-04-28 18:07:02 +020069 "keyword",
70 "ctrl_x",
71 "scroll",
72 "whole_line",
73 "files",
74 "tags",
75 "path_patterns",
76 "path_defines",
77 "unknown", // CTRL_X_FINISHED
78 "dictionary",
79 "thesaurus",
80 "cmdline",
81 "function",
82 "omni",
83 "spell",
84 NULL, // CTRL_X_LOCAL_MSG only used in "ctrl_x_msgs"
85 "eval",
86 "cmdline",
Bram Moolenaar7591bb32019-03-30 13:53:47 +010087};
Bram Moolenaar9cb698d2019-08-21 15:30:45 +020088#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +010089
90/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +010091 * Structure used to store one match for insert completion.
92 */
93typedef struct compl_S compl_T;
94struct compl_S
95{
96 compl_T *cp_next;
97 compl_T *cp_prev;
glepnir80b66202024-11-27 21:53:53 +010098 compl_T *cp_match_next; // matched next compl_T
John Marriott5e6ea922024-11-23 14:01:57 +010099 string_T cp_str; // matched text
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200100 char_u *(cp_text[CPT_COUNT]); // text for the menu
Bram Moolenaarab782c52020-01-04 19:00:11 +0100101#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +0100102 typval_T cp_user_data;
Bram Moolenaarab782c52020-01-04 19:00:11 +0100103#endif
glepnir0fe17f82024-10-08 22:26:44 +0200104 char_u *cp_fname; // file containing the match, allocated when
105 // cp_flags has CP_FREE_FNAME
106 int cp_flags; // CP_ values
107 int cp_number; // sequence number
Girish Palyab1565882025-04-15 20:16:00 +0200108 int cp_score; // fuzzy match score or proximity score
glepnird4088ed2024-12-31 10:55:22 +0100109 int cp_in_match_array; // collected by compl_match_array
glepnir7baa0142024-10-09 20:19:25 +0200110 int cp_user_abbr_hlattr; // highlight attribute for abbr
glepnir0fe17f82024-10-08 22:26:44 +0200111 int cp_user_kind_hlattr; // highlight attribute for kind
Girish Palya0ac1eb32025-04-16 20:18:33 +0200112 int cp_cpt_source_idx; // index of this match's source in 'cpt' option
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100113};
114
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200115// values for cp_flags
116# define CP_ORIGINAL_TEXT 1 // the original text when the expansion begun
117# define CP_FREE_FNAME 2 // cp_fname is allocated
118# define CP_CONT_S_IPOS 4 // use CONT_S_IPOS for compl_cont_status
119# define CP_EQUAL 8 // ins_compl_equal() always returns TRUE
120# define CP_ICASE 16 // ins_compl_equal() ignores case
Bram Moolenaar440cf092021-04-03 20:13:30 +0200121# define CP_FAST 32 // use fast_breakcheck instead of ui_breakcheck
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100122
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100123/*
124 * All the current matches are stored in a list.
125 * "compl_first_match" points to the start of the list.
126 * "compl_curr_match" points to the currently selected entry.
127 * "compl_shown_match" is different from compl_curr_match during
Girish Palyacbe53192025-04-14 22:13:15 +0200128 * ins_compl_get_exp(), when new matches are added to the list.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000129 * "compl_old_match" points to previous "compl_curr_match".
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100130 */
131static compl_T *compl_first_match = NULL;
132static compl_T *compl_curr_match = NULL;
133static compl_T *compl_shown_match = NULL;
134static compl_T *compl_old_match = NULL;
135
glepnirf31cfa22025-03-06 21:59:13 +0100136// list used to store the compl_T which have the max score
137// used for completefuzzycollect
138static compl_T **compl_best_matches = NULL;
139static int compl_num_bests = 0;
140// inserted a longest when completefuzzycollect enabled
141static int compl_cfc_longest_ins = FALSE;
142
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100143// After using a cursor key <Enter> selects a match in the popup menu,
144// otherwise it inserts a line break.
145static int compl_enter_selects = FALSE;
146
147// When "compl_leader" is not NULL only matches that start with this string
148// are used.
John Marriott5e6ea922024-11-23 14:01:57 +0100149static string_T compl_leader = {NULL, 0};
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100150
151static int compl_get_longest = FALSE; // put longest common string
152 // in compl_leader
153
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100154// Selected one of the matches. When FALSE the match was edited or using the
155// longest common string.
156static int compl_used_match;
157
158// didn't finish finding completions.
159static int compl_was_interrupted = FALSE;
160
161// Set when character typed while looking for matches and it means we should
162// stop looking for matches.
163static int compl_interrupted = FALSE;
164
165static int compl_restarting = FALSE; // don't insert match
166
167// When the first completion is done "compl_started" is set. When it's
168// FALSE the word to be completed must be located.
169static int compl_started = FALSE;
170
171// Which Ctrl-X mode are we in?
172static int ctrl_x_mode = CTRL_X_NORMAL;
173
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000174static int compl_matches = 0; // number of completion matches
Girish Palyacbe53192025-04-14 22:13:15 +0200175static string_T compl_pattern = {NULL, 0}; // search pattern for matching items
176#ifdef FEAT_COMPL_FUNC
177static string_T cpt_compl_pattern = {NULL, 0}; // pattern returned by func in 'cpt'
178#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100179static int compl_direction = FORWARD;
180static int compl_shows_dir = FORWARD;
181static int compl_pending = 0; // > 1 for postponed CTRL-N
182static pos_T compl_startpos;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000183// Length in bytes of the text being completed (this is deleted to be replaced
184// by the match.)
185static int compl_length = 0;
glepnir76bdb822025-02-08 19:04:51 +0100186static linenr_T compl_lnum = 0; // lnum where the completion start
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100187static colnr_T compl_col = 0; // column where the text starts
188 // that is being completed
glepnir6a38aff2024-12-16 21:56:16 +0100189static colnr_T compl_ins_end_col = 0;
John Marriott5e6ea922024-11-23 14:01:57 +0100190static string_T compl_orig_text = {NULL, 0}; // text as it was before
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100191 // completion started
192static int compl_cont_mode = 0;
193static expand_T compl_xp;
194
glepnircf7f0122025-04-15 19:02:00 +0200195static win_T *compl_curr_win = NULL; // win where completion is active
196static buf_T *compl_curr_buf = NULL; // buf where completion is active
197
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000198// List of flags for method of completion.
199static int compl_cont_status = 0;
200# define CONT_ADDING 1 // "normal" or "adding" expansion
201# define CONT_INTRPT (2 + 4) // a ^X interrupted the current expansion
202 // it's set only iff N_ADDS is set
203# define CONT_N_ADDS 4 // next ^X<> will add-new or expand-current
204# define CONT_S_IPOS 8 // next ^X<> will set initial_pos?
205 // if so, word-wise-expansion will set SOL
206# define CONT_SOL 16 // pattern includes start of line, just for
207 // word-wise expansion, not set for ^X^L
208# define CONT_LOCAL 32 // for ctrl_x_mode 0, ^X^P/^X^N do a local
209 // expansion, (eg use complete=.)
210
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100211static int compl_opt_refresh_always = FALSE;
212static int compl_opt_suppress_empty = FALSE;
213
glepnira218cc62024-06-03 19:32:39 +0200214static int compl_selected_item = -1;
215
glepnir8159fb12024-07-17 20:32:54 +0200216static int *compl_fuzzy_scores;
217
Girish Palya0ac1eb32025-04-16 20:18:33 +0200218// Define the structure for completion source (in 'cpt' option) information
219typedef struct cpt_source_T
220{
221 int refresh_always; // Flag array to indicate which 'cpt' functions have 'refresh:always' set
222 int max_matches; // Maximum number of items to display in the menu from the source
223} cpt_source_T;
224
225static cpt_source_T *cpt_sources_array; // Pointer to the array of completion sources
226static int cpt_sources_count; // Total number of completion sources specified in the 'cpt' option
227static int cpt_sources_index; // Index of the current completion source being expanded
Girish Palyacbe53192025-04-14 22:13:15 +0200228
glepnir6a38aff2024-12-16 21:56:16 +0100229// "compl_match_array" points the currently displayed list of entries in the
230// popup menu. It is NULL when there is no popup menu.
231static pumitem_T *compl_match_array = NULL;
232static int compl_match_arraysize;
233
glepnirf31cfa22025-03-06 21:59:13 +0100234static 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 +0100235static void ins_compl_longest_match(compl_T *match);
236static void ins_compl_del_pum(void);
237static 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 +0100238static void ins_compl_free(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100239static int ins_compl_need_restart(void);
240static void ins_compl_new_leader(void);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000241static int get_compl_len(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100242static void ins_compl_restart(void);
John Marriott5e6ea922024-11-23 14:01:57 +0100243static void ins_compl_set_original_text(char_u *str, size_t len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100244static void ins_compl_fixRedoBufForLeader(char_u *ptr_arg);
245# if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
246static void ins_compl_add_list(list_T *list);
247static void ins_compl_add_dict(dict_T *dict);
Girish Palyacbe53192025-04-14 22:13:15 +0200248static int get_userdefined_compl_info(colnr_T curs_col, callback_T *cb, int *startcol);
Girish Palyacbe53192025-04-14 22:13:15 +0200249static void get_cpt_func_completion_matches(callback_T *cb);
Girish Palya0ac1eb32025-04-16 20:18:33 +0200250static callback_T *get_cpt_func_callback(char_u *funcname);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100251# endif
Girish Palya0ac1eb32025-04-16 20:18:33 +0200252static int cpt_sources_init(void);
Girish Palyacbe53192025-04-14 22:13:15 +0200253static int is_cpt_func_refresh_always(void);
Girish Palya0ac1eb32025-04-16 20:18:33 +0200254static void cpt_sources_clear(void);
Girish Palyacbe53192025-04-14 22:13:15 +0200255static void cpt_compl_refresh(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100256static int ins_compl_key2dir(int c);
257static int ins_compl_pum_key(int c);
258static int ins_compl_key2count(int c);
259static void show_pum(int prev_w_wrow, int prev_w_leftcol);
260static unsigned quote_meta(char_u *dest, char_u *str, int len);
glepnir76bdb822025-02-08 19:04:51 +0100261static int ins_compl_has_multiple(void);
262static void ins_compl_expand_multiple(char_u *str);
glepnirf31cfa22025-03-06 21:59:13 +0100263static void ins_compl_longest_insert(char_u *prefix);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100264
265#ifdef FEAT_SPELL
266static void spell_back_to_badword(void);
267static int spell_bad_len = 0; // length of located bad word
268#endif
269
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100270/*
271 * CTRL-X pressed in Insert mode.
272 */
273 void
274ins_ctrl_x(void)
275{
zeertzjqdca29d92021-08-31 19:12:51 +0200276 if (!ctrl_x_mode_cmdline())
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100277 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000278 // if the next ^X<> won't ADD nothing, then reset compl_cont_status
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100279 if (compl_cont_status & CONT_N_ADDS)
280 compl_cont_status |= CONT_INTRPT;
281 else
282 compl_cont_status = 0;
283 // We're not sure which CTRL-X mode it will be yet
284 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
285 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
286 edit_submode_pre = NULL;
287 showmode();
288 }
zeertzjqdca29d92021-08-31 19:12:51 +0200289 else
290 // CTRL-X in CTRL-X CTRL-V mode behaves differently to make CTRL-X
291 // CTRL-V look like CTRL-N
292 ctrl_x_mode = CTRL_X_CMDLINE_CTRL_X;
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +0100293
LemonBoy2bf52dd2022-04-09 18:17:34 +0100294 may_trigger_modechanged();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100295}
296
297/*
298 * Functions to check the current CTRL-X mode.
299 */
Bram Moolenaarebfec1c2023-01-22 21:14:53 +0000300int ctrl_x_mode_none(void)
301 { return ctrl_x_mode == 0; }
302int ctrl_x_mode_normal(void)
303 { return ctrl_x_mode == CTRL_X_NORMAL; }
304int ctrl_x_mode_scroll(void)
305 { return ctrl_x_mode == CTRL_X_SCROLL; }
306int ctrl_x_mode_whole_line(void)
307 { return ctrl_x_mode == CTRL_X_WHOLE_LINE; }
308int ctrl_x_mode_files(void)
309 { return ctrl_x_mode == CTRL_X_FILES; }
310int ctrl_x_mode_tags(void)
311 { return ctrl_x_mode == CTRL_X_TAGS; }
312int ctrl_x_mode_path_patterns(void)
313 { return ctrl_x_mode == CTRL_X_PATH_PATTERNS; }
314int ctrl_x_mode_path_defines(void)
315 { return ctrl_x_mode == CTRL_X_PATH_DEFINES; }
316int ctrl_x_mode_dictionary(void)
317 { return ctrl_x_mode == CTRL_X_DICTIONARY; }
318int ctrl_x_mode_thesaurus(void)
319 { return ctrl_x_mode == CTRL_X_THESAURUS; }
320int ctrl_x_mode_cmdline(void)
321 { return ctrl_x_mode == CTRL_X_CMDLINE
zeertzjqdca29d92021-08-31 19:12:51 +0200322 || ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X; }
Bram Moolenaarebfec1c2023-01-22 21:14:53 +0000323int ctrl_x_mode_function(void)
324 { return ctrl_x_mode == CTRL_X_FUNCTION; }
325int ctrl_x_mode_omni(void)
326 { return ctrl_x_mode == CTRL_X_OMNI; }
327int ctrl_x_mode_spell(void)
328 { return ctrl_x_mode == CTRL_X_SPELL; }
329static int ctrl_x_mode_eval(void)
330 { return ctrl_x_mode == CTRL_X_EVAL; }
331int ctrl_x_mode_line_or_eval(void)
332 { return ctrl_x_mode == CTRL_X_WHOLE_LINE || ctrl_x_mode == CTRL_X_EVAL; }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100333
334/*
335 * Whether other than default completion has been selected.
336 */
337 int
338ctrl_x_mode_not_default(void)
339{
340 return ctrl_x_mode != CTRL_X_NORMAL;
341}
342
343/*
zeertzjqdca29d92021-08-31 19:12:51 +0200344 * Whether CTRL-X was typed without a following character,
345 * not including when in CTRL-X CTRL-V mode.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100346 */
347 int
348ctrl_x_mode_not_defined_yet(void)
349{
350 return ctrl_x_mode == CTRL_X_NOT_DEFINED_YET;
351}
352
353/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000354 * Return TRUE if currently in "normal" or "adding" insert completion matches
355 * state
356 */
357 int
358compl_status_adding(void)
359{
360 return compl_cont_status & CONT_ADDING;
361}
362
363/*
364 * Return TRUE if the completion pattern includes start of line, just for
365 * word-wise expansion.
366 */
367 int
368compl_status_sol(void)
369{
370 return compl_cont_status & CONT_SOL;
371}
372
373/*
374 * Return TRUE if ^X^P/^X^N will do a local completion (i.e. use complete=.)
375 */
376 int
377compl_status_local(void)
378{
379 return compl_cont_status & CONT_LOCAL;
380}
381
382/*
383 * Clear the completion status flags
384 */
385 void
386compl_status_clear(void)
387{
388 compl_cont_status = 0;
389}
390
391/*
392 * Return TRUE if completion is using the forward direction matches
393 */
394 static int
395compl_dir_forward(void)
396{
397 return compl_direction == FORWARD;
398}
399
400/*
401 * Return TRUE if currently showing forward completion matches
402 */
403 static int
404compl_shows_dir_forward(void)
405{
406 return compl_shows_dir == FORWARD;
407}
408
409/*
410 * Return TRUE if currently showing backward completion matches
411 */
412 static int
413compl_shows_dir_backward(void)
414{
415 return compl_shows_dir == BACKWARD;
416}
417
418/*
419 * Return TRUE if the 'dictionary' or 'thesaurus' option can be used.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100420 */
421 int
422has_compl_option(int dict_opt)
423{
424 if (dict_opt ? (*curbuf->b_p_dict == NUL && *p_dict == NUL
Bram Moolenaare2c453d2019-08-21 14:37:09 +0200425#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100426 && !curwin->w_p_spell
Bram Moolenaare2c453d2019-08-21 14:37:09 +0200427#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100428 )
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +0100429 : (*curbuf->b_p_tsr == NUL && *p_tsr == NUL
430#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +0100431 && *curbuf->b_p_tsrfu == NUL && *p_tsrfu == NUL
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +0100432#endif
433 ))
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100434 {
435 ctrl_x_mode = CTRL_X_NORMAL;
436 edit_submode = NULL;
437 msg_attr(dict_opt ? _("'dictionary' option is empty")
438 : _("'thesaurus' option is empty"),
439 HL_ATTR(HLF_E));
Bram Moolenaar28ee8922020-10-28 20:20:00 +0100440 if (emsg_silent == 0 && !in_assert_fails)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100441 {
442 vim_beep(BO_COMPL);
443 setcursor();
444 out_flush();
445#ifdef FEAT_EVAL
446 if (!get_vim_var_nr(VV_TESTING))
447#endif
Bram Moolenaareda1da02019-11-17 17:06:33 +0100448 ui_delay(2004L, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100449 }
450 return FALSE;
451 }
452 return TRUE;
453}
454
455/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000456 * Is the character "c" a valid key to go to or keep us in CTRL-X mode?
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100457 * This depends on the current mode.
458 */
459 int
460vim_is_ctrl_x_key(int c)
461{
462 // Always allow ^R - let its results then be checked
463 if (c == Ctrl_R)
464 return TRUE;
465
466 // Accept <PageUp> and <PageDown> if the popup menu is visible.
467 if (ins_compl_pum_key(c))
468 return TRUE;
469
470 switch (ctrl_x_mode)
471 {
472 case 0: // Not in any CTRL-X mode
473 return (c == Ctrl_N || c == Ctrl_P || c == Ctrl_X);
474 case CTRL_X_NOT_DEFINED_YET:
zeertzjqdca29d92021-08-31 19:12:51 +0200475 case CTRL_X_CMDLINE_CTRL_X:
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100476 return ( c == Ctrl_X || c == Ctrl_Y || c == Ctrl_E
477 || c == Ctrl_L || c == Ctrl_F || c == Ctrl_RSB
478 || c == Ctrl_I || c == Ctrl_D || c == Ctrl_P
479 || c == Ctrl_N || c == Ctrl_T || c == Ctrl_V
480 || c == Ctrl_Q || c == Ctrl_U || c == Ctrl_O
zeertzjqdca29d92021-08-31 19:12:51 +0200481 || c == Ctrl_S || c == Ctrl_K || c == 's'
482 || c == Ctrl_Z);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100483 case CTRL_X_SCROLL:
484 return (c == Ctrl_Y || c == Ctrl_E);
485 case CTRL_X_WHOLE_LINE:
486 return (c == Ctrl_L || c == Ctrl_P || c == Ctrl_N);
487 case CTRL_X_FILES:
488 return (c == Ctrl_F || c == Ctrl_P || c == Ctrl_N);
489 case CTRL_X_DICTIONARY:
490 return (c == Ctrl_K || c == Ctrl_P || c == Ctrl_N);
491 case CTRL_X_THESAURUS:
492 return (c == Ctrl_T || c == Ctrl_P || c == Ctrl_N);
493 case CTRL_X_TAGS:
494 return (c == Ctrl_RSB || c == Ctrl_P || c == Ctrl_N);
495#ifdef FEAT_FIND_ID
496 case CTRL_X_PATH_PATTERNS:
497 return (c == Ctrl_P || c == Ctrl_N);
498 case CTRL_X_PATH_DEFINES:
499 return (c == Ctrl_D || c == Ctrl_P || c == Ctrl_N);
500#endif
501 case CTRL_X_CMDLINE:
502 return (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_P || c == Ctrl_N
503 || c == Ctrl_X);
504#ifdef FEAT_COMPL_FUNC
505 case CTRL_X_FUNCTION:
506 return (c == Ctrl_U || c == Ctrl_P || c == Ctrl_N);
507 case CTRL_X_OMNI:
508 return (c == Ctrl_O || c == Ctrl_P || c == Ctrl_N);
509#endif
510 case CTRL_X_SPELL:
511 return (c == Ctrl_S || c == Ctrl_P || c == Ctrl_N);
512 case CTRL_X_EVAL:
513 return (c == Ctrl_P || c == Ctrl_N);
514 }
515 internal_error("vim_is_ctrl_x_key()");
516 return FALSE;
517}
518
519/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000520 * Return TRUE if "match" is the original text when the completion began.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000521 */
522 static int
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000523match_at_original_text(compl_T *match)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000524{
525 return match->cp_flags & CP_ORIGINAL_TEXT;
526}
527
528/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000529 * Returns TRUE if "match" is the first match in the completion list.
530 */
531 static int
532is_first_match(compl_T *match)
533{
534 return match == compl_first_match;
535}
536
537/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100538 * Return TRUE when character "c" is part of the item currently being
539 * completed. Used to decide whether to abandon complete mode when the menu
540 * is visible.
541 */
542 int
543ins_compl_accept_char(int c)
544{
545 if (ctrl_x_mode & CTRL_X_WANT_IDENT)
546 // When expanding an identifier only accept identifier chars.
547 return vim_isIDc(c);
548
549 switch (ctrl_x_mode)
550 {
551 case CTRL_X_FILES:
552 // When expanding file name only accept file name chars. But not
553 // path separators, so that "proto/<Tab>" expands files in
554 // "proto", not "proto/" as a whole
555 return vim_isfilec(c) && !vim_ispathsep(c);
556
557 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +0200558 case CTRL_X_CMDLINE_CTRL_X:
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100559 case CTRL_X_OMNI:
560 // Command line and Omni completion can work with just about any
561 // printable character, but do stop at white space.
562 return vim_isprintc(c) && !VIM_ISWHITE(c);
563
564 case CTRL_X_WHOLE_LINE:
565 // For while line completion a space can be part of the line.
566 return vim_isprintc(c);
567 }
568 return vim_iswordc(c);
569}
570
571/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000572 * Get the completed text by inferring the case of the originally typed text.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100573 * If the result is in allocated memory "tofree" is set to it.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000574 */
575 static char_u *
576ins_compl_infercase_gettext(
glepnir19e1dd62025-05-08 22:50:38 +0200577 char_u *str,
578 int char_len,
579 int compl_char_len,
580 int min_len,
581 char_u **tofree)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000582{
583 int *wca; // Wide character array.
584 char_u *p;
585 int i, c;
586 int has_lower = FALSE;
587 int was_letter = FALSE;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100588 garray_T gap;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000589
590 IObuff[0] = NUL;
591
592 // Allocate wide character array for the completion and fill it.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100593 wca = ALLOC_MULT(int, char_len);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000594 if (wca == NULL)
595 return IObuff;
596
597 p = str;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100598 for (i = 0; i < char_len; ++i)
glepnir6e199932024-12-14 21:13:27 +0100599 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000600 if (has_mbyte)
601 wca[i] = mb_ptr2char_adv(&p);
602 else
603 wca[i] = *(p++);
glepnir6e199932024-12-14 21:13:27 +0100604 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000605
606 // Rule 1: Were any chars converted to lower?
John Marriott5e6ea922024-11-23 14:01:57 +0100607 p = compl_orig_text.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000608 for (i = 0; i < min_len; ++i)
609 {
glepnir6e199932024-12-14 21:13:27 +0100610 c = has_mbyte ? mb_ptr2char_adv(&p) : *(p++);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000611 if (MB_ISLOWER(c))
612 {
613 has_lower = TRUE;
614 if (MB_ISUPPER(wca[i]))
615 {
616 // Rule 1 is satisfied.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100617 for (i = compl_char_len; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000618 wca[i] = MB_TOLOWER(wca[i]);
619 break;
620 }
621 }
622 }
623
624 // Rule 2: No lower case, 2nd consecutive letter converted to
625 // upper case.
626 if (!has_lower)
627 {
John Marriott5e6ea922024-11-23 14:01:57 +0100628 p = compl_orig_text.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000629 for (i = 0; i < min_len; ++i)
630 {
glepnir6e199932024-12-14 21:13:27 +0100631 c = has_mbyte ? mb_ptr2char_adv(&p) : *(p++);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000632 if (was_letter && MB_ISUPPER(c) && MB_ISLOWER(wca[i]))
633 {
634 // Rule 2 is satisfied.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100635 for (i = compl_char_len; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000636 wca[i] = MB_TOUPPER(wca[i]);
637 break;
638 }
639 was_letter = MB_ISLOWER(c) || MB_ISUPPER(c);
640 }
641 }
642
643 // Copy the original case of the part we typed.
John Marriott5e6ea922024-11-23 14:01:57 +0100644 p = compl_orig_text.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000645 for (i = 0; i < min_len; ++i)
646 {
glepnir6e199932024-12-14 21:13:27 +0100647 c = has_mbyte ? mb_ptr2char_adv(&p) : *(p++);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000648 if (MB_ISLOWER(c))
649 wca[i] = MB_TOLOWER(wca[i]);
650 else if (MB_ISUPPER(c))
651 wca[i] = MB_TOUPPER(wca[i]);
652 }
653
654 // Generate encoding specific output from wide character array.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000655 p = IObuff;
656 i = 0;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100657 ga_init2(&gap, 1, 500);
658 while (i < char_len)
659 {
660 if (gap.ga_data != NULL)
661 {
662 if (ga_grow(&gap, 10) == FAIL)
663 {
664 ga_clear(&gap);
665 return (char_u *)"[failed]";
666 }
667 p = (char_u *)gap.ga_data + gap.ga_len;
668 if (has_mbyte)
669 gap.ga_len += (*mb_char2bytes)(wca[i++], p);
670 else
671 {
672 *p = wca[i++];
673 ++gap.ga_len;
674 }
675 }
676 else if ((p - IObuff) + 6 >= IOSIZE)
677 {
678 // Multi-byte characters can occupy up to five bytes more than
679 // ASCII characters, and we also need one byte for NUL, so when
680 // getting to six bytes from the edge of IObuff switch to using a
681 // growarray. Add the character in the next round.
682 if (ga_grow(&gap, IOSIZE) == FAIL)
zeertzjq70e566b2024-03-21 07:11:58 +0100683 {
684 vim_free(wca);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100685 return (char_u *)"[failed]";
zeertzjq70e566b2024-03-21 07:11:58 +0100686 }
Bram Moolenaarb9e71732022-07-23 06:53:08 +0100687 *p = NUL;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100688 STRCPY(gap.ga_data, IObuff);
John Marriott5e6ea922024-11-23 14:01:57 +0100689 gap.ga_len = (int)(p - IObuff);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100690 }
691 else if (has_mbyte)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000692 p += (*mb_char2bytes)(wca[i++], p);
693 else
694 *(p++) = wca[i++];
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100695 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000696 vim_free(wca);
697
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100698 if (gap.ga_data != NULL)
699 {
700 *tofree = gap.ga_data;
701 return gap.ga_data;
702 }
703
704 *p = NUL;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000705 return IObuff;
706}
707
708/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100709 * This is like ins_compl_add(), but if 'ic' and 'inf' are set, then the
710 * case of the originally typed text is used, and the case of the completed
711 * text is inferred, ie this tries to work out what case you probably wanted
712 * the rest of the word to be in -- webb
713 */
714 int
715ins_compl_add_infercase(
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200716 char_u *str_arg,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100717 int len,
718 int icase,
719 char_u *fname,
720 int dir,
glepnirf31cfa22025-03-06 21:59:13 +0100721 int cont_s_ipos, // next ^X<> will set initial_pos
722 int score)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100723{
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200724 char_u *str = str_arg;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100725 char_u *p;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100726 int char_len; // count multi-byte characters
727 int compl_char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100728 int min_len;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200729 int flags = 0;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100730 int res;
731 char_u *tofree = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100732
733 if (p_ic && curbuf->b_p_inf && len > 0)
734 {
735 // Infer case of completed part.
736
737 // Find actual length of completion.
738 if (has_mbyte)
739 {
740 p = str;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100741 char_len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100742 while (*p != NUL)
743 {
744 MB_PTR_ADV(p);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100745 ++char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100746 }
747 }
748 else
glepnir6e199932024-12-14 21:13:27 +0100749 {
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100750 char_len = len;
glepnir6e199932024-12-14 21:13:27 +0100751 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100752
753 // Find actual length of original text.
754 if (has_mbyte)
755 {
John Marriott5e6ea922024-11-23 14:01:57 +0100756 p = compl_orig_text.string;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100757 compl_char_len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100758 while (*p != NUL)
759 {
760 MB_PTR_ADV(p);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100761 ++compl_char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100762 }
763 }
764 else
glepnir6e199932024-12-14 21:13:27 +0100765 {
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100766 compl_char_len = compl_length;
glepnir6e199932024-12-14 21:13:27 +0100767 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100768
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100769 // "char_len" may be smaller than "compl_char_len" when using
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100770 // thesaurus, only use the minimum when comparing.
glepnir6e199932024-12-14 21:13:27 +0100771 min_len = MIN(char_len, compl_char_len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100772
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100773 str = ins_compl_infercase_gettext(str, char_len,
774 compl_char_len, min_len, &tofree);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100775 }
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200776 if (cont_s_ipos)
777 flags |= CP_CONT_S_IPOS;
778 if (icase)
779 flags |= CP_ICASE;
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200780
glepnirf31cfa22025-03-06 21:59:13 +0100781 res = ins_compl_add(str, len, fname, NULL, NULL, dir, flags, FALSE, NULL, score);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100782 vim_free(tofree);
783 return res;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100784}
785
786/*
glepnirf31cfa22025-03-06 21:59:13 +0100787 * Check if ctrl_x_mode has been configured in 'completefuzzycollect'
788 */
789 static int
790cfc_has_mode(void)
791{
glepnir58760162025-03-13 21:39:51 +0100792 if (ctrl_x_mode_normal() || ctrl_x_mode_dictionary())
793 return (cfc_flags & CFC_KEYWORD) != 0;
794 else if (ctrl_x_mode_files())
795 return (cfc_flags & CFC_FILES) != 0;
796 else if (ctrl_x_mode_whole_line())
797 return (cfc_flags & CFC_WHOLELINE) != 0;
798 else
799 return FALSE;
glepnirf31cfa22025-03-06 21:59:13 +0100800}
801
802/*
Girish Palyab1565882025-04-15 20:16:00 +0200803 * Returns TRUE if matches should be sorted based on proximity to the cursor.
804 */
805 static int
806is_nearest_active(void)
807{
808 unsigned int flags = get_cot_flags();
809
810 return (flags & COT_NEAREST) && !(flags & COT_FUZZY);
811}
812
813/*
814 * Repositions a match in the completion list based on its proximity score.
815 * If the match is at the head and has a higher score than the next node,
816 * or if it's in the middle/tail and has a lower score than the previous node,
817 * it is moved to the correct position while maintaining ascending order.
818 */
819 static void
820reposition_match(compl_T *match)
821{
822 compl_T *insert_before = NULL;
823 compl_T *insert_after = NULL;
824
825 // Node is at head and score is too big
826 if (!match->cp_prev)
827 {
828 if (match->cp_next && match->cp_next->cp_score > 0 &&
829 match->cp_next->cp_score < match->cp_score)
830 {
831 // <c-p>: compl_first_match is at head and newly inserted node
832 compl_first_match = compl_curr_match = match->cp_next;
833 // Find the correct position in ascending order
834 insert_before = match->cp_next;
835 do
836 {
837 insert_after = insert_before;
838 insert_before = insert_before->cp_next;
839 } while (insert_before && insert_before->cp_score > 0 &&
840 insert_before->cp_score < match->cp_score);
841 }
842 else
843 return;
844 }
845 // Node is at tail or in the middle but score is too small
846 else
847 {
848 if (match->cp_prev->cp_score > 0 && match->cp_prev->cp_score > match->cp_score)
849 {
850 // <c-n>: compl_curr_match (and newly inserted match) is at tail
851 if (!match->cp_next)
852 compl_curr_match = compl_curr_match->cp_prev;
853 // Find the correct position in ascending order
854 insert_after = match->cp_prev;
855 do
856 {
857 insert_before = insert_after;
858 insert_after = insert_after->cp_prev;
859 } while (insert_after && insert_after->cp_score > 0 &&
860 insert_after->cp_score > match->cp_score);
861 }
862 else
863 return;
864 }
865
866 if (insert_after)
867 {
868 // Remove the match from its current position
869 if (match->cp_prev)
870 match->cp_prev->cp_next = match->cp_next;
871 else
872 compl_first_match = match->cp_next;
873 if (match->cp_next)
874 match->cp_next->cp_prev = match->cp_prev;
875
876 // Insert the match at the correct position
877 match->cp_next = insert_before;
878 match->cp_prev = insert_after;
879 insert_after->cp_next = match;
880 insert_before->cp_prev = match;
881 }
882}
883
884/*
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000885 * Add a match to the list of matches. The arguments are:
886 * str - text of the match to add
887 * len - length of "str". If -1, then the length of "str" is
888 * computed.
889 * fname - file name to associate with this match.
890 * cptext - list of strings to use with this match (for abbr, menu, info
891 * and kind)
892 * user_data - user supplied data (any vim type) for this match
893 * cdir - match direction. If 0, use "compl_direction".
894 * flags_arg - match flags (cp_flags)
895 * adup - accept this match even if it is already present.
glepnir80b66202024-11-27 21:53:53 +0100896 * *user_hl - list of extra highlight attributes for abbr kind.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000897 * If "cdir" is FORWARD, then the match is added after the current match.
898 * Otherwise, it is added before the current match.
899 *
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100900 * If the given string is already in the list of completions, then return
901 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
902 * maybe because alloc() returns NULL, then FAIL is returned.
903 */
904 static int
905ins_compl_add(
906 char_u *str,
907 int len,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100908 char_u *fname,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100909 char_u **cptext, // extra text for popup menu or NULL
910 typval_T *user_data UNUSED, // "user_data" entry or NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100911 int cdir,
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200912 int flags_arg,
glepnir508e7852024-07-25 21:39:08 +0200913 int adup, // accept duplicate match
glepnirf31cfa22025-03-06 21:59:13 +0100914 int *user_hl, // user abbr/kind hlattr
915 int score)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100916{
glepnirf31cfa22025-03-06 21:59:13 +0100917 compl_T *match, *current, *prev;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100918 int dir = (cdir == 0 ? compl_direction : cdir);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200919 int flags = flags_arg;
glepnirf31cfa22025-03-06 21:59:13 +0100920 int inserted = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100921
Bram Moolenaarceb06192021-04-04 15:05:22 +0200922 if (flags & CP_FAST)
923 fast_breakcheck();
924 else
925 ui_breakcheck();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100926 if (got_int)
927 return FAIL;
928 if (len < 0)
929 len = (int)STRLEN(str);
930
931 // If the same match is already present, don't add it.
932 if (compl_first_match != NULL && !adup)
933 {
934 match = compl_first_match;
935 do
936 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000937 if (!match_at_original_text(match)
John Marriott5e6ea922024-11-23 14:01:57 +0100938 && STRNCMP(match->cp_str.string, str, len) == 0
939 && ((int)match->cp_str.length <= len
940 || match->cp_str.string[len] == NUL))
Girish Palyab1565882025-04-15 20:16:00 +0200941 {
942 if (is_nearest_active() && score > 0 && score < match->cp_score)
943 {
944 match->cp_score = score;
945 reposition_match(match);
946 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100947 return NOTDONE;
Girish Palyab1565882025-04-15 20:16:00 +0200948 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100949 match = match->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000950 } while (match != NULL && !is_first_match(match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100951 }
952
953 // Remove any popup menu before changing the list of matches.
954 ins_compl_del_pum();
955
956 // Allocate a new match structure.
957 // Copy the values to the new match structure.
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200958 match = ALLOC_CLEAR_ONE(compl_T);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100959 if (match == NULL)
960 return FAIL;
glepnir40891ba2025-02-10 22:18:00 +0100961 match->cp_number = flags & CP_ORIGINAL_TEXT ? 0 : -1;
John Marriott5e6ea922024-11-23 14:01:57 +0100962 if ((match->cp_str.string = vim_strnsave(str, len)) == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100963 {
964 vim_free(match);
965 return FAIL;
966 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100967
John Marriott5e6ea922024-11-23 14:01:57 +0100968 match->cp_str.length = len;
969
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100970 // match-fname is:
971 // - compl_curr_match->cp_fname if it is a string equal to fname.
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200972 // - a copy of fname, CP_FREE_FNAME is set to free later THE allocated mem.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100973 // - NULL otherwise. --Acevedo
974 if (fname != NULL
975 && compl_curr_match != NULL
976 && compl_curr_match->cp_fname != NULL
977 && STRCMP(fname, compl_curr_match->cp_fname) == 0)
978 match->cp_fname = compl_curr_match->cp_fname;
979 else if (fname != NULL)
980 {
981 match->cp_fname = vim_strsave(fname);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200982 flags |= CP_FREE_FNAME;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100983 }
984 else
985 match->cp_fname = NULL;
986 match->cp_flags = flags;
glepnir80b66202024-11-27 21:53:53 +0100987 match->cp_user_abbr_hlattr = user_hl ? user_hl[0] : -1;
988 match->cp_user_kind_hlattr = user_hl ? user_hl[1] : -1;
glepnirf31cfa22025-03-06 21:59:13 +0100989 match->cp_score = score;
Girish Palya0ac1eb32025-04-16 20:18:33 +0200990 match->cp_cpt_source_idx = cpt_sources_index;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100991
992 if (cptext != NULL)
993 {
glepnir19e1dd62025-05-08 22:50:38 +0200994 for (int i = 0; i < CPT_COUNT; ++i)
glepnir6e199932024-12-14 21:13:27 +0100995 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100996 if (cptext[i] != NULL && *cptext[i] != NUL)
997 match->cp_text[i] = vim_strsave(cptext[i]);
glepnir6e199932024-12-14 21:13:27 +0100998 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100999 }
Bram Moolenaarab782c52020-01-04 19:00:11 +01001000#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +01001001 if (user_data != NULL)
1002 match->cp_user_data = *user_data;
Bram Moolenaarab782c52020-01-04 19:00:11 +01001003#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001004
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00001005 // Link the new match structure after (FORWARD) or before (BACKWARD) the
1006 // current match in the list of matches .
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001007 if (compl_first_match == NULL)
1008 match->cp_next = match->cp_prev = NULL;
glepnirf31cfa22025-03-06 21:59:13 +01001009 else if (cfc_has_mode() && score > 0 && compl_get_longest)
1010 {
1011 current = compl_first_match->cp_next;
1012 prev = compl_first_match;
1013 inserted = FALSE;
1014 // The direction is ignored when using longest and
1015 // completefuzzycollect, because matches are inserted
1016 // and sorted by score.
1017 while (current != NULL && current != compl_first_match)
1018 {
1019 if (current->cp_score < score)
1020 {
Hirohito Higashi355db992025-04-28 18:07:02 +02001021 match->cp_next = current;
1022 match->cp_prev = current->cp_prev;
1023 if (current->cp_prev)
glepnirf31cfa22025-03-06 21:59:13 +01001024 current->cp_prev->cp_next = match;
Hirohito Higashi355db992025-04-28 18:07:02 +02001025 current->cp_prev = match;
1026 inserted = TRUE;
1027 break;
glepnirf31cfa22025-03-06 21:59:13 +01001028 }
1029 prev = current;
1030 current = current->cp_next;
1031 }
1032 if (!inserted)
1033 {
1034 prev->cp_next = match;
1035 match->cp_prev = prev;
1036 match->cp_next = compl_first_match;
1037 compl_first_match->cp_prev = match;
1038 }
1039 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001040 else if (dir == FORWARD)
1041 {
1042 match->cp_next = compl_curr_match->cp_next;
1043 match->cp_prev = compl_curr_match;
1044 }
1045 else // BACKWARD
1046 {
1047 match->cp_next = compl_curr_match;
1048 match->cp_prev = compl_curr_match->cp_prev;
1049 }
1050 if (match->cp_next)
1051 match->cp_next->cp_prev = match;
1052 if (match->cp_prev)
1053 match->cp_prev->cp_next = match;
1054 else // if there's nothing before, it is the first match
1055 compl_first_match = match;
1056 compl_curr_match = match;
1057
Girish Palyab1565882025-04-15 20:16:00 +02001058 if (is_nearest_active() && score > 0)
1059 reposition_match(match);
1060
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001061 // Find the longest common string if still doing that.
glepnirf31cfa22025-03-06 21:59:13 +01001062 if (compl_get_longest && (flags & CP_ORIGINAL_TEXT) == 0 && !cfc_has_mode())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001063 ins_compl_longest_match(match);
1064
1065 return OK;
1066}
1067
1068/*
1069 * Return TRUE if "str[len]" matches with match->cp_str, considering
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001070 * match->cp_flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001071 */
1072 static int
1073ins_compl_equal(compl_T *match, char_u *str, int len)
1074{
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001075 if (match->cp_flags & CP_EQUAL)
Bram Moolenaar73655cf2019-04-06 13:45:55 +02001076 return TRUE;
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001077 if (match->cp_flags & CP_ICASE)
John Marriott5e6ea922024-11-23 14:01:57 +01001078 return STRNICMP(match->cp_str.string, str, (size_t)len) == 0;
1079 return STRNCMP(match->cp_str.string, str, (size_t)len) == 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001080}
1081
1082/*
glepnir6a38aff2024-12-16 21:56:16 +01001083 * when len is -1 mean use whole length of p otherwise part of p
1084 */
1085 static void
1086ins_compl_insert_bytes(char_u *p, int len)
1087{
1088 if (len == -1)
1089 len = (int)STRLEN(p);
1090 ins_bytes_len(p, len);
zeertzjqf25d8f92024-12-18 21:12:25 +01001091 compl_ins_end_col = curwin->w_cursor.col;
glepnir6a38aff2024-12-16 21:56:16 +01001092}
1093
1094/*
zeertzjqd32bf0a2024-12-17 20:55:13 +01001095 * Checks if the column is within the currently inserted completion text
1096 * column range. If it is, it returns a special highlight attribute.
glepnir76bdb822025-02-08 19:04:51 +01001097 * -1 means normal item.
glepnir6a38aff2024-12-16 21:56:16 +01001098 */
1099 int
glepnir76bdb822025-02-08 19:04:51 +01001100ins_compl_col_range_attr(linenr_T lnum, int col)
glepnir6a38aff2024-12-16 21:56:16 +01001101{
glepnir76bdb822025-02-08 19:04:51 +01001102 int start_col;
1103 int attr;
1104
1105 if ((get_cot_flags() & COT_FUZZY)
1106 || (attr = syn_name2attr((char_u *)"ComplMatchIns")) == 0)
glepnire8908872025-01-08 18:30:45 +01001107 return -1;
1108
glepnir76bdb822025-02-08 19:04:51 +01001109 start_col = compl_col + (int)ins_compl_leader_len();
1110 if (!ins_compl_has_multiple())
1111 return (col >= start_col && col < compl_ins_end_col) ? attr : -1;
1112
1113 // Multiple lines
1114 if ((lnum == compl_lnum && col >= start_col && col < MAXCOL) ||
1115 (lnum > compl_lnum && lnum < curwin->w_cursor.lnum) ||
1116 (lnum == curwin->w_cursor.lnum && col <= compl_ins_end_col))
1117 return attr;
glepnir6a38aff2024-12-16 21:56:16 +01001118
1119 return -1;
1120}
1121
1122/*
glepnir76bdb822025-02-08 19:04:51 +01001123 * Returns TRUE if the current completion string contains newline characters,
1124 * indicating it's a multi-line completion.
1125 */
1126 static int
1127ins_compl_has_multiple(void)
1128{
1129 return vim_strchr(compl_shown_match->cp_str.string, '\n') != NULL;
1130}
1131
1132/*
1133 * Returns TRUE if the given line number falls within the range of a multi-line
1134 * completion, i.e. between the starting line (compl_lnum) and current cursor
1135 * line. Always returns FALSE for single-line completions.
1136 */
1137 int
1138ins_compl_lnum_in_range(linenr_T lnum)
1139{
1140 if (!ins_compl_has_multiple())
1141 return FALSE;
1142 return lnum >= compl_lnum && lnum <= curwin->w_cursor.lnum;
1143}
1144
1145/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001146 * Reduce the longest common string for match "match".
1147 */
1148 static void
1149ins_compl_longest_match(compl_T *match)
1150{
1151 char_u *p, *s;
1152 int c1, c2;
1153 int had_match;
1154
John Marriott5e6ea922024-11-23 14:01:57 +01001155 if (compl_leader.string == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001156 {
1157 // First match, use it as a whole.
John Marriott5e6ea922024-11-23 14:01:57 +01001158 compl_leader.string = vim_strnsave(match->cp_str.string, match->cp_str.length);
1159 if (compl_leader.string == NULL)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001160 return;
1161
John Marriott5e6ea922024-11-23 14:01:57 +01001162 compl_leader.length = match->cp_str.length;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001163 had_match = (curwin->w_cursor.col > compl_col);
glepnirf31cfa22025-03-06 21:59:13 +01001164 ins_compl_longest_insert(compl_leader.string);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001165
1166 // When the match isn't there (to avoid matching itself) remove it
1167 // again after redrawing.
1168 if (!had_match)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001169 ins_compl_delete();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001170 compl_used_match = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001171
1172 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001173 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001174
1175 // Reduce the text if this match differs from compl_leader.
John Marriott5e6ea922024-11-23 14:01:57 +01001176 p = compl_leader.string;
1177 s = match->cp_str.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001178 while (*p != NUL)
1179 {
1180 if (has_mbyte)
1181 {
1182 c1 = mb_ptr2char(p);
1183 c2 = mb_ptr2char(s);
1184 }
1185 else
1186 {
1187 c1 = *p;
1188 c2 = *s;
1189 }
1190 if ((match->cp_flags & CP_ICASE)
1191 ? (MB_TOLOWER(c1) != MB_TOLOWER(c2)) : (c1 != c2))
1192 break;
1193 if (has_mbyte)
1194 {
1195 MB_PTR_ADV(p);
1196 MB_PTR_ADV(s);
1197 }
1198 else
1199 {
1200 ++p;
1201 ++s;
1202 }
1203 }
1204
1205 if (*p != NUL)
1206 {
1207 // Leader was shortened, need to change the inserted text.
1208 *p = NUL;
John Marriott5e6ea922024-11-23 14:01:57 +01001209 compl_leader.length = (size_t)(p - compl_leader.string);
1210
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001211 had_match = (curwin->w_cursor.col > compl_col);
glepnirf31cfa22025-03-06 21:59:13 +01001212 ins_compl_longest_insert(compl_leader.string);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001213
1214 // When the match isn't there (to avoid matching itself) remove it
1215 // again after redrawing.
1216 if (!had_match)
1217 ins_compl_delete();
1218 }
1219
1220 compl_used_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001221}
1222
1223/*
1224 * Add an array of matches to the list of matches.
1225 * Frees matches[].
1226 */
1227 static void
1228ins_compl_add_matches(
1229 int num_matches,
1230 char_u **matches,
1231 int icase)
1232{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001233 int add_r = OK;
1234 int dir = compl_direction;
1235
glepnir19e1dd62025-05-08 22:50:38 +02001236 for (int i = 0; i < num_matches && add_r != FAIL; i++)
glepnir6e199932024-12-14 21:13:27 +01001237 {
1238 add_r = ins_compl_add(matches[i], -1, NULL, NULL, NULL, dir,
glepnirf31cfa22025-03-06 21:59:13 +01001239 CP_FAST | (icase ? CP_ICASE : 0), FALSE, NULL, 0);
glepnir6e199932024-12-14 21:13:27 +01001240 if (add_r == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001241 // if dir was BACKWARD then honor it just once
1242 dir = FORWARD;
glepnir6e199932024-12-14 21:13:27 +01001243 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001244 FreeWild(num_matches, matches);
1245}
1246
1247/*
1248 * Make the completion list cyclic.
1249 * Return the number of matches (excluding the original).
1250 */
1251 static int
1252ins_compl_make_cyclic(void)
1253{
1254 compl_T *match;
1255 int count = 0;
1256
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001257 if (compl_first_match == NULL)
1258 return 0;
1259
1260 // Find the end of the list.
1261 match = compl_first_match;
1262 // there's always an entry for the compl_orig_text, it doesn't count.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001263 while (match->cp_next != NULL && !is_first_match(match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001264 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001265 match = match->cp_next;
1266 ++count;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001267 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001268 match->cp_next = compl_first_match;
1269 compl_first_match->cp_prev = match;
1270
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001271 return count;
1272}
1273
1274/*
1275 * Return whether there currently is a shown match.
1276 */
1277 int
1278ins_compl_has_shown_match(void)
1279{
1280 return compl_shown_match == NULL
1281 || compl_shown_match != compl_shown_match->cp_next;
1282}
1283
1284/*
1285 * Return whether the shown match is long enough.
1286 */
1287 int
1288ins_compl_long_shown_match(void)
1289{
John Marriott5e6ea922024-11-23 14:01:57 +01001290 return (int)compl_shown_match->cp_str.length
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001291 > curwin->w_cursor.col - compl_col;
1292}
1293
1294/*
zeertzjq529b9ad2024-06-05 20:27:06 +02001295 * Get the local or global value of 'completeopt' flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001296 */
zeertzjq529b9ad2024-06-05 20:27:06 +02001297 unsigned int
1298get_cot_flags(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001299{
zeertzjq529b9ad2024-06-05 20:27:06 +02001300 return curbuf->b_cot_flags != 0 ? curbuf->b_cot_flags : cot_flags;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001301}
1302
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001303/*
1304 * Update the screen and when there is any scrolling remove the popup menu.
1305 */
1306 static void
1307ins_compl_upd_pum(void)
1308{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001309 if (compl_match_array == NULL)
1310 return;
1311
glepnir19e1dd62025-05-08 22:50:38 +02001312 int h = curwin->w_cline_height;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001313 // Update the screen later, before drawing the popup menu over it.
1314 pum_call_update_screen();
1315 if (h != curwin->w_cline_height)
1316 ins_compl_del_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001317}
1318
1319/*
1320 * Remove any popup menu.
1321 */
1322 static void
1323ins_compl_del_pum(void)
1324{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001325 if (compl_match_array == NULL)
1326 return;
1327
1328 pum_undisplay();
1329 VIM_CLEAR(compl_match_array);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001330}
1331
1332/*
1333 * Return TRUE if the popup menu should be displayed.
1334 */
1335 int
1336pum_wanted(void)
1337{
1338 // 'completeopt' must contain "menu" or "menuone"
zeertzjq529b9ad2024-06-05 20:27:06 +02001339 if ((get_cot_flags() & COT_ANY_MENU) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001340 return FALSE;
1341
1342 // The display looks bad on a B&W display.
1343 if (t_colors < 8
1344#ifdef FEAT_GUI
1345 && !gui.in_use
1346#endif
1347 )
1348 return FALSE;
1349 return TRUE;
1350}
1351
1352/*
1353 * Return TRUE if there are two or more matches to be shown in the popup menu.
1354 * One if 'completopt' contains "menuone".
1355 */
1356 static int
1357pum_enough_matches(void)
1358{
1359 compl_T *compl;
glepnir6e199932024-12-14 21:13:27 +01001360 int i = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001361
1362 // Don't display the popup menu if there are no matches or there is only
1363 // one (ignoring the original text).
1364 compl = compl_first_match;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001365 do
1366 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001367 if (compl == NULL || (!match_at_original_text(compl) && ++i == 2))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001368 break;
1369 compl = compl->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001370 } while (!is_first_match(compl));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001371
zeertzjq529b9ad2024-06-05 20:27:06 +02001372 if (get_cot_flags() & COT_MENUONE)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001373 return (i >= 1);
1374 return (i >= 2);
1375}
1376
Bram Moolenaar3075a452021-11-17 15:51:52 +00001377#if defined(FEAT_EVAL) || defined(PROTO)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001378/*
1379 * Allocate Dict for the completed item.
1380 * { word, abbr, menu, kind, info }
1381 */
1382 static dict_T *
1383ins_compl_dict_alloc(compl_T *match)
1384{
1385 dict_T *dict = dict_alloc_lock(VAR_FIXED);
1386
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001387 if (dict == NULL)
1388 return NULL;
1389
John Marriott5e6ea922024-11-23 14:01:57 +01001390 dict_add_string(dict, "word", match->cp_str.string);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001391 dict_add_string(dict, "abbr", match->cp_text[CPT_ABBR]);
1392 dict_add_string(dict, "menu", match->cp_text[CPT_MENU]);
1393 dict_add_string(dict, "kind", match->cp_text[CPT_KIND]);
1394 dict_add_string(dict, "info", match->cp_text[CPT_INFO]);
1395 if (match->cp_user_data.v_type == VAR_UNKNOWN)
1396 dict_add_string(dict, "user_data", (char_u *)"");
1397 else
1398 dict_add_tv(dict, "user_data", &match->cp_user_data);
1399
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001400 return dict;
1401}
1402
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001403/*
1404 * Trigger the CompleteChanged autocmd event. Invoked each time the Insert mode
1405 * completion menu is changed.
1406 */
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001407 static void
1408trigger_complete_changed_event(int cur)
1409{
1410 dict_T *v_event;
1411 dict_T *item;
1412 static int recursive = FALSE;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001413 save_v_event_T save_v_event;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001414
1415 if (recursive)
1416 return;
1417
glepnir40891ba2025-02-10 22:18:00 +01001418 item = cur < 0 ? dict_alloc() : ins_compl_dict_alloc(compl_curr_match);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001419 if (item == NULL)
1420 return;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001421 v_event = get_v_event(&save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001422 dict_add_dict(v_event, "completed_item", item);
1423 pum_set_event_info(v_event);
1424 dict_set_items_ro(v_event);
1425
1426 recursive = TRUE;
zeertzjqcfe45652022-05-27 17:26:55 +01001427 textlock++;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001428 apply_autocmds(EVENT_COMPLETECHANGED, NULL, NULL, FALSE, curbuf);
zeertzjqcfe45652022-05-27 17:26:55 +01001429 textlock--;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001430 recursive = FALSE;
1431
Bram Moolenaar3075a452021-11-17 15:51:52 +00001432 restore_v_event(v_event, &save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001433}
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001434#endif
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001435
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001436/*
glepnira218cc62024-06-03 19:32:39 +02001437 * pumitem qsort compare func
1438 */
1439 static int
zeertzjq8e567472024-06-14 20:04:42 +02001440ins_compl_fuzzy_cmp(const void *a, const void *b)
glepnira218cc62024-06-03 19:32:39 +02001441{
1442 const int sa = (*(pumitem_T *)a).pum_score;
1443 const int sb = (*(pumitem_T *)b).pum_score;
zeertzjq8e567472024-06-14 20:04:42 +02001444 const int ia = (*(pumitem_T *)a).pum_idx;
1445 const int ib = (*(pumitem_T *)b).pum_idx;
1446 return sa == sb ? (ia == ib ? 0 : (ia < ib ? -1 : 1)) : (sa < sb ? 1 : -1);
glepnira218cc62024-06-03 19:32:39 +02001447}
1448
1449/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001450 * Build a popup menu to show the completion matches.
1451 * Returns the popup menu entry that should be selected. Returns -1 if nothing
1452 * should be selected.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001453 */
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001454 static int
1455ins_compl_build_pum(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001456{
1457 compl_T *compl;
1458 compl_T *shown_compl = NULL;
1459 int did_find_shown_match = FALSE;
1460 int shown_match_ok = FALSE;
glepnira49c0772024-11-30 10:56:30 +01001461 int i = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001462 int cur = -1;
glepnira218cc62024-06-03 19:32:39 +02001463 int max_fuzzy_score = 0;
zeertzjqaa925ee2024-06-09 18:24:05 +02001464 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02001465 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
zeertzjqd65aa1b2025-01-25 15:29:03 +01001466 int fuzzy_filter = (cur_cot_flags & COT_FUZZY) != 0;
1467 int fuzzy_sort = fuzzy_filter && !(cur_cot_flags & COT_NOSORT);
glepnir80b66202024-11-27 21:53:53 +01001468 compl_T *match_head = NULL;
1469 compl_T *match_tail = NULL;
1470 compl_T *match_next = NULL;
glepnire4e4d1c2025-04-02 20:18:25 +02001471 int update_shown_match = fuzzy_filter;
Christian Brabandtb53d4fb2025-04-16 21:12:30 +02001472 int match_count = 0;
Girish Palya0ac1eb32025-04-16 20:18:33 +02001473 int cur_source = -1;
1474 int max_matches_found = FALSE;
1475 int is_forward = compl_shows_dir_forward() && !fuzzy_filter;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001476
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001477 // Need to build the popup menu list.
1478 compl_match_arraysize = 0;
1479 compl = compl_first_match;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001480
glepnira49c0772024-11-30 10:56:30 +01001481 // If the current match is the original text don't find the first
1482 // match after it, don't highlight anything.
1483 if (match_at_original_text(compl_shown_match))
1484 shown_match_ok = TRUE;
1485
glepnire4e4d1c2025-04-02 20:18:25 +02001486 if (fuzzy_filter && ctrl_x_mode_normal() && compl_leader.string == NULL
1487 && compl_shown_match->cp_score > 0)
1488 update_shown_match = FALSE;
1489
glepnira49c0772024-11-30 10:56:30 +01001490 if (compl_leader.string != NULL
1491 && STRCMP(compl_leader.string, compl_orig_text.string) == 0
1492 && shown_match_ok == FALSE)
1493 compl_shown_match = compl_no_select ? compl_first_match
1494 : compl_first_match->cp_next;
1495
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001496 do
1497 {
glepnird4088ed2024-12-31 10:55:22 +01001498 compl->cp_in_match_array = FALSE;
zeertzjq551d8c32024-06-05 19:53:32 +02001499 // When 'completeopt' contains "fuzzy" and leader is not NULL or empty,
1500 // set the cp_score for later comparisons.
glepnirf400a0c2025-01-23 19:55:14 +01001501 if (fuzzy_filter && compl_leader.string != NULL && compl_leader.length > 0)
John Marriott5e6ea922024-11-23 14:01:57 +01001502 compl->cp_score = fuzzy_match_str(compl->cp_str.string, compl_leader.string);
glepnira218cc62024-06-03 19:32:39 +02001503
Girish Palya0ac1eb32025-04-16 20:18:33 +02001504 if (is_forward && compl->cp_cpt_source_idx != -1)
1505 {
1506 if (cur_source != compl->cp_cpt_source_idx)
1507 {
1508 cur_source = compl->cp_cpt_source_idx;
1509 match_count = 1;
1510 max_matches_found = FALSE;
1511 }
1512 else if (cpt_sources_array && !max_matches_found)
1513 {
1514 int max_matches = cpt_sources_array[cur_source].max_matches;
1515 if (max_matches > 0 && match_count > max_matches)
1516 max_matches_found = TRUE;
1517 }
1518 }
1519
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001520 if (!match_at_original_text(compl)
Girish Palya0ac1eb32025-04-16 20:18:33 +02001521 && !max_matches_found
John Marriott5e6ea922024-11-23 14:01:57 +01001522 && (compl_leader.string == NULL
1523 || ins_compl_equal(compl, compl_leader.string, (int)compl_leader.length)
glepnirf400a0c2025-01-23 19:55:14 +01001524 || (fuzzy_filter && compl->cp_score > 0)))
glepnir80b66202024-11-27 21:53:53 +01001525 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001526 ++compl_match_arraysize;
glepnird4088ed2024-12-31 10:55:22 +01001527 compl->cp_in_match_array = TRUE;
glepnir80b66202024-11-27 21:53:53 +01001528 if (match_head == NULL)
1529 match_head = compl;
1530 else
glepnira49c0772024-11-30 10:56:30 +01001531 match_tail->cp_match_next = compl;
glepnir80b66202024-11-27 21:53:53 +01001532 match_tail = compl;
glepnira49c0772024-11-30 10:56:30 +01001533
glepnirf400a0c2025-01-23 19:55:14 +01001534 if (!shown_match_ok && !fuzzy_filter)
glepnira49c0772024-11-30 10:56:30 +01001535 {
1536 if (compl == compl_shown_match || did_find_shown_match)
1537 {
1538 // This item is the shown match or this is the
1539 // first displayed item after the shown match.
1540 compl_shown_match = compl;
1541 did_find_shown_match = TRUE;
1542 shown_match_ok = TRUE;
1543 }
1544 else
1545 // Remember this displayed match for when the
1546 // shown match is just below it.
1547 shown_compl = compl;
1548 cur = i;
1549 }
glepnirf400a0c2025-01-23 19:55:14 +01001550 else if (fuzzy_filter)
glepnira49c0772024-11-30 10:56:30 +01001551 {
1552 if (i == 0)
1553 shown_compl = compl;
1554 // Update the maximum fuzzy score and the shown match
1555 // if the current item's score is higher
glepnire4e4d1c2025-04-02 20:18:25 +02001556 if (fuzzy_sort && compl->cp_score > max_fuzzy_score
1557 && update_shown_match)
glepnira49c0772024-11-30 10:56:30 +01001558 {
1559 did_find_shown_match = TRUE;
1560 max_fuzzy_score = compl->cp_score;
1561 if (!compl_no_select)
1562 compl_shown_match = compl;
1563 }
1564
glepnir3af0a8d2025-02-20 22:06:16 +01001565 if (!shown_match_ok && compl == compl_shown_match)
glepnira49c0772024-11-30 10:56:30 +01001566 {
1567 cur = i;
1568 shown_match_ok = TRUE;
1569 }
1570 }
Girish Palya0ac1eb32025-04-16 20:18:33 +02001571 if (is_forward && compl->cp_cpt_source_idx != -1)
1572 match_count++;
glepnira49c0772024-11-30 10:56:30 +01001573 i++;
glepnir80b66202024-11-27 21:53:53 +01001574 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001575
glepnirf400a0c2025-01-23 19:55:14 +01001576 if (compl == compl_shown_match && !fuzzy_filter)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001577 {
1578 did_find_shown_match = TRUE;
1579
1580 // When the original text is the shown match don't set
1581 // compl_shown_match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001582 if (match_at_original_text(compl))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001583 shown_match_ok = TRUE;
1584
1585 if (!shown_match_ok && shown_compl != NULL)
1586 {
1587 // The shown match isn't displayed, set it to the
1588 // previously displayed match.
1589 compl_shown_match = shown_compl;
1590 shown_match_ok = TRUE;
1591 }
1592 }
glepnira49c0772024-11-30 10:56:30 +01001593 compl = compl->cp_next;
1594 } while (compl != NULL && !is_first_match(compl));
1595
1596 if (compl_match_arraysize == 0)
1597 return -1;
1598
glepnirc0b7ca42025-02-13 20:27:44 +01001599 if (fuzzy_filter && !fuzzy_sort && !compl_no_select && !shown_match_ok)
1600 {
1601 compl_shown_match = shown_compl;
1602 shown_match_ok = TRUE;
1603 cur = 0;
1604 }
1605
glepnira49c0772024-11-30 10:56:30 +01001606 compl_match_array = ALLOC_CLEAR_MULT(pumitem_T, compl_match_arraysize);
1607 if (compl_match_array == NULL)
1608 return -1;
1609
1610 compl = match_head;
1611 i = 0;
1612 while (compl != NULL)
1613 {
glepnir6e199932024-12-14 21:13:27 +01001614 compl_match_array[i].pum_text = compl->cp_text[CPT_ABBR] != NULL
1615 ? compl->cp_text[CPT_ABBR] : compl->cp_str.string;
glepnira49c0772024-11-30 10:56:30 +01001616 compl_match_array[i].pum_kind = compl->cp_text[CPT_KIND];
1617 compl_match_array[i].pum_info = compl->cp_text[CPT_INFO];
1618 compl_match_array[i].pum_score = compl->cp_score;
1619 compl_match_array[i].pum_user_abbr_hlattr = compl->cp_user_abbr_hlattr;
1620 compl_match_array[i].pum_user_kind_hlattr = compl->cp_user_kind_hlattr;
glepnir6e199932024-12-14 21:13:27 +01001621 compl_match_array[i++].pum_extra = compl->cp_text[CPT_MENU] != NULL
1622 ? compl->cp_text[CPT_MENU] : compl->cp_fname;
glepnir80b66202024-11-27 21:53:53 +01001623 match_next = compl->cp_match_next;
1624 compl->cp_match_next = NULL;
1625 compl = match_next;
1626 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001627
zeertzjqd65aa1b2025-01-25 15:29:03 +01001628 if (fuzzy_sort && compl_leader.string != NULL && compl_leader.length > 0)
zeertzjq8e567472024-06-14 20:04:42 +02001629 {
1630 for (i = 0; i < compl_match_arraysize; i++)
1631 compl_match_array[i].pum_idx = i;
glepnira218cc62024-06-03 19:32:39 +02001632 // sort by the largest score of fuzzy match
zeertzjq8e567472024-06-14 20:04:42 +02001633 qsort(compl_match_array, (size_t)compl_match_arraysize,
1634 sizeof(pumitem_T), ins_compl_fuzzy_cmp);
glepnir65407ce2024-07-06 16:09:19 +02001635 shown_match_ok = TRUE;
zeertzjq8e567472024-06-14 20:04:42 +02001636 }
glepnira218cc62024-06-03 19:32:39 +02001637
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001638 if (!shown_match_ok) // no displayed match at all
1639 cur = -1;
1640
1641 return cur;
1642}
1643
1644/*
1645 * Show the popup menu for the list of matches.
1646 * Also adjusts "compl_shown_match" to an entry that is actually displayed.
1647 */
1648 void
1649ins_compl_show_pum(void)
1650{
1651 int i;
1652 int cur = -1;
1653 colnr_T col;
1654
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001655 if (!pum_wanted() || !pum_enough_matches())
1656 return;
1657
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001658 // Update the screen later, before drawing the popup menu over it.
1659 pum_call_update_screen();
1660
1661 if (compl_match_array == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001662 // Need to build the popup menu list.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001663 cur = ins_compl_build_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001664 else
1665 {
1666 // popup menu already exists, only need to find the current item.
1667 for (i = 0; i < compl_match_arraysize; ++i)
glepnir19e1dd62025-05-08 22:50:38 +02001668 {
John Marriott5e6ea922024-11-23 14:01:57 +01001669 if (compl_match_array[i].pum_text == compl_shown_match->cp_str.string
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001670 || compl_match_array[i].pum_text
1671 == compl_shown_match->cp_text[CPT_ABBR])
1672 {
1673 cur = i;
1674 break;
1675 }
glepnir19e1dd62025-05-08 22:50:38 +02001676 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001677 }
1678
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001679 if (compl_match_array == NULL)
glepnir0d3c0a62024-02-11 17:52:40 +01001680 {
1681#ifdef FEAT_EVAL
1682 if (compl_started && has_completechanged())
1683 trigger_complete_changed_event(cur);
1684#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001685 return;
glepnir0d3c0a62024-02-11 17:52:40 +01001686 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001687
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001688 // In Replace mode when a $ is displayed at the end of the line only
1689 // part of the screen would be updated. We do need to redraw here.
1690 dollar_vcol = -1;
1691
1692 // Compute the screen column of the start of the completed text.
1693 // Use the cursor to get all wrapping and other settings right.
1694 col = curwin->w_cursor.col;
1695 curwin->w_cursor.col = compl_col;
glepnira218cc62024-06-03 19:32:39 +02001696 compl_selected_item = cur;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001697 pum_display(compl_match_array, compl_match_arraysize, cur);
1698 curwin->w_cursor.col = col;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001699
glepnircbb46b42024-02-03 18:11:13 +01001700 // After adding leader, set the current match to shown match.
1701 if (compl_started && compl_curr_match != compl_shown_match)
1702 compl_curr_match = compl_shown_match;
1703
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001704#ifdef FEAT_EVAL
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001705 if (has_completechanged())
1706 trigger_complete_changed_event(cur);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001707#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001708}
1709
1710#define DICT_FIRST (1) // use just first element in "dict"
1711#define DICT_EXACT (2) // "dict" is the exact name of a file
1712
1713/*
glepnir40c1c332024-06-11 19:37:04 +02001714 * Get current completion leader
1715 */
1716 char_u *
1717ins_compl_leader(void)
1718{
John Marriott5e6ea922024-11-23 14:01:57 +01001719 return compl_leader.string != NULL ? compl_leader.string : compl_orig_text.string;
1720}
1721
1722/*
1723 * Get current completion leader length
1724 */
1725 size_t
1726ins_compl_leader_len(void)
1727{
1728 return compl_leader.string != NULL ? compl_leader.length : compl_orig_text.length;
glepnir40c1c332024-06-11 19:37:04 +02001729}
1730
1731/*
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001732 * Add any identifiers that match the given pattern "pat" in the list of
1733 * dictionary files "dict_start" to the list of completions.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001734 */
1735 static void
1736ins_compl_dictionaries(
1737 char_u *dict_start,
1738 char_u *pat,
1739 int flags, // DICT_FIRST and/or DICT_EXACT
1740 int thesaurus) // Thesaurus completion
1741{
1742 char_u *dict = dict_start;
1743 char_u *ptr;
1744 char_u *buf;
1745 regmatch_T regmatch;
1746 char_u **files;
1747 int count;
1748 int save_p_scs;
1749 int dir = compl_direction;
1750
1751 if (*dict == NUL)
1752 {
1753#ifdef FEAT_SPELL
1754 // When 'dictionary' is empty and spell checking is enabled use
1755 // "spell".
1756 if (!thesaurus && curwin->w_p_spell)
1757 dict = (char_u *)"spell";
1758 else
1759#endif
1760 return;
1761 }
1762
1763 buf = alloc(LSIZE);
1764 if (buf == NULL)
1765 return;
1766 regmatch.regprog = NULL; // so that we can goto theend
1767
1768 // If 'infercase' is set, don't use 'smartcase' here
1769 save_p_scs = p_scs;
1770 if (curbuf->b_p_inf)
1771 p_scs = FALSE;
1772
1773 // When invoked to match whole lines for CTRL-X CTRL-L adjust the pattern
1774 // to only match at the start of a line. Otherwise just match the
1775 // pattern. Also need to double backslashes.
1776 if (ctrl_x_mode_line_or_eval())
1777 {
1778 char_u *pat_esc = vim_strsave_escaped(pat, (char_u *)"\\");
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001779
1780 if (pat_esc == NULL)
1781 goto theend;
glepnir19e1dd62025-05-08 22:50:38 +02001782 size_t len = STRLEN(pat_esc) + 10;
Bram Moolenaar964b3742019-05-24 18:54:09 +02001783 ptr = alloc(len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001784 if (ptr == NULL)
1785 {
1786 vim_free(pat_esc);
1787 goto theend;
1788 }
1789 vim_snprintf((char *)ptr, len, "^\\s*\\zs\\V%s", pat_esc);
1790 regmatch.regprog = vim_regcomp(ptr, RE_MAGIC);
1791 vim_free(pat_esc);
1792 vim_free(ptr);
1793 }
1794 else
1795 {
Bram Moolenaarf4e20992020-12-21 19:59:08 +01001796 regmatch.regprog = vim_regcomp(pat, magic_isset() ? RE_MAGIC : 0);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001797 if (regmatch.regprog == NULL)
1798 goto theend;
1799 }
1800
1801 // ignore case depends on 'ignorecase', 'smartcase' and "pat"
1802 regmatch.rm_ic = ignorecase(pat);
1803 while (*dict != NUL && !got_int && !compl_interrupted)
1804 {
1805 // copy one dictionary file name into buf
1806 if (flags == DICT_EXACT)
1807 {
1808 count = 1;
1809 files = &dict;
1810 }
1811 else
1812 {
1813 // Expand wildcards in the dictionary name, but do not allow
1814 // backticks (for security, the 'dict' option may have been set in
1815 // a modeline).
1816 copy_option_part(&dict, buf, LSIZE, ",");
1817# ifdef FEAT_SPELL
1818 if (!thesaurus && STRCMP(buf, "spell") == 0)
1819 count = -1;
1820 else
1821# endif
1822 if (vim_strchr(buf, '`') != NULL
1823 || expand_wildcards(1, &buf, &count, &files,
1824 EW_FILE|EW_SILENT) != OK)
1825 count = 0;
1826 }
1827
1828# ifdef FEAT_SPELL
1829 if (count == -1)
1830 {
1831 // Complete from active spelling. Skip "\<" in the pattern, we
1832 // don't use it as a RE.
1833 if (pat[0] == '\\' && pat[1] == '<')
1834 ptr = pat + 2;
1835 else
1836 ptr = pat;
1837 spell_dump_compl(ptr, regmatch.rm_ic, &dir, 0);
1838 }
1839 else
1840# endif
1841 if (count > 0) // avoid warning for using "files" uninit
1842 {
1843 ins_compl_files(count, files, thesaurus, flags,
glepnirf31cfa22025-03-06 21:59:13 +01001844 (cfc_has_mode() ? NULL : &regmatch), buf, &dir);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001845 if (flags != DICT_EXACT)
1846 FreeWild(count, files);
1847 }
1848 if (flags != 0)
1849 break;
1850 }
1851
1852theend:
1853 p_scs = save_p_scs;
1854 vim_regfree(regmatch.regprog);
1855 vim_free(buf);
1856}
1857
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001858/*
1859 * Add all the words in the line "*buf_arg" from the thesaurus file "fname"
1860 * skipping the word at 'skip_word'. Returns OK on success.
1861 */
1862 static int
zeertzjq5fb3aab2022-08-24 16:48:23 +01001863thesaurus_add_words_in_line(
glepnir19e1dd62025-05-08 22:50:38 +02001864 char_u *fname,
1865 char_u **buf_arg,
1866 int dir,
1867 char_u *skip_word)
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001868{
1869 int status = OK;
1870 char_u *ptr;
1871 char_u *wstart;
1872
1873 // Add the other matches on the line
1874 ptr = *buf_arg;
1875 while (!got_int)
1876 {
1877 // Find start of the next word. Skip white
1878 // space and punctuation.
1879 ptr = find_word_start(ptr);
1880 if (*ptr == NUL || *ptr == NL)
1881 break;
1882 wstart = ptr;
1883
1884 // Find end of the word.
1885 if (has_mbyte)
1886 // Japanese words may have characters in
1887 // different classes, only separate words
1888 // with single-byte non-word characters.
1889 while (*ptr != NUL)
1890 {
1891 int l = (*mb_ptr2len)(ptr);
1892
1893 if (l < 2 && !vim_iswordc(*ptr))
1894 break;
1895 ptr += l;
1896 }
1897 else
1898 ptr = find_word_end(ptr);
1899
1900 // Add the word. Skip the regexp match.
1901 if (wstart != skip_word)
1902 {
1903 status = ins_compl_add_infercase(wstart, (int)(ptr - wstart), p_ic,
glepnirf31cfa22025-03-06 21:59:13 +01001904 fname, dir, FALSE, 0);
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001905 if (status == FAIL)
1906 break;
1907 }
1908 }
1909
1910 *buf_arg = ptr;
1911 return status;
1912}
1913
1914/*
1915 * Process "count" dictionary/thesaurus "files" and add the text matching
1916 * "regmatch".
1917 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001918 static void
1919ins_compl_files(
1920 int count,
1921 char_u **files,
1922 int thesaurus,
1923 int flags,
1924 regmatch_T *regmatch,
1925 char_u *buf,
1926 int *dir)
1927{
1928 char_u *ptr;
1929 int i;
1930 FILE *fp;
1931 int add_r;
glepnirf31cfa22025-03-06 21:59:13 +01001932 char_u *leader = NULL;
1933 int leader_len = 0;
glepnir58760162025-03-13 21:39:51 +01001934 int in_fuzzy_collect = cfc_has_mode();
glepnirf31cfa22025-03-06 21:59:13 +01001935 int score = 0;
1936 int len = 0;
1937 char_u *line_end = NULL;
1938
1939 if (in_fuzzy_collect)
1940 {
1941 leader = ins_compl_leader();
Yegappan Lakshmanan7b6add02025-04-01 20:38:37 +02001942 leader_len = (int)ins_compl_leader_len();
glepnirf31cfa22025-03-06 21:59:13 +01001943 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001944
1945 for (i = 0; i < count && !got_int && !compl_interrupted; i++)
1946 {
1947 fp = mch_fopen((char *)files[i], "r"); // open dictionary file
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01001948 if (flags != DICT_EXACT && !shortmess(SHM_COMPLETIONSCAN))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001949 {
Bram Moolenaarcc233582020-12-12 13:32:07 +01001950 msg_hist_off = TRUE; // reset in msg_trunc_attr()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001951 vim_snprintf((char *)IObuff, IOSIZE,
1952 _("Scanning dictionary: %s"), (char *)files[i]);
1953 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
1954 }
1955
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001956 if (fp == NULL)
1957 continue;
1958
1959 // Read dictionary file line by line.
1960 // Check each line for a match.
1961 while (!got_int && !compl_interrupted && !vim_fgets(buf, LSIZE, fp))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001962 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001963 ptr = buf;
glepnirf31cfa22025-03-06 21:59:13 +01001964 if (regmatch != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001965 {
glepnirf31cfa22025-03-06 21:59:13 +01001966 while (vim_regexec(regmatch, buf, (colnr_T)(ptr - buf)))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001967 {
glepnirf31cfa22025-03-06 21:59:13 +01001968 ptr = regmatch->startp[0];
1969 ptr = ctrl_x_mode_line_or_eval() ? find_line_end(ptr)
1970 : find_word_end(ptr);
1971 add_r = ins_compl_add_infercase(regmatch->startp[0],
1972 (int)(ptr - regmatch->startp[0]),
1973 p_ic, files[i], *dir, FALSE, 0);
1974 if (thesaurus)
1975 {
1976 // For a thesaurus, add all the words in the line
1977 ptr = buf;
1978 add_r = thesaurus_add_words_in_line(files[i], &ptr, *dir,
1979 regmatch->startp[0]);
1980 }
1981 if (add_r == OK)
1982 // if dir was BACKWARD then honor it just once
1983 *dir = FORWARD;
1984 else if (add_r == FAIL)
1985 break;
1986 // avoid expensive call to vim_regexec() when at end
1987 // of line
1988 if (*ptr == '\n' || got_int)
1989 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001990 }
glepnirf31cfa22025-03-06 21:59:13 +01001991 }
1992 else if (in_fuzzy_collect && leader_len > 0)
1993 {
1994 line_end = find_line_end(ptr);
1995 while (ptr < line_end)
1996 {
1997 if (fuzzy_match_str_in_line(&ptr, leader, &len, NULL, &score))
1998 {
1999 char_u *end_ptr = ctrl_x_mode_line_or_eval()
2000 ? find_line_end(ptr) : find_word_end(ptr);
2001 add_r = ins_compl_add_infercase(ptr, (int)(end_ptr - ptr),
2002 p_ic, files[i], *dir, FALSE, score);
2003 if (add_r == FAIL)
2004 break;
2005 ptr = end_ptr; // start from next word
2006 if (compl_get_longest && ctrl_x_mode_normal()
2007 && compl_first_match->cp_next
2008 && score == compl_first_match->cp_next->cp_score)
2009 compl_num_bests++;
2010 }
glepnirf31cfa22025-03-06 21:59:13 +01002011 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002012 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002013 line_breakcheck();
2014 ins_compl_check_keys(50, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002015 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002016 fclose(fp);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002017 }
2018}
2019
2020/*
2021 * Find the start of the next word.
2022 * Returns a pointer to the first char of the word. Also stops at a NUL.
2023 */
2024 char_u *
2025find_word_start(char_u *ptr)
2026{
2027 if (has_mbyte)
glepnir19e1dd62025-05-08 22:50:38 +02002028 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002029 while (*ptr != NUL && *ptr != '\n' && mb_get_class(ptr) <= 1)
2030 ptr += (*mb_ptr2len)(ptr);
glepnir19e1dd62025-05-08 22:50:38 +02002031 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002032 else
glepnir19e1dd62025-05-08 22:50:38 +02002033 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002034 while (*ptr != NUL && *ptr != '\n' && !vim_iswordc(*ptr))
2035 ++ptr;
glepnir19e1dd62025-05-08 22:50:38 +02002036 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002037 return ptr;
2038}
2039
2040/*
2041 * Find the end of the word. Assumes it starts inside a word.
2042 * Returns a pointer to just after the word.
2043 */
2044 char_u *
2045find_word_end(char_u *ptr)
2046{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002047 if (has_mbyte)
2048 {
glepnir19e1dd62025-05-08 22:50:38 +02002049 int start_class = mb_get_class(ptr);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002050 if (start_class > 1)
2051 while (*ptr != NUL)
2052 {
2053 ptr += (*mb_ptr2len)(ptr);
2054 if (mb_get_class(ptr) != start_class)
2055 break;
2056 }
2057 }
2058 else
2059 while (vim_iswordc(*ptr))
2060 ++ptr;
2061 return ptr;
2062}
2063
2064/*
2065 * Find the end of the line, omitting CR and NL at the end.
2066 * Returns a pointer to just after the line.
2067 */
glepnirdd42b052025-03-08 16:52:55 +01002068 char_u *
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002069find_line_end(char_u *ptr)
2070{
glepnir19e1dd62025-05-08 22:50:38 +02002071 char_u *s = ptr + STRLEN(ptr);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002072 while (s > ptr && (s[-1] == CAR || s[-1] == NL))
2073 --s;
2074 return s;
2075}
2076
2077/*
Girish Palyacbe53192025-04-14 22:13:15 +02002078 * Free a completion item in the list
2079 */
2080 static void
2081ins_compl_item_free(compl_T *match)
2082{
Girish Palyacbe53192025-04-14 22:13:15 +02002083 VIM_CLEAR_STRING(match->cp_str);
2084 // several entries may use the same fname, free it just once.
2085 if (match->cp_flags & CP_FREE_FNAME)
2086 vim_free(match->cp_fname);
glepnir19e1dd62025-05-08 22:50:38 +02002087 for (int i = 0; i < CPT_COUNT; ++i)
Girish Palyacbe53192025-04-14 22:13:15 +02002088 vim_free(match->cp_text[i]);
2089#ifdef FEAT_EVAL
2090 clear_tv(&match->cp_user_data);
2091#endif
2092 vim_free(match);
2093}
2094
2095/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002096 * Free the list of completions
2097 */
2098 static void
2099ins_compl_free(void)
2100{
2101 compl_T *match;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002102
John Marriott5e6ea922024-11-23 14:01:57 +01002103 VIM_CLEAR_STRING(compl_pattern);
2104 VIM_CLEAR_STRING(compl_leader);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002105
2106 if (compl_first_match == NULL)
2107 return;
2108
2109 ins_compl_del_pum();
2110 pum_clear();
2111
2112 compl_curr_match = compl_first_match;
2113 do
2114 {
2115 match = compl_curr_match;
2116 compl_curr_match = compl_curr_match->cp_next;
Girish Palyacbe53192025-04-14 22:13:15 +02002117 ins_compl_item_free(match);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002118 } while (compl_curr_match != NULL && !is_first_match(compl_curr_match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002119 compl_first_match = compl_curr_match = NULL;
2120 compl_shown_match = NULL;
2121 compl_old_match = NULL;
2122}
2123
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002124/*
2125 * Reset/clear the completion state.
2126 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002127 void
2128ins_compl_clear(void)
2129{
2130 compl_cont_status = 0;
2131 compl_started = FALSE;
glepnirf31cfa22025-03-06 21:59:13 +01002132 compl_cfc_longest_ins = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002133 compl_matches = 0;
glepnir07f0dbe2025-02-18 20:27:30 +01002134 compl_selected_item = -1;
glepnir6a38aff2024-12-16 21:56:16 +01002135 compl_ins_end_col = 0;
glepnircf7f0122025-04-15 19:02:00 +02002136 compl_curr_win = NULL;
2137 compl_curr_buf = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002138 VIM_CLEAR_STRING(compl_pattern);
2139 VIM_CLEAR_STRING(compl_leader);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002140 edit_submode_extra = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002141 VIM_CLEAR_STRING(compl_orig_text);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002142 compl_enter_selects = FALSE;
Girish Palya0ac1eb32025-04-16 20:18:33 +02002143 cpt_sources_clear();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002144#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002145 // clear v:completed_item
2146 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002147#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002148}
2149
2150/*
2151 * Return TRUE when Insert completion is active.
2152 */
2153 int
2154ins_compl_active(void)
2155{
2156 return compl_started;
2157}
2158
2159/*
glepnir8d0bb6d2024-12-24 09:44:35 +01002160 * Return True when wp is the actual completion window
2161 */
2162 int
glepnircf7f0122025-04-15 19:02:00 +02002163ins_compl_win_active(win_T *wp)
glepnir8d0bb6d2024-12-24 09:44:35 +01002164{
glepnircf7f0122025-04-15 19:02:00 +02002165 return ins_compl_active() && wp == compl_curr_win
2166 && wp->w_buffer == compl_curr_buf;
glepnir8d0bb6d2024-12-24 09:44:35 +01002167}
2168
2169/*
Girish Palyacbe53192025-04-14 22:13:15 +02002170 * Selected one of the matches. When FALSE, the match was either edited or
2171 * using the longest common string.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002172 */
2173 int
2174ins_compl_used_match(void)
2175{
2176 return compl_used_match;
2177}
2178
2179/*
2180 * Initialize get longest common string.
2181 */
2182 void
2183ins_compl_init_get_longest(void)
2184{
2185 compl_get_longest = FALSE;
2186}
2187
2188/*
2189 * Returns TRUE when insert completion is interrupted.
2190 */
2191 int
2192ins_compl_interrupted(void)
2193{
2194 return compl_interrupted;
2195}
2196
2197/*
2198 * Returns TRUE if the <Enter> key selects a match in the completion popup
2199 * menu.
2200 */
2201 int
2202ins_compl_enter_selects(void)
2203{
2204 return compl_enter_selects;
2205}
2206
2207/*
2208 * Return the column where the text starts that is being completed
2209 */
2210 colnr_T
2211ins_compl_col(void)
2212{
2213 return compl_col;
2214}
2215
2216/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002217 * Return the length in bytes of the text being completed
2218 */
2219 int
2220ins_compl_len(void)
2221{
2222 return compl_length;
2223}
2224
2225/*
glepnir94a045e2025-03-01 16:12:23 +01002226 * Return TRUE when the 'completeopt' "preinsert" flag is in effect,
2227 * otherwise return FALSE.
glepniredd4ac32025-01-29 18:53:51 +01002228 */
2229 static int
2230ins_compl_has_preinsert(void)
2231{
glepnira2c55592025-02-28 17:43:42 +01002232 int cur_cot_flags = get_cot_flags();
glepnir94a045e2025-03-01 16:12:23 +01002233 return (cur_cot_flags & (COT_PREINSERT | COT_FUZZY | COT_MENUONE))
2234 == (COT_PREINSERT | COT_MENUONE);
glepniredd4ac32025-01-29 18:53:51 +01002235}
2236
2237/*
2238 * Returns TRUE if the pre-insert effect is valid and the cursor is within
2239 * the `compl_ins_end_col` range.
2240 */
2241 int
2242ins_compl_preinsert_effect(void)
2243{
2244 if (!ins_compl_has_preinsert())
2245 return FALSE;
2246
2247 return curwin->w_cursor.col < compl_ins_end_col;
2248}
2249
2250/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002251 * Delete one character before the cursor and show the subset of the matches
2252 * that match the word that is now before the cursor.
2253 * Returns the character to be used, NUL if the work is done and another char
2254 * to be got from the user.
2255 */
2256 int
2257ins_compl_bs(void)
2258{
2259 char_u *line;
2260 char_u *p;
2261
glepniredd4ac32025-01-29 18:53:51 +01002262 if (ins_compl_preinsert_effect())
2263 ins_compl_delete();
2264
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002265 line = ml_get_curline();
2266 p = line + curwin->w_cursor.col;
2267 MB_PTR_BACK(line, p);
2268
2269 // Stop completion when the whole word was deleted. For Omni completion
2270 // allow the word to be deleted, we won't match everything.
2271 // Respect the 'backspace' option.
2272 if ((int)(p - line) - (int)compl_col < 0
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002273 || ((int)(p - line) - (int)compl_col == 0 && !ctrl_x_mode_omni())
2274 || ctrl_x_mode_eval()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002275 || (!can_bs(BS_START) && (int)(p - line) - (int)compl_col
2276 - compl_length < 0))
2277 return K_BS;
2278
2279 // Deleted more than what was used to find matches or didn't finish
2280 // finding all matches: need to look for matches all over again.
2281 if (curwin->w_cursor.col <= compl_col + compl_length
2282 || ins_compl_need_restart())
2283 ins_compl_restart();
2284
John Marriott5e6ea922024-11-23 14:01:57 +01002285 VIM_CLEAR_STRING(compl_leader);
2286 compl_leader.length = (size_t)((p - line) - compl_col);
2287 compl_leader.string = vim_strnsave(line + compl_col, compl_leader.length);
2288 if (compl_leader.string == NULL)
2289 {
2290 compl_leader.length = 0;
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00002291 return K_BS;
John Marriott5e6ea922024-11-23 14:01:57 +01002292 }
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00002293
2294 ins_compl_new_leader();
2295 if (compl_shown_match != NULL)
2296 // Make sure current match is not a hidden item.
2297 compl_curr_match = compl_shown_match;
2298 return NUL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002299}
2300
2301/*
2302 * Return TRUE when we need to find matches again, ins_compl_restart() is to
2303 * be called.
2304 */
2305 static int
2306ins_compl_need_restart(void)
2307{
2308 // Return TRUE if we didn't complete finding matches or when the
2309 // 'completefunc' returned "always" in the "refresh" dictionary item.
2310 return compl_was_interrupted
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002311 || ((ctrl_x_mode_function() || ctrl_x_mode_omni())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002312 && compl_opt_refresh_always);
2313}
2314
2315/*
2316 * Called after changing "compl_leader".
2317 * Show the popup menu with a different set of matches.
2318 * May also search for matches again if the previous search was interrupted.
2319 */
2320 static void
2321ins_compl_new_leader(void)
2322{
2323 ins_compl_del_pum();
2324 ins_compl_delete();
glepnir6a38aff2024-12-16 21:56:16 +01002325 ins_compl_insert_bytes(compl_leader.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002326 compl_used_match = FALSE;
2327
2328 if (compl_started)
Girish Palyacbe53192025-04-14 22:13:15 +02002329 {
John Marriott5e6ea922024-11-23 14:01:57 +01002330 ins_compl_set_original_text(compl_leader.string, compl_leader.length);
Girish Palyacbe53192025-04-14 22:13:15 +02002331 if (is_cpt_func_refresh_always())
2332 cpt_compl_refresh();
2333 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002334 else
2335 {
2336#ifdef FEAT_SPELL
2337 spell_bad_len = 0; // need to redetect bad word
2338#endif
Bram Moolenaar32aa1022019-11-02 22:54:41 +01002339 // Matches were cleared, need to search for them now. Before drawing
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002340 // the popup menu display the changed text before the cursor. Set
2341 // "compl_restarting" to avoid that the first match is inserted.
2342 pum_call_update_screen();
2343#ifdef FEAT_GUI
2344 if (gui.in_use)
2345 {
2346 // Show the cursor after the match, not after the redrawn text.
2347 setcursor();
2348 out_flush_cursor(FALSE, FALSE);
2349 }
2350#endif
2351 compl_restarting = TRUE;
2352 if (ins_complete(Ctrl_N, TRUE) == FAIL)
2353 compl_cont_status = 0;
2354 compl_restarting = FALSE;
2355 }
2356
glepnir44180412025-02-20 22:09:48 +01002357 compl_enter_selects = !compl_used_match && compl_selected_item != -1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002358
2359 // Show the popup menu with a different set of matches.
2360 ins_compl_show_pum();
2361
2362 // Don't let Enter select the original text when there is no popup menu.
2363 if (compl_match_array == NULL)
2364 compl_enter_selects = FALSE;
glepniredd4ac32025-01-29 18:53:51 +01002365 else if (ins_compl_has_preinsert() && compl_leader.length > 0)
2366 ins_compl_insert(FALSE, TRUE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002367}
2368
2369/*
2370 * Return the length of the completion, from the completion start column to
2371 * the cursor column. Making sure it never goes below zero.
2372 */
2373 static int
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002374get_compl_len(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002375{
2376 int off = (int)curwin->w_cursor.col - (int)compl_col;
glepnir40891ba2025-02-10 22:18:00 +01002377 return MAX(0, off);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002378}
2379
2380/*
2381 * Append one character to the match leader. May reduce the number of
2382 * matches.
2383 */
2384 void
2385ins_compl_addleader(int c)
2386{
glepnir19e1dd62025-05-08 22:50:38 +02002387 int cc;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002388
glepniredd4ac32025-01-29 18:53:51 +01002389 if (ins_compl_preinsert_effect())
2390 ins_compl_delete();
2391
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002392 if (stop_arrow() == FAIL)
2393 return;
2394 if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)
2395 {
2396 char_u buf[MB_MAXBYTES + 1];
2397
2398 (*mb_char2bytes)(c, buf);
2399 buf[cc] = NUL;
2400 ins_char_bytes(buf, cc);
2401 if (compl_opt_refresh_always)
2402 AppendToRedobuff(buf);
2403 }
2404 else
2405 {
2406 ins_char(c);
2407 if (compl_opt_refresh_always)
2408 AppendCharToRedobuff(c);
2409 }
2410
2411 // If we didn't complete finding matches we must search again.
2412 if (ins_compl_need_restart())
2413 ins_compl_restart();
2414
2415 // When 'always' is set, don't reset compl_leader. While completing,
2416 // cursor doesn't point original position, changing compl_leader would
2417 // break redo.
2418 if (!compl_opt_refresh_always)
2419 {
John Marriott5e6ea922024-11-23 14:01:57 +01002420 VIM_CLEAR_STRING(compl_leader);
2421 compl_leader.length = (size_t)(curwin->w_cursor.col - compl_col);
2422 compl_leader.string = vim_strnsave(ml_get_curline() + compl_col,
2423 compl_leader.length);
2424 if (compl_leader.string == NULL)
2425 {
2426 compl_leader.length = 0;
2427 return;
2428 }
2429
2430 ins_compl_new_leader();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002431 }
2432}
2433
2434/*
2435 * Setup for finding completions again without leaving CTRL-X mode. Used when
2436 * BS or a key was typed while still searching for matches.
2437 */
2438 static void
2439ins_compl_restart(void)
2440{
2441 ins_compl_free();
2442 compl_started = FALSE;
2443 compl_matches = 0;
2444 compl_cont_status = 0;
2445 compl_cont_mode = 0;
Girish Palya0ac1eb32025-04-16 20:18:33 +02002446 cpt_sources_clear();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002447}
2448
2449/*
2450 * Set the first match, the original text.
2451 */
2452 static void
John Marriott5e6ea922024-11-23 14:01:57 +01002453ins_compl_set_original_text(char_u *str, size_t len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002454{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002455 // Replace the original text entry.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002456 // The CP_ORIGINAL_TEXT flag is either at the first item or might possibly
2457 // be at the last item for backward completion
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002458 if (match_at_original_text(compl_first_match)) // safety check
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002459 {
John Marriott5e6ea922024-11-23 14:01:57 +01002460 char_u *p = vim_strnsave(str, len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002461 if (p != NULL)
2462 {
John Marriott5e6ea922024-11-23 14:01:57 +01002463 VIM_CLEAR_STRING(compl_first_match->cp_str);
2464 compl_first_match->cp_str.string = p;
2465 compl_first_match->cp_str.length = len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002466 }
2467 }
2468 else if (compl_first_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002469 && match_at_original_text(compl_first_match->cp_prev))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002470 {
John Marriott5e6ea922024-11-23 14:01:57 +01002471 char_u *p = vim_strnsave(str, len);
2472 if (p != NULL)
2473 {
2474 VIM_CLEAR_STRING(compl_first_match->cp_prev->cp_str);
2475 compl_first_match->cp_prev->cp_str.string = p;
2476 compl_first_match->cp_prev->cp_str.length = len;
2477 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002478 }
2479}
2480
2481/*
2482 * Append one character to the match leader. May reduce the number of
2483 * matches.
2484 */
2485 void
2486ins_compl_addfrommatch(void)
2487{
2488 char_u *p;
2489 int len = (int)curwin->w_cursor.col - (int)compl_col;
2490 int c;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002491
John Marriott5e6ea922024-11-23 14:01:57 +01002492 p = compl_shown_match->cp_str.string;
2493 if ((int)compl_shown_match->cp_str.length <= len) // the match is too short
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002494 {
John Marriott5e6ea922024-11-23 14:01:57 +01002495 size_t plen;
2496 compl_T *cp;
2497
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002498 // When still at the original match use the first entry that matches
2499 // the leader.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002500 if (!match_at_original_text(compl_shown_match))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002501 return;
2502
2503 p = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002504 plen = 0;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002505 for (cp = compl_shown_match->cp_next; cp != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002506 && !is_first_match(cp); cp = cp->cp_next)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002507 {
John Marriott5e6ea922024-11-23 14:01:57 +01002508 if (compl_leader.string == NULL
2509 || ins_compl_equal(cp, compl_leader.string,
2510 (int)compl_leader.length))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002511 {
John Marriott5e6ea922024-11-23 14:01:57 +01002512 p = cp->cp_str.string;
2513 plen = cp->cp_str.length;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002514 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002515 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002516 }
John Marriott5e6ea922024-11-23 14:01:57 +01002517 if (p == NULL || (int)plen <= len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002518 return;
2519 }
2520 p += len;
2521 c = PTR2CHAR(p);
2522 ins_compl_addleader(c);
2523}
2524
2525/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002526 * Set the CTRL-X completion mode based on the key "c" typed after a CTRL-X.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002527 * Uses the global variables: ctrl_x_mode, edit_submode, edit_submode_pre,
2528 * compl_cont_mode and compl_cont_status.
2529 * Returns TRUE when the character is not to be inserted.
2530 */
2531 static int
2532set_ctrl_x_mode(int c)
2533{
2534 int retval = FALSE;
2535
2536 switch (c)
2537 {
2538 case Ctrl_E:
2539 case Ctrl_Y:
2540 // scroll the window one line up or down
2541 ctrl_x_mode = CTRL_X_SCROLL;
2542 if (!(State & REPLACE_FLAG))
2543 edit_submode = (char_u *)_(" (insert) Scroll (^E/^Y)");
2544 else
2545 edit_submode = (char_u *)_(" (replace) Scroll (^E/^Y)");
2546 edit_submode_pre = NULL;
2547 showmode();
2548 break;
2549 case Ctrl_L:
2550 // complete whole line
2551 ctrl_x_mode = CTRL_X_WHOLE_LINE;
2552 break;
2553 case Ctrl_F:
2554 // complete filenames
2555 ctrl_x_mode = CTRL_X_FILES;
2556 break;
2557 case Ctrl_K:
zeertzjq5fb3aab2022-08-24 16:48:23 +01002558 // complete words from a dictionary
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002559 ctrl_x_mode = CTRL_X_DICTIONARY;
2560 break;
2561 case Ctrl_R:
2562 // Register insertion without exiting CTRL-X mode
2563 // Simply allow ^R to happen without affecting ^X mode
2564 break;
2565 case Ctrl_T:
2566 // complete words from a thesaurus
2567 ctrl_x_mode = CTRL_X_THESAURUS;
2568 break;
2569#ifdef FEAT_COMPL_FUNC
2570 case Ctrl_U:
2571 // user defined completion
2572 ctrl_x_mode = CTRL_X_FUNCTION;
2573 break;
2574 case Ctrl_O:
2575 // omni completion
2576 ctrl_x_mode = CTRL_X_OMNI;
2577 break;
2578#endif
2579 case 's':
2580 case Ctrl_S:
2581 // complete spelling suggestions
2582 ctrl_x_mode = CTRL_X_SPELL;
2583#ifdef FEAT_SPELL
2584 ++emsg_off; // Avoid getting the E756 error twice.
2585 spell_back_to_badword();
2586 --emsg_off;
2587#endif
2588 break;
2589 case Ctrl_RSB:
2590 // complete tag names
2591 ctrl_x_mode = CTRL_X_TAGS;
2592 break;
2593#ifdef FEAT_FIND_ID
2594 case Ctrl_I:
2595 case K_S_TAB:
2596 // complete keywords from included files
2597 ctrl_x_mode = CTRL_X_PATH_PATTERNS;
2598 break;
2599 case Ctrl_D:
2600 // complete definitions from included files
2601 ctrl_x_mode = CTRL_X_PATH_DEFINES;
2602 break;
2603#endif
2604 case Ctrl_V:
2605 case Ctrl_Q:
2606 // complete vim commands
2607 ctrl_x_mode = CTRL_X_CMDLINE;
2608 break;
2609 case Ctrl_Z:
2610 // stop completion
2611 ctrl_x_mode = CTRL_X_NORMAL;
2612 edit_submode = NULL;
2613 showmode();
2614 retval = TRUE;
2615 break;
2616 case Ctrl_P:
2617 case Ctrl_N:
2618 // ^X^P means LOCAL expansion if nothing interrupted (eg we
2619 // just started ^X mode, or there were enough ^X's to cancel
2620 // the previous mode, say ^X^F^X^X^P or ^P^X^X^X^P, see below)
2621 // do normal expansion when interrupting a different mode (say
2622 // ^X^F^X^P or ^P^X^X^P, see below)
2623 // nothing changes if interrupting mode 0, (eg, the flag
2624 // doesn't change when going to ADDING mode -- Acevedo
2625 if (!(compl_cont_status & CONT_INTRPT))
2626 compl_cont_status |= CONT_LOCAL;
2627 else if (compl_cont_mode != 0)
2628 compl_cont_status &= ~CONT_LOCAL;
2629 // FALLTHROUGH
2630 default:
2631 // If we have typed at least 2 ^X's... for modes != 0, we set
2632 // compl_cont_status = 0 (eg, as if we had just started ^X
2633 // mode).
2634 // For mode 0, we set "compl_cont_mode" to an impossible
2635 // value, in both cases ^X^X can be used to restart the same
2636 // mode (avoiding ADDING mode).
2637 // Undocumented feature: In a mode != 0 ^X^P and ^X^X^P start
2638 // 'complete' and local ^P expansions respectively.
2639 // In mode 0 an extra ^X is needed since ^X^P goes to ADDING
2640 // mode -- Acevedo
2641 if (c == Ctrl_X)
2642 {
2643 if (compl_cont_mode != 0)
2644 compl_cont_status = 0;
2645 else
2646 compl_cont_mode = CTRL_X_NOT_DEFINED_YET;
2647 }
2648 ctrl_x_mode = CTRL_X_NORMAL;
2649 edit_submode = NULL;
2650 showmode();
2651 break;
2652 }
2653
2654 return retval;
2655}
2656
2657/*
glepnir1c5a1202024-12-04 20:27:34 +01002658 * Trigger CompleteDone event and adds relevant information to v:event
2659 */
2660 static void
2661trigger_complete_done_event(int mode UNUSED, char_u *word UNUSED)
2662{
2663#if defined(FEAT_EVAL)
2664 save_v_event_T save_v_event;
2665 dict_T *v_event = get_v_event(&save_v_event);
2666 char_u *mode_str = NULL;
2667
2668 mode = mode & ~CTRL_X_WANT_IDENT;
2669 if (ctrl_x_mode_names[mode])
2670 mode_str = (char_u *)ctrl_x_mode_names[mode];
2671
2672 (void)dict_add_string(v_event, "complete_word",
2673 word == NULL ? (char_u *)"" : word);
2674 (void)dict_add_string(v_event, "complete_type",
2675 mode_str != NULL ? mode_str : (char_u *)"");
2676
2677 dict_set_items_ro(v_event);
2678#endif
2679 ins_apply_autocmds(EVENT_COMPLETEDONE);
2680
2681#if defined(FEAT_EVAL)
2682 restore_v_event(v_event, &save_v_event);
2683#endif
2684}
2685
2686/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002687 * Stop insert completion mode
2688 */
2689 static int
2690ins_compl_stop(int c, int prev_mode, int retval)
2691{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002692 int want_cindent;
glepnir1c5a1202024-12-04 20:27:34 +01002693 char_u *word = NULL;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002694
glepnir84a75032025-03-15 09:59:22 +01002695 // Remove pre-inserted text when present.
zeertzjq13436812025-04-23 20:46:35 +02002696 if (ins_compl_preinsert_effect() && ins_compl_win_active(curwin))
glepnir84a75032025-03-15 09:59:22 +01002697 ins_compl_delete();
2698
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002699 // Get here when we have finished typing a sequence of ^N and
2700 // ^P or other completion characters in CTRL-X mode. Free up
2701 // memory that was used, and make sure we can redo the insert.
John Marriott5e6ea922024-11-23 14:01:57 +01002702 if (compl_curr_match != NULL || compl_leader.string != NULL || c == Ctrl_E)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002703 {
glepnir40891ba2025-02-10 22:18:00 +01002704 char_u *ptr = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002705
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002706 // If any of the original typed text has been changed, eg when
2707 // ignorecase is set, we must add back-spaces to the redo
2708 // buffer. We add as few as necessary to delete just the part
2709 // of the original text that has changed.
2710 // When using the longest match, edited the match or used
2711 // CTRL-E then don't use the current match.
2712 if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E)
John Marriott5e6ea922024-11-23 14:01:57 +01002713 ptr = compl_curr_match->cp_str.string;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002714 ins_compl_fixRedoBufForLeader(ptr);
2715 }
2716
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002717 want_cindent = (get_can_cindent() && cindent_on());
Bram Moolenaar8e145b82022-05-21 20:17:31 +01002718
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002719 // When completing whole lines: fix indent for 'cindent'.
2720 // Otherwise, break line if it's too long.
2721 if (compl_cont_mode == CTRL_X_WHOLE_LINE)
2722 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002723 // re-indent the current line
2724 if (want_cindent)
2725 {
2726 do_c_expr_indent();
2727 want_cindent = FALSE; // don't do it again
2728 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002729 }
2730 else
2731 {
2732 int prev_col = curwin->w_cursor.col;
2733
2734 // put the cursor on the last char, for 'tw' formatting
2735 if (prev_col > 0)
2736 dec_cursor();
2737 // only format when something was inserted
2738 if (!arrow_used && !ins_need_undo_get() && c != Ctrl_E)
2739 insertchar(NUL, 0, -1);
2740 if (prev_col > 0
2741 && ml_get_curline()[curwin->w_cursor.col] != NUL)
2742 inc_cursor();
2743 }
2744
2745 // If the popup menu is displayed pressing CTRL-Y means accepting
2746 // the selection without inserting anything. When
2747 // compl_enter_selects is set the Enter key does the same.
2748 if ((c == Ctrl_Y || (compl_enter_selects
2749 && (c == CAR || c == K_KENTER || c == NL)))
2750 && pum_visible())
glepnir1c5a1202024-12-04 20:27:34 +01002751 {
2752 word = vim_strsave(compl_shown_match->cp_str.string);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002753 retval = TRUE;
glepnir1c5a1202024-12-04 20:27:34 +01002754 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002755
2756 // CTRL-E means completion is Ended, go back to the typed text.
2757 // but only do this, if the Popup is still visible
2758 if (c == Ctrl_E)
2759 {
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002760 char_u *p = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002761 size_t plen = 0;
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002762
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002763 ins_compl_delete();
John Marriott5e6ea922024-11-23 14:01:57 +01002764 if (compl_leader.string != NULL)
2765 {
2766 p = compl_leader.string;
2767 plen = compl_leader.length;
2768 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002769 else if (compl_first_match != NULL)
John Marriott5e6ea922024-11-23 14:01:57 +01002770 {
2771 p = compl_orig_text.string;
2772 plen = compl_orig_text.length;
2773 }
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002774 if (p != NULL)
2775 {
2776 int compl_len = get_compl_len();
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002777
John Marriott5e6ea922024-11-23 14:01:57 +01002778 if ((int)plen > compl_len)
zeertzjqf25d8f92024-12-18 21:12:25 +01002779 ins_compl_insert_bytes(p + compl_len, (int)plen - compl_len);
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002780 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002781 retval = TRUE;
2782 }
2783
2784 auto_format(FALSE, TRUE);
2785
2786 // Trigger the CompleteDonePre event to give scripts a chance to
2787 // act upon the completion before clearing the info, and restore
2788 // ctrl_x_mode, so that complete_info() can be used.
2789 ctrl_x_mode = prev_mode;
2790 ins_apply_autocmds(EVENT_COMPLETEDONEPRE);
2791
2792 ins_compl_free();
2793 compl_started = FALSE;
2794 compl_matches = 0;
2795 if (!shortmess(SHM_COMPLETIONMENU))
2796 msg_clr_cmdline(); // necessary for "noshowmode"
2797 ctrl_x_mode = CTRL_X_NORMAL;
2798 compl_enter_selects = FALSE;
2799 if (edit_submode != NULL)
2800 {
2801 edit_submode = NULL;
2802 showmode();
2803 }
2804
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002805 if (c == Ctrl_C && cmdwin_type != 0)
2806 // Avoid the popup menu remains displayed when leaving the
2807 // command line window.
2808 update_screen(0);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002809 // Indent now if a key was typed that is in 'cinkeys'.
2810 if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0)))
2811 do_c_expr_indent();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002812 // Trigger the CompleteDone event to give scripts a chance to act
2813 // upon the end of completion.
glepnir1c5a1202024-12-04 20:27:34 +01002814 trigger_complete_done_event(prev_mode, word);
2815 vim_free(word);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002816
2817 return retval;
2818}
2819
2820/*
glepnircf7f0122025-04-15 19:02:00 +02002821 * Cancel completion.
2822 */
2823 int
2824ins_compl_cancel(void)
2825{
2826 return ins_compl_stop(' ', ctrl_x_mode, TRUE);
2827}
2828
2829/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002830 * Prepare for Insert mode completion, or stop it.
2831 * Called just after typing a character in Insert mode.
2832 * Returns TRUE when the character is not to be inserted;
2833 */
2834 int
2835ins_compl_prep(int c)
2836{
glepnir19e1dd62025-05-08 22:50:38 +02002837 int retval = FALSE;
2838 int prev_mode = ctrl_x_mode;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002839
2840 // Forget any previous 'special' messages if this is actually
2841 // a ^X mode key - bar ^R, in which case we wait to see what it gives us.
2842 if (c != Ctrl_R && vim_is_ctrl_x_key(c))
2843 edit_submode_extra = NULL;
2844
zeertzjq440d4cb2023-03-02 17:51:32 +00002845 // Ignore end of Select mode mapping and mouse scroll/movement.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002846 if (c == K_SELECT || c == K_MOUSEDOWN || c == K_MOUSEUP
zeertzjq440d4cb2023-03-02 17:51:32 +00002847 || c == K_MOUSELEFT || c == K_MOUSERIGHT || c == K_MOUSEMOVE
Bram Moolenaare32c3c42022-01-15 18:26:04 +00002848 || c == K_COMMAND || c == K_SCRIPT_COMMAND)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002849 return retval;
2850
Bram Moolenaar05ad5ff2019-11-30 22:48:27 +01002851#ifdef FEAT_PROP_POPUP
Bram Moolenaarf0bc15c2019-08-18 19:23:45 +02002852 // Ignore mouse events in a popup window
2853 if (is_mouse_key(c))
2854 {
2855 // Ignore drag and release events, the position does not need to be in
2856 // the popup and it may have just closed.
2857 if (c == K_LEFTRELEASE
2858 || c == K_LEFTRELEASE_NM
2859 || c == K_MIDDLERELEASE
2860 || c == K_RIGHTRELEASE
2861 || c == K_X1RELEASE
2862 || c == K_X2RELEASE
2863 || c == K_LEFTDRAG
2864 || c == K_MIDDLEDRAG
2865 || c == K_RIGHTDRAG
2866 || c == K_X1DRAG
2867 || c == K_X2DRAG)
2868 return retval;
2869 if (popup_visible)
2870 {
2871 int row = mouse_row;
2872 int col = mouse_col;
2873 win_T *wp = mouse_find_win(&row, &col, FIND_POPUP);
2874
2875 if (wp != NULL && WIN_IS_POPUP(wp))
2876 return retval;
2877 }
2878 }
2879#endif
2880
zeertzjqdca29d92021-08-31 19:12:51 +02002881 if (ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X && c != Ctrl_X)
2882 {
2883 if (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_Z || ins_compl_pum_key(c)
2884 || !vim_is_ctrl_x_key(c))
2885 {
2886 // Not starting another completion mode.
2887 ctrl_x_mode = CTRL_X_CMDLINE;
2888
2889 // CTRL-X CTRL-Z should stop completion without inserting anything
2890 if (c == Ctrl_Z)
2891 retval = TRUE;
2892 }
2893 else
2894 {
2895 ctrl_x_mode = CTRL_X_CMDLINE;
2896
2897 // Other CTRL-X keys first stop completion, then start another
2898 // completion mode.
2899 ins_compl_prep(' ');
2900 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
2901 }
2902 }
2903
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002904 // Set "compl_get_longest" when finding the first matches.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002905 if (ctrl_x_mode_not_defined_yet()
2906 || (ctrl_x_mode_normal() && !compl_started))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002907 {
zeertzjq529b9ad2024-06-05 20:27:06 +02002908 compl_get_longest = (get_cot_flags() & COT_LONGEST) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002909 compl_used_match = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002910 }
2911
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002912 if (ctrl_x_mode_not_defined_yet())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002913 // We have just typed CTRL-X and aren't quite sure which CTRL-X mode
2914 // it will be yet. Now we decide.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002915 retval = set_ctrl_x_mode(c);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002916 else if (ctrl_x_mode_not_default())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002917 {
2918 // We're already in CTRL-X mode, do we stay in it?
2919 if (!vim_is_ctrl_x_key(c))
2920 {
glepnir40891ba2025-02-10 22:18:00 +01002921 ctrl_x_mode = ctrl_x_mode_scroll() ? CTRL_X_NORMAL : CTRL_X_FINISHED;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002922 edit_submode = NULL;
2923 }
2924 showmode();
2925 }
2926
2927 if (compl_started || ctrl_x_mode == CTRL_X_FINISHED)
2928 {
2929 // Show error message from attempted keyword completion (probably
2930 // 'Pattern not found') until another key is hit, then go back to
2931 // showing what mode we are in.
2932 showmode();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002933 if ((ctrl_x_mode_normal() && c != Ctrl_N && c != Ctrl_P
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002934 && c != Ctrl_R && !ins_compl_pum_key(c))
2935 || ctrl_x_mode == CTRL_X_FINISHED)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002936 retval = ins_compl_stop(c, prev_mode, retval);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002937 }
2938 else if (ctrl_x_mode == CTRL_X_LOCAL_MSG)
2939 // Trigger the CompleteDone event to give scripts a chance to act
2940 // upon the (possibly failed) completion.
glepnir1c5a1202024-12-04 20:27:34 +01002941 trigger_complete_done_event(ctrl_x_mode, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002942
LemonBoy2bf52dd2022-04-09 18:17:34 +01002943 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01002944
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002945 // reset continue_* if we left expansion-mode, if we stay they'll be
2946 // (re)set properly in ins_complete()
2947 if (!vim_is_ctrl_x_key(c))
2948 {
2949 compl_cont_status = 0;
2950 compl_cont_mode = 0;
2951 }
2952
2953 return retval;
2954}
2955
2956/*
2957 * Fix the redo buffer for the completion leader replacing some of the typed
2958 * text. This inserts backspaces and appends the changed text.
2959 * "ptr" is the known leader text or NUL.
2960 */
2961 static void
2962ins_compl_fixRedoBufForLeader(char_u *ptr_arg)
2963{
John Marriott5e6ea922024-11-23 14:01:57 +01002964 int len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002965 char_u *p;
2966 char_u *ptr = ptr_arg;
2967
2968 if (ptr == NULL)
2969 {
John Marriott5e6ea922024-11-23 14:01:57 +01002970 if (compl_leader.string != NULL)
2971 ptr = compl_leader.string;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002972 else
2973 return; // nothing to do
2974 }
John Marriott5e6ea922024-11-23 14:01:57 +01002975 if (compl_orig_text.string != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002976 {
John Marriott5e6ea922024-11-23 14:01:57 +01002977 p = compl_orig_text.string;
glepnir40891ba2025-02-10 22:18:00 +01002978 // Find length of common prefix between original text and new completion
2979 while (p[len] != NUL && p[len] == ptr[len])
2980 len++;
2981 // Adjust length to not break inside a multi-byte character
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002982 if (len > 0)
2983 len -= (*mb_head_off)(p, p + len);
glepnir40891ba2025-02-10 22:18:00 +01002984 // Add backspace characters for each remaining character in
2985 // original text
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002986 for (p += len; *p != NUL; MB_PTR_ADV(p))
2987 AppendCharToRedobuff(K_BS);
2988 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002989 if (ptr != NULL)
2990 AppendToRedobuffLit(ptr + len, -1);
2991}
2992
2993/*
2994 * Loops through the list of windows, loaded-buffers or non-loaded-buffers
2995 * (depending on flag) starting from buf and looking for a non-scanned
2996 * buffer (other than curbuf). curbuf is special, if it is called with
2997 * buf=curbuf then it has to be the first call for a given flag/expansion.
2998 *
2999 * Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo
3000 */
3001 static buf_T *
3002ins_compl_next_buf(buf_T *buf, int flag)
3003{
glepnir19e1dd62025-05-08 22:50:38 +02003004 static win_T *wp = NULL;
3005 int skip_buffer;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003006
3007 if (flag == 'w') // just windows
3008 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003009 if (buf == curbuf || !win_valid(wp))
3010 // first call for this flag/expansion or window was closed
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003011 wp = curwin;
glepnir40891ba2025-02-10 22:18:00 +01003012
3013 while (TRUE)
3014 {
Hirohito Higashi355db992025-04-28 18:07:02 +02003015 // Move to next window (wrap to first window if at the end)
3016 wp = (wp->w_next != NULL) ? wp->w_next : firstwin;
3017 // Break if we're back at start or found an unscanned buffer
3018 if (wp == curwin || !wp->w_buffer->b_scanned)
3019 break;
glepnir40891ba2025-02-10 22:18:00 +01003020 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003021 buf = wp->w_buffer;
3022 }
3023 else
glepnir40891ba2025-02-10 22:18:00 +01003024 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003025 // 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U'
3026 // (unlisted buffers)
3027 // When completing whole lines skip unloaded buffers.
glepnir40891ba2025-02-10 22:18:00 +01003028 while (TRUE)
3029 {
3030 // Move to next buffer (wrap to first buffer if at the end)
3031 buf = (buf->b_next != NULL) ? buf->b_next : firstbuf;
3032 // Break if we're back at start buffer
3033 if (buf == curbuf)
3034 break;
3035
3036 // Check buffer conditions based on flag
3037 if (flag == 'U')
3038 skip_buffer = buf->b_p_bl;
3039 else
3040 skip_buffer = !buf->b_p_bl ||
3041 (buf->b_ml.ml_mfp == NULL) != (flag == 'u');
3042
3043 // Break if we found a buffer that matches our criteria
3044 if (!skip_buffer && !buf->b_scanned)
3045 break;
3046 }
3047 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003048 return buf;
3049}
3050
3051#ifdef FEAT_COMPL_FUNC
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003052
3053# ifdef FEAT_EVAL
3054static callback_T cfu_cb; // 'completefunc' callback function
3055static callback_T ofu_cb; // 'omnifunc' callback function
3056static callback_T tsrfu_cb; // 'thesaurusfunc' callback function
3057# endif
3058
3059/*
3060 * Copy a global callback function to a buffer local callback.
3061 */
3062 static void
3063copy_global_to_buflocal_cb(callback_T *globcb, callback_T *bufcb)
3064{
3065 free_callback(bufcb);
3066 if (globcb->cb_name != NULL && *globcb->cb_name != NUL)
3067 copy_callback(bufcb, globcb);
3068}
3069
3070/*
3071 * Parse the 'completefunc' option value and set the callback function.
3072 * Invoked when the 'completefunc' option is set. The option value can be a
3073 * name of a function (string), or function(<name>) or funcref(<name>) or a
3074 * lambda expression.
3075 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003076 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00003077did_set_completefunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003078{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003079 if (option_set_callback_func(curbuf->b_p_cfu, &cfu_cb) == FAIL)
3080 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003081
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003082 set_buflocal_cfu_callback(curbuf);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003083
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003084 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003085}
3086
3087/*
3088 * Copy the global 'completefunc' callback function to the buffer-local
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003089 * 'completefunc' callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003090 */
3091 void
3092set_buflocal_cfu_callback(buf_T *buf UNUSED)
3093{
3094# ifdef FEAT_EVAL
3095 copy_global_to_buflocal_cb(&cfu_cb, &buf->b_cfu_cb);
3096# endif
3097}
3098
3099/*
3100 * Parse the 'omnifunc' option value and set the callback function.
3101 * Invoked when the 'omnifunc' option is set. The option value can be a
3102 * name of a function (string), or function(<name>) or funcref(<name>) or a
3103 * lambda expression.
3104 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003105 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00003106did_set_omnifunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003107{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003108 if (option_set_callback_func(curbuf->b_p_ofu, &ofu_cb) == FAIL)
3109 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003110
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003111 set_buflocal_ofu_callback(curbuf);
3112 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003113}
3114
3115/*
3116 * Copy the global 'omnifunc' callback function to the buffer-local 'omnifunc'
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003117 * callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003118 */
3119 void
3120set_buflocal_ofu_callback(buf_T *buf UNUSED)
3121{
3122# ifdef FEAT_EVAL
3123 copy_global_to_buflocal_cb(&ofu_cb, &buf->b_ofu_cb);
3124# endif
3125}
3126
3127/*
3128 * Parse the 'thesaurusfunc' option value and set the callback function.
3129 * Invoked when the 'thesaurusfunc' option is set. The option value can be a
3130 * name of a function (string), or function(<name>) or funcref(<name>) or a
3131 * lambda expression.
3132 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003133 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00003134did_set_thesaurusfunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003135{
3136 int retval;
3137
zeertzjq6eda2692024-11-03 09:23:33 +01003138 if (args->os_flags & OPT_LOCAL)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003139 // buffer-local option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003140 retval = option_set_callback_func(curbuf->b_p_tsrfu,
3141 &curbuf->b_tsrfu_cb);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003142 else
3143 {
3144 // global option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003145 retval = option_set_callback_func(p_tsrfu, &tsrfu_cb);
zeertzjq6eda2692024-11-03 09:23:33 +01003146 // when using :set, free the local callback
3147 if (!(args->os_flags & OPT_GLOBAL))
3148 free_callback(&curbuf->b_tsrfu_cb);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003149 }
3150
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003151 return retval == FAIL ? e_invalid_argument : NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003152}
3153
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00003154/*
3155 * Mark the global 'completefunc' 'omnifunc' and 'thesaurusfunc' callbacks with
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003156 * "copyID" so that they are not garbage collected.
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00003157 */
3158 int
3159set_ref_in_insexpand_funcs(int copyID)
3160{
glepnir19e1dd62025-05-08 22:50:38 +02003161 int abort = set_ref_in_callback(&cfu_cb, copyID);
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00003162 abort = abort || set_ref_in_callback(&ofu_cb, copyID);
3163 abort = abort || set_ref_in_callback(&tsrfu_cb, copyID);
3164
3165 return abort;
3166}
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003167
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003168/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003169 * Get the user-defined completion function name for completion "type"
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003170 */
3171 static char_u *
3172get_complete_funcname(int type)
3173{
3174 switch (type)
3175 {
3176 case CTRL_X_FUNCTION:
3177 return curbuf->b_p_cfu;
3178 case CTRL_X_OMNI:
3179 return curbuf->b_p_ofu;
3180 case CTRL_X_THESAURUS:
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01003181 return *curbuf->b_p_tsrfu == NUL ? p_tsrfu : curbuf->b_p_tsrfu;
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003182 default:
3183 return (char_u *)"";
3184 }
3185}
3186
3187/*
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003188 * Get the callback to use for insert mode completion.
3189 */
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003190 static callback_T *
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003191get_insert_callback(int type)
3192{
3193 if (type == CTRL_X_FUNCTION)
3194 return &curbuf->b_cfu_cb;
3195 if (type == CTRL_X_OMNI)
3196 return &curbuf->b_ofu_cb;
3197 // CTRL_X_THESAURUS
3198 return (*curbuf->b_p_tsrfu != NUL) ? &curbuf->b_tsrfu_cb : &tsrfu_cb;
3199}
3200
3201/*
Yegappan Lakshmanan05e59e32021-12-01 10:30:07 +00003202 * Execute user defined complete function 'completefunc', 'omnifunc' or
3203 * 'thesaurusfunc', and get matches in "matches".
Girish Palyacbe53192025-04-14 22:13:15 +02003204 * "type" can be one of CTRL_X_OMNI, CTRL_X_FUNCTION, or CTRL_X_THESAURUS.
3205 * Callback function "cb" is set if triggered by a function in the 'cpt'
3206 * option; otherwise, it is NULL.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003207 */
3208 static void
Girish Palyacbe53192025-04-14 22:13:15 +02003209expand_by_function(int type, char_u *base, callback_T *cb)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003210{
3211 list_T *matchlist = NULL;
3212 dict_T *matchdict = NULL;
3213 typval_T args[3];
3214 char_u *funcname;
3215 pos_T pos;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003216 typval_T rettv;
3217 int save_State = State;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003218 int retval;
Girish Palyacbe53192025-04-14 22:13:15 +02003219 int is_cpt_function = (cb != NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003220
Girish Palyacbe53192025-04-14 22:13:15 +02003221 if (!is_cpt_function)
3222 {
3223 funcname = get_complete_funcname(type);
3224 if (*funcname == NUL)
3225 return;
3226 cb = get_insert_callback(type);
3227 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003228
3229 // Call 'completefunc' to obtain the list of matches.
3230 args[0].v_type = VAR_NUMBER;
3231 args[0].vval.v_number = 0;
3232 args[1].v_type = VAR_STRING;
3233 args[1].vval.v_string = base != NULL ? base : (char_u *)"";
3234 args[2].v_type = VAR_UNKNOWN;
3235
3236 pos = curwin->w_cursor;
Bram Moolenaar28976e22021-01-29 21:07:07 +01003237 // Lock the text to avoid weird things from happening. Also disallow
3238 // switching to another window, it should not be needed and may end up in
3239 // Insert mode in another buffer.
zeertzjqcfe45652022-05-27 17:26:55 +01003240 ++textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003241
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003242 retval = call_callback(cb, 0, &rettv, 2, args);
3243
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003244 // Call a function, which returns a list or dict.
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003245 if (retval == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003246 {
3247 switch (rettv.v_type)
3248 {
3249 case VAR_LIST:
3250 matchlist = rettv.vval.v_list;
3251 break;
3252 case VAR_DICT:
3253 matchdict = rettv.vval.v_dict;
3254 break;
3255 case VAR_SPECIAL:
3256 if (rettv.vval.v_number == VVAL_NONE)
3257 compl_opt_suppress_empty = TRUE;
3258 // FALLTHROUGH
3259 default:
3260 // TODO: Give error message?
3261 clear_tv(&rettv);
3262 break;
3263 }
3264 }
zeertzjqcfe45652022-05-27 17:26:55 +01003265 --textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003266
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003267 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02003268 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003269 validate_cursor();
3270 if (!EQUAL_POS(curwin->w_cursor, pos))
3271 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00003272 emsg(_(e_complete_function_deleted_text));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003273 goto theend;
3274 }
3275
3276 if (matchlist != NULL)
3277 ins_compl_add_list(matchlist);
3278 else if (matchdict != NULL)
3279 ins_compl_add_dict(matchdict);
3280
3281theend:
3282 // Restore State, it might have been changed.
3283 State = save_State;
3284
3285 if (matchdict != NULL)
3286 dict_unref(matchdict);
3287 if (matchlist != NULL)
3288 list_unref(matchlist);
3289}
3290#endif // FEAT_COMPL_FUNC
3291
3292#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL) || defined(PROTO)
glepnir38f99a12024-08-23 18:31:06 +02003293
3294 static inline int
3295get_user_highlight_attr(char_u *hlname)
3296{
3297 if (hlname != NULL && *hlname != NUL)
Hirohito Higashi355db992025-04-28 18:07:02 +02003298 return syn_name2attr(hlname);
glepnir38f99a12024-08-23 18:31:06 +02003299 return -1;
3300}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003301/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003302 * Add a match to the list of matches from a typeval_T.
3303 * If the given string is already in the list of completions, then return
3304 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
3305 * maybe because alloc() returns NULL, then FAIL is returned.
Bram Moolenaar440cf092021-04-03 20:13:30 +02003306 * When "fast" is TRUE use fast_breakcheck() instead of ui_breakcheck().
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003307 */
3308 static int
Bram Moolenaar440cf092021-04-03 20:13:30 +02003309ins_compl_add_tv(typval_T *tv, int dir, int fast)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003310{
3311 char_u *word;
3312 int dup = FALSE;
3313 int empty = FALSE;
Bram Moolenaar440cf092021-04-03 20:13:30 +02003314 int flags = fast ? CP_FAST : 0;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003315 char_u *(cptext[CPT_COUNT]);
Bram Moolenaar08928322020-01-04 14:32:48 +01003316 typval_T user_data;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003317 int status;
glepnir0fe17f82024-10-08 22:26:44 +02003318 char_u *user_abbr_hlname;
glepnir38f99a12024-08-23 18:31:06 +02003319 char_u *user_kind_hlname;
glepnir80b66202024-11-27 21:53:53 +01003320 int user_hl[2] = { -1, -1 };
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003321
Bram Moolenaar08928322020-01-04 14:32:48 +01003322 user_data.v_type = VAR_UNKNOWN;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003323 if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL)
3324 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01003325 word = dict_get_string(tv->vval.v_dict, "word", FALSE);
3326 cptext[CPT_ABBR] = dict_get_string(tv->vval.v_dict, "abbr", FALSE);
3327 cptext[CPT_MENU] = dict_get_string(tv->vval.v_dict, "menu", FALSE);
3328 cptext[CPT_KIND] = dict_get_string(tv->vval.v_dict, "kind", FALSE);
3329 cptext[CPT_INFO] = dict_get_string(tv->vval.v_dict, "info", FALSE);
glepnir38f99a12024-08-23 18:31:06 +02003330
glepnir0fe17f82024-10-08 22:26:44 +02003331 user_abbr_hlname = dict_get_string(tv->vval.v_dict, "abbr_hlgroup", FALSE);
glepnir80b66202024-11-27 21:53:53 +01003332 user_hl[0] = get_user_highlight_attr(user_abbr_hlname);
glepnir38f99a12024-08-23 18:31:06 +02003333
3334 user_kind_hlname = dict_get_string(tv->vval.v_dict, "kind_hlgroup", FALSE);
glepnir80b66202024-11-27 21:53:53 +01003335 user_hl[1] = get_user_highlight_attr(user_kind_hlname);
glepnir508e7852024-07-25 21:39:08 +02003336
Bram Moolenaard61efa52022-07-23 09:52:04 +01003337 dict_get_tv(tv->vval.v_dict, "user_data", &user_data);
3338 if (dict_get_string(tv->vval.v_dict, "icase", FALSE) != NULL
3339 && dict_get_number(tv->vval.v_dict, "icase"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003340 flags |= CP_ICASE;
Bram Moolenaard61efa52022-07-23 09:52:04 +01003341 if (dict_get_string(tv->vval.v_dict, "dup", FALSE) != NULL)
3342 dup = dict_get_number(tv->vval.v_dict, "dup");
3343 if (dict_get_string(tv->vval.v_dict, "empty", FALSE) != NULL)
3344 empty = dict_get_number(tv->vval.v_dict, "empty");
3345 if (dict_get_string(tv->vval.v_dict, "equal", FALSE) != NULL
3346 && dict_get_number(tv->vval.v_dict, "equal"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003347 flags |= CP_EQUAL;
3348 }
3349 else
3350 {
3351 word = tv_get_string_chk(tv);
Bram Moolenaara80faa82020-04-12 19:37:17 +02003352 CLEAR_FIELD(cptext);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003353 }
3354 if (word == NULL || (!empty && *word == NUL))
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003355 {
3356 clear_tv(&user_data);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003357 return FAIL;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003358 }
glepnir508e7852024-07-25 21:39:08 +02003359 status = ins_compl_add(word, -1, NULL, cptext,
glepnirf31cfa22025-03-06 21:59:13 +01003360 &user_data, dir, flags, dup, user_hl, 0);
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003361 if (status != OK)
3362 clear_tv(&user_data);
3363 return status;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003364}
3365
3366/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003367 * Add completions from a list.
3368 */
3369 static void
3370ins_compl_add_list(list_T *list)
3371{
3372 listitem_T *li;
3373 int dir = compl_direction;
3374
3375 // Go through the List with matches and add each of them.
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003376 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003377 FOR_ALL_LIST_ITEMS(list, li)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003378 {
Bram Moolenaar440cf092021-04-03 20:13:30 +02003379 if (ins_compl_add_tv(&li->li_tv, dir, TRUE) == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003380 // if dir was BACKWARD then honor it just once
3381 dir = FORWARD;
3382 else if (did_emsg)
3383 break;
3384 }
3385}
3386
3387/*
3388 * Add completions from a dict.
3389 */
3390 static void
3391ins_compl_add_dict(dict_T *dict)
3392{
3393 dictitem_T *di_refresh;
3394 dictitem_T *di_words;
3395
3396 // Check for optional "refresh" item.
3397 compl_opt_refresh_always = FALSE;
3398 di_refresh = dict_find(dict, (char_u *)"refresh", 7);
3399 if (di_refresh != NULL && di_refresh->di_tv.v_type == VAR_STRING)
3400 {
3401 char_u *v = di_refresh->di_tv.vval.v_string;
3402
3403 if (v != NULL && STRCMP(v, (char_u *)"always") == 0)
3404 compl_opt_refresh_always = TRUE;
3405 }
3406
3407 // Add completions from a "words" list.
3408 di_words = dict_find(dict, (char_u *)"words", 5);
3409 if (di_words != NULL && di_words->di_tv.v_type == VAR_LIST)
3410 ins_compl_add_list(di_words->di_tv.vval.v_list);
3411}
3412
3413/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003414 * Start completion for the complete() function.
3415 * "startcol" is where the matched text starts (1 is first column).
3416 * "list" is the list of matches.
3417 */
3418 static void
3419set_completion(colnr_T startcol, list_T *list)
3420{
3421 int save_w_wrow = curwin->w_wrow;
3422 int save_w_leftcol = curwin->w_leftcol;
3423 int flags = CP_ORIGINAL_TEXT;
zeertzjqaa925ee2024-06-09 18:24:05 +02003424 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02003425 int compl_longest = (cur_cot_flags & COT_LONGEST) != 0;
3426 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
3427 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003428
3429 // If already doing completions stop it.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003430 if (ctrl_x_mode_not_default())
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003431 ins_compl_prep(' ');
3432 ins_compl_clear();
3433 ins_compl_free();
bfredl87af60c2022-09-24 11:17:51 +01003434 compl_get_longest = compl_longest;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003435
3436 compl_direction = FORWARD;
3437 if (startcol > curwin->w_cursor.col)
3438 startcol = curwin->w_cursor.col;
3439 compl_col = startcol;
glepnir76bdb822025-02-08 19:04:51 +01003440 compl_lnum = curwin->w_cursor.lnum;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003441 compl_length = (int)curwin->w_cursor.col - (int)startcol;
3442 // compl_pattern doesn't need to be set
glepniredd4ac32025-01-29 18:53:51 +01003443 compl_orig_text.string = vim_strnsave(ml_get_curline() + compl_col,
3444 (size_t)compl_length);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003445 if (p_ic)
3446 flags |= CP_ICASE;
John Marriott5e6ea922024-11-23 14:01:57 +01003447 if (compl_orig_text.string == NULL)
3448 {
3449 compl_orig_text.length = 0;
3450 return;
3451 }
3452 compl_orig_text.length = (size_t)compl_length;
3453 if (ins_compl_add(compl_orig_text.string,
Hirohito Higashi355db992025-04-28 18:07:02 +02003454 (int)compl_orig_text.length, NULL, NULL, NULL, 0,
3455 flags | CP_FAST, FALSE, NULL, 0) != OK)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003456 return;
3457
3458 ctrl_x_mode = CTRL_X_EVAL;
3459
3460 ins_compl_add_list(list);
3461 compl_matches = ins_compl_make_cyclic();
3462 compl_started = TRUE;
3463 compl_used_match = TRUE;
3464 compl_cont_status = 0;
3465
3466 compl_curr_match = compl_first_match;
bfredl87af60c2022-09-24 11:17:51 +01003467 int no_select = compl_no_select || compl_longest;
3468 if (compl_no_insert || no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003469 {
3470 ins_complete(K_DOWN, FALSE);
bfredl87af60c2022-09-24 11:17:51 +01003471 if (no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003472 // Down/Up has no real effect.
3473 ins_complete(K_UP, FALSE);
3474 }
3475 else
3476 ins_complete(Ctrl_N, FALSE);
3477 compl_enter_selects = compl_no_insert;
3478
3479 // Lazily show the popup menu, unless we got interrupted.
3480 if (!compl_interrupted)
3481 show_pum(save_w_wrow, save_w_leftcol);
LemonBoy2bf52dd2022-04-09 18:17:34 +01003482 may_trigger_modechanged();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003483 out_flush();
3484}
3485
3486/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003487 * "complete()" function
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003488 */
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003489 void
3490f_complete(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003491{
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003492 if (in_vim9script()
3493 && (check_for_number_arg(argvars, 0) == FAIL
3494 || check_for_list_arg(argvars, 1) == FAIL))
3495 return;
3496
Bram Moolenaar24959102022-05-07 20:01:16 +01003497 if ((State & MODE_INSERT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003498 {
Bram Moolenaar677658a2022-01-05 16:09:06 +00003499 emsg(_(e_complete_can_only_be_used_in_insert_mode));
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003500 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003501 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003502
3503 // Check for undo allowed here, because if something was already inserted
3504 // the line was already saved for undo and this check isn't done.
3505 if (!undo_allowed())
3506 return;
3507
Bram Moolenaard83392a2022-09-01 12:22:46 +01003508 if (check_for_nonnull_list_arg(argvars, 1) != FAIL)
Bram Moolenaarff06f282020-04-21 22:01:14 +02003509 {
glepnir19e1dd62025-05-08 22:50:38 +02003510 int startcol = (int)tv_get_number_chk(&argvars[0], NULL);
Bram Moolenaarff06f282020-04-21 22:01:14 +02003511 if (startcol > 0)
3512 set_completion(startcol - 1, argvars[1].vval.v_list);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003513 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003514}
3515
3516/*
3517 * "complete_add()" function
3518 */
3519 void
3520f_complete_add(typval_T *argvars, typval_T *rettv)
3521{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003522 if (in_vim9script() && check_for_string_or_dict_arg(argvars, 0) == FAIL)
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003523 return;
3524
Bram Moolenaar440cf092021-04-03 20:13:30 +02003525 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0, FALSE);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003526}
3527
3528/*
3529 * "complete_check()" function
3530 */
3531 void
3532f_complete_check(typval_T *argvars UNUSED, typval_T *rettv)
3533{
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003534 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003535 RedrawingDisabled = 0;
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003536
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003537 ins_compl_check_keys(0, TRUE);
3538 rettv->vval.v_number = ins_compl_interrupted();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003539
3540 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003541}
3542
3543/*
glepnirbcd59952025-04-24 21:48:35 +02003544 * Add match item to the return list.
3545 * Returns FAIL if out of memory, OK otherwise.
3546 */
3547 static int
3548add_match_to_list(
3549 typval_T *rettv,
3550 char_u *str,
3551 int len,
3552 int pos)
3553{
3554 list_T *match;
3555 int ret;
3556
3557 match = list_alloc();
3558 if (match == NULL)
Hirohito Higashi355db992025-04-28 18:07:02 +02003559 return FAIL;
glepnirbcd59952025-04-24 21:48:35 +02003560
3561 if ((ret = list_append_number(match, pos + 1)) == FAIL
3562 || (ret = list_append_string(match, str, len)) == FAIL
3563 || (ret = list_append_list(rettv->vval.v_list, match)) == FAIL)
3564 {
Hirohito Higashi355db992025-04-28 18:07:02 +02003565 vim_free(match);
3566 return FAIL;
glepnirbcd59952025-04-24 21:48:35 +02003567 }
3568
3569 return OK;
3570}
3571
3572/*
3573 * "complete_match()" function
3574 */
3575 void
3576f_complete_match(typval_T *argvars, typval_T *rettv)
3577{
3578 linenr_T lnum;
3579 colnr_T col;
3580 char_u *line = NULL;
3581 char_u *ise = NULL;
3582 regmatch_T regmatch;
3583 char_u *before_cursor = NULL;
3584 char_u *cur_end = NULL;
glepnirbcd59952025-04-24 21:48:35 +02003585 int bytepos = 0;
3586 char_u part[MAXPATHL];
3587 int ret;
3588
3589 if (rettv_list_alloc(rettv) == FAIL)
3590 return;
3591
3592 ise = curbuf->b_p_ise[0] != NUL ? curbuf->b_p_ise : p_ise;
3593
3594 if (argvars[0].v_type == VAR_UNKNOWN)
3595 {
3596 lnum = curwin->w_cursor.lnum;
3597 col = curwin->w_cursor.col;
3598 }
3599 else if (argvars[1].v_type == VAR_UNKNOWN)
3600 {
3601 emsg(_(e_invalid_argument));
3602 return;
3603 }
3604 else
3605 {
3606 lnum = (linenr_T)tv_get_number(&argvars[0]);
3607 col = (colnr_T)tv_get_number(&argvars[1]);
3608 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
3609 {
3610 semsg(_(e_invalid_line_number_nr), lnum);
3611 return;
3612 }
3613 if (col < 1 || col > ml_get_buf_len(curbuf, lnum))
3614 {
3615 semsg(_(e_invalid_column_number_nr), col + 1);
3616 return;
3617 }
3618 }
3619
3620 line = ml_get_buf(curbuf, lnum, FALSE);
3621 if (line == NULL)
3622 return;
3623
3624 before_cursor = vim_strnsave(line, col);
3625 if (before_cursor == NULL)
3626 return;
3627
3628 if (ise == NULL || *ise == NUL)
3629 {
3630 regmatch.regprog = vim_regcomp((char_u *)"\\k\\+$", RE_MAGIC);
3631 if (regmatch.regprog != NULL)
3632 {
3633 if (vim_regexec_nl(&regmatch, before_cursor, (colnr_T)0))
3634 {
Christian Brabandt3accf042025-04-25 19:01:06 +02003635 char_u *trig = vim_strnsave(regmatch.startp[0],
glepnirbcd59952025-04-24 21:48:35 +02003636 regmatch.endp[0] - regmatch.startp[0]);
3637 if (trig == NULL)
3638 {
3639 vim_free(before_cursor);
Christian Brabandt3accf042025-04-25 19:01:06 +02003640 vim_regfree(regmatch.regprog);
glepnirbcd59952025-04-24 21:48:35 +02003641 return;
3642 }
3643
Christian Brabandt3accf042025-04-25 19:01:06 +02003644 bytepos = (int)(regmatch.startp[0] - before_cursor);
glepnirbcd59952025-04-24 21:48:35 +02003645 ret = add_match_to_list(rettv, trig, -1, bytepos);
3646 vim_free(trig);
3647 if (ret == FAIL)
3648 {
Christian Brabandt3accf042025-04-25 19:01:06 +02003649 vim_free(before_cursor);
glepnirbcd59952025-04-24 21:48:35 +02003650 vim_regfree(regmatch.regprog);
3651 return;
3652 }
3653 }
3654 vim_regfree(regmatch.regprog);
3655 }
3656 }
3657 else
3658 {
3659 char_u *p = ise;
3660 cur_end = before_cursor + (int)STRLEN(before_cursor);
3661
3662 while (*p != NUL)
3663 {
3664 int len = copy_option_part(&p, part, MAXPATHL, ",");
3665
3666 if (len > 0 && len <= col)
3667 {
3668 if (STRNCMP(cur_end - len, part, len) == 0)
3669 {
3670 bytepos = col - len;
3671 if (add_match_to_list(rettv, part, len, bytepos) == FAIL)
3672 {
3673 vim_free(before_cursor);
3674 return;
3675 }
3676 }
3677 }
3678 }
3679 }
3680
3681 vim_free(before_cursor);
3682}
3683
3684/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003685 * Return Insert completion mode name string
3686 */
3687 static char_u *
3688ins_compl_mode(void)
3689{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003690 if (ctrl_x_mode_not_defined_yet() || ctrl_x_mode_scroll() || compl_started)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003691 return (char_u *)ctrl_x_mode_names[ctrl_x_mode & ~CTRL_X_WANT_IDENT];
3692
3693 return (char_u *)"";
3694}
3695
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00003696/*
3697 * Assign the sequence number to all the completion matches which don't have
3698 * one assigned yet.
3699 */
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003700 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003701ins_compl_update_sequence_numbers(void)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003702{
3703 int number = 0;
3704 compl_T *match;
3705
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003706 if (compl_dir_forward())
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003707 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003708 // Search backwards for the first valid (!= -1) number.
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003709 // This should normally succeed already at the first loop
3710 // cycle, so it's fast!
3711 for (match = compl_curr_match->cp_prev; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003712 && !is_first_match(match); match = match->cp_prev)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003713 if (match->cp_number != -1)
3714 {
3715 number = match->cp_number;
3716 break;
3717 }
3718 if (match != NULL)
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003719 // go up and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003720 for (match = match->cp_next;
3721 match != NULL && match->cp_number == -1;
3722 match = match->cp_next)
3723 match->cp_number = ++number;
3724 }
3725 else // BACKWARD
3726 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003727 // Search forwards (upwards) for the first valid (!= -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003728 // number. This should normally succeed already at the
3729 // first loop cycle, so it's fast!
3730 for (match = compl_curr_match->cp_next; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003731 && !is_first_match(match); match = match->cp_next)
glepnir40891ba2025-02-10 22:18:00 +01003732 {
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003733 if (match->cp_number != -1)
3734 {
3735 number = match->cp_number;
3736 break;
3737 }
glepnir40891ba2025-02-10 22:18:00 +01003738 }
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003739 if (match != NULL)
glepnir40891ba2025-02-10 22:18:00 +01003740 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003741 // go down and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003742 for (match = match->cp_prev; match
3743 && match->cp_number == -1;
3744 match = match->cp_prev)
3745 match->cp_number = ++number;
glepnir40891ba2025-02-10 22:18:00 +01003746 }
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003747 }
3748}
3749
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003750/*
glepnir037b0282025-01-16 14:37:44 +01003751 * Fill the dict of complete_info
3752 */
3753 static void
3754fill_complete_info_dict(dict_T *di, compl_T *match, int add_match)
3755{
3756 dict_add_string(di, "word", match->cp_str.string);
3757 dict_add_string(di, "abbr", match->cp_text[CPT_ABBR]);
3758 dict_add_string(di, "menu", match->cp_text[CPT_MENU]);
3759 dict_add_string(di, "kind", match->cp_text[CPT_KIND]);
3760 dict_add_string(di, "info", match->cp_text[CPT_INFO]);
3761 if (add_match)
Hirohito Higashi355db992025-04-28 18:07:02 +02003762 dict_add_bool(di, "match", match->cp_in_match_array);
glepnir037b0282025-01-16 14:37:44 +01003763 if (match->cp_user_data.v_type == VAR_UNKNOWN)
Hirohito Higashi355db992025-04-28 18:07:02 +02003764 // Add an empty string for backwards compatibility
3765 dict_add_string(di, "user_data", (char_u *)"");
glepnir037b0282025-01-16 14:37:44 +01003766 else
Hirohito Higashi355db992025-04-28 18:07:02 +02003767 dict_add_tv(di, "user_data", &match->cp_user_data);
glepnir037b0282025-01-16 14:37:44 +01003768}
3769
3770/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003771 * Get complete information
3772 */
3773 static void
3774get_complete_info(list_T *what_list, dict_T *retdict)
3775{
3776 int ret = OK;
3777 listitem_T *item;
3778#define CI_WHAT_MODE 0x01
3779#define CI_WHAT_PUM_VISIBLE 0x02
3780#define CI_WHAT_ITEMS 0x04
3781#define CI_WHAT_SELECTED 0x08
glepnir037b0282025-01-16 14:37:44 +01003782#define CI_WHAT_COMPLETED 0x10
glepnird4088ed2024-12-31 10:55:22 +01003783#define CI_WHAT_MATCHES 0x20
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003784#define CI_WHAT_ALL 0xff
3785 int what_flag;
Girish Palya0ac1eb32025-04-16 20:18:33 +02003786 int compl_fuzzy_match = (get_cot_flags() & COT_FUZZY) != 0;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003787
3788 if (what_list == NULL)
glepnir037b0282025-01-16 14:37:44 +01003789 what_flag = CI_WHAT_ALL & ~(CI_WHAT_MATCHES | CI_WHAT_COMPLETED);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003790 else
3791 {
3792 what_flag = 0;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003793 CHECK_LIST_MATERIALIZE(what_list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003794 FOR_ALL_LIST_ITEMS(what_list, item)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003795 {
3796 char_u *what = tv_get_string(&item->li_tv);
3797
3798 if (STRCMP(what, "mode") == 0)
3799 what_flag |= CI_WHAT_MODE;
3800 else if (STRCMP(what, "pum_visible") == 0)
3801 what_flag |= CI_WHAT_PUM_VISIBLE;
3802 else if (STRCMP(what, "items") == 0)
3803 what_flag |= CI_WHAT_ITEMS;
3804 else if (STRCMP(what, "selected") == 0)
3805 what_flag |= CI_WHAT_SELECTED;
glepnir037b0282025-01-16 14:37:44 +01003806 else if (STRCMP(what, "completed") == 0)
3807 what_flag |= CI_WHAT_COMPLETED;
glepnird4088ed2024-12-31 10:55:22 +01003808 else if (STRCMP(what, "matches") == 0)
3809 what_flag |= CI_WHAT_MATCHES;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003810 }
3811 }
3812
3813 if (ret == OK && (what_flag & CI_WHAT_MODE))
3814 ret = dict_add_string(retdict, "mode", ins_compl_mode());
3815
3816 if (ret == OK && (what_flag & CI_WHAT_PUM_VISIBLE))
3817 ret = dict_add_number(retdict, "pum_visible", pum_visible());
3818
glepnir037b0282025-01-16 14:37:44 +01003819 if (ret == OK && (what_flag & (CI_WHAT_ITEMS | CI_WHAT_SELECTED
3820 | CI_WHAT_MATCHES | CI_WHAT_COMPLETED)))
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003821 {
Christian Brabandt9eb236f2024-03-21 20:12:59 +01003822 list_T *li = NULL;
Girish Palya8950bf72024-03-20 20:07:29 +01003823 dict_T *di;
3824 compl_T *match;
3825 int selected_idx = -1;
glepnird4088ed2024-12-31 10:55:22 +01003826 int has_items = what_flag & CI_WHAT_ITEMS;
3827 int has_matches = what_flag & CI_WHAT_MATCHES;
glepnir037b0282025-01-16 14:37:44 +01003828 int has_completed = what_flag & CI_WHAT_COMPLETED;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003829
glepnird4088ed2024-12-31 10:55:22 +01003830 if (has_items || has_matches)
Girish Palya8950bf72024-03-20 20:07:29 +01003831 {
3832 li = list_alloc();
3833 if (li == NULL)
3834 return;
glepnird4088ed2024-12-31 10:55:22 +01003835 ret = dict_add_list(retdict, (has_matches && !has_items)
3836 ? "matches" : "items", li);
Girish Palya8950bf72024-03-20 20:07:29 +01003837 }
3838 if (ret == OK && what_flag & CI_WHAT_SELECTED)
3839 if (compl_curr_match != NULL && compl_curr_match->cp_number == -1)
3840 ins_compl_update_sequence_numbers();
3841 if (ret == OK && compl_first_match != NULL)
3842 {
3843 int list_idx = 0;
3844 match = compl_first_match;
3845 do
3846 {
3847 if (!match_at_original_text(match))
3848 {
glepnird4088ed2024-12-31 10:55:22 +01003849 if (has_items
3850 || (has_matches && match->cp_in_match_array))
Girish Palya8950bf72024-03-20 20:07:29 +01003851 {
3852 di = dict_alloc();
3853 if (di == NULL)
3854 return;
3855 ret = list_append_dict(li, di);
3856 if (ret != OK)
3857 return;
glepnir037b0282025-01-16 14:37:44 +01003858 fill_complete_info_dict(di, match, has_matches && has_items);
Girish Palya8950bf72024-03-20 20:07:29 +01003859 }
glepnird4088ed2024-12-31 10:55:22 +01003860 if (compl_curr_match != NULL
3861 && compl_curr_match->cp_number == match->cp_number)
Girish Palya8950bf72024-03-20 20:07:29 +01003862 selected_idx = list_idx;
Girish Palya0ac1eb32025-04-16 20:18:33 +02003863 if (compl_fuzzy_match || match->cp_in_match_array)
3864 list_idx += 1;
Girish Palya8950bf72024-03-20 20:07:29 +01003865 }
3866 match = match->cp_next;
3867 }
3868 while (match != NULL && !is_first_match(match));
3869 }
3870 if (ret == OK && (what_flag & CI_WHAT_SELECTED))
3871 ret = dict_add_number(retdict, "selected", selected_idx);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003872
glepnir037b0282025-01-16 14:37:44 +01003873 if (ret == OK && selected_idx != -1 && has_completed)
3874 {
3875 di = dict_alloc();
3876 if (di == NULL)
3877 return;
3878 fill_complete_info_dict(di, compl_curr_match, FALSE);
3879 ret = dict_add_dict(retdict, "completed", di);
3880 }
Yegappan Lakshmanan6b085b92022-09-04 12:47:21 +01003881 }
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003882}
3883
3884/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003885 * "complete_info()" function
3886 */
3887 void
3888f_complete_info(typval_T *argvars, typval_T *rettv)
3889{
3890 list_T *what_list = NULL;
3891
Bram Moolenaar93a10962022-06-16 11:42:09 +01003892 if (rettv_dict_alloc(rettv) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003893 return;
3894
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003895 if (in_vim9script() && check_for_opt_list_arg(argvars, 0) == FAIL)
3896 return;
3897
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003898 if (argvars[0].v_type != VAR_UNKNOWN)
3899 {
Bram Moolenaard83392a2022-09-01 12:22:46 +01003900 if (check_for_list_arg(argvars, 0) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003901 return;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003902 what_list = argvars[0].vval.v_list;
3903 }
3904 get_complete_info(what_list, rettv->vval.v_dict);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003905}
3906#endif
3907
3908/*
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003909 * Returns TRUE when using a user-defined function for thesaurus completion.
3910 */
3911 static int
3912thesaurus_func_complete(int type UNUSED)
3913{
3914#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01003915 return type == CTRL_X_THESAURUS
3916 && (*curbuf->b_p_tsrfu != NUL || *p_tsrfu != NUL);
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003917#else
3918 return FALSE;
3919#endif
3920}
3921
3922/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003923 * Return value of process_next_cpt_value()
3924 */
3925enum
3926{
3927 INS_COMPL_CPT_OK = 1,
3928 INS_COMPL_CPT_CONT,
3929 INS_COMPL_CPT_END
3930};
3931
3932/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003933 * state information used for getting the next set of insert completion
3934 * matches.
3935 */
3936typedef struct
3937{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003938 char_u *e_cpt_copy; // copy of 'complete'
3939 char_u *e_cpt; // current entry in "e_cpt_copy"
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003940 buf_T *ins_buf; // buffer being scanned
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003941 pos_T *cur_match_pos; // current match position
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003942 pos_T prev_match_pos; // previous match position
3943 int set_match_pos; // save first_match_pos/last_match_pos
3944 pos_T first_match_pos; // first match position
3945 pos_T last_match_pos; // last match position
3946 int found_all; // found all matches of a certain type.
3947 char_u *dict; // dictionary file to search
3948 int dict_f; // "dict" is an exact file name or not
Girish Palyacbe53192025-04-14 22:13:15 +02003949 callback_T *func_cb; // callback of function in 'cpt' option
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003950} ins_compl_next_state_T;
3951
3952/*
3953 * Process the next 'complete' option value in st->e_cpt.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003954 *
3955 * If successful, the arguments are set as below:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003956 * st->cpt - pointer to the next option value in "st->cpt"
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003957 * compl_type_arg - type of insert mode completion to use
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003958 * st->found_all - all matches of this type are found
3959 * st->ins_buf - search for completions in this buffer
3960 * st->first_match_pos - position of the first completion match
3961 * st->last_match_pos - position of the last completion match
3962 * st->set_match_pos - TRUE if the first match position should be saved to
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01003963 * avoid loops after the search wraps around.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003964 * st->dict - name of the dictionary or thesaurus file to search
3965 * st->dict_f - flag specifying whether "dict" is an exact file name or not
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003966 *
3967 * Returns INS_COMPL_CPT_OK if the next value is processed successfully.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003968 * Returns INS_COMPL_CPT_CONT to skip the current completion source matching
3969 * the "st->e_cpt" option value and process the next matching source.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003970 * Returns INS_COMPL_CPT_END if all the values in "st->e_cpt" are processed.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003971 */
3972 static int
3973process_next_cpt_value(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003974 ins_compl_next_state_T *st,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003975 int *compl_type_arg,
glepnir8159fb12024-07-17 20:32:54 +02003976 pos_T *start_match_pos,
glepnir53b14572025-03-12 21:28:39 +01003977 int fuzzy_collect)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003978{
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003979 int compl_type = -1;
3980 int status = INS_COMPL_CPT_OK;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003981
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003982 st->found_all = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003983
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003984 while (*st->e_cpt == ',' || *st->e_cpt == ' ')
3985 st->e_cpt++;
3986
3987 if (*st->e_cpt == '.' && !curbuf->b_scanned)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003988 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003989 st->ins_buf = curbuf;
3990 st->first_match_pos = *start_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003991 // Move the cursor back one character so that ^N can match the
3992 // word immediately after the cursor.
glepnir53b14572025-03-12 21:28:39 +01003993 if (ctrl_x_mode_normal() && (!fuzzy_collect && dec(&st->first_match_pos) < 0))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003994 {
3995 // Move the cursor to after the last character in the
3996 // buffer, so that word at start of buffer is found
3997 // correctly.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003998 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count;
zeertzjq94b7c322024-03-12 21:50:32 +01003999 st->first_match_pos.col = ml_get_len(st->first_match_pos.lnum);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004000 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004001 st->last_match_pos = st->first_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004002 compl_type = 0;
4003
4004 // Remember the first match so that the loop stops when we
4005 // wrap and come back there a second time.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004006 st->set_match_pos = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004007 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004008 else if (vim_strchr((char_u *)"buwU", *st->e_cpt) != NULL
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004009 && (st->ins_buf = ins_compl_next_buf(
4010 st->ins_buf, *st->e_cpt)) != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004011 {
4012 // Scan a buffer, but not the current one.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004013 if (st->ins_buf->b_ml.ml_mfp != NULL) // loaded buffer
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004014 {
4015 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004016 st->first_match_pos.col = st->last_match_pos.col = 0;
4017 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count + 1;
4018 st->last_match_pos.lnum = 0;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004019 compl_type = 0;
4020 }
4021 else // unloaded buffer, scan like dictionary
4022 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004023 st->found_all = TRUE;
4024 if (st->ins_buf->b_fname == NULL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004025 {
4026 status = INS_COMPL_CPT_CONT;
4027 goto done;
4028 }
4029 compl_type = CTRL_X_DICTIONARY;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004030 st->dict = st->ins_buf->b_fname;
4031 st->dict_f = DICT_EXACT;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004032 }
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01004033 if (!shortmess(SHM_COMPLETIONSCAN))
4034 {
4035 msg_hist_off = TRUE; // reset in msg_trunc_attr()
4036 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning: %s"),
4037 st->ins_buf->b_fname == NULL
4038 ? buf_spname(st->ins_buf)
4039 : st->ins_buf->b_sfname == NULL
4040 ? st->ins_buf->b_fname
4041 : st->ins_buf->b_sfname);
4042 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
4043 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004044 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004045 else if (*st->e_cpt == NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004046 status = INS_COMPL_CPT_END;
4047 else
4048 {
4049 if (ctrl_x_mode_line_or_eval())
4050 compl_type = -1;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004051 else if (*st->e_cpt == 'k' || *st->e_cpt == 's')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004052 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004053 if (*st->e_cpt == 'k')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004054 compl_type = CTRL_X_DICTIONARY;
4055 else
4056 compl_type = CTRL_X_THESAURUS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004057 if (*++st->e_cpt != ',' && *st->e_cpt != NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004058 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004059 st->dict = st->e_cpt;
4060 st->dict_f = DICT_FIRST;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004061 }
4062 }
Girish Palyacbe53192025-04-14 22:13:15 +02004063#ifdef FEAT_COMPL_FUNC
4064 else if (*st->e_cpt == 'f' || *st->e_cpt == 'o')
4065 {
4066 compl_type = CTRL_X_FUNCTION;
4067 if (*st->e_cpt == 'o')
4068 st->func_cb = &curbuf->b_ofu_cb;
4069 else
4070 st->func_cb = (*++st->e_cpt != ',' && *st->e_cpt != NUL)
4071 ? get_cpt_func_callback(st->e_cpt) : &curbuf->b_cfu_cb;
4072 if (!st->func_cb)
4073 compl_type = -1;
4074 }
4075#endif
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004076#ifdef FEAT_FIND_ID
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004077 else if (*st->e_cpt == 'i')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004078 compl_type = CTRL_X_PATH_PATTERNS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004079 else if (*st->e_cpt == 'd')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004080 compl_type = CTRL_X_PATH_DEFINES;
4081#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004082 else if (*st->e_cpt == ']' || *st->e_cpt == 't')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004083 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004084 compl_type = CTRL_X_TAGS;
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01004085 if (!shortmess(SHM_COMPLETIONSCAN))
4086 {
4087 msg_hist_off = TRUE; // reset in msg_trunc_attr()
4088 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning tags."));
4089 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
4090 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004091 }
4092 else
4093 compl_type = -1;
4094
4095 // in any case e_cpt is advanced to the next entry
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004096 (void)copy_option_part(&st->e_cpt, IObuff, IOSIZE, ",");
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004097
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004098 st->found_all = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004099 if (compl_type == -1)
4100 status = INS_COMPL_CPT_CONT;
4101 }
4102
4103done:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004104 *compl_type_arg = compl_type;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004105 return status;
4106}
4107
4108#ifdef FEAT_FIND_ID
4109/*
4110 * Get the next set of identifiers or defines matching "compl_pattern" in
4111 * included files.
4112 */
4113 static void
4114get_next_include_file_completion(int compl_type)
4115{
John Marriott5e6ea922024-11-23 14:01:57 +01004116 find_pattern_in_path(compl_pattern.string, compl_direction,
4117 (int)compl_pattern.length, FALSE, FALSE,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004118 (compl_type == CTRL_X_PATH_DEFINES
4119 && !(compl_cont_status & CONT_SOL))
4120 ? FIND_DEFINE : FIND_ANY, 1L, ACTION_EXPAND,
Colin Kennedy21570352024-03-03 16:16:47 +01004121 (linenr_T)1, (linenr_T)MAXLNUM, FALSE);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004122}
4123#endif
4124
4125/*
4126 * Get the next set of words matching "compl_pattern" in dictionary or
4127 * thesaurus files.
4128 */
4129 static void
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004130get_next_dict_tsr_completion(int compl_type, char_u *dict, int dict_f)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004131{
4132#ifdef FEAT_COMPL_FUNC
4133 if (thesaurus_func_complete(compl_type))
Girish Palyacbe53192025-04-14 22:13:15 +02004134 expand_by_function(compl_type, compl_pattern.string, NULL);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004135 else
4136#endif
4137 ins_compl_dictionaries(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004138 dict != NULL ? dict
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004139 : (compl_type == CTRL_X_THESAURUS
4140 ? (*curbuf->b_p_tsr == NUL ? p_tsr : curbuf->b_p_tsr)
4141 : (*curbuf->b_p_dict == NUL ? p_dict : curbuf->b_p_dict)),
John Marriott5e6ea922024-11-23 14:01:57 +01004142 compl_pattern.string,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004143 dict != NULL ? dict_f : 0,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004144 compl_type == CTRL_X_THESAURUS);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004145}
4146
4147/*
4148 * Get the next set of tag names matching "compl_pattern".
4149 */
4150 static void
4151get_next_tag_completion(void)
4152{
4153 int save_p_ic;
4154 char_u **matches;
4155 int num_matches;
4156
4157 // set p_ic according to p_ic, p_scs and pat for find_tags().
4158 save_p_ic = p_ic;
John Marriott5e6ea922024-11-23 14:01:57 +01004159 p_ic = ignorecase(compl_pattern.string);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004160
4161 // Find up to TAG_MANY matches. Avoids that an enormous number
4162 // of matches is found when compl_pattern is empty
4163 g_tag_at_cursor = TRUE;
John Marriott5e6ea922024-11-23 14:01:57 +01004164 if (find_tags(compl_pattern.string, &num_matches, &matches,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004165 TAG_REGEXP | TAG_NAMES | TAG_NOIC | TAG_INS_COMP
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004166 | (ctrl_x_mode_not_default() ? TAG_VERBOSE : 0),
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004167 TAG_MANY, curbuf->b_ffname) == OK && num_matches > 0)
4168 ins_compl_add_matches(num_matches, matches, p_ic);
4169 g_tag_at_cursor = FALSE;
4170 p_ic = save_p_ic;
4171}
4172
4173/*
glepnir8159fb12024-07-17 20:32:54 +02004174 * Compare function for qsort
4175 */
glepnirf31cfa22025-03-06 21:59:13 +01004176 static int
4177compare_scores(const void *a, const void *b)
glepnir8159fb12024-07-17 20:32:54 +02004178{
4179 int idx_a = *(const int *)a;
4180 int idx_b = *(const int *)b;
4181 int score_a = compl_fuzzy_scores[idx_a];
4182 int score_b = compl_fuzzy_scores[idx_b];
zeertzjq58d70522024-08-31 17:05:39 +02004183 return score_a == score_b ? (idx_a == idx_b ? 0 : (idx_a < idx_b ? -1 : 1))
4184 : (score_a > score_b ? -1 : 1);
glepnir8159fb12024-07-17 20:32:54 +02004185}
4186
4187/*
glepnirf31cfa22025-03-06 21:59:13 +01004188 * insert prefix with redraw
4189 */
4190 static void
4191ins_compl_longest_insert(char_u *prefix)
4192{
4193 ins_compl_delete();
4194 ins_compl_insert_bytes(prefix + get_compl_len(), -1);
4195 ins_redraw(FALSE);
4196}
4197
4198/*
4199 * Calculate the longest common prefix among the best fuzzy matches
4200 * stored in compl_best_matches, and insert it as the longest.
4201 */
4202 static void
4203fuzzy_longest_match(void)
4204{
4205 char_u *prefix = NULL;
4206 int prefix_len = 0;
4207 int i = 0;
4208 int j = 0;
4209 char_u *match_str = NULL;
4210 char_u *prefix_ptr = NULL;
4211 char_u *match_ptr = NULL;
4212 char_u *leader = NULL;
4213 size_t leader_len = 0;
4214 compl_T *compl = NULL;
4215 int more_candidates = FALSE;
4216 compl_T *nn_compl = NULL;
4217
4218 if (compl_num_bests == 0)
Hirohito Higashi355db992025-04-28 18:07:02 +02004219 return;
glepnirf31cfa22025-03-06 21:59:13 +01004220
4221 nn_compl = compl_first_match->cp_next->cp_next;
4222 if (nn_compl && nn_compl != compl_first_match)
4223 more_candidates = TRUE;
4224
4225 compl = ctrl_x_mode_whole_line() ? compl_first_match
4226 : compl_first_match->cp_next;
4227 if (compl_num_bests == 1)
4228 {
4229 // no more candidates insert the match str
4230 if (!more_candidates)
4231 {
4232 ins_compl_longest_insert(compl->cp_str.string);
4233 compl_num_bests = 0;
4234 }
4235 compl_num_bests = 0;
4236 return;
4237 }
4238
4239 compl_best_matches = (compl_T **)alloc(compl_num_bests * sizeof(compl_T *));
4240 if (compl_best_matches == NULL)
Hirohito Higashi355db992025-04-28 18:07:02 +02004241 return;
glepnirf31cfa22025-03-06 21:59:13 +01004242 while (compl != NULL && i < compl_num_bests)
4243 {
Hirohito Higashi355db992025-04-28 18:07:02 +02004244 compl_best_matches[i] = compl;
4245 compl = compl->cp_next;
4246 i++;
glepnirf31cfa22025-03-06 21:59:13 +01004247 }
4248
4249 prefix = compl_best_matches[0]->cp_str.string;
zeertzjq4422de62025-03-07 19:06:02 +01004250 prefix_len = (int)compl_best_matches[0]->cp_str.length;
glepnirf31cfa22025-03-06 21:59:13 +01004251
4252 for (i = 1; i < compl_num_bests; i++)
4253 {
4254 match_str = compl_best_matches[i]->cp_str.string;
Hirohito Higashi355db992025-04-28 18:07:02 +02004255 prefix_ptr = prefix;
4256 match_ptr = match_str;
4257 j = 0;
glepnirf31cfa22025-03-06 21:59:13 +01004258
4259 while (j < prefix_len && *match_ptr != NUL && *prefix_ptr != NUL)
4260 {
4261 if (STRNCMP(prefix_ptr, match_ptr, mb_ptr2len(prefix_ptr)) != 0)
4262 break;
4263
4264 MB_PTR_ADV(prefix_ptr);
4265 MB_PTR_ADV(match_ptr);
4266 j++;
4267 }
4268
4269 if (j > 0)
4270 prefix_len = j;
4271 }
4272
4273 leader = ins_compl_leader();
zeertzjq4422de62025-03-07 19:06:02 +01004274 leader_len = ins_compl_leader_len();
glepnirf31cfa22025-03-06 21:59:13 +01004275
4276 // skip non-consecutive prefixes
zeertzjq4422de62025-03-07 19:06:02 +01004277 if (leader_len > 0 && STRNCMP(prefix, leader, leader_len) != 0)
glepnirf31cfa22025-03-06 21:59:13 +01004278 goto end;
4279
zeertzjq4422de62025-03-07 19:06:02 +01004280 prefix = vim_strnsave(prefix, prefix_len);
glepnirf31cfa22025-03-06 21:59:13 +01004281 if (prefix != NULL)
4282 {
4283 ins_compl_longest_insert(prefix);
4284 compl_cfc_longest_ins = TRUE;
4285 vim_free(prefix);
4286 }
4287
4288end:
4289 vim_free(compl_best_matches);
4290 compl_best_matches = NULL;
4291 compl_num_bests = 0;
4292}
4293
4294/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004295 * Get the next set of filename matching "compl_pattern".
4296 */
4297 static void
4298get_next_filename_completion(void)
4299{
4300 char_u **matches;
4301 int num_matches;
glepnir8159fb12024-07-17 20:32:54 +02004302 char_u *ptr;
4303 garray_T fuzzy_indices;
4304 int i;
4305 int score;
4306 char_u *leader = ins_compl_leader();
John Marriott5e6ea922024-11-23 14:01:57 +01004307 size_t leader_len = ins_compl_leader_len();;
glepnirf31cfa22025-03-06 21:59:13 +01004308 int in_fuzzy_collect = (cfc_has_mode() && leader_len > 0);
glepnir8159fb12024-07-17 20:32:54 +02004309 int *fuzzy_indices_data;
glepnir0be03e12024-07-19 16:45:05 +02004310 char_u *last_sep = NULL;
glepnirf31cfa22025-03-06 21:59:13 +01004311 int need_collect_bests = in_fuzzy_collect && compl_get_longest;
4312 int max_score = 0;
4313 int current_score = 0;
4314 int dir = compl_direction;
glepnir8159fb12024-07-17 20:32:54 +02004315
glepnirb9de1a02024-08-02 19:14:38 +02004316#ifdef BACKSLASH_IN_FILENAME
4317 char pathsep = (curbuf->b_p_csl[0] == 's') ?
4318 '/' : (curbuf->b_p_csl[0] == 'b') ? '\\' : PATHSEP;
4319#else
4320 char pathsep = PATHSEP;
4321#endif
4322
glepnirf31cfa22025-03-06 21:59:13 +01004323 if (in_fuzzy_collect)
glepnir8159fb12024-07-17 20:32:54 +02004324 {
glepnirb9de1a02024-08-02 19:14:38 +02004325#ifdef BACKSLASH_IN_FILENAME
4326 if (curbuf->b_p_csl[0] == 's')
4327 {
John Marriott5e6ea922024-11-23 14:01:57 +01004328 for (i = 0; i < (int)leader_len; i++)
glepnirb9de1a02024-08-02 19:14:38 +02004329 {
4330 if (leader[i] == '\\')
4331 leader[i] = '/';
4332 }
4333 }
4334 else if (curbuf->b_p_csl[0] == 'b')
4335 {
John Marriott5e6ea922024-11-23 14:01:57 +01004336 for (i = 0; i < (int)leader_len; i++)
glepnirb9de1a02024-08-02 19:14:38 +02004337 {
4338 if (leader[i] == '/')
4339 leader[i] = '\\';
4340 }
4341 }
4342#endif
4343 last_sep = vim_strrchr(leader, pathsep);
glepnir0be03e12024-07-19 16:45:05 +02004344 if (last_sep == NULL)
4345 {
4346 // No path separator or separator is the last character,
4347 // fuzzy match the whole leader
John Marriott5e6ea922024-11-23 14:01:57 +01004348 VIM_CLEAR_STRING(compl_pattern);
4349 compl_pattern.string = vim_strnsave((char_u *)"*", 1);
4350 if (compl_pattern.string == NULL)
4351 return;
4352 compl_pattern.length = 1;
glepnir0be03e12024-07-19 16:45:05 +02004353 }
4354 else if (*(last_sep + 1) == '\0')
glepnirf31cfa22025-03-06 21:59:13 +01004355 in_fuzzy_collect = FALSE;
glepnir0be03e12024-07-19 16:45:05 +02004356 else
4357 {
4358 // Split leader into path and file parts
4359 int path_len = last_sep - leader + 1;
John Marriott5e6ea922024-11-23 14:01:57 +01004360 char_u *path_with_wildcard;
4361
4362 path_with_wildcard = alloc(path_len + 2);
glepnir0be03e12024-07-19 16:45:05 +02004363 if (path_with_wildcard != NULL)
4364 {
John Marriott5e6ea922024-11-23 14:01:57 +01004365 vim_snprintf((char *)path_with_wildcard, path_len + 2, "%*.*s*", path_len, path_len, leader);
4366 VIM_CLEAR_STRING(compl_pattern);
4367 compl_pattern.string = path_with_wildcard;
4368 compl_pattern.length = path_len + 1;
glepnir0be03e12024-07-19 16:45:05 +02004369
4370 // Move leader to the file part
4371 leader = last_sep + 1;
John Marriott5e6ea922024-11-23 14:01:57 +01004372 leader_len -= path_len;
glepnir0be03e12024-07-19 16:45:05 +02004373 }
4374 }
glepnir8159fb12024-07-17 20:32:54 +02004375 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004376
John Marriott5e6ea922024-11-23 14:01:57 +01004377 if (expand_wildcards(1, &compl_pattern.string, &num_matches, &matches,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004378 EW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) != OK)
4379 return;
4380
4381 // May change home directory back to "~".
John Marriott5e6ea922024-11-23 14:01:57 +01004382 tilde_replace(compl_pattern.string, num_matches, matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004383#ifdef BACKSLASH_IN_FILENAME
4384 if (curbuf->b_p_csl[0] != NUL)
4385 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004386 for (i = 0; i < num_matches; ++i)
4387 {
glepnir8159fb12024-07-17 20:32:54 +02004388 ptr = matches[i];
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004389 while (*ptr != NUL)
4390 {
4391 if (curbuf->b_p_csl[0] == 's' && *ptr == '\\')
4392 *ptr = '/';
4393 else if (curbuf->b_p_csl[0] == 'b' && *ptr == '/')
4394 *ptr = '\\';
4395 ptr += (*mb_ptr2len)(ptr);
4396 }
4397 }
4398 }
4399#endif
glepnir8159fb12024-07-17 20:32:54 +02004400
glepnirf31cfa22025-03-06 21:59:13 +01004401 if (in_fuzzy_collect)
glepnir8159fb12024-07-17 20:32:54 +02004402 {
4403 ga_init2(&fuzzy_indices, sizeof(int), 10);
4404 compl_fuzzy_scores = (int *)alloc(sizeof(int) * num_matches);
4405
4406 for (i = 0; i < num_matches; i++)
4407 {
4408 ptr = matches[i];
4409 score = fuzzy_match_str(ptr, leader);
4410 if (score > 0)
4411 {
4412 if (ga_grow(&fuzzy_indices, 1) == OK)
4413 {
4414 ((int *)fuzzy_indices.ga_data)[fuzzy_indices.ga_len] = i;
4415 compl_fuzzy_scores[i] = score;
4416 fuzzy_indices.ga_len++;
4417 }
4418 }
4419 }
4420
Christian Brabandt220474d2024-07-20 13:26:44 +02004421 // prevent qsort from deref NULL pointer
4422 if (fuzzy_indices.ga_len > 0)
4423 {
glepnirf31cfa22025-03-06 21:59:13 +01004424 char_u *match = NULL;
Christian Brabandt220474d2024-07-20 13:26:44 +02004425 fuzzy_indices_data = (int *)fuzzy_indices.ga_data;
4426 qsort(fuzzy_indices_data, fuzzy_indices.ga_len, sizeof(int), compare_scores);
glepnir8159fb12024-07-17 20:32:54 +02004427
Christian Brabandt220474d2024-07-20 13:26:44 +02004428 for (i = 0; i < fuzzy_indices.ga_len; ++i)
glepnirf31cfa22025-03-06 21:59:13 +01004429 {
Hirohito Higashi355db992025-04-28 18:07:02 +02004430 match = matches[fuzzy_indices_data[i]];
glepnirf31cfa22025-03-06 21:59:13 +01004431 current_score = compl_fuzzy_scores[fuzzy_indices_data[i]];
4432 if (ins_compl_add(match, -1, NULL, NULL, NULL, dir,
Hirohito Higashi355db992025-04-28 18:07:02 +02004433 CP_FAST | ((p_fic || p_wic) ? CP_ICASE : 0),
4434 FALSE, NULL, current_score) == OK)
glepnirf31cfa22025-03-06 21:59:13 +01004435 dir = FORWARD;
4436
4437 if (need_collect_bests)
4438 {
4439 if (i == 0 || current_score == max_score)
4440 {
4441 compl_num_bests++;
4442 max_score = current_score;
4443 }
4444 }
4445 }
glepnir8159fb12024-07-17 20:32:54 +02004446
Christian Brabandt220474d2024-07-20 13:26:44 +02004447 FreeWild(num_matches, matches);
Christian Brabandt220474d2024-07-20 13:26:44 +02004448 }
glepnir6b6280c2024-07-27 16:25:45 +02004449 else if (leader_len > 0)
4450 {
4451 FreeWild(num_matches, matches);
4452 num_matches = 0;
4453 }
Christian Brabandt220474d2024-07-20 13:26:44 +02004454
glepnir8159fb12024-07-17 20:32:54 +02004455 vim_free(compl_fuzzy_scores);
4456 ga_clear(&fuzzy_indices);
glepnirf31cfa22025-03-06 21:59:13 +01004457
4458 if (compl_num_bests > 0 && compl_get_longest)
4459 fuzzy_longest_match();
4460 return;
glepnir8159fb12024-07-17 20:32:54 +02004461 }
4462
glepnir6b6280c2024-07-27 16:25:45 +02004463 if (num_matches > 0)
4464 ins_compl_add_matches(num_matches, matches, p_fic || p_wic);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004465}
4466
4467/*
4468 * Get the next set of command-line completions matching "compl_pattern".
4469 */
4470 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00004471get_next_cmdline_completion(void)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004472{
4473 char_u **matches;
4474 int num_matches;
4475
John Marriott5e6ea922024-11-23 14:01:57 +01004476 if (expand_cmdline(&compl_xp, compl_pattern.string,
4477 (int)compl_pattern.length, &num_matches, &matches) == EXPAND_OK)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004478 ins_compl_add_matches(num_matches, matches, FALSE);
4479}
4480
4481/*
4482 * Get the next set of spell suggestions matching "compl_pattern".
4483 */
4484 static void
4485get_next_spell_completion(linenr_T lnum UNUSED)
4486{
4487#ifdef FEAT_SPELL
4488 char_u **matches;
4489 int num_matches;
4490
John Marriott5e6ea922024-11-23 14:01:57 +01004491 num_matches = expand_spelling(lnum, compl_pattern.string, &matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004492 if (num_matches > 0)
4493 ins_compl_add_matches(num_matches, matches, p_ic);
Bram Moolenaar8e7cc6b2021-12-30 10:32:25 +00004494 else
4495 vim_free(matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004496#endif
4497}
4498
4499/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004500 * Return the next word or line from buffer "ins_buf" at position
4501 * "cur_match_pos" for completion. The length of the match is set in "len".
4502 */
4503 static char_u *
zeertzjq440d4cb2023-03-02 17:51:32 +00004504ins_compl_get_next_word_or_line(
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004505 buf_T *ins_buf, // buffer being scanned
4506 pos_T *cur_match_pos, // current match position
4507 int *match_len,
4508 int *cont_s_ipos) // next ^X<> will set initial_pos
4509{
4510 char_u *ptr;
4511 int len;
4512
4513 *match_len = 0;
4514 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum, FALSE) +
4515 cur_match_pos->col;
John Marriott5e6ea922024-11-23 14:01:57 +01004516 len = (int)ml_get_buf_len(ins_buf, cur_match_pos->lnum) - cur_match_pos->col;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004517 if (ctrl_x_mode_line_or_eval())
4518 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004519 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004520 {
4521 if (cur_match_pos->lnum >= ins_buf->b_ml.ml_line_count)
4522 return NULL;
4523 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
John Marriott5e6ea922024-11-23 14:01:57 +01004524 len = ml_get_buf_len(ins_buf, cur_match_pos->lnum + 1);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004525 if (!p_paste)
John Marriott5e6ea922024-11-23 14:01:57 +01004526 {
4527 char_u *tmp_ptr = ptr;
4528
4529 ptr = skipwhite(tmp_ptr);
4530 len -= (int)(ptr - tmp_ptr);
4531 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004532 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004533 }
4534 else
4535 {
4536 char_u *tmp_ptr = ptr;
4537
John Marriott5e6ea922024-11-23 14:01:57 +01004538 if (compl_status_adding() && compl_length <= len)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004539 {
4540 tmp_ptr += compl_length;
4541 // Skip if already inside a word.
4542 if (vim_iswordp(tmp_ptr))
4543 return NULL;
4544 // Find start of next word.
4545 tmp_ptr = find_word_start(tmp_ptr);
4546 }
4547 // Find end of this word.
4548 tmp_ptr = find_word_end(tmp_ptr);
4549 len = (int)(tmp_ptr - ptr);
4550
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004551 if (compl_status_adding() && len == compl_length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004552 {
4553 if (cur_match_pos->lnum < ins_buf->b_ml.ml_line_count)
4554 {
4555 // Try next line, if any. the new word will be
4556 // "join" as if the normal command "J" was used.
4557 // IOSIZE is always greater than
4558 // compl_length, so the next STRNCPY always
4559 // works -- Acevedo
4560 STRNCPY(IObuff, ptr, len);
4561 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
4562 tmp_ptr = ptr = skipwhite(ptr);
4563 // Find start of next word.
4564 tmp_ptr = find_word_start(tmp_ptr);
4565 // Find end of next word.
4566 tmp_ptr = find_word_end(tmp_ptr);
4567 if (tmp_ptr > ptr)
4568 {
4569 if (*ptr != ')' && IObuff[len - 1] != TAB)
4570 {
4571 if (IObuff[len - 1] != ' ')
4572 IObuff[len++] = ' ';
4573 // IObuf =~ "\k.* ", thus len >= 2
4574 if (p_js
4575 && (IObuff[len - 2] == '.'
4576 || (vim_strchr(p_cpo, CPO_JOINSP)
4577 == NULL
4578 && (IObuff[len - 2] == '?'
4579 || IObuff[len - 2] == '!'))))
4580 IObuff[len++] = ' ';
4581 }
4582 // copy as much as possible of the new word
4583 if (tmp_ptr - ptr >= IOSIZE - len)
4584 tmp_ptr = ptr + IOSIZE - len - 1;
4585 STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);
4586 len += (int)(tmp_ptr - ptr);
4587 *cont_s_ipos = TRUE;
4588 }
4589 IObuff[len] = NUL;
4590 ptr = IObuff;
4591 }
4592 if (len == compl_length)
4593 return NULL;
4594 }
4595 }
4596
4597 *match_len = len;
4598 return ptr;
4599}
4600
4601/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004602 * Get the next set of words matching "compl_pattern" for default completion(s)
4603 * (normal ^P/^N and ^X^L).
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004604 * Search for "compl_pattern" in the buffer "st->ins_buf" starting from the
4605 * position "st->start_pos" in the "compl_direction" direction. If
4606 * "st->set_match_pos" is TRUE, then set the "st->first_match_pos" and
4607 * "st->last_match_pos".
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004608 * Returns OK if a new next match is found, otherwise returns FAIL.
4609 */
4610 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004611get_next_default_completion(ins_compl_next_state_T *st, pos_T *start_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004612{
4613 int found_new_match = FAIL;
4614 int save_p_scs;
4615 int save_p_ws;
4616 int looped_around = FALSE;
glepnir8159fb12024-07-17 20:32:54 +02004617 char_u *ptr = NULL;
4618 int len = 0;
glepnirf31cfa22025-03-06 21:59:13 +01004619 int in_collect = (cfc_has_mode() && compl_length > 0);
glepnir8159fb12024-07-17 20:32:54 +02004620 char_u *leader = ins_compl_leader();
glepnirf31cfa22025-03-06 21:59:13 +01004621 int score = 0;
Girish Palyab1565882025-04-15 20:16:00 +02004622 int in_curbuf = st->ins_buf == curbuf;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004623
4624 // If 'infercase' is set, don't use 'smartcase' here
4625 save_p_scs = p_scs;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004626 if (st->ins_buf->b_p_inf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004627 p_scs = FALSE;
4628
4629 // Buffers other than curbuf are scanned from the beginning or the
4630 // end but never from the middle, thus setting nowrapscan in this
4631 // buffer is a good idea, on the other hand, we always set
4632 // wrapscan for curbuf to avoid missing matches -- Acevedo,Webb
4633 save_p_ws = p_ws;
Girish Palyab1565882025-04-15 20:16:00 +02004634 if (!in_curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004635 p_ws = FALSE;
glepnirf31cfa22025-03-06 21:59:13 +01004636 else if (*st->e_cpt == '.')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004637 p_ws = TRUE;
4638 looped_around = FALSE;
4639 for (;;)
4640 {
4641 int cont_s_ipos = FALSE;
4642
4643 ++msg_silent; // Don't want messages for wrapscan.
4644
glepnirf31cfa22025-03-06 21:59:13 +01004645 if (in_collect)
4646 {
Hirohito Higashi355db992025-04-28 18:07:02 +02004647 found_new_match = search_for_fuzzy_match(st->ins_buf,
glepnir8159fb12024-07-17 20:32:54 +02004648 st->cur_match_pos, leader, compl_direction,
glepnirf31cfa22025-03-06 21:59:13 +01004649 start_pos, &len, &ptr, &score);
4650 }
4651 // ctrl_x_mode_line_or_eval() || word-wise search that
4652 // has added a word that was at the beginning of the line
4653 else if (ctrl_x_mode_whole_line() || ctrl_x_mode_eval() || (compl_cont_status & CONT_SOL))
4654 found_new_match = search_for_exact_line(st->ins_buf,
4655 st->cur_match_pos, compl_direction, compl_pattern.string);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004656 else
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004657 found_new_match = searchit(NULL, st->ins_buf, st->cur_match_pos,
John Marriott5e6ea922024-11-23 14:01:57 +01004658 NULL, compl_direction, compl_pattern.string, (int)compl_pattern.length,
John Marriott8c85a2a2024-05-20 19:18:26 +02004659 1L, SEARCH_KEEP + SEARCH_NFMSG, RE_LAST, NULL);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004660 --msg_silent;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004661 if (!compl_started || st->set_match_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004662 {
4663 // set "compl_started" even on fail
4664 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004665 st->first_match_pos = *st->cur_match_pos;
4666 st->last_match_pos = *st->cur_match_pos;
4667 st->set_match_pos = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004668 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004669 else if (st->first_match_pos.lnum == st->last_match_pos.lnum
4670 && st->first_match_pos.col == st->last_match_pos.col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004671 {
4672 found_new_match = FAIL;
4673 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004674 else if (compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004675 && (st->prev_match_pos.lnum > st->cur_match_pos->lnum
4676 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
4677 && st->prev_match_pos.col >= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004678 {
4679 if (looped_around)
4680 found_new_match = FAIL;
4681 else
4682 looped_around = TRUE;
4683 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004684 else if (!compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004685 && (st->prev_match_pos.lnum < st->cur_match_pos->lnum
4686 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
4687 && st->prev_match_pos.col <= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004688 {
4689 if (looped_around)
4690 found_new_match = FAIL;
4691 else
4692 looped_around = TRUE;
4693 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004694 st->prev_match_pos = *st->cur_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004695 if (found_new_match == FAIL)
4696 break;
4697
4698 // when ADDING, the text before the cursor matches, skip it
Girish Palyab1565882025-04-15 20:16:00 +02004699 if (compl_status_adding() && in_curbuf
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004700 && start_pos->lnum == st->cur_match_pos->lnum
4701 && start_pos->col == st->cur_match_pos->col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004702 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004703
glepnirf31cfa22025-03-06 21:59:13 +01004704 if (!in_collect)
glepnir8159fb12024-07-17 20:32:54 +02004705 ptr = ins_compl_get_next_word_or_line(st->ins_buf, st->cur_match_pos,
4706 &len, &cont_s_ipos);
glepnirbfb4eea2025-01-31 15:28:29 +01004707 if (ptr == NULL || (ins_compl_has_preinsert() && STRCMP(ptr, compl_pattern.string) == 0))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004708 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004709
Girish Palyab1565882025-04-15 20:16:00 +02004710 if (is_nearest_active() && in_curbuf)
4711 {
4712 score = st->cur_match_pos->lnum - curwin->w_cursor.lnum;
4713 if (score < 0)
4714 score = -score;
4715 score++;
4716 }
4717
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004718 if (ins_compl_add_infercase(ptr, len, p_ic,
Girish Palyab1565882025-04-15 20:16:00 +02004719 in_curbuf ? NULL : st->ins_buf->b_sfname,
glepnirf31cfa22025-03-06 21:59:13 +01004720 0, cont_s_ipos, score) != NOTDONE)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004721 {
glepnirf31cfa22025-03-06 21:59:13 +01004722 if (in_collect && score == compl_first_match->cp_next->cp_score)
4723 compl_num_bests++;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004724 found_new_match = OK;
4725 break;
4726 }
4727 }
4728 p_scs = save_p_scs;
4729 p_ws = save_p_ws;
4730
4731 return found_new_match;
4732}
4733
4734/*
Girish Palyacbe53192025-04-14 22:13:15 +02004735 * Return the callback function associated with "funcname".
4736 */
4737#ifdef FEAT_COMPL_FUNC
4738 static callback_T *
4739get_cpt_func_callback(char_u *funcname)
4740{
4741 static callback_T cb;
4742 char_u buf[LSIZE];
4743 int slen;
4744
4745 slen = copy_option_part(&funcname, buf, LSIZE, ",");
4746 if (slen > 0 && option_set_callback_func(buf, &cb))
4747 return &cb;
4748 return NULL;
4749}
4750
4751/*
4752 * Retrieve new completion matches by invoking callback "cb".
4753 */
4754 static void
4755expand_cpt_function(callback_T *cb)
4756{
4757 // Re-insert the text removed by ins_compl_delete().
4758 ins_compl_insert_bytes(compl_orig_text.string + get_compl_len(), -1);
4759 // Get matches
4760 get_cpt_func_completion_matches(cb);
4761 // Undo insertion
4762 ins_compl_delete();
4763}
4764#endif
4765
4766/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004767 * get the next set of completion matches for "type".
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004768 * Returns TRUE if a new match is found. Otherwise returns FALSE.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004769 */
4770 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004771get_next_completion_match(int type, ins_compl_next_state_T *st, pos_T *ini)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004772{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004773 int found_new_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004774
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004775 switch (type)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004776 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004777 case -1:
4778 break;
4779#ifdef FEAT_FIND_ID
4780 case CTRL_X_PATH_PATTERNS:
4781 case CTRL_X_PATH_DEFINES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004782 get_next_include_file_completion(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004783 break;
4784#endif
4785
4786 case CTRL_X_DICTIONARY:
4787 case CTRL_X_THESAURUS:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004788 get_next_dict_tsr_completion(type, st->dict, st->dict_f);
4789 st->dict = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004790 break;
4791
4792 case CTRL_X_TAGS:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004793 get_next_tag_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004794 break;
4795
4796 case CTRL_X_FILES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004797 get_next_filename_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004798 break;
4799
4800 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +02004801 case CTRL_X_CMDLINE_CTRL_X:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004802 get_next_cmdline_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004803 break;
4804
4805#ifdef FEAT_COMPL_FUNC
4806 case CTRL_X_FUNCTION:
Girish Palyacbe53192025-04-14 22:13:15 +02004807 if (ctrl_x_mode_normal()) // Invoked by a func in 'cpt' option
4808 expand_cpt_function(st->func_cb);
4809 else
4810 expand_by_function(type, compl_pattern.string, NULL);
4811 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004812 case CTRL_X_OMNI:
Girish Palyacbe53192025-04-14 22:13:15 +02004813 expand_by_function(type, compl_pattern.string, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004814 break;
4815#endif
4816
4817 case CTRL_X_SPELL:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004818 get_next_spell_completion(st->first_match_pos.lnum);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004819 break;
4820
4821 default: // normal ^P/^N and ^X^L
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004822 found_new_match = get_next_default_completion(st, ini);
4823 if (found_new_match == FAIL && st->ins_buf == curbuf)
4824 st->found_all = TRUE;
4825 }
4826
4827 // check if compl_curr_match has changed, (e.g. other type of
4828 // expansion added something)
4829 if (type != 0 && compl_curr_match != compl_old_match)
4830 found_new_match = OK;
4831
4832 return found_new_match;
4833}
4834
4835/*
Girish Palya0ac1eb32025-04-16 20:18:33 +02004836 * Strips carets followed by numbers. This suffix typically represents the
4837 * max_matches setting.
4838 */
4839 static void
4840strip_caret_numbers_in_place(char_u *str)
4841{
4842 char_u *read = str, *write = str, *p;
4843
4844 if (str == NULL)
4845 return;
4846
4847 while (*read)
4848 {
4849 if (*read == '^')
4850 {
4851 p = read + 1;
4852 while (vim_isdigit(*p))
4853 p++;
4854 if ((*p == ',' || *p == '\0') && p != read + 1)
4855 {
4856 read = p;
4857 continue;
4858 }
4859 else
4860 *write++ = *read++;
4861 }
4862 else
4863 *write++ = *read++;
4864 }
4865 *write = '\0';
4866}
4867
4868/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004869 * Get the next expansion(s), using "compl_pattern".
4870 * The search starts at position "ini" in curbuf and in the direction
4871 * compl_direction.
4872 * When "compl_started" is FALSE start at that position, otherwise continue
4873 * where we stopped searching before.
4874 * This may return before finding all the matches.
4875 * Return the total number of matches or -1 if still unknown -- Acevedo
4876 */
4877 static int
4878ins_compl_get_exp(pos_T *ini)
4879{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004880 static ins_compl_next_state_T st;
4881 static int st_cleared = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004882 int i;
4883 int found_new_match;
4884 int type = ctrl_x_mode;
4885
4886 if (!compl_started)
4887 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004888 buf_T *buf;
4889
4890 FOR_ALL_BUFFERS(buf)
4891 buf->b_scanned = 0;
4892 if (!st_cleared)
4893 {
4894 CLEAR_FIELD(st);
4895 st_cleared = TRUE;
4896 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004897 st.found_all = FALSE;
4898 st.ins_buf = curbuf;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004899 vim_free(st.e_cpt_copy);
Christian Brabandtee17b6f2023-09-09 11:23:50 +02004900 // Make a copy of 'complete', in case the buffer is wiped out.
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004901 st.e_cpt_copy = vim_strsave((compl_cont_status & CONT_LOCAL)
4902 ? (char_u *)"." : curbuf->b_p_cpt);
Girish Palya0ac1eb32025-04-16 20:18:33 +02004903 strip_caret_numbers_in_place(st.e_cpt_copy);
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004904 st.e_cpt = st.e_cpt_copy == NULL ? (char_u *)"" : st.e_cpt_copy;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004905 st.last_match_pos = st.first_match_pos = *ini;
Girish Palyacbe53192025-04-14 22:13:15 +02004906
4907 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Girish Palya0ac1eb32025-04-16 20:18:33 +02004908 && !cpt_sources_init())
Girish Palyacbe53192025-04-14 22:13:15 +02004909 return FAIL;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004910 }
4911 else if (st.ins_buf != curbuf && !buf_valid(st.ins_buf))
4912 st.ins_buf = curbuf; // In case the buffer was wiped out.
4913
4914 compl_old_match = compl_curr_match; // remember the last current match
Christian Brabandt13032a42024-07-28 21:16:48 +02004915 st.cur_match_pos = (compl_dir_forward())
glepnir8159fb12024-07-17 20:32:54 +02004916 ? &st.last_match_pos : &st.first_match_pos;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004917
4918 // For ^N/^P loop over all the flags/windows/buffers in 'complete'.
Girish Palya0ac1eb32025-04-16 20:18:33 +02004919 for (cpt_sources_index = 0;;)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004920 {
4921 found_new_match = FAIL;
4922 st.set_match_pos = FALSE;
4923
4924 // For ^N/^P pick a new entry from e_cpt if compl_started is off,
4925 // or if found_all says this entry is done. For ^X^L only use the
4926 // entries from 'complete' that look in loaded buffers.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004927 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004928 && (!compl_started || st.found_all))
4929 {
glepnir53b14572025-03-12 21:28:39 +01004930 int status = process_next_cpt_value(&st, &type, ini, cfc_has_mode());
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004931
4932 if (status == INS_COMPL_CPT_END)
4933 break;
4934 if (status == INS_COMPL_CPT_CONT)
Girish Palyacbe53192025-04-14 22:13:15 +02004935 {
Girish Palya0ac1eb32025-04-16 20:18:33 +02004936 cpt_sources_index++;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004937 continue;
Girish Palyacbe53192025-04-14 22:13:15 +02004938 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004939 }
4940
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004941 // If complete() was called then compl_pattern has been reset. The
4942 // following won't work then, bail out.
John Marriott5e6ea922024-11-23 14:01:57 +01004943 if (compl_pattern.string == NULL)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004944 break;
4945
4946 // get the next set of completion matches
4947 found_new_match = get_next_completion_match(type, &st, ini);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004948
Girish Palyacbe53192025-04-14 22:13:15 +02004949 if (type > 0)
Girish Palya0ac1eb32025-04-16 20:18:33 +02004950 cpt_sources_index++;
Girish Palyacbe53192025-04-14 22:13:15 +02004951
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004952 // break the loop for specialized modes (use 'complete' just for the
4953 // generic ctrl_x_mode == CTRL_X_NORMAL) or when we've found a new
4954 // match
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004955 if ((ctrl_x_mode_not_default() && !ctrl_x_mode_line_or_eval())
4956 || found_new_match != FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004957 {
4958 if (got_int)
4959 break;
4960 // Fill the popup menu as soon as possible.
4961 if (type != -1)
4962 ins_compl_check_keys(0, FALSE);
4963
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004964 if ((ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004965 && !ctrl_x_mode_line_or_eval()) || compl_interrupted)
4966 break;
4967 compl_started = TRUE;
4968 }
4969 else
4970 {
4971 // Mark a buffer scanned when it has been scanned completely
Christian Brabandtee9166e2023-09-03 21:24:33 +02004972 if (buf_valid(st.ins_buf) && (type == 0 || type == CTRL_X_PATH_PATTERNS))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004973 st.ins_buf->b_scanned = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004974
4975 compl_started = FALSE;
4976 }
4977 }
Girish Palya0ac1eb32025-04-16 20:18:33 +02004978 cpt_sources_index = -1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004979 compl_started = TRUE;
4980
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004981 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004982 && *st.e_cpt == NUL) // Got to end of 'complete'
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004983 found_new_match = FAIL;
4984
4985 i = -1; // total of matches, unknown
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004986 if (found_new_match == FAIL || (ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004987 && !ctrl_x_mode_line_or_eval()))
4988 i = ins_compl_make_cyclic();
4989
glepnirf31cfa22025-03-06 21:59:13 +01004990 if (cfc_has_mode() && compl_get_longest && compl_num_bests > 0)
4991 fuzzy_longest_match();
4992
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004993 if (compl_old_match != NULL)
4994 {
4995 // If several matches were added (FORWARD) or the search failed and has
4996 // just been made cyclic then we have to move compl_curr_match to the
4997 // next or previous entry (if any) -- Acevedo
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004998 compl_curr_match = compl_dir_forward() ? compl_old_match->cp_next
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004999 : compl_old_match->cp_prev;
5000 if (compl_curr_match == NULL)
5001 compl_curr_match = compl_old_match;
5002 }
LemonBoy2bf52dd2022-04-09 18:17:34 +01005003 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01005004
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005005 return i;
5006}
5007
5008/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005009 * Update "compl_shown_match" to the actually shown match, it may differ when
5010 * "compl_leader" is used to omit some of the matches.
5011 */
5012 static void
5013ins_compl_update_shown_match(void)
5014{
5015 while (!ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01005016 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005017 && compl_shown_match->cp_next != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005018 && !is_first_match(compl_shown_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005019 compl_shown_match = compl_shown_match->cp_next;
5020
5021 // If we didn't find it searching forward, and compl_shows_dir is
5022 // backward, find the last match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005023 if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005024 && !ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01005025 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005026 && (compl_shown_match->cp_next == NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005027 || is_first_match(compl_shown_match->cp_next)))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005028 {
5029 while (!ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01005030 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005031 && compl_shown_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005032 && !is_first_match(compl_shown_match->cp_prev))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005033 compl_shown_match = compl_shown_match->cp_prev;
5034 }
5035}
5036
5037/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005038 * Delete the old text being completed.
5039 */
5040 void
5041ins_compl_delete(void)
5042{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005043 // In insert mode: Delete the typed part.
5044 // In replace mode: Put the old characters back, if any.
glepniredd4ac32025-01-29 18:53:51 +01005045 int col = compl_col + (compl_status_adding() ? compl_length : 0);
John Marriottf4b36412025-02-23 09:09:59 +01005046 string_T remaining = {NULL, 0};
glepnir76bdb822025-02-08 19:04:51 +01005047 int orig_col;
glepniredd4ac32025-01-29 18:53:51 +01005048 int has_preinsert = ins_compl_preinsert_effect();
5049 if (has_preinsert)
5050 {
Yegappan Lakshmanan7b6add02025-04-01 20:38:37 +02005051 col += (int)ins_compl_leader_len();
glepniredd4ac32025-01-29 18:53:51 +01005052 curwin->w_cursor.col = compl_ins_end_col;
5053 }
5054
glepnir76bdb822025-02-08 19:04:51 +01005055 if (curwin->w_cursor.lnum > compl_lnum)
5056 {
5057 if (curwin->w_cursor.col < ml_get_curline_len())
5058 {
John Marriottf4b36412025-02-23 09:09:59 +01005059 char_u *line = ml_get_cursor();
5060 remaining.length = ml_get_cursor_len();
5061 remaining.string = vim_strnsave(line, remaining.length);
5062 if (remaining.string == NULL)
glepnir76bdb822025-02-08 19:04:51 +01005063 return;
5064 }
5065 while (curwin->w_cursor.lnum > compl_lnum)
5066 {
5067 if (ml_delete(curwin->w_cursor.lnum) == FAIL)
5068 {
John Marriottf4b36412025-02-23 09:09:59 +01005069 if (remaining.string)
5070 vim_free(remaining.string);
glepnir76bdb822025-02-08 19:04:51 +01005071 return;
5072 }
zeertzjq060e6552025-02-21 20:06:26 +01005073 deleted_lines_mark(curwin->w_cursor.lnum, 1L);
glepnir76bdb822025-02-08 19:04:51 +01005074 curwin->w_cursor.lnum--;
5075 }
5076 // move cursor to end of line
5077 curwin->w_cursor.col = ml_get_curline_len();
5078 }
5079
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005080 if ((int)curwin->w_cursor.col > col)
5081 {
5082 if (stop_arrow() == FAIL)
glepnire3647c82025-02-10 21:16:32 +01005083 {
John Marriottf4b36412025-02-23 09:09:59 +01005084 if (remaining.string)
5085 vim_free(remaining.string);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005086 return;
glepnire3647c82025-02-10 21:16:32 +01005087 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005088 backspace_until_column(col);
zeertzjqf25d8f92024-12-18 21:12:25 +01005089 compl_ins_end_col = curwin->w_cursor.col;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005090 }
5091
John Marriottf4b36412025-02-23 09:09:59 +01005092 if (remaining.string != NULL)
glepnir76bdb822025-02-08 19:04:51 +01005093 {
5094 orig_col = curwin->w_cursor.col;
John Marriottf4b36412025-02-23 09:09:59 +01005095 ins_str(remaining.string, remaining.length);
glepnir76bdb822025-02-08 19:04:51 +01005096 curwin->w_cursor.col = orig_col;
John Marriottf4b36412025-02-23 09:09:59 +01005097 vim_free(remaining.string);
glepnir76bdb822025-02-08 19:04:51 +01005098 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005099 // TODO: is this sufficient for redrawing? Redrawing everything causes
5100 // flicker, thus we can't do that.
5101 changed_cline_bef_curs();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02005102#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005103 // clear v:completed_item
5104 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02005105#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005106}
5107
5108/*
glepnir76bdb822025-02-08 19:04:51 +01005109 * Insert a completion string that contains newlines.
5110 * The string is split and inserted line by line.
5111 */
5112 static void
5113ins_compl_expand_multiple(char_u *str)
5114{
5115 char_u *start = str;
5116 char_u *curr = str;
glepnir5090a1f2025-02-24 19:10:37 +01005117 int base_indent = get_indent();
glepnir76bdb822025-02-08 19:04:51 +01005118
5119 while (*curr != NUL)
5120 {
5121 if (*curr == '\n')
5122 {
5123 // Insert the text chunk before newline
5124 if (curr > start)
5125 ins_char_bytes(start, (int)(curr - start));
5126
5127 // Handle newline
glepnir5090a1f2025-02-24 19:10:37 +01005128 open_line(FORWARD, OPENLINE_KEEPTRAIL | OPENLINE_FORCE_INDENT, base_indent, NULL);
glepnir76bdb822025-02-08 19:04:51 +01005129 start = curr + 1;
5130 }
5131 curr++;
5132 }
5133
5134 // Handle remaining text after last newline (if any)
5135 if (curr > start)
5136 ins_char_bytes(start, (int)(curr - start));
5137
5138 compl_ins_end_col = curwin->w_cursor.col;
5139}
5140
5141/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005142 * Insert the new text being completed.
5143 * "in_compl_func" is TRUE when called from complete_check().
glepniredd4ac32025-01-29 18:53:51 +01005144 * "move_cursor" is used when 'completeopt' includes "preinsert" and when TRUE
5145 * cursor needs to move back from the inserted text to the compl_leader.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005146 */
5147 void
glepniredd4ac32025-01-29 18:53:51 +01005148ins_compl_insert(int in_compl_func, int move_cursor)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005149{
glepnir76bdb822025-02-08 19:04:51 +01005150 int compl_len = get_compl_len();
5151 int preinsert = ins_compl_has_preinsert();
5152 char_u *cp_str = compl_shown_match->cp_str.string;
5153 size_t cp_str_len = compl_shown_match->cp_str.length;
5154 size_t leader_len = ins_compl_leader_len();
5155 char_u *has_multiple = vim_strchr(cp_str, '\n');
Bram Moolenaar4b28ba32021-12-27 19:28:37 +00005156
5157 // Make sure we don't go over the end of the string, this can happen with
5158 // illegal bytes.
zeertzjq8297e2c2025-01-30 11:04:47 +01005159 if (compl_len < (int)cp_str_len)
glepniredd4ac32025-01-29 18:53:51 +01005160 {
glepnir76bdb822025-02-08 19:04:51 +01005161 if (has_multiple)
5162 ins_compl_expand_multiple(cp_str + compl_len);
5163 else
5164 {
5165 ins_compl_insert_bytes(cp_str + compl_len, -1);
5166 if (preinsert && move_cursor)
5167 curwin->w_cursor.col -= (colnr_T)(cp_str_len - leader_len);
5168 }
glepniredd4ac32025-01-29 18:53:51 +01005169 }
5170 if (match_at_original_text(compl_shown_match) || preinsert)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005171 compl_used_match = FALSE;
5172 else
5173 compl_used_match = TRUE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02005174#ifdef FEAT_EVAL
5175 {
5176 dict_T *dict = ins_compl_dict_alloc(compl_shown_match);
5177
5178 set_vim_var_dict(VV_COMPLETED_ITEM, dict);
5179 }
5180#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005181 if (!in_compl_func)
5182 compl_curr_match = compl_shown_match;
5183}
5184
5185/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005186 * show the file name for the completion match (if any). Truncate the file
5187 * name to avoid a wait for return.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005188 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005189 static void
5190ins_compl_show_filename(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005191{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005192 char *lead = _("match in file");
5193 int space = sc_col - vim_strsize((char_u *)lead) - 2;
5194 char_u *s;
5195 char_u *e;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005196
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005197 if (space <= 0)
5198 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005199
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005200 // We need the tail that fits. With double-byte encoding going
5201 // back from the end is very slow, thus go from the start and keep
5202 // the text that fits in "space" between "s" and "e".
5203 for (s = e = compl_shown_match->cp_fname; *e != NUL; MB_PTR_ADV(e))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005204 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005205 space -= ptr2cells(e);
5206 while (space < 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005207 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005208 space += ptr2cells(s);
5209 MB_PTR_ADV(s);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005210 }
5211 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005212 msg_hist_off = TRUE;
5213 vim_snprintf((char *)IObuff, IOSIZE, "%s %s%s", lead,
5214 s > compl_shown_match->cp_fname ? "<" : "", s);
5215 msg((char *)IObuff);
5216 msg_hist_off = FALSE;
5217 redraw_cmdline = FALSE; // don't overwrite!
5218}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005219
glepnirdca57fb2024-06-04 22:01:21 +02005220/*
zeertzjq551d8c32024-06-05 19:53:32 +02005221 * Find a completion item when 'completeopt' contains "fuzzy".
glepnirdca57fb2024-06-04 22:01:21 +02005222 */
glepnira218cc62024-06-03 19:32:39 +02005223 static compl_T *
5224find_comp_when_fuzzy(void)
5225{
5226 int score;
5227 char_u* str;
5228 int target_idx = -1;
5229 int is_forward = compl_shows_dir_forward();
5230 int is_backward = compl_shows_dir_backward();
5231 compl_T *comp = NULL;
5232
glepnir43eef882024-06-19 20:20:48 +02005233 if ((is_forward && compl_selected_item == compl_match_arraysize - 1)
glepnira218cc62024-06-03 19:32:39 +02005234 || (is_backward && compl_selected_item == 0))
glepnir3e50a282025-04-03 21:17:06 +02005235 return compl_first_match != compl_shown_match ?
5236 (is_forward ? compl_shown_match->cp_next : compl_first_match) :
glepnir65407ce2024-07-06 16:09:19 +02005237 (compl_first_match->cp_prev ? compl_first_match->cp_prev : NULL);
glepnira218cc62024-06-03 19:32:39 +02005238
5239 if (is_forward)
5240 target_idx = compl_selected_item + 1;
5241 else if (is_backward)
Hirohito Higashi355db992025-04-28 18:07:02 +02005242 target_idx = compl_selected_item == -1 ? compl_match_arraysize - 1
glepnirdca57fb2024-06-04 22:01:21 +02005243 : compl_selected_item - 1;
glepnira218cc62024-06-03 19:32:39 +02005244
5245 score = compl_match_array[target_idx].pum_score;
5246 str = compl_match_array[target_idx].pum_text;
5247
5248 comp = compl_first_match;
Hirohito Higashia4a00a72025-05-08 22:58:31 +02005249 do
5250 {
Hirohito Higashi355db992025-04-28 18:07:02 +02005251 if (comp->cp_score == score && (str == comp->cp_str.string || str == comp->cp_text[CPT_ABBR]))
5252 return comp;
5253 comp = comp->cp_next;
glepnira218cc62024-06-03 19:32:39 +02005254 } while (comp != NULL && !is_first_match(comp));
5255
5256 return NULL;
5257}
5258
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005259/*
Girish Palya0ac1eb32025-04-16 20:18:33 +02005260 * Find the appropriate completion item when 'complete' ('cpt') includes
5261 * a 'max_matches' postfix. In this case, we search for a match where
5262 * 'cp_in_match_array' is set, indicating that the match is also present
5263 * in 'compl_match_array'.
5264 */
5265 static compl_T *
5266find_comp_when_cpt_sources(void)
5267{
5268 int is_forward = compl_shows_dir_forward();
5269 compl_T *match = compl_shown_match;
5270
5271 do
5272 match = is_forward ? match->cp_next : match->cp_prev;
5273 while (match->cp_next && !match->cp_in_match_array
5274 && !match_at_original_text(match));
5275 return match;
5276}
5277
5278/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005279 * Find the next set of matches for completion. Repeat the completion "todo"
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005280 * times. The number of matches found is returned in 'num_matches'.
5281 *
5282 * If "allow_get_expansion" is TRUE, then ins_compl_get_exp() may be called to
5283 * get more completions. If it is FALSE, then do nothing when there are no more
5284 * completions in the given direction.
5285 *
5286 * If "advance" is TRUE, then completion will move to the first match.
5287 * Otherwise, the original text will be shown.
5288 *
5289 * Returns OK on success and -1 if the number of matches are unknown.
5290 */
5291 static int
5292find_next_completion_match(
5293 int allow_get_expansion,
5294 int todo, // repeat completion this many times
5295 int advance,
5296 int *num_matches)
5297{
5298 int found_end = FALSE;
5299 compl_T *found_compl = NULL;
zeertzjqaa925ee2024-06-09 18:24:05 +02005300 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02005301 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
5302 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Girish Palya0ac1eb32025-04-16 20:18:33 +02005303 int cpt_sources_active = compl_match_array && cpt_sources_array;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005304
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005305 while (--todo >= 0)
5306 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005307 if (compl_shows_dir_forward() && compl_shown_match->cp_next != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005308 {
Girish Palya0ac1eb32025-04-16 20:18:33 +02005309 if (compl_match_array != NULL && compl_fuzzy_match)
5310 compl_shown_match = find_comp_when_fuzzy();
5311 else if (cpt_sources_active)
5312 compl_shown_match = find_comp_when_cpt_sources();
5313 else
5314 compl_shown_match = compl_shown_match->cp_next;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005315 found_end = (compl_first_match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005316 && (is_first_match(compl_shown_match->cp_next)
5317 || is_first_match(compl_shown_match)));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005318 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005319 else if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005320 && compl_shown_match->cp_prev != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005321 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005322 found_end = is_first_match(compl_shown_match);
Girish Palya0ac1eb32025-04-16 20:18:33 +02005323 if (compl_match_array != NULL && compl_fuzzy_match)
5324 compl_shown_match = find_comp_when_fuzzy();
5325 else if (cpt_sources_active)
5326 compl_shown_match = find_comp_when_cpt_sources();
5327 else
5328 compl_shown_match = compl_shown_match->cp_prev;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005329 found_end |= is_first_match(compl_shown_match);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005330 }
5331 else
5332 {
5333 if (!allow_get_expansion)
5334 {
5335 if (advance)
5336 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005337 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005338 compl_pending -= todo + 1;
5339 else
5340 compl_pending += todo + 1;
5341 }
5342 return -1;
5343 }
5344
5345 if (!compl_no_select && advance)
5346 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005347 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005348 --compl_pending;
5349 else
5350 ++compl_pending;
5351 }
5352
5353 // Find matches.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005354 *num_matches = ins_compl_get_exp(&compl_startpos);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005355
5356 // handle any pending completions
5357 while (compl_pending != 0 && compl_direction == compl_shows_dir
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005358 && advance)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005359 {
5360 if (compl_pending > 0 && compl_shown_match->cp_next != NULL)
5361 {
5362 compl_shown_match = compl_shown_match->cp_next;
5363 --compl_pending;
5364 }
5365 if (compl_pending < 0 && compl_shown_match->cp_prev != NULL)
5366 {
5367 compl_shown_match = compl_shown_match->cp_prev;
5368 ++compl_pending;
5369 }
5370 else
5371 break;
5372 }
5373 found_end = FALSE;
5374 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005375 if (!match_at_original_text(compl_shown_match)
John Marriott5e6ea922024-11-23 14:01:57 +01005376 && compl_leader.string != NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005377 && !ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01005378 compl_leader.string, (int)compl_leader.length)
glepnira218cc62024-06-03 19:32:39 +02005379 && !(compl_fuzzy_match && compl_shown_match->cp_score > 0))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005380 ++todo;
5381 else
5382 // Remember a matching item.
5383 found_compl = compl_shown_match;
5384
5385 // Stop at the end of the list when we found a usable match.
5386 if (found_end)
5387 {
5388 if (found_compl != NULL)
5389 {
5390 compl_shown_match = found_compl;
5391 break;
5392 }
5393 todo = 1; // use first usable match after wrapping around
5394 }
5395 }
5396
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005397 return OK;
5398}
5399
5400/*
5401 * Fill in the next completion in the current direction.
5402 * If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to
5403 * get more completions. If it is FALSE, then we just do nothing when there
5404 * are no more completions in a given direction. The latter case is used when
5405 * we are still in the middle of finding completions, to allow browsing
5406 * through the ones found so far.
5407 * Return the total number of matches, or -1 if still unknown -- webb.
5408 *
5409 * compl_curr_match is currently being used by ins_compl_get_exp(), so we use
5410 * compl_shown_match here.
5411 *
5412 * Note that this function may be called recursively once only. First with
5413 * "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn
5414 * calls this function with "allow_get_expansion" FALSE.
5415 */
5416 static int
5417ins_compl_next(
5418 int allow_get_expansion,
5419 int count, // repeat completion this many times; should
5420 // be at least 1
5421 int insert_match, // Insert the newly selected match
5422 int in_compl_func) // called from complete_check()
5423{
5424 int num_matches = -1;
5425 int todo = count;
5426 int advance;
5427 int started = compl_started;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005428 buf_T *orig_curbuf = curbuf;
zeertzjqaa925ee2024-06-09 18:24:05 +02005429 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02005430 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
5431 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
glepniredd4ac32025-01-29 18:53:51 +01005432 int compl_preinsert = ins_compl_has_preinsert();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005433
5434 // When user complete function return -1 for findstart which is next
5435 // time of 'always', compl_shown_match become NULL.
5436 if (compl_shown_match == NULL)
5437 return -1;
5438
John Marriott5e6ea922024-11-23 14:01:57 +01005439 if (compl_leader.string != NULL
glepnira218cc62024-06-03 19:32:39 +02005440 && !match_at_original_text(compl_shown_match)
5441 && !compl_fuzzy_match)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005442 // Update "compl_shown_match" to the actually shown match
5443 ins_compl_update_shown_match();
5444
5445 if (allow_get_expansion && insert_match
nwounkn2e3cd522023-10-17 11:05:38 +02005446 && (!compl_get_longest || compl_used_match))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005447 // Delete old text to be replaced
5448 ins_compl_delete();
5449
5450 // When finding the longest common text we stick at the original text,
5451 // don't let CTRL-N or CTRL-P move to the first match.
5452 advance = count != 1 || !allow_get_expansion || !compl_get_longest;
5453
5454 // When restarting the search don't insert the first match either.
5455 if (compl_restarting)
5456 {
5457 advance = FALSE;
5458 compl_restarting = FALSE;
5459 }
5460
5461 // Repeat this for when <PageUp> or <PageDown> is typed. But don't wrap
5462 // around.
5463 if (find_next_completion_match(allow_get_expansion, todo, advance,
5464 &num_matches) == -1)
5465 return -1;
5466
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005467 if (curbuf != orig_curbuf)
5468 {
5469 // In case some completion function switched buffer, don't want to
5470 // insert the completion elsewhere.
5471 return -1;
5472 }
5473
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005474 // Insert the text of the new completion, or the compl_leader.
glepniredd4ac32025-01-29 18:53:51 +01005475 if (compl_no_insert && !started && !compl_preinsert)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005476 {
glepnir6a38aff2024-12-16 21:56:16 +01005477 ins_compl_insert_bytes(compl_orig_text.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005478 compl_used_match = FALSE;
5479 }
5480 else if (insert_match)
5481 {
5482 if (!compl_get_longest || compl_used_match)
glepniredd4ac32025-01-29 18:53:51 +01005483 ins_compl_insert(in_compl_func, TRUE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005484 else
glepnir6a38aff2024-12-16 21:56:16 +01005485 ins_compl_insert_bytes(compl_leader.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005486 }
5487 else
5488 compl_used_match = FALSE;
5489
5490 if (!allow_get_expansion)
5491 {
5492 // may undisplay the popup menu first
5493 ins_compl_upd_pum();
5494
5495 if (pum_enough_matches())
5496 // Will display the popup menu, don't redraw yet to avoid flicker.
5497 pum_call_update_screen();
5498 else
5499 // Not showing the popup menu yet, redraw to show the user what was
5500 // inserted.
5501 update_screen(0);
5502
5503 // display the updated popup menu
5504 ins_compl_show_pum();
5505#ifdef FEAT_GUI
5506 if (gui.in_use)
5507 {
5508 // Show the cursor after the match, not after the redrawn text.
5509 setcursor();
5510 out_flush_cursor(FALSE, FALSE);
5511 }
5512#endif
5513
5514 // Delete old text to be replaced, since we're still searching and
5515 // don't want to match ourselves!
5516 ins_compl_delete();
5517 }
5518
5519 // Enter will select a match when the match wasn't inserted and the popup
5520 // menu is visible.
5521 if (compl_no_insert && !started)
5522 compl_enter_selects = TRUE;
5523 else
5524 compl_enter_selects = !insert_match && compl_match_array != NULL;
5525
5526 // Show the file name for the match (if any)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005527 if (compl_shown_match->cp_fname != NULL)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005528 ins_compl_show_filename();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005529
5530 return num_matches;
5531}
5532
5533/*
5534 * Call this while finding completions, to check whether the user has hit a key
5535 * that should change the currently displayed completion, or exit completion
5536 * mode. Also, when compl_pending is not zero, show a completion as soon as
5537 * possible. -- webb
5538 * "frequency" specifies out of how many calls we actually check.
5539 * "in_compl_func" is TRUE when called from complete_check(), don't set
5540 * compl_curr_match.
5541 */
5542 void
5543ins_compl_check_keys(int frequency, int in_compl_func)
5544{
5545 static int count = 0;
5546 int c;
5547
5548 // Don't check when reading keys from a script, :normal or feedkeys().
5549 // That would break the test scripts. But do check for keys when called
5550 // from complete_check().
5551 if (!in_compl_func && (using_script() || ex_normal_busy))
5552 return;
5553
5554 // Only do this at regular intervals
5555 if (++count < frequency)
5556 return;
5557 count = 0;
5558
5559 // Check for a typed key. Do use mappings, otherwise vim_is_ctrl_x_key()
5560 // can't do its work correctly.
5561 c = vpeekc_any();
5562 if (c != NUL)
5563 {
5564 if (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R)
5565 {
5566 c = safe_vgetc(); // Eat the character
5567 compl_shows_dir = ins_compl_key2dir(c);
5568 (void)ins_compl_next(FALSE, ins_compl_key2count(c),
5569 c != K_UP && c != K_DOWN, in_compl_func);
5570 }
5571 else
5572 {
5573 // Need to get the character to have KeyTyped set. We'll put it
5574 // back with vungetc() below. But skip K_IGNORE.
5575 c = safe_vgetc();
5576 if (c != K_IGNORE)
5577 {
5578 // Don't interrupt completion when the character wasn't typed,
5579 // e.g., when doing @q to replay keys.
5580 if (c != Ctrl_R && KeyTyped)
5581 compl_interrupted = TRUE;
5582
5583 vungetc(c);
5584 }
5585 }
5586 }
zeertzjq529b9ad2024-06-05 20:27:06 +02005587 if (compl_pending != 0 && !got_int && !(cot_flags & COT_NOINSERT))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005588 {
5589 int todo = compl_pending > 0 ? compl_pending : -compl_pending;
5590
5591 compl_pending = 0;
5592 (void)ins_compl_next(FALSE, todo, TRUE, in_compl_func);
5593 }
5594}
5595
5596/*
5597 * Decide the direction of Insert mode complete from the key typed.
5598 * Returns BACKWARD or FORWARD.
5599 */
5600 static int
5601ins_compl_key2dir(int c)
5602{
5603 if (c == Ctrl_P || c == Ctrl_L
5604 || c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP || c == K_UP)
5605 return BACKWARD;
5606 return FORWARD;
5607}
5608
5609/*
5610 * Return TRUE for keys that are used for completion only when the popup menu
5611 * is visible.
5612 */
5613 static int
5614ins_compl_pum_key(int c)
5615{
5616 return pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP
5617 || c == K_PAGEDOWN || c == K_KPAGEDOWN || c == K_S_DOWN
5618 || c == K_UP || c == K_DOWN);
5619}
5620
5621/*
5622 * Decide the number of completions to move forward.
5623 * Returns 1 for most keys, height of the popup menu for page-up/down keys.
5624 */
5625 static int
5626ins_compl_key2count(int c)
5627{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005628 if (ins_compl_pum_key(c) && c != K_UP && c != K_DOWN)
5629 {
glepnir19e1dd62025-05-08 22:50:38 +02005630 int h = pum_get_height();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005631 if (h > 3)
5632 h -= 2; // keep some context
5633 return h;
5634 }
5635 return 1;
5636}
5637
5638/*
5639 * Return TRUE if completion with "c" should insert the match, FALSE if only
5640 * to change the currently selected completion.
5641 */
5642 static int
5643ins_compl_use_match(int c)
5644{
5645 switch (c)
5646 {
5647 case K_UP:
5648 case K_DOWN:
5649 case K_PAGEDOWN:
5650 case K_KPAGEDOWN:
5651 case K_S_DOWN:
5652 case K_PAGEUP:
5653 case K_KPAGEUP:
5654 case K_S_UP:
5655 return FALSE;
5656 }
5657 return TRUE;
5658}
5659
5660/*
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005661 * Get the pattern, column and length for normal completion (CTRL-N CTRL-P
5662 * completion)
John Marriott5e6ea922024-11-23 14:01:57 +01005663 * Sets the global variables: compl_col, compl_length and compl_pattern.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005664 * Uses the global variables: compl_cont_status and ctrl_x_mode
5665 */
5666 static int
5667get_normal_compl_info(char_u *line, int startcol, colnr_T curs_col)
5668{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005669 if ((compl_cont_status & CONT_SOL) || ctrl_x_mode_path_defines())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005670 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005671 if (!compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005672 {
5673 while (--startcol >= 0 && vim_isIDc(line[startcol]))
5674 ;
5675 compl_col += ++startcol;
5676 compl_length = curs_col - startcol;
5677 }
5678 if (p_ic)
John Marriott8c85a2a2024-05-20 19:18:26 +02005679 {
John Marriott5e6ea922024-11-23 14:01:57 +01005680 compl_pattern.string = str_foldcase(line + compl_col,
5681 compl_length, NULL, 0);
5682 if (compl_pattern.string == NULL)
5683 {
5684 compl_pattern.length = 0;
5685 return FAIL;
5686 }
5687 compl_pattern.length = STRLEN(compl_pattern.string);
5688 }
5689 else
5690 {
5691 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5692 if (compl_pattern.string == NULL)
5693 {
5694 compl_pattern.length = 0;
5695 return FAIL;
5696 }
5697 compl_pattern.length = (size_t)compl_length;
John Marriott8c85a2a2024-05-20 19:18:26 +02005698 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005699 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005700 else if (compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005701 {
5702 char_u *prefix = (char_u *)"\\<";
John Marriott8c85a2a2024-05-20 19:18:26 +02005703 size_t prefixlen = STRLEN_LITERAL("\\<");
John Marriott5e6ea922024-11-23 14:01:57 +01005704 size_t n;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005705
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005706 if (!vim_iswordp(line + compl_col)
5707 || (compl_col > 0
5708 && (vim_iswordp(mb_prevptr(line, line + compl_col)))))
John Marriott8c85a2a2024-05-20 19:18:26 +02005709 {
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005710 prefix = (char_u *)"";
John Marriott8c85a2a2024-05-20 19:18:26 +02005711 prefixlen = 0;
5712 }
John Marriott5e6ea922024-11-23 14:01:57 +01005713
5714 // we need up to 2 extra chars for the prefix
5715 n = quote_meta(NULL, line + compl_col, compl_length) + prefixlen;
5716 compl_pattern.string = alloc(n);
5717 if (compl_pattern.string == NULL)
5718 {
5719 compl_pattern.length = 0;
5720 return FAIL;
5721 }
5722 STRCPY((char *)compl_pattern.string, prefix);
5723 (void)quote_meta(compl_pattern.string + prefixlen,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005724 line + compl_col, compl_length);
John Marriott5e6ea922024-11-23 14:01:57 +01005725 compl_pattern.length = n - 1;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005726 }
5727 else if (--startcol < 0
5728 || !vim_iswordp(mb_prevptr(line, line + startcol + 1)))
5729 {
John Marriott5e6ea922024-11-23 14:01:57 +01005730 size_t len = STRLEN_LITERAL("\\<\\k\\k");
5731
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005732 // Match any word of at least two chars
John Marriott5e6ea922024-11-23 14:01:57 +01005733 compl_pattern.string = vim_strnsave((char_u *)"\\<\\k\\k", len);
5734 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005735 {
John Marriott5e6ea922024-11-23 14:01:57 +01005736 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005737 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005738 }
John Marriott5e6ea922024-11-23 14:01:57 +01005739 compl_pattern.length = len;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005740 compl_col += curs_col;
5741 compl_length = 0;
5742 }
5743 else
5744 {
5745 // Search the point of change class of multibyte character
5746 // or not a word single byte character backward.
5747 if (has_mbyte)
5748 {
5749 int base_class;
5750 int head_off;
5751
5752 startcol -= (*mb_head_off)(line, line + startcol);
5753 base_class = mb_get_class(line + startcol);
5754 while (--startcol >= 0)
5755 {
5756 head_off = (*mb_head_off)(line, line + startcol);
5757 if (base_class != mb_get_class(line + startcol
5758 - head_off))
5759 break;
5760 startcol -= head_off;
5761 }
5762 }
5763 else
glepnir19e1dd62025-05-08 22:50:38 +02005764 {
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005765 while (--startcol >= 0 && vim_iswordc(line[startcol]))
5766 ;
glepnir19e1dd62025-05-08 22:50:38 +02005767 }
5768
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005769 compl_col += ++startcol;
5770 compl_length = (int)curs_col - startcol;
5771 if (compl_length == 1)
5772 {
5773 // Only match word with at least two chars -- webb
5774 // there's no need to call quote_meta,
5775 // alloc(7) is enough -- Acevedo
John Marriott5e6ea922024-11-23 14:01:57 +01005776 compl_pattern.string = alloc(7);
5777 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005778 {
John Marriott5e6ea922024-11-23 14:01:57 +01005779 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005780 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005781 }
John Marriott5e6ea922024-11-23 14:01:57 +01005782 STRCPY((char *)compl_pattern.string, "\\<");
5783 (void)quote_meta(compl_pattern.string + 2, line + compl_col, 1);
5784 STRCAT((char *)compl_pattern.string, "\\k");
5785 compl_pattern.length = STRLEN(compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005786 }
5787 else
5788 {
John Marriott5e6ea922024-11-23 14:01:57 +01005789 size_t n = quote_meta(NULL, line + compl_col, compl_length) + 2;
5790
5791 compl_pattern.string = alloc(n);
5792 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005793 {
John Marriott5e6ea922024-11-23 14:01:57 +01005794 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005795 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005796 }
John Marriott5e6ea922024-11-23 14:01:57 +01005797 STRCPY((char *)compl_pattern.string, "\\<");
5798 (void)quote_meta(compl_pattern.string + 2, line + compl_col,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005799 compl_length);
John Marriott5e6ea922024-11-23 14:01:57 +01005800 compl_pattern.length = n - 1;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005801 }
5802 }
5803
5804 return OK;
5805}
5806
5807/*
5808 * Get the pattern, column and length for whole line completion or for the
5809 * complete() function.
5810 * Sets the global variables: compl_col, compl_length and compl_pattern.
5811 */
5812 static int
5813get_wholeline_compl_info(char_u *line, colnr_T curs_col)
5814{
5815 compl_col = (colnr_T)getwhitecols(line);
5816 compl_length = (int)curs_col - (int)compl_col;
5817 if (compl_length < 0) // cursor in indent: empty pattern
5818 compl_length = 0;
5819 if (p_ic)
John Marriott8c85a2a2024-05-20 19:18:26 +02005820 {
John Marriott5e6ea922024-11-23 14:01:57 +01005821 compl_pattern.string = str_foldcase(line + compl_col, compl_length,
5822 NULL, 0);
5823 if (compl_pattern.string == NULL)
5824 {
5825 compl_pattern.length = 0;
5826 return FAIL;
5827 }
5828 compl_pattern.length = STRLEN(compl_pattern.string);
John Marriott8c85a2a2024-05-20 19:18:26 +02005829 }
John Marriott5e6ea922024-11-23 14:01:57 +01005830 else
5831 {
5832 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5833 if (compl_pattern.string == NULL)
5834 {
5835 compl_pattern.length = 0;
5836 return FAIL;
5837 }
5838 compl_pattern.length = (size_t)compl_length;
5839 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005840
5841 return OK;
5842}
5843
5844/*
5845 * Get the pattern, column and length for filename completion.
5846 * Sets the global variables: compl_col, compl_length and compl_pattern.
5847 */
5848 static int
5849get_filename_compl_info(char_u *line, int startcol, colnr_T curs_col)
5850{
5851 // Go back to just before the first filename character.
5852 if (startcol > 0)
5853 {
5854 char_u *p = line + startcol;
5855
5856 MB_PTR_BACK(line, p);
5857 while (p > line && vim_isfilec(PTR2CHAR(p)))
5858 MB_PTR_BACK(line, p);
5859 if (p == line && vim_isfilec(PTR2CHAR(p)))
5860 startcol = 0;
5861 else
5862 startcol = (int)(p - line) + 1;
5863 }
5864
5865 compl_col += startcol;
5866 compl_length = (int)curs_col - startcol;
John Marriott5e6ea922024-11-23 14:01:57 +01005867 compl_pattern.string = addstar(line + compl_col, compl_length, EXPAND_FILES);
5868 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005869 {
John Marriott5e6ea922024-11-23 14:01:57 +01005870 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005871 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005872 }
5873
John Marriott5e6ea922024-11-23 14:01:57 +01005874 compl_pattern.length = STRLEN(compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005875
5876 return OK;
5877}
5878
5879/*
5880 * Get the pattern, column and length for command-line completion.
5881 * Sets the global variables: compl_col, compl_length and compl_pattern.
5882 */
5883 static int
5884get_cmdline_compl_info(char_u *line, colnr_T curs_col)
5885{
John Marriott5e6ea922024-11-23 14:01:57 +01005886 compl_pattern.string = vim_strnsave(line, curs_col);
5887 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005888 {
John Marriott5e6ea922024-11-23 14:01:57 +01005889 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005890 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005891 }
John Marriott5e6ea922024-11-23 14:01:57 +01005892 compl_pattern.length = curs_col;
5893 set_cmd_context(&compl_xp, compl_pattern.string,
5894 (int)compl_pattern.length, curs_col, FALSE);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005895 if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL
5896 || compl_xp.xp_context == EXPAND_NOTHING)
5897 // No completion possible, use an empty pattern to get a
5898 // "pattern not found" message.
5899 compl_col = curs_col;
5900 else
John Marriott5e6ea922024-11-23 14:01:57 +01005901 compl_col = (int)(compl_xp.xp_pattern - compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005902 compl_length = curs_col - compl_col;
5903
5904 return OK;
5905}
5906
5907/*
5908 * Get the pattern, column and length for user defined completion ('omnifunc',
5909 * 'completefunc' and 'thesaurusfunc')
5910 * Sets the global variables: compl_col, compl_length and compl_pattern.
5911 * Uses the global variable: spell_bad_len
Girish Palyacbe53192025-04-14 22:13:15 +02005912 * Callback function "cb" is set if triggered by a function in the 'cpt'
5913 * option; otherwise, it is NULL.
5914 * "startcol", when not NULL, contains the column returned by function.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005915 */
5916 static int
glepnir19e1dd62025-05-08 22:50:38 +02005917get_userdefined_compl_info(
5918 colnr_T curs_col UNUSED,
5919 callback_T *cb UNUSED,
5920 int *startcol UNUSED)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005921{
5922 int ret = FAIL;
5923
5924#ifdef FEAT_COMPL_FUNC
5925 // Call user defined function 'completefunc' with "a:findstart"
5926 // set to 1 to obtain the length of text to use for completion.
glepnir19e1dd62025-05-08 22:50:38 +02005927 char_u *line = NULL;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005928 typval_T args[3];
5929 int col;
glepnir19e1dd62025-05-08 22:50:38 +02005930 char_u *funcname = NULL;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005931 pos_T pos;
5932 int save_State = State;
Girish Palyacbe53192025-04-14 22:13:15 +02005933 int len;
glepnir19e1dd62025-05-08 22:50:38 +02005934 string_T *compl_pat = NULL;
Girish Palyacbe53192025-04-14 22:13:15 +02005935 int is_cpt_function = (cb != NULL);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005936
Girish Palyacbe53192025-04-14 22:13:15 +02005937 if (!is_cpt_function)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005938 {
Girish Palyacbe53192025-04-14 22:13:15 +02005939 // Call 'completefunc' or 'omnifunc' or 'thesaurusfunc' and get pattern
5940 // length as a string
5941 funcname = get_complete_funcname(ctrl_x_mode);
5942 if (*funcname == NUL)
5943 {
5944 semsg(_(e_option_str_is_not_set), ctrl_x_mode_function()
5945 ? "completefunc" : "omnifunc");
5946 return FAIL;
5947 }
5948 cb = get_insert_callback(ctrl_x_mode);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005949 }
5950
5951 args[0].v_type = VAR_NUMBER;
5952 args[0].vval.v_number = 1;
5953 args[1].v_type = VAR_STRING;
5954 args[1].vval.v_string = (char_u *)"";
5955 args[2].v_type = VAR_UNKNOWN;
5956 pos = curwin->w_cursor;
zeertzjqcfe45652022-05-27 17:26:55 +01005957 ++textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005958 col = call_callback_retnr(cb, 2, args);
zeertzjqcfe45652022-05-27 17:26:55 +01005959 --textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005960
5961 State = save_State;
5962 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02005963 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005964 validate_cursor();
5965 if (!EQUAL_POS(curwin->w_cursor, pos))
5966 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00005967 emsg(_(e_complete_function_deleted_text));
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005968 return FAIL;
5969 }
5970
Girish Palyacbe53192025-04-14 22:13:15 +02005971 if (startcol != NULL)
5972 *startcol = col;
5973
LemonBoy9bcb9ca2022-05-26 15:23:26 +01005974 // Return value -2 means the user complete function wants to cancel the
5975 // complete without an error, do the same if the function did not execute
5976 // successfully.
5977 if (col == -2 || aborting())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005978 return FAIL;
glepnir19e1dd62025-05-08 22:50:38 +02005979
LemonBoy9bcb9ca2022-05-26 15:23:26 +01005980 // Return value -3 does the same as -2 and leaves CTRL-X mode.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005981 if (col == -3)
5982 {
Girish Palyacbe53192025-04-14 22:13:15 +02005983 if (is_cpt_function)
5984 return FAIL;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005985 ctrl_x_mode = CTRL_X_NORMAL;
5986 edit_submode = NULL;
5987 if (!shortmess(SHM_COMPLETIONMENU))
5988 msg_clr_cmdline();
5989 return FAIL;
5990 }
5991
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00005992 // Reset extended parameters of completion, when starting new
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005993 // completion.
5994 compl_opt_refresh_always = FALSE;
5995 compl_opt_suppress_empty = FALSE;
5996
Girish Palyacbe53192025-04-14 22:13:15 +02005997 if (col < 0 || col > curs_col)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005998 col = curs_col;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005999
6000 // Setup variables for completion. Need to obtain "line" again,
6001 // it may have become invalid.
6002 line = ml_get(curwin->w_cursor.lnum);
Girish Palyacbe53192025-04-14 22:13:15 +02006003 len = curs_col - col;
6004 compl_pat = is_cpt_function ? &cpt_compl_pattern : &compl_pattern;
6005 compl_pat->string = vim_strnsave(line + col, (size_t)len);
6006 if (compl_pat->string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02006007 {
Girish Palyacbe53192025-04-14 22:13:15 +02006008 compl_pat->length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006009 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02006010 }
Girish Palyacbe53192025-04-14 22:13:15 +02006011 compl_pat->length = (size_t)compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006012
Girish Palyacbe53192025-04-14 22:13:15 +02006013 if (!is_cpt_function)
6014 {
6015 compl_col = col;
6016 compl_length = len;
6017 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006018 ret = OK;
6019#endif
6020
6021 return ret;
6022}
6023
6024/*
6025 * Get the pattern, column and length for spell completion.
6026 * Sets the global variables: compl_col, compl_length and compl_pattern.
6027 * Uses the global variable: spell_bad_len
6028 */
6029 static int
6030get_spell_compl_info(int startcol UNUSED, colnr_T curs_col UNUSED)
6031{
6032 int ret = FAIL;
6033#ifdef FEAT_SPELL
glepnir19e1dd62025-05-08 22:50:38 +02006034 char_u *line = NULL;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006035
6036 if (spell_bad_len > 0)
6037 compl_col = curs_col - spell_bad_len;
6038 else
6039 compl_col = spell_word_start(startcol);
glepnir19e1dd62025-05-08 22:50:38 +02006040
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006041 if (compl_col >= (colnr_T)startcol)
6042 {
6043 compl_length = 0;
6044 compl_col = curs_col;
6045 }
6046 else
6047 {
6048 spell_expand_check_cap(compl_col);
6049 compl_length = (int)curs_col - compl_col;
6050 }
6051 // Need to obtain "line" again, it may have become invalid.
6052 line = ml_get(curwin->w_cursor.lnum);
John Marriott5e6ea922024-11-23 14:01:57 +01006053 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
6054 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02006055 {
John Marriott5e6ea922024-11-23 14:01:57 +01006056 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006057 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02006058 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006059
John Marriott5e6ea922024-11-23 14:01:57 +01006060 compl_pattern.length = (size_t)compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006061 ret = OK;
6062#endif
6063
6064 return ret;
6065}
6066
6067/*
6068 * Get the completion pattern, column and length.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006069 * "startcol" - start column number of the completion pattern/text
6070 * "cur_col" - current cursor column
6071 * On return, "line_invalid" is set to TRUE, if the current line may have
6072 * become invalid and needs to be fetched again.
6073 * Returns OK on success.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006074 */
6075 static int
6076compl_get_info(char_u *line, int startcol, colnr_T curs_col, int *line_invalid)
6077{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006078 if (ctrl_x_mode_normal()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006079 || (ctrl_x_mode & CTRL_X_WANT_IDENT
6080 && !thesaurus_func_complete(ctrl_x_mode)))
6081 {
6082 return get_normal_compl_info(line, startcol, curs_col);
6083 }
6084 else if (ctrl_x_mode_line_or_eval())
6085 {
6086 return get_wholeline_compl_info(line, curs_col);
6087 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006088 else if (ctrl_x_mode_files())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006089 {
6090 return get_filename_compl_info(line, startcol, curs_col);
6091 }
6092 else if (ctrl_x_mode == CTRL_X_CMDLINE)
6093 {
6094 return get_cmdline_compl_info(line, curs_col);
6095 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006096 else if (ctrl_x_mode_function() || ctrl_x_mode_omni()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006097 || thesaurus_func_complete(ctrl_x_mode))
6098 {
Girish Palyacbe53192025-04-14 22:13:15 +02006099 if (get_userdefined_compl_info(curs_col, NULL, NULL) != OK)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006100 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006101 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006102 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006103 else if (ctrl_x_mode_spell())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006104 {
6105 if (get_spell_compl_info(startcol, curs_col) == FAIL)
6106 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006107 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006108 }
6109 else
6110 {
6111 internal_error("ins_complete()");
6112 return FAIL;
6113 }
6114
6115 return OK;
6116}
6117
6118/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006119 * Continue an interrupted completion mode search in "line".
6120 *
6121 * If this same ctrl_x_mode has been interrupted use the text from
6122 * "compl_startpos" to the cursor as a pattern to add a new word instead of
6123 * expand the one before the cursor, in word-wise if "compl_startpos" is not in
6124 * the same line as the cursor then fix it (the line has been split because it
6125 * was longer than 'tw'). if SOL is set then skip the previous pattern, a word
6126 * at the beginning of the line has been inserted, we'll look for that.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006127 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006128 static void
6129ins_compl_continue_search(char_u *line)
6130{
6131 // it is a continued search
6132 compl_cont_status &= ~CONT_INTRPT; // remove INTRPT
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006133 if (ctrl_x_mode_normal() || ctrl_x_mode_path_patterns()
6134 || ctrl_x_mode_path_defines())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006135 {
6136 if (compl_startpos.lnum != curwin->w_cursor.lnum)
6137 {
6138 // line (probably) wrapped, set compl_startpos to the
6139 // first non_blank in the line, if it is not a wordchar
6140 // include it to get a better pattern, but then we don't
6141 // want the "\\<" prefix, check it below
6142 compl_col = (colnr_T)getwhitecols(line);
6143 compl_startpos.col = compl_col;
6144 compl_startpos.lnum = curwin->w_cursor.lnum;
6145 compl_cont_status &= ~CONT_SOL; // clear SOL if present
6146 }
6147 else
6148 {
6149 // S_IPOS was set when we inserted a word that was at the
6150 // beginning of the line, which means that we'll go to SOL
6151 // mode but first we need to redefine compl_startpos
6152 if (compl_cont_status & CONT_S_IPOS)
6153 {
6154 compl_cont_status |= CONT_SOL;
6155 compl_startpos.col = (colnr_T)(skipwhite(
6156 line + compl_length
6157 + compl_startpos.col) - line);
6158 }
6159 compl_col = compl_startpos.col;
6160 }
6161 compl_length = curwin->w_cursor.col - (int)compl_col;
6162 // IObuff is used to add a "word from the next line" would we
6163 // have enough space? just being paranoid
6164#define MIN_SPACE 75
6165 if (compl_length > (IOSIZE - MIN_SPACE))
6166 {
6167 compl_cont_status &= ~CONT_SOL;
6168 compl_length = (IOSIZE - MIN_SPACE);
6169 compl_col = curwin->w_cursor.col - compl_length;
6170 }
6171 compl_cont_status |= CONT_ADDING | CONT_N_ADDS;
6172 if (compl_length < 1)
6173 compl_cont_status &= CONT_LOCAL;
6174 }
6175 else if (ctrl_x_mode_line_or_eval())
6176 compl_cont_status = CONT_ADDING | CONT_N_ADDS;
6177 else
6178 compl_cont_status = 0;
6179}
6180
6181/*
6182 * start insert mode completion
6183 */
6184 static int
6185ins_compl_start(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006186{
glepnir19e1dd62025-05-08 22:50:38 +02006187 char_u *line = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006188 int startcol = 0; // column where searched text starts
6189 colnr_T curs_col; // cursor column
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006190 int line_invalid = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006191 int save_did_ai = did_ai;
Bram Moolenaard9eefe32019-04-06 14:22:21 +02006192 int flags = CP_ORIGINAL_TEXT;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006193
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006194 // First time we hit ^N or ^P (in a row, I mean)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006195 did_ai = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006196 did_si = FALSE;
6197 can_si = FALSE;
6198 can_si_back = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006199 if (stop_arrow() == FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006200 return FAIL;
6201
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006202 line = ml_get(curwin->w_cursor.lnum);
6203 curs_col = curwin->w_cursor.col;
6204 compl_pending = 0;
glepnir76bdb822025-02-08 19:04:51 +01006205 compl_lnum = curwin->w_cursor.lnum;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006206
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006207 if ((compl_cont_status & CONT_INTRPT) == CONT_INTRPT
6208 && compl_cont_mode == ctrl_x_mode)
6209 // this same ctrl-x_mode was interrupted previously. Continue the
6210 // completion.
6211 ins_compl_continue_search(line);
6212 else
6213 compl_cont_status &= CONT_LOCAL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006214
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006215 if (!compl_status_adding()) // normal expansion
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006216 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006217 compl_cont_mode = ctrl_x_mode;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006218 if (ctrl_x_mode_not_default())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006219 // Remove LOCAL if ctrl_x_mode != CTRL_X_NORMAL
6220 compl_cont_status = 0;
6221 compl_cont_status |= CONT_N_ADDS;
6222 compl_startpos = curwin->w_cursor;
6223 startcol = (int)curs_col;
6224 compl_col = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006225 }
6226
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006227 // Work out completion pattern and original text -- webb
6228 if (compl_get_info(line, startcol, curs_col, &line_invalid) == FAIL)
6229 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006230 if (ctrl_x_mode_function() || ctrl_x_mode_omni()
6231 || thesaurus_func_complete(ctrl_x_mode))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006232 // restore did_ai, so that adding comment leader works
6233 did_ai = save_did_ai;
6234 return FAIL;
6235 }
6236 // If "line" was changed while getting completion info get it again.
6237 if (line_invalid)
6238 line = ml_get(curwin->w_cursor.lnum);
6239
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006240 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006241 {
6242 edit_submode_pre = (char_u *)_(" Adding");
6243 if (ctrl_x_mode_line_or_eval())
6244 {
6245 // Insert a new line, keep indentation but ignore 'comments'.
6246 char_u *old = curbuf->b_p_com;
6247
6248 curbuf->b_p_com = (char_u *)"";
6249 compl_startpos.lnum = curwin->w_cursor.lnum;
6250 compl_startpos.col = compl_col;
6251 ins_eol('\r');
6252 curbuf->b_p_com = old;
6253 compl_length = 0;
6254 compl_col = curwin->w_cursor.col;
glepnir76bdb822025-02-08 19:04:51 +01006255 compl_lnum = curwin->w_cursor.lnum;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006256 }
glepnircfe502c2025-04-17 20:17:53 +02006257 else if (ctrl_x_mode_normal() && cfc_has_mode())
glepnir7cfe6932024-09-15 20:06:28 +02006258 {
6259 compl_startpos = curwin->w_cursor;
6260 compl_cont_status &= CONT_S_IPOS;
6261 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006262 }
6263 else
6264 {
6265 edit_submode_pre = NULL;
6266 compl_startpos.col = compl_col;
6267 }
6268
6269 if (compl_cont_status & CONT_LOCAL)
6270 edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]);
6271 else
6272 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
6273
6274 // If any of the original typed text has been changed we need to fix
6275 // the redo buffer.
6276 ins_compl_fixRedoBufForLeader(NULL);
6277
6278 // Always add completion for the original text.
John Marriott5e6ea922024-11-23 14:01:57 +01006279 VIM_CLEAR_STRING(compl_orig_text);
6280 compl_orig_text.length = (size_t)compl_length;
6281 compl_orig_text.string = vim_strnsave(line + compl_col, (size_t)compl_length);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006282 if (p_ic)
6283 flags |= CP_ICASE;
zeertzjq4422de62025-03-07 19:06:02 +01006284 if (compl_orig_text.string == NULL
6285 || ins_compl_add(compl_orig_text.string,
6286 (int)compl_orig_text.length,
6287 NULL, NULL, NULL, 0, flags, FALSE, NULL, 0) != OK)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006288 {
John Marriott5e6ea922024-11-23 14:01:57 +01006289 VIM_CLEAR_STRING(compl_pattern);
6290 VIM_CLEAR_STRING(compl_orig_text);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006291 return FAIL;
6292 }
6293
6294 // showmode might reset the internal line pointers, so it must
6295 // be called before line = ml_get(), or when this address is no
6296 // longer needed. -- Acevedo.
6297 edit_submode_extra = (char_u *)_("-- Searching...");
6298 edit_submode_highl = HLF_COUNT;
6299 showmode();
6300 edit_submode_extra = NULL;
6301 out_flush();
6302
6303 return OK;
6304}
6305
6306/*
6307 * display the completion status message
6308 */
6309 static void
6310ins_compl_show_statusmsg(void)
6311{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006312 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006313 if (is_first_match(compl_first_match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006314 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006315 edit_submode_extra = compl_status_adding() && compl_length > 1
Bram Moolenaarb53a1902022-11-15 13:57:38 +00006316 ? (char_u *)_("Hit end of paragraph")
6317 : (char_u *)_("Pattern not found");
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006318 edit_submode_highl = HLF_E;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006319 }
6320
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006321 if (edit_submode_extra == NULL)
6322 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006323 if (match_at_original_text(compl_curr_match))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006324 {
6325 edit_submode_extra = (char_u *)_("Back at original");
6326 edit_submode_highl = HLF_W;
6327 }
6328 else if (compl_cont_status & CONT_S_IPOS)
6329 {
6330 edit_submode_extra = (char_u *)_("Word from other line");
6331 edit_submode_highl = HLF_COUNT;
6332 }
6333 else if (compl_curr_match->cp_next == compl_curr_match->cp_prev)
6334 {
6335 edit_submode_extra = (char_u *)_("The only match");
6336 edit_submode_highl = HLF_COUNT;
Bram Moolenaarf9d51352020-10-26 19:22:42 +01006337 compl_curr_match->cp_number = 1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006338 }
6339 else
6340 {
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01006341#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006342 // Update completion sequence number when needed.
6343 if (compl_curr_match->cp_number == -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01006344 ins_compl_update_sequence_numbers();
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01006345#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006346 // The match should always have a sequence number now, this is
6347 // just a safety check.
6348 if (compl_curr_match->cp_number != -1)
6349 {
6350 // Space for 10 text chars. + 2x10-digit no.s = 31.
6351 // Translations may need more than twice that.
6352 static char_u match_ref[81];
6353
6354 if (compl_matches > 0)
6355 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006356 _("match %d of %d"),
6357 compl_curr_match->cp_number, compl_matches);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006358 else
6359 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006360 _("match %d"),
6361 compl_curr_match->cp_number);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006362 edit_submode_extra = match_ref;
6363 edit_submode_highl = HLF_R;
6364 if (dollar_vcol >= 0)
6365 curs_columns(FALSE);
6366 }
6367 }
6368 }
6369
6370 // Show a message about what (completion) mode we're in.
6371 if (!compl_opt_suppress_empty)
6372 {
6373 showmode();
6374 if (!shortmess(SHM_COMPLETIONMENU))
6375 {
6376 if (edit_submode_extra != NULL)
6377 {
6378 if (!p_smd)
Bram Moolenaarcc233582020-12-12 13:32:07 +01006379 {
6380 msg_hist_off = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006381 msg_attr((char *)edit_submode_extra,
6382 edit_submode_highl < HLF_COUNT
6383 ? HL_ATTR(edit_submode_highl) : 0);
Bram Moolenaarcc233582020-12-12 13:32:07 +01006384 msg_hist_off = FALSE;
6385 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006386 }
6387 else
6388 msg_clr_cmdline(); // necessary for "noshowmode"
6389 }
6390 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006391}
6392
6393/*
6394 * Do Insert mode completion.
6395 * Called when character "c" was typed, which has a meaning for completion.
6396 * Returns OK if completion was done, FAIL if something failed (out of mem).
6397 */
6398 int
6399ins_complete(int c, int enable_pum)
6400{
6401 int n;
6402 int save_w_wrow;
6403 int save_w_leftcol;
6404 int insert_match;
6405
6406 compl_direction = ins_compl_key2dir(c);
6407 insert_match = ins_compl_use_match(c);
6408
6409 if (!compl_started)
6410 {
6411 if (ins_compl_start() == FAIL)
6412 return FAIL;
6413 }
6414 else if (insert_match && stop_arrow() == FAIL)
6415 return FAIL;
6416
glepnircf7f0122025-04-15 19:02:00 +02006417 compl_curr_win = curwin;
6418 compl_curr_buf = curwin->w_buffer;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006419 compl_shown_match = compl_curr_match;
6420 compl_shows_dir = compl_direction;
6421
6422 // Find next match (and following matches).
6423 save_w_wrow = curwin->w_wrow;
6424 save_w_leftcol = curwin->w_leftcol;
6425 n = ins_compl_next(TRUE, ins_compl_key2count(c), insert_match, FALSE);
6426
6427 // may undisplay the popup menu
6428 ins_compl_upd_pum();
6429
6430 if (n > 1) // all matches have been found
6431 compl_matches = n;
6432 compl_curr_match = compl_shown_match;
6433 compl_direction = compl_shows_dir;
6434
6435 // Eat the ESC that vgetc() returns after a CTRL-C to avoid leaving Insert
6436 // mode.
6437 if (got_int && !global_busy)
6438 {
6439 (void)vgetc();
6440 got_int = FALSE;
6441 }
6442
6443 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006444 if (is_first_match(compl_first_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006445 {
6446 // remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,
6447 // because we couldn't expand anything at first place, but if we used
6448 // ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word
6449 // (such as M in M'exico) if not tried already. -- Acevedo
6450 if (compl_length > 1
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006451 || compl_status_adding()
6452 || (ctrl_x_mode_not_default()
6453 && !ctrl_x_mode_path_patterns()
6454 && !ctrl_x_mode_path_defines()))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006455 compl_cont_status &= ~CONT_N_ADDS;
6456 }
6457
6458 if (compl_curr_match->cp_flags & CP_CONT_S_IPOS)
6459 compl_cont_status |= CONT_S_IPOS;
6460 else
6461 compl_cont_status &= ~CONT_S_IPOS;
6462
6463 ins_compl_show_statusmsg();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006464
6465 // Show the popup menu, unless we got interrupted.
6466 if (enable_pum && !compl_interrupted)
6467 show_pum(save_w_wrow, save_w_leftcol);
6468
6469 compl_was_interrupted = compl_interrupted;
6470 compl_interrupted = FALSE;
6471
6472 return OK;
6473}
6474
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00006475/*
6476 * Remove (if needed) and show the popup menu
6477 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006478 static void
6479show_pum(int prev_w_wrow, int prev_w_leftcol)
6480{
6481 // RedrawingDisabled may be set when invoked through complete().
Bram Moolenaar79cdf022023-05-20 14:07:00 +01006482 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006483 RedrawingDisabled = 0;
6484
6485 // If the cursor moved or the display scrolled we need to remove the pum
6486 // first.
6487 setcursor();
6488 if (prev_w_wrow != curwin->w_wrow || prev_w_leftcol != curwin->w_leftcol)
6489 ins_compl_del_pum();
6490
6491 ins_compl_show_pum();
6492 setcursor();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01006493
6494 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006495}
6496
6497/*
6498 * Looks in the first "len" chars. of "src" for search-metachars.
6499 * If dest is not NULL the chars. are copied there quoting (with
6500 * a backslash) the metachars, and dest would be NUL terminated.
6501 * Returns the length (needed) of dest
6502 */
6503 static unsigned
6504quote_meta(char_u *dest, char_u *src, int len)
6505{
6506 unsigned m = (unsigned)len + 1; // one extra for the NUL
6507
6508 for ( ; --len >= 0; src++)
6509 {
6510 switch (*src)
6511 {
6512 case '.':
6513 case '*':
6514 case '[':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006515 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006516 break;
6517 // FALLTHROUGH
6518 case '~':
Bram Moolenaarf4e20992020-12-21 19:59:08 +01006519 if (!magic_isset()) // quote these only if magic is set
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006520 break;
6521 // FALLTHROUGH
6522 case '\\':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006523 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006524 break;
6525 // FALLTHROUGH
6526 case '^': // currently it's not needed.
6527 case '$':
6528 m++;
6529 if (dest != NULL)
6530 *dest++ = '\\';
6531 break;
6532 }
6533 if (dest != NULL)
6534 *dest++ = *src;
6535 // Copy remaining bytes of a multibyte character.
6536 if (has_mbyte)
6537 {
glepnir19e1dd62025-05-08 22:50:38 +02006538 int mb_len = (*mb_ptr2len)(src) - 1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006539 if (mb_len > 0 && len >= mb_len)
glepnir19e1dd62025-05-08 22:50:38 +02006540 for (int i = 0; i < mb_len; ++i)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006541 {
6542 --len;
6543 ++src;
6544 if (dest != NULL)
6545 *dest++ = *src;
6546 }
6547 }
6548 }
6549 if (dest != NULL)
6550 *dest = NUL;
6551
6552 return m;
6553}
6554
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006555#if defined(EXITFREE) || defined(PROTO)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006556 void
6557free_insexpand_stuff(void)
6558{
John Marriott5e6ea922024-11-23 14:01:57 +01006559 VIM_CLEAR_STRING(compl_orig_text);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00006560# ifdef FEAT_EVAL
6561 free_callback(&cfu_cb);
6562 free_callback(&ofu_cb);
6563 free_callback(&tsrfu_cb);
6564# endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006565}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006566#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006567
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006568#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006569/*
6570 * Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly
6571 * spelled word, if there is one.
6572 */
6573 static void
6574spell_back_to_badword(void)
6575{
6576 pos_T tpos = curwin->w_cursor;
6577
Christ van Willegen - van Noort8e4c4c72024-05-17 18:49:27 +02006578 spell_bad_len = spell_move_to(curwin, BACKWARD, SMT_ALL, TRUE, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006579 if (curwin->w_cursor.col != tpos.col)
6580 start_arrow(&tpos);
6581}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006582#endif
Girish Palyacbe53192025-04-14 22:13:15 +02006583
6584/*
6585 * Reset the info associated with completion sources.
6586 */
6587 static void
Girish Palya0ac1eb32025-04-16 20:18:33 +02006588cpt_sources_clear(void)
Girish Palyacbe53192025-04-14 22:13:15 +02006589{
Girish Palya0ac1eb32025-04-16 20:18:33 +02006590 VIM_CLEAR(cpt_sources_array);
6591 cpt_sources_index = -1;
6592 cpt_sources_count = 0;
Girish Palyacbe53192025-04-14 22:13:15 +02006593}
6594
6595/*
6596 * Initialize the info associated with completion sources.
6597 */
6598 static int
Girish Palya0ac1eb32025-04-16 20:18:33 +02006599cpt_sources_init(void)
Girish Palyacbe53192025-04-14 22:13:15 +02006600{
Girish Palya0ac1eb32025-04-16 20:18:33 +02006601 char_u buf[LSIZE];
6602 int slen;
Girish Palyacbe53192025-04-14 22:13:15 +02006603 int count = 0;
Girish Palya0ac1eb32025-04-16 20:18:33 +02006604 char_u *p;
Girish Palyacbe53192025-04-14 22:13:15 +02006605
Girish Palya0ac1eb32025-04-16 20:18:33 +02006606 for (p = curbuf->b_p_cpt; *p;)
Girish Palyacbe53192025-04-14 22:13:15 +02006607 {
6608 while (*p == ',' || *p == ' ') // Skip delimiters
6609 p++;
6610 if (*p) // If not end of string, count this segment
6611 {
Girish Palya0ac1eb32025-04-16 20:18:33 +02006612 (void)copy_option_part(&p, buf, LSIZE, ","); // Advance p
Girish Palyacbe53192025-04-14 22:13:15 +02006613 count++;
Girish Palyacbe53192025-04-14 22:13:15 +02006614 }
6615 }
Girish Palya0ac1eb32025-04-16 20:18:33 +02006616 cpt_sources_clear();
6617 cpt_sources_count = count;
Girish Palyacbe53192025-04-14 22:13:15 +02006618 if (count > 0)
6619 {
Girish Palya0ac1eb32025-04-16 20:18:33 +02006620 cpt_sources_array = ALLOC_CLEAR_MULT(cpt_source_T, count);
6621 if (cpt_sources_array == NULL)
Girish Palyacbe53192025-04-14 22:13:15 +02006622 {
Girish Palya0ac1eb32025-04-16 20:18:33 +02006623 cpt_sources_count = 0;
Girish Palyacbe53192025-04-14 22:13:15 +02006624 return FAIL;
6625 }
Girish Palya0ac1eb32025-04-16 20:18:33 +02006626 count = 0;
6627 for (p = curbuf->b_p_cpt; *p;)
6628 {
6629 while (*p == ',' || *p == ' ') // Skip delimiters
6630 p++;
6631 if (*p) // If not end of string, count this segment
6632 {
6633 char_u *t;
6634
6635 vim_memset(buf, 0, LSIZE);
6636 slen = copy_option_part(&p, buf, LSIZE, ","); // Advance p
6637 if (slen > 0 && (t = vim_strchr(buf, '^')) != NULL)
6638 cpt_sources_array[count].max_matches = atoi((char *)t + 1);
6639 count++;
6640 }
6641 }
Girish Palyacbe53192025-04-14 22:13:15 +02006642 }
6643 return OK;
6644}
6645
6646/*
6647 * Return TRUE if any of the completion sources have 'refresh' set to 'always'.
6648 */
6649 static int
6650is_cpt_func_refresh_always(void)
6651{
6652#ifdef FEAT_COMPL_FUNC
glepnir19e1dd62025-05-08 22:50:38 +02006653 for (int i = 0; i < cpt_sources_count; i++)
Girish Palya0ac1eb32025-04-16 20:18:33 +02006654 if (cpt_sources_array[i].refresh_always)
Girish Palyacbe53192025-04-14 22:13:15 +02006655 return TRUE;
6656#endif
6657 return FALSE;
6658}
6659
6660/*
6661 * Make the completion list non-cyclic.
6662 */
6663#ifdef FEAT_COMPL_FUNC
6664 static void
6665ins_compl_make_linear(void)
6666{
6667 compl_T *m;
6668
6669 if (compl_first_match == NULL || compl_first_match->cp_prev == NULL)
6670 return;
6671 m = compl_first_match->cp_prev;
6672 m->cp_next = NULL;
6673 compl_first_match->cp_prev = NULL;
6674}
6675#endif
6676
6677/*
6678 * Remove the matches linked to the current completion source (as indicated by
Girish Palya0ac1eb32025-04-16 20:18:33 +02006679 * cpt_sources_index) from the completion list.
Girish Palyacbe53192025-04-14 22:13:15 +02006680 */
6681#ifdef FEAT_COMPL_FUNC
6682 static compl_T *
6683remove_old_matches(void)
6684{
6685 compl_T *sublist_start = NULL, *sublist_end = NULL, *insert_at = NULL;
6686 compl_T *current, *next;
Girish Palya0ac1eb32025-04-16 20:18:33 +02006687 int compl_shown_removed = FALSE;
6688 int forward = (compl_first_match->cp_cpt_source_idx < 0);
6689
6690 compl_direction = forward ? FORWARD : BACKWARD;
6691 compl_shows_dir = compl_direction;
Girish Palyacbe53192025-04-14 22:13:15 +02006692
6693 // Identify the sublist of old matches that needs removal
6694 for (current = compl_first_match; current != NULL; current = current->cp_next)
6695 {
Girish Palya0ac1eb32025-04-16 20:18:33 +02006696 if (current->cp_cpt_source_idx < cpt_sources_index &&
6697 (forward || (!forward && !insert_at)))
Girish Palyacbe53192025-04-14 22:13:15 +02006698 insert_at = current;
6699
Girish Palya0ac1eb32025-04-16 20:18:33 +02006700 if (current->cp_cpt_source_idx == cpt_sources_index)
Girish Palyacbe53192025-04-14 22:13:15 +02006701 {
6702 if (!sublist_start)
6703 sublist_start = current;
6704 sublist_end = current;
6705 if (!compl_shown_removed && compl_shown_match == current)
6706 compl_shown_removed = TRUE;
6707 }
6708
Girish Palya0ac1eb32025-04-16 20:18:33 +02006709 if ((forward && current->cp_cpt_source_idx > cpt_sources_index)
6710 || (!forward && insert_at))
Girish Palyacbe53192025-04-14 22:13:15 +02006711 break;
6712 }
6713
6714 // Re-assign compl_shown_match if necessary
6715 if (compl_shown_removed)
6716 {
6717 if (forward)
6718 compl_shown_match = compl_first_match;
6719 else
6720 { // Last node will have the prefix that is being completed
Girish Palya0ac1eb32025-04-16 20:18:33 +02006721 for (current = compl_first_match; current->cp_next != NULL;
6722 current = current->cp_next)
Girish Palyacbe53192025-04-14 22:13:15 +02006723 ;
6724 compl_shown_match = current;
6725 }
6726 }
6727
6728 if (!sublist_start) // No nodes to remove
6729 return insert_at;
6730
6731 // Update links to remove sublist
6732 if (sublist_start->cp_prev)
6733 sublist_start->cp_prev->cp_next = sublist_end->cp_next;
6734 else
6735 compl_first_match = sublist_end->cp_next;
6736
6737 if (sublist_end->cp_next)
6738 sublist_end->cp_next->cp_prev = sublist_start->cp_prev;
6739
6740 // Free all nodes in the sublist
6741 sublist_end->cp_next = NULL;
6742 for (current = sublist_start; current != NULL; current = next)
6743 {
6744 next = current->cp_next;
6745 ins_compl_item_free(current);
6746 }
6747
6748 return insert_at;
6749}
6750#endif
6751
6752/*
6753 * Retrieve completion matches using the callback function "cb" and store the
6754 * 'refresh:always' flag.
6755 */
6756#ifdef FEAT_COMPL_FUNC
6757 static void
6758get_cpt_func_completion_matches(callback_T *cb UNUSED)
6759{
glepnir19e1dd62025-05-08 22:50:38 +02006760 int ret;
6761 int startcol;
Girish Palyacbe53192025-04-14 22:13:15 +02006762
6763 VIM_CLEAR_STRING(cpt_compl_pattern);
6764 ret = get_userdefined_compl_info(curwin->w_cursor.col, cb, &startcol);
6765 if (ret == FAIL && startcol == -3)
Girish Palya0ac1eb32025-04-16 20:18:33 +02006766 cpt_sources_array[cpt_sources_index].refresh_always = FALSE;
Girish Palyacbe53192025-04-14 22:13:15 +02006767 else if (ret == OK)
6768 {
6769 expand_by_function(0, cpt_compl_pattern.string, cb);
Girish Palya0ac1eb32025-04-16 20:18:33 +02006770 cpt_sources_array[cpt_sources_index].refresh_always =
6771 compl_opt_refresh_always;
Girish Palyacbe53192025-04-14 22:13:15 +02006772 compl_opt_refresh_always = FALSE;
6773 }
6774}
6775#endif
6776
6777/*
6778 * Retrieve completion matches from functions in the 'cpt' option where the
6779 * 'refresh:always' flag is set.
6780 */
6781 static void
6782cpt_compl_refresh(void)
6783{
6784#ifdef FEAT_COMPL_FUNC
6785 char_u *cpt;
6786 char_u *p;
Christian Brabandtd2079cf2025-04-15 18:10:26 +02006787 callback_T *cb = NULL;
Girish Palyacbe53192025-04-14 22:13:15 +02006788
6789 // Make the completion list linear (non-cyclic)
6790 ins_compl_make_linear();
6791 // Make a copy of 'cpt' in case the buffer gets wiped out
6792 cpt = vim_strsave(curbuf->b_p_cpt);
Girish Palya0ac1eb32025-04-16 20:18:33 +02006793 strip_caret_numbers_in_place(cpt);
Girish Palyacbe53192025-04-14 22:13:15 +02006794
Girish Palya0ac1eb32025-04-16 20:18:33 +02006795 cpt_sources_index = 0;
6796 for (p = cpt; *p; cpt_sources_index++)
Girish Palyacbe53192025-04-14 22:13:15 +02006797 {
6798 while (*p == ',' || *p == ' ') // Skip delimiters
6799 p++;
6800
Girish Palya0ac1eb32025-04-16 20:18:33 +02006801 if (cpt_sources_array[cpt_sources_index].refresh_always)
Girish Palyacbe53192025-04-14 22:13:15 +02006802 {
6803 if (*p == 'o')
6804 cb = &curbuf->b_ofu_cb;
6805 else if (*p == 'f')
6806 cb = (*(p + 1) != ',' && *(p + 1) != NUL)
6807 ? get_cpt_func_callback(p + 1) : &curbuf->b_cfu_cb;
6808 if (cb)
6809 {
6810 compl_curr_match = remove_old_matches();
6811 get_cpt_func_completion_matches(cb);
6812 }
6813 }
6814
6815 copy_option_part(&p, IObuff, IOSIZE, ","); // Advance p
6816 }
Girish Palya0ac1eb32025-04-16 20:18:33 +02006817 cpt_sources_index = -1;
Girish Palyacbe53192025-04-14 22:13:15 +02006818
6819 vim_free(cpt);
6820 // Make the list cyclic
6821 compl_matches = ins_compl_make_cyclic();
6822#endif
6823}