blob: 7bbff4ecb4fccff850dbf5eb8c5ec4acb13602f4 [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{
glepnirc3fbaa02025-05-08 23:05:10 +0200808 return (get_cot_flags() & (COT_NEAREST | COT_FUZZY)) == COT_NEAREST;
Girish Palyab1565882025-04-15 20:16:00 +0200809}
810
811/*
812 * Repositions a match in the completion list based on its proximity score.
813 * If the match is at the head and has a higher score than the next node,
814 * or if it's in the middle/tail and has a lower score than the previous node,
815 * it is moved to the correct position while maintaining ascending order.
816 */
817 static void
818reposition_match(compl_T *match)
819{
820 compl_T *insert_before = NULL;
821 compl_T *insert_after = NULL;
822
823 // Node is at head and score is too big
824 if (!match->cp_prev)
825 {
826 if (match->cp_next && match->cp_next->cp_score > 0 &&
827 match->cp_next->cp_score < match->cp_score)
828 {
829 // <c-p>: compl_first_match is at head and newly inserted node
830 compl_first_match = compl_curr_match = match->cp_next;
831 // Find the correct position in ascending order
832 insert_before = match->cp_next;
833 do
834 {
835 insert_after = insert_before;
836 insert_before = insert_before->cp_next;
837 } while (insert_before && insert_before->cp_score > 0 &&
838 insert_before->cp_score < match->cp_score);
839 }
840 else
841 return;
842 }
843 // Node is at tail or in the middle but score is too small
844 else
845 {
846 if (match->cp_prev->cp_score > 0 && match->cp_prev->cp_score > match->cp_score)
847 {
848 // <c-n>: compl_curr_match (and newly inserted match) is at tail
849 if (!match->cp_next)
850 compl_curr_match = compl_curr_match->cp_prev;
851 // Find the correct position in ascending order
852 insert_after = match->cp_prev;
853 do
854 {
855 insert_before = insert_after;
856 insert_after = insert_after->cp_prev;
857 } while (insert_after && insert_after->cp_score > 0 &&
858 insert_after->cp_score > match->cp_score);
859 }
860 else
861 return;
862 }
863
864 if (insert_after)
865 {
866 // Remove the match from its current position
867 if (match->cp_prev)
868 match->cp_prev->cp_next = match->cp_next;
869 else
870 compl_first_match = match->cp_next;
871 if (match->cp_next)
872 match->cp_next->cp_prev = match->cp_prev;
873
874 // Insert the match at the correct position
875 match->cp_next = insert_before;
876 match->cp_prev = insert_after;
877 insert_after->cp_next = match;
878 insert_before->cp_prev = match;
879 }
880}
881
882/*
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000883 * Add a match to the list of matches. The arguments are:
884 * str - text of the match to add
885 * len - length of "str". If -1, then the length of "str" is
886 * computed.
887 * fname - file name to associate with this match.
888 * cptext - list of strings to use with this match (for abbr, menu, info
889 * and kind)
890 * user_data - user supplied data (any vim type) for this match
891 * cdir - match direction. If 0, use "compl_direction".
892 * flags_arg - match flags (cp_flags)
893 * adup - accept this match even if it is already present.
glepnir80b66202024-11-27 21:53:53 +0100894 * *user_hl - list of extra highlight attributes for abbr kind.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000895 * If "cdir" is FORWARD, then the match is added after the current match.
896 * Otherwise, it is added before the current match.
897 *
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100898 * If the given string is already in the list of completions, then return
899 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
900 * maybe because alloc() returns NULL, then FAIL is returned.
901 */
902 static int
903ins_compl_add(
904 char_u *str,
905 int len,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100906 char_u *fname,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100907 char_u **cptext, // extra text for popup menu or NULL
908 typval_T *user_data UNUSED, // "user_data" entry or NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100909 int cdir,
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200910 int flags_arg,
glepnir508e7852024-07-25 21:39:08 +0200911 int adup, // accept duplicate match
glepnirf31cfa22025-03-06 21:59:13 +0100912 int *user_hl, // user abbr/kind hlattr
913 int score)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100914{
glepnirf31cfa22025-03-06 21:59:13 +0100915 compl_T *match, *current, *prev;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100916 int dir = (cdir == 0 ? compl_direction : cdir);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200917 int flags = flags_arg;
glepnirf31cfa22025-03-06 21:59:13 +0100918 int inserted = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100919
Bram Moolenaarceb06192021-04-04 15:05:22 +0200920 if (flags & CP_FAST)
921 fast_breakcheck();
922 else
923 ui_breakcheck();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100924 if (got_int)
925 return FAIL;
926 if (len < 0)
927 len = (int)STRLEN(str);
928
929 // If the same match is already present, don't add it.
930 if (compl_first_match != NULL && !adup)
931 {
932 match = compl_first_match;
933 do
934 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000935 if (!match_at_original_text(match)
John Marriott5e6ea922024-11-23 14:01:57 +0100936 && STRNCMP(match->cp_str.string, str, len) == 0
937 && ((int)match->cp_str.length <= len
938 || match->cp_str.string[len] == NUL))
Girish Palyab1565882025-04-15 20:16:00 +0200939 {
940 if (is_nearest_active() && score > 0 && score < match->cp_score)
941 {
942 match->cp_score = score;
943 reposition_match(match);
944 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100945 return NOTDONE;
Girish Palyab1565882025-04-15 20:16:00 +0200946 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100947 match = match->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000948 } while (match != NULL && !is_first_match(match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100949 }
950
951 // Remove any popup menu before changing the list of matches.
952 ins_compl_del_pum();
953
954 // Allocate a new match structure.
955 // Copy the values to the new match structure.
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200956 match = ALLOC_CLEAR_ONE(compl_T);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100957 if (match == NULL)
958 return FAIL;
glepnir40891ba2025-02-10 22:18:00 +0100959 match->cp_number = flags & CP_ORIGINAL_TEXT ? 0 : -1;
John Marriott5e6ea922024-11-23 14:01:57 +0100960 if ((match->cp_str.string = vim_strnsave(str, len)) == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100961 {
962 vim_free(match);
963 return FAIL;
964 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100965
John Marriott5e6ea922024-11-23 14:01:57 +0100966 match->cp_str.length = len;
967
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100968 // match-fname is:
969 // - compl_curr_match->cp_fname if it is a string equal to fname.
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200970 // - a copy of fname, CP_FREE_FNAME is set to free later THE allocated mem.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100971 // - NULL otherwise. --Acevedo
972 if (fname != NULL
973 && compl_curr_match != NULL
974 && compl_curr_match->cp_fname != NULL
975 && STRCMP(fname, compl_curr_match->cp_fname) == 0)
976 match->cp_fname = compl_curr_match->cp_fname;
977 else if (fname != NULL)
978 {
979 match->cp_fname = vim_strsave(fname);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200980 flags |= CP_FREE_FNAME;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100981 }
982 else
983 match->cp_fname = NULL;
984 match->cp_flags = flags;
glepnir80b66202024-11-27 21:53:53 +0100985 match->cp_user_abbr_hlattr = user_hl ? user_hl[0] : -1;
986 match->cp_user_kind_hlattr = user_hl ? user_hl[1] : -1;
glepnirf31cfa22025-03-06 21:59:13 +0100987 match->cp_score = score;
Girish Palya0ac1eb32025-04-16 20:18:33 +0200988 match->cp_cpt_source_idx = cpt_sources_index;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100989
990 if (cptext != NULL)
991 {
glepnir19e1dd62025-05-08 22:50:38 +0200992 for (int i = 0; i < CPT_COUNT; ++i)
glepnir6e199932024-12-14 21:13:27 +0100993 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100994 if (cptext[i] != NULL && *cptext[i] != NUL)
995 match->cp_text[i] = vim_strsave(cptext[i]);
glepnir6e199932024-12-14 21:13:27 +0100996 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100997 }
Bram Moolenaarab782c52020-01-04 19:00:11 +0100998#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +0100999 if (user_data != NULL)
1000 match->cp_user_data = *user_data;
Bram Moolenaarab782c52020-01-04 19:00:11 +01001001#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001002
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00001003 // Link the new match structure after (FORWARD) or before (BACKWARD) the
1004 // current match in the list of matches .
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001005 if (compl_first_match == NULL)
1006 match->cp_next = match->cp_prev = NULL;
glepnirf31cfa22025-03-06 21:59:13 +01001007 else if (cfc_has_mode() && score > 0 && compl_get_longest)
1008 {
1009 current = compl_first_match->cp_next;
1010 prev = compl_first_match;
1011 inserted = FALSE;
1012 // The direction is ignored when using longest and
1013 // completefuzzycollect, because matches are inserted
1014 // and sorted by score.
1015 while (current != NULL && current != compl_first_match)
1016 {
1017 if (current->cp_score < score)
1018 {
Hirohito Higashi355db992025-04-28 18:07:02 +02001019 match->cp_next = current;
1020 match->cp_prev = current->cp_prev;
1021 if (current->cp_prev)
glepnirf31cfa22025-03-06 21:59:13 +01001022 current->cp_prev->cp_next = match;
Hirohito Higashi355db992025-04-28 18:07:02 +02001023 current->cp_prev = match;
1024 inserted = TRUE;
1025 break;
glepnirf31cfa22025-03-06 21:59:13 +01001026 }
1027 prev = current;
1028 current = current->cp_next;
1029 }
1030 if (!inserted)
1031 {
1032 prev->cp_next = match;
1033 match->cp_prev = prev;
1034 match->cp_next = compl_first_match;
1035 compl_first_match->cp_prev = match;
1036 }
1037 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001038 else if (dir == FORWARD)
1039 {
1040 match->cp_next = compl_curr_match->cp_next;
1041 match->cp_prev = compl_curr_match;
1042 }
1043 else // BACKWARD
1044 {
1045 match->cp_next = compl_curr_match;
1046 match->cp_prev = compl_curr_match->cp_prev;
1047 }
1048 if (match->cp_next)
1049 match->cp_next->cp_prev = match;
1050 if (match->cp_prev)
1051 match->cp_prev->cp_next = match;
1052 else // if there's nothing before, it is the first match
1053 compl_first_match = match;
1054 compl_curr_match = match;
1055
Girish Palyab1565882025-04-15 20:16:00 +02001056 if (is_nearest_active() && score > 0)
1057 reposition_match(match);
1058
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001059 // Find the longest common string if still doing that.
glepnirf31cfa22025-03-06 21:59:13 +01001060 if (compl_get_longest && (flags & CP_ORIGINAL_TEXT) == 0 && !cfc_has_mode())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001061 ins_compl_longest_match(match);
1062
1063 return OK;
1064}
1065
1066/*
1067 * Return TRUE if "str[len]" matches with match->cp_str, considering
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001068 * match->cp_flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001069 */
1070 static int
1071ins_compl_equal(compl_T *match, char_u *str, int len)
1072{
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001073 if (match->cp_flags & CP_EQUAL)
Bram Moolenaar73655cf2019-04-06 13:45:55 +02001074 return TRUE;
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001075 if (match->cp_flags & CP_ICASE)
John Marriott5e6ea922024-11-23 14:01:57 +01001076 return STRNICMP(match->cp_str.string, str, (size_t)len) == 0;
1077 return STRNCMP(match->cp_str.string, str, (size_t)len) == 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001078}
1079
1080/*
glepnir6a38aff2024-12-16 21:56:16 +01001081 * when len is -1 mean use whole length of p otherwise part of p
1082 */
1083 static void
1084ins_compl_insert_bytes(char_u *p, int len)
1085{
1086 if (len == -1)
1087 len = (int)STRLEN(p);
1088 ins_bytes_len(p, len);
zeertzjqf25d8f92024-12-18 21:12:25 +01001089 compl_ins_end_col = curwin->w_cursor.col;
glepnir6a38aff2024-12-16 21:56:16 +01001090}
1091
1092/*
zeertzjqd32bf0a2024-12-17 20:55:13 +01001093 * Checks if the column is within the currently inserted completion text
1094 * column range. If it is, it returns a special highlight attribute.
glepnir76bdb822025-02-08 19:04:51 +01001095 * -1 means normal item.
glepnir6a38aff2024-12-16 21:56:16 +01001096 */
1097 int
glepnir76bdb822025-02-08 19:04:51 +01001098ins_compl_col_range_attr(linenr_T lnum, int col)
glepnir6a38aff2024-12-16 21:56:16 +01001099{
glepnir76bdb822025-02-08 19:04:51 +01001100 int start_col;
1101 int attr;
1102
1103 if ((get_cot_flags() & COT_FUZZY)
1104 || (attr = syn_name2attr((char_u *)"ComplMatchIns")) == 0)
glepnire8908872025-01-08 18:30:45 +01001105 return -1;
1106
glepnir76bdb822025-02-08 19:04:51 +01001107 start_col = compl_col + (int)ins_compl_leader_len();
1108 if (!ins_compl_has_multiple())
1109 return (col >= start_col && col < compl_ins_end_col) ? attr : -1;
1110
1111 // Multiple lines
1112 if ((lnum == compl_lnum && col >= start_col && col < MAXCOL) ||
1113 (lnum > compl_lnum && lnum < curwin->w_cursor.lnum) ||
1114 (lnum == curwin->w_cursor.lnum && col <= compl_ins_end_col))
1115 return attr;
glepnir6a38aff2024-12-16 21:56:16 +01001116
1117 return -1;
1118}
1119
1120/*
glepnir76bdb822025-02-08 19:04:51 +01001121 * Returns TRUE if the current completion string contains newline characters,
1122 * indicating it's a multi-line completion.
1123 */
1124 static int
1125ins_compl_has_multiple(void)
1126{
1127 return vim_strchr(compl_shown_match->cp_str.string, '\n') != NULL;
1128}
1129
1130/*
1131 * Returns TRUE if the given line number falls within the range of a multi-line
1132 * completion, i.e. between the starting line (compl_lnum) and current cursor
1133 * line. Always returns FALSE for single-line completions.
1134 */
1135 int
1136ins_compl_lnum_in_range(linenr_T lnum)
1137{
1138 if (!ins_compl_has_multiple())
1139 return FALSE;
1140 return lnum >= compl_lnum && lnum <= curwin->w_cursor.lnum;
1141}
1142
1143/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001144 * Reduce the longest common string for match "match".
1145 */
1146 static void
1147ins_compl_longest_match(compl_T *match)
1148{
1149 char_u *p, *s;
1150 int c1, c2;
1151 int had_match;
1152
John Marriott5e6ea922024-11-23 14:01:57 +01001153 if (compl_leader.string == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001154 {
1155 // First match, use it as a whole.
John Marriott5e6ea922024-11-23 14:01:57 +01001156 compl_leader.string = vim_strnsave(match->cp_str.string, match->cp_str.length);
1157 if (compl_leader.string == NULL)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001158 return;
1159
John Marriott5e6ea922024-11-23 14:01:57 +01001160 compl_leader.length = match->cp_str.length;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001161 had_match = (curwin->w_cursor.col > compl_col);
glepnirf31cfa22025-03-06 21:59:13 +01001162 ins_compl_longest_insert(compl_leader.string);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001163
1164 // When the match isn't there (to avoid matching itself) remove it
1165 // again after redrawing.
1166 if (!had_match)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001167 ins_compl_delete();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001168 compl_used_match = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001169
1170 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001171 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001172
1173 // Reduce the text if this match differs from compl_leader.
John Marriott5e6ea922024-11-23 14:01:57 +01001174 p = compl_leader.string;
1175 s = match->cp_str.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001176 while (*p != NUL)
1177 {
1178 if (has_mbyte)
1179 {
1180 c1 = mb_ptr2char(p);
1181 c2 = mb_ptr2char(s);
1182 }
1183 else
1184 {
1185 c1 = *p;
1186 c2 = *s;
1187 }
1188 if ((match->cp_flags & CP_ICASE)
1189 ? (MB_TOLOWER(c1) != MB_TOLOWER(c2)) : (c1 != c2))
1190 break;
1191 if (has_mbyte)
1192 {
1193 MB_PTR_ADV(p);
1194 MB_PTR_ADV(s);
1195 }
1196 else
1197 {
1198 ++p;
1199 ++s;
1200 }
1201 }
1202
1203 if (*p != NUL)
1204 {
1205 // Leader was shortened, need to change the inserted text.
1206 *p = NUL;
John Marriott5e6ea922024-11-23 14:01:57 +01001207 compl_leader.length = (size_t)(p - compl_leader.string);
1208
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001209 had_match = (curwin->w_cursor.col > compl_col);
glepnirf31cfa22025-03-06 21:59:13 +01001210 ins_compl_longest_insert(compl_leader.string);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001211
1212 // When the match isn't there (to avoid matching itself) remove it
1213 // again after redrawing.
1214 if (!had_match)
1215 ins_compl_delete();
1216 }
1217
1218 compl_used_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001219}
1220
1221/*
1222 * Add an array of matches to the list of matches.
1223 * Frees matches[].
1224 */
1225 static void
1226ins_compl_add_matches(
1227 int num_matches,
1228 char_u **matches,
1229 int icase)
1230{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001231 int add_r = OK;
1232 int dir = compl_direction;
1233
glepnir19e1dd62025-05-08 22:50:38 +02001234 for (int i = 0; i < num_matches && add_r != FAIL; i++)
glepnir6e199932024-12-14 21:13:27 +01001235 {
1236 add_r = ins_compl_add(matches[i], -1, NULL, NULL, NULL, dir,
glepnirf31cfa22025-03-06 21:59:13 +01001237 CP_FAST | (icase ? CP_ICASE : 0), FALSE, NULL, 0);
glepnir6e199932024-12-14 21:13:27 +01001238 if (add_r == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001239 // if dir was BACKWARD then honor it just once
1240 dir = FORWARD;
glepnir6e199932024-12-14 21:13:27 +01001241 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001242 FreeWild(num_matches, matches);
1243}
1244
1245/*
1246 * Make the completion list cyclic.
1247 * Return the number of matches (excluding the original).
1248 */
1249 static int
1250ins_compl_make_cyclic(void)
1251{
1252 compl_T *match;
1253 int count = 0;
1254
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001255 if (compl_first_match == NULL)
1256 return 0;
1257
1258 // Find the end of the list.
1259 match = compl_first_match;
1260 // there's always an entry for the compl_orig_text, it doesn't count.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001261 while (match->cp_next != NULL && !is_first_match(match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001262 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001263 match = match->cp_next;
1264 ++count;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001265 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001266 match->cp_next = compl_first_match;
1267 compl_first_match->cp_prev = match;
1268
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001269 return count;
1270}
1271
1272/*
1273 * Return whether there currently is a shown match.
1274 */
1275 int
1276ins_compl_has_shown_match(void)
1277{
1278 return compl_shown_match == NULL
1279 || compl_shown_match != compl_shown_match->cp_next;
1280}
1281
1282/*
1283 * Return whether the shown match is long enough.
1284 */
1285 int
1286ins_compl_long_shown_match(void)
1287{
John Marriott5e6ea922024-11-23 14:01:57 +01001288 return (int)compl_shown_match->cp_str.length
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001289 > curwin->w_cursor.col - compl_col;
1290}
1291
1292/*
zeertzjq529b9ad2024-06-05 20:27:06 +02001293 * Get the local or global value of 'completeopt' flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001294 */
zeertzjq529b9ad2024-06-05 20:27:06 +02001295 unsigned int
1296get_cot_flags(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001297{
zeertzjq529b9ad2024-06-05 20:27:06 +02001298 return curbuf->b_cot_flags != 0 ? curbuf->b_cot_flags : cot_flags;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001299}
1300
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001301/*
1302 * Update the screen and when there is any scrolling remove the popup menu.
1303 */
1304 static void
1305ins_compl_upd_pum(void)
1306{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001307 if (compl_match_array == NULL)
1308 return;
1309
glepnir19e1dd62025-05-08 22:50:38 +02001310 int h = curwin->w_cline_height;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001311 // Update the screen later, before drawing the popup menu over it.
1312 pum_call_update_screen();
1313 if (h != curwin->w_cline_height)
1314 ins_compl_del_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001315}
1316
1317/*
1318 * Remove any popup menu.
1319 */
1320 static void
1321ins_compl_del_pum(void)
1322{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001323 if (compl_match_array == NULL)
1324 return;
1325
1326 pum_undisplay();
1327 VIM_CLEAR(compl_match_array);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001328}
1329
1330/*
1331 * Return TRUE if the popup menu should be displayed.
1332 */
1333 int
1334pum_wanted(void)
1335{
1336 // 'completeopt' must contain "menu" or "menuone"
zeertzjq529b9ad2024-06-05 20:27:06 +02001337 if ((get_cot_flags() & COT_ANY_MENU) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001338 return FALSE;
1339
1340 // The display looks bad on a B&W display.
1341 if (t_colors < 8
1342#ifdef FEAT_GUI
1343 && !gui.in_use
1344#endif
1345 )
1346 return FALSE;
1347 return TRUE;
1348}
1349
1350/*
1351 * Return TRUE if there are two or more matches to be shown in the popup menu.
1352 * One if 'completopt' contains "menuone".
1353 */
1354 static int
1355pum_enough_matches(void)
1356{
1357 compl_T *compl;
glepnir6e199932024-12-14 21:13:27 +01001358 int i = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001359
1360 // Don't display the popup menu if there are no matches or there is only
1361 // one (ignoring the original text).
1362 compl = compl_first_match;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001363 do
1364 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001365 if (compl == NULL || (!match_at_original_text(compl) && ++i == 2))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001366 break;
1367 compl = compl->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001368 } while (!is_first_match(compl));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001369
zeertzjq529b9ad2024-06-05 20:27:06 +02001370 if (get_cot_flags() & COT_MENUONE)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001371 return (i >= 1);
1372 return (i >= 2);
1373}
1374
Bram Moolenaar3075a452021-11-17 15:51:52 +00001375#if defined(FEAT_EVAL) || defined(PROTO)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001376/*
1377 * Allocate Dict for the completed item.
1378 * { word, abbr, menu, kind, info }
1379 */
1380 static dict_T *
1381ins_compl_dict_alloc(compl_T *match)
1382{
1383 dict_T *dict = dict_alloc_lock(VAR_FIXED);
1384
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001385 if (dict == NULL)
1386 return NULL;
1387
John Marriott5e6ea922024-11-23 14:01:57 +01001388 dict_add_string(dict, "word", match->cp_str.string);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001389 dict_add_string(dict, "abbr", match->cp_text[CPT_ABBR]);
1390 dict_add_string(dict, "menu", match->cp_text[CPT_MENU]);
1391 dict_add_string(dict, "kind", match->cp_text[CPT_KIND]);
1392 dict_add_string(dict, "info", match->cp_text[CPT_INFO]);
1393 if (match->cp_user_data.v_type == VAR_UNKNOWN)
1394 dict_add_string(dict, "user_data", (char_u *)"");
1395 else
1396 dict_add_tv(dict, "user_data", &match->cp_user_data);
1397
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001398 return dict;
1399}
1400
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001401/*
1402 * Trigger the CompleteChanged autocmd event. Invoked each time the Insert mode
1403 * completion menu is changed.
1404 */
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001405 static void
1406trigger_complete_changed_event(int cur)
1407{
1408 dict_T *v_event;
1409 dict_T *item;
1410 static int recursive = FALSE;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001411 save_v_event_T save_v_event;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001412
1413 if (recursive)
1414 return;
1415
glepnir40891ba2025-02-10 22:18:00 +01001416 item = cur < 0 ? dict_alloc() : ins_compl_dict_alloc(compl_curr_match);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001417 if (item == NULL)
1418 return;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001419 v_event = get_v_event(&save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001420 dict_add_dict(v_event, "completed_item", item);
1421 pum_set_event_info(v_event);
1422 dict_set_items_ro(v_event);
1423
1424 recursive = TRUE;
zeertzjqcfe45652022-05-27 17:26:55 +01001425 textlock++;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001426 apply_autocmds(EVENT_COMPLETECHANGED, NULL, NULL, FALSE, curbuf);
zeertzjqcfe45652022-05-27 17:26:55 +01001427 textlock--;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001428 recursive = FALSE;
1429
Bram Moolenaar3075a452021-11-17 15:51:52 +00001430 restore_v_event(v_event, &save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001431}
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001432#endif
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001433
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001434/*
glepnira218cc62024-06-03 19:32:39 +02001435 * pumitem qsort compare func
1436 */
1437 static int
zeertzjq8e567472024-06-14 20:04:42 +02001438ins_compl_fuzzy_cmp(const void *a, const void *b)
glepnira218cc62024-06-03 19:32:39 +02001439{
1440 const int sa = (*(pumitem_T *)a).pum_score;
1441 const int sb = (*(pumitem_T *)b).pum_score;
zeertzjq8e567472024-06-14 20:04:42 +02001442 const int ia = (*(pumitem_T *)a).pum_idx;
1443 const int ib = (*(pumitem_T *)b).pum_idx;
1444 return sa == sb ? (ia == ib ? 0 : (ia < ib ? -1 : 1)) : (sa < sb ? 1 : -1);
glepnira218cc62024-06-03 19:32:39 +02001445}
1446
1447/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001448 * Build a popup menu to show the completion matches.
1449 * Returns the popup menu entry that should be selected. Returns -1 if nothing
1450 * should be selected.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001451 */
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001452 static int
1453ins_compl_build_pum(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001454{
1455 compl_T *compl;
1456 compl_T *shown_compl = NULL;
1457 int did_find_shown_match = FALSE;
1458 int shown_match_ok = FALSE;
glepnira49c0772024-11-30 10:56:30 +01001459 int i = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001460 int cur = -1;
glepnira218cc62024-06-03 19:32:39 +02001461 int max_fuzzy_score = 0;
zeertzjqaa925ee2024-06-09 18:24:05 +02001462 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02001463 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
zeertzjqd65aa1b2025-01-25 15:29:03 +01001464 int fuzzy_filter = (cur_cot_flags & COT_FUZZY) != 0;
1465 int fuzzy_sort = fuzzy_filter && !(cur_cot_flags & COT_NOSORT);
glepnir80b66202024-11-27 21:53:53 +01001466 compl_T *match_head = NULL;
1467 compl_T *match_tail = NULL;
1468 compl_T *match_next = NULL;
glepnire4e4d1c2025-04-02 20:18:25 +02001469 int update_shown_match = fuzzy_filter;
Christian Brabandtb53d4fb2025-04-16 21:12:30 +02001470 int match_count = 0;
Girish Palya0ac1eb32025-04-16 20:18:33 +02001471 int cur_source = -1;
1472 int max_matches_found = FALSE;
1473 int is_forward = compl_shows_dir_forward() && !fuzzy_filter;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001474
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001475 // Need to build the popup menu list.
1476 compl_match_arraysize = 0;
1477 compl = compl_first_match;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001478
glepnira49c0772024-11-30 10:56:30 +01001479 // If the current match is the original text don't find the first
1480 // match after it, don't highlight anything.
1481 if (match_at_original_text(compl_shown_match))
1482 shown_match_ok = TRUE;
1483
glepnire4e4d1c2025-04-02 20:18:25 +02001484 if (fuzzy_filter && ctrl_x_mode_normal() && compl_leader.string == NULL
1485 && compl_shown_match->cp_score > 0)
1486 update_shown_match = FALSE;
1487
glepnira49c0772024-11-30 10:56:30 +01001488 if (compl_leader.string != NULL
1489 && STRCMP(compl_leader.string, compl_orig_text.string) == 0
1490 && shown_match_ok == FALSE)
1491 compl_shown_match = compl_no_select ? compl_first_match
1492 : compl_first_match->cp_next;
1493
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001494 do
1495 {
glepnird4088ed2024-12-31 10:55:22 +01001496 compl->cp_in_match_array = FALSE;
zeertzjq551d8c32024-06-05 19:53:32 +02001497 // When 'completeopt' contains "fuzzy" and leader is not NULL or empty,
1498 // set the cp_score for later comparisons.
glepnirf400a0c2025-01-23 19:55:14 +01001499 if (fuzzy_filter && compl_leader.string != NULL && compl_leader.length > 0)
John Marriott5e6ea922024-11-23 14:01:57 +01001500 compl->cp_score = fuzzy_match_str(compl->cp_str.string, compl_leader.string);
glepnira218cc62024-06-03 19:32:39 +02001501
Girish Palya0ac1eb32025-04-16 20:18:33 +02001502 if (is_forward && compl->cp_cpt_source_idx != -1)
1503 {
1504 if (cur_source != compl->cp_cpt_source_idx)
1505 {
1506 cur_source = compl->cp_cpt_source_idx;
1507 match_count = 1;
1508 max_matches_found = FALSE;
1509 }
Girish Palyadc314052025-05-08 23:28:52 +02001510 else if (cpt_sources_array != NULL && !max_matches_found)
Girish Palya0ac1eb32025-04-16 20:18:33 +02001511 {
1512 int max_matches = cpt_sources_array[cur_source].max_matches;
1513 if (max_matches > 0 && match_count > max_matches)
1514 max_matches_found = TRUE;
1515 }
1516 }
1517
Girish Palyadc314052025-05-08 23:28:52 +02001518 // Apply 'smartcase' behavior during normal mode
1519 if (ctrl_x_mode_normal() && !p_inf && compl_leader.string
1520 && !ignorecase(compl_leader.string) && !fuzzy_filter)
1521 compl->cp_flags &= ~CP_ICASE;
1522
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001523 if (!match_at_original_text(compl)
Girish Palya0ac1eb32025-04-16 20:18:33 +02001524 && !max_matches_found
John Marriott5e6ea922024-11-23 14:01:57 +01001525 && (compl_leader.string == NULL
Girish Palyadc314052025-05-08 23:28:52 +02001526 || ins_compl_equal(compl, compl_leader.string,
1527 (int)compl_leader.length)
glepnirf400a0c2025-01-23 19:55:14 +01001528 || (fuzzy_filter && compl->cp_score > 0)))
glepnir80b66202024-11-27 21:53:53 +01001529 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001530 ++compl_match_arraysize;
glepnird4088ed2024-12-31 10:55:22 +01001531 compl->cp_in_match_array = TRUE;
glepnir80b66202024-11-27 21:53:53 +01001532 if (match_head == NULL)
1533 match_head = compl;
1534 else
glepnira49c0772024-11-30 10:56:30 +01001535 match_tail->cp_match_next = compl;
glepnir80b66202024-11-27 21:53:53 +01001536 match_tail = compl;
glepnira49c0772024-11-30 10:56:30 +01001537
glepnirf400a0c2025-01-23 19:55:14 +01001538 if (!shown_match_ok && !fuzzy_filter)
glepnira49c0772024-11-30 10:56:30 +01001539 {
1540 if (compl == compl_shown_match || did_find_shown_match)
1541 {
1542 // This item is the shown match or this is the
1543 // first displayed item after the shown match.
1544 compl_shown_match = compl;
1545 did_find_shown_match = TRUE;
1546 shown_match_ok = TRUE;
1547 }
1548 else
1549 // Remember this displayed match for when the
1550 // shown match is just below it.
1551 shown_compl = compl;
1552 cur = i;
1553 }
glepnirf400a0c2025-01-23 19:55:14 +01001554 else if (fuzzy_filter)
glepnira49c0772024-11-30 10:56:30 +01001555 {
1556 if (i == 0)
1557 shown_compl = compl;
1558 // Update the maximum fuzzy score and the shown match
1559 // if the current item's score is higher
glepnire4e4d1c2025-04-02 20:18:25 +02001560 if (fuzzy_sort && compl->cp_score > max_fuzzy_score
1561 && update_shown_match)
glepnira49c0772024-11-30 10:56:30 +01001562 {
1563 did_find_shown_match = TRUE;
1564 max_fuzzy_score = compl->cp_score;
1565 if (!compl_no_select)
1566 compl_shown_match = compl;
1567 }
1568
glepnir3af0a8d2025-02-20 22:06:16 +01001569 if (!shown_match_ok && compl == compl_shown_match)
glepnira49c0772024-11-30 10:56:30 +01001570 {
1571 cur = i;
1572 shown_match_ok = TRUE;
1573 }
1574 }
Girish Palya0ac1eb32025-04-16 20:18:33 +02001575 if (is_forward && compl->cp_cpt_source_idx != -1)
1576 match_count++;
glepnira49c0772024-11-30 10:56:30 +01001577 i++;
glepnir80b66202024-11-27 21:53:53 +01001578 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001579
glepnirf400a0c2025-01-23 19:55:14 +01001580 if (compl == compl_shown_match && !fuzzy_filter)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001581 {
1582 did_find_shown_match = TRUE;
1583
1584 // When the original text is the shown match don't set
1585 // compl_shown_match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001586 if (match_at_original_text(compl))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001587 shown_match_ok = TRUE;
1588
1589 if (!shown_match_ok && shown_compl != NULL)
1590 {
1591 // The shown match isn't displayed, set it to the
1592 // previously displayed match.
1593 compl_shown_match = shown_compl;
1594 shown_match_ok = TRUE;
1595 }
1596 }
glepnira49c0772024-11-30 10:56:30 +01001597 compl = compl->cp_next;
1598 } while (compl != NULL && !is_first_match(compl));
1599
1600 if (compl_match_arraysize == 0)
1601 return -1;
1602
glepnirc0b7ca42025-02-13 20:27:44 +01001603 if (fuzzy_filter && !fuzzy_sort && !compl_no_select && !shown_match_ok)
1604 {
1605 compl_shown_match = shown_compl;
1606 shown_match_ok = TRUE;
1607 cur = 0;
1608 }
1609
glepnira49c0772024-11-30 10:56:30 +01001610 compl_match_array = ALLOC_CLEAR_MULT(pumitem_T, compl_match_arraysize);
1611 if (compl_match_array == NULL)
1612 return -1;
1613
1614 compl = match_head;
1615 i = 0;
1616 while (compl != NULL)
1617 {
glepnir6e199932024-12-14 21:13:27 +01001618 compl_match_array[i].pum_text = compl->cp_text[CPT_ABBR] != NULL
1619 ? compl->cp_text[CPT_ABBR] : compl->cp_str.string;
glepnira49c0772024-11-30 10:56:30 +01001620 compl_match_array[i].pum_kind = compl->cp_text[CPT_KIND];
1621 compl_match_array[i].pum_info = compl->cp_text[CPT_INFO];
1622 compl_match_array[i].pum_score = compl->cp_score;
1623 compl_match_array[i].pum_user_abbr_hlattr = compl->cp_user_abbr_hlattr;
1624 compl_match_array[i].pum_user_kind_hlattr = compl->cp_user_kind_hlattr;
glepnir6e199932024-12-14 21:13:27 +01001625 compl_match_array[i++].pum_extra = compl->cp_text[CPT_MENU] != NULL
1626 ? compl->cp_text[CPT_MENU] : compl->cp_fname;
glepnir80b66202024-11-27 21:53:53 +01001627 match_next = compl->cp_match_next;
1628 compl->cp_match_next = NULL;
1629 compl = match_next;
1630 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001631
zeertzjqd65aa1b2025-01-25 15:29:03 +01001632 if (fuzzy_sort && compl_leader.string != NULL && compl_leader.length > 0)
zeertzjq8e567472024-06-14 20:04:42 +02001633 {
1634 for (i = 0; i < compl_match_arraysize; i++)
1635 compl_match_array[i].pum_idx = i;
glepnira218cc62024-06-03 19:32:39 +02001636 // sort by the largest score of fuzzy match
zeertzjq8e567472024-06-14 20:04:42 +02001637 qsort(compl_match_array, (size_t)compl_match_arraysize,
1638 sizeof(pumitem_T), ins_compl_fuzzy_cmp);
glepnir65407ce2024-07-06 16:09:19 +02001639 shown_match_ok = TRUE;
zeertzjq8e567472024-06-14 20:04:42 +02001640 }
glepnira218cc62024-06-03 19:32:39 +02001641
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001642 if (!shown_match_ok) // no displayed match at all
1643 cur = -1;
1644
1645 return cur;
1646}
1647
1648/*
1649 * Show the popup menu for the list of matches.
1650 * Also adjusts "compl_shown_match" to an entry that is actually displayed.
1651 */
1652 void
1653ins_compl_show_pum(void)
1654{
1655 int i;
1656 int cur = -1;
1657 colnr_T col;
1658
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001659 if (!pum_wanted() || !pum_enough_matches())
1660 return;
1661
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001662 // Update the screen later, before drawing the popup menu over it.
1663 pum_call_update_screen();
1664
1665 if (compl_match_array == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001666 // Need to build the popup menu list.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001667 cur = ins_compl_build_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001668 else
1669 {
1670 // popup menu already exists, only need to find the current item.
1671 for (i = 0; i < compl_match_arraysize; ++i)
glepnir19e1dd62025-05-08 22:50:38 +02001672 {
John Marriott5e6ea922024-11-23 14:01:57 +01001673 if (compl_match_array[i].pum_text == compl_shown_match->cp_str.string
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001674 || compl_match_array[i].pum_text
1675 == compl_shown_match->cp_text[CPT_ABBR])
1676 {
1677 cur = i;
1678 break;
1679 }
glepnir19e1dd62025-05-08 22:50:38 +02001680 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001681 }
1682
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001683 if (compl_match_array == NULL)
glepnir0d3c0a62024-02-11 17:52:40 +01001684 {
1685#ifdef FEAT_EVAL
1686 if (compl_started && has_completechanged())
1687 trigger_complete_changed_event(cur);
1688#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001689 return;
glepnir0d3c0a62024-02-11 17:52:40 +01001690 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001691
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001692 // In Replace mode when a $ is displayed at the end of the line only
1693 // part of the screen would be updated. We do need to redraw here.
1694 dollar_vcol = -1;
1695
1696 // Compute the screen column of the start of the completed text.
1697 // Use the cursor to get all wrapping and other settings right.
1698 col = curwin->w_cursor.col;
1699 curwin->w_cursor.col = compl_col;
glepnira218cc62024-06-03 19:32:39 +02001700 compl_selected_item = cur;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001701 pum_display(compl_match_array, compl_match_arraysize, cur);
1702 curwin->w_cursor.col = col;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001703
glepnircbb46b42024-02-03 18:11:13 +01001704 // After adding leader, set the current match to shown match.
1705 if (compl_started && compl_curr_match != compl_shown_match)
1706 compl_curr_match = compl_shown_match;
1707
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001708#ifdef FEAT_EVAL
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001709 if (has_completechanged())
1710 trigger_complete_changed_event(cur);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001711#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001712}
1713
1714#define DICT_FIRST (1) // use just first element in "dict"
1715#define DICT_EXACT (2) // "dict" is the exact name of a file
1716
1717/*
glepnir40c1c332024-06-11 19:37:04 +02001718 * Get current completion leader
1719 */
1720 char_u *
1721ins_compl_leader(void)
1722{
John Marriott5e6ea922024-11-23 14:01:57 +01001723 return compl_leader.string != NULL ? compl_leader.string : compl_orig_text.string;
1724}
1725
1726/*
1727 * Get current completion leader length
1728 */
1729 size_t
1730ins_compl_leader_len(void)
1731{
1732 return compl_leader.string != NULL ? compl_leader.length : compl_orig_text.length;
glepnir40c1c332024-06-11 19:37:04 +02001733}
1734
1735/*
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001736 * Add any identifiers that match the given pattern "pat" in the list of
1737 * dictionary files "dict_start" to the list of completions.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001738 */
1739 static void
1740ins_compl_dictionaries(
1741 char_u *dict_start,
1742 char_u *pat,
1743 int flags, // DICT_FIRST and/or DICT_EXACT
1744 int thesaurus) // Thesaurus completion
1745{
1746 char_u *dict = dict_start;
1747 char_u *ptr;
1748 char_u *buf;
1749 regmatch_T regmatch;
1750 char_u **files;
1751 int count;
1752 int save_p_scs;
1753 int dir = compl_direction;
1754
1755 if (*dict == NUL)
1756 {
1757#ifdef FEAT_SPELL
1758 // When 'dictionary' is empty and spell checking is enabled use
1759 // "spell".
1760 if (!thesaurus && curwin->w_p_spell)
1761 dict = (char_u *)"spell";
1762 else
1763#endif
1764 return;
1765 }
1766
1767 buf = alloc(LSIZE);
1768 if (buf == NULL)
1769 return;
1770 regmatch.regprog = NULL; // so that we can goto theend
1771
1772 // If 'infercase' is set, don't use 'smartcase' here
1773 save_p_scs = p_scs;
1774 if (curbuf->b_p_inf)
1775 p_scs = FALSE;
1776
1777 // When invoked to match whole lines for CTRL-X CTRL-L adjust the pattern
1778 // to only match at the start of a line. Otherwise just match the
1779 // pattern. Also need to double backslashes.
1780 if (ctrl_x_mode_line_or_eval())
1781 {
1782 char_u *pat_esc = vim_strsave_escaped(pat, (char_u *)"\\");
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001783
1784 if (pat_esc == NULL)
1785 goto theend;
glepnir19e1dd62025-05-08 22:50:38 +02001786 size_t len = STRLEN(pat_esc) + 10;
Bram Moolenaar964b3742019-05-24 18:54:09 +02001787 ptr = alloc(len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001788 if (ptr == NULL)
1789 {
1790 vim_free(pat_esc);
1791 goto theend;
1792 }
1793 vim_snprintf((char *)ptr, len, "^\\s*\\zs\\V%s", pat_esc);
1794 regmatch.regprog = vim_regcomp(ptr, RE_MAGIC);
1795 vim_free(pat_esc);
1796 vim_free(ptr);
1797 }
1798 else
1799 {
Bram Moolenaarf4e20992020-12-21 19:59:08 +01001800 regmatch.regprog = vim_regcomp(pat, magic_isset() ? RE_MAGIC : 0);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001801 if (regmatch.regprog == NULL)
1802 goto theend;
1803 }
1804
1805 // ignore case depends on 'ignorecase', 'smartcase' and "pat"
1806 regmatch.rm_ic = ignorecase(pat);
1807 while (*dict != NUL && !got_int && !compl_interrupted)
1808 {
1809 // copy one dictionary file name into buf
1810 if (flags == DICT_EXACT)
1811 {
1812 count = 1;
1813 files = &dict;
1814 }
1815 else
1816 {
1817 // Expand wildcards in the dictionary name, but do not allow
1818 // backticks (for security, the 'dict' option may have been set in
1819 // a modeline).
1820 copy_option_part(&dict, buf, LSIZE, ",");
1821# ifdef FEAT_SPELL
1822 if (!thesaurus && STRCMP(buf, "spell") == 0)
1823 count = -1;
1824 else
1825# endif
1826 if (vim_strchr(buf, '`') != NULL
1827 || expand_wildcards(1, &buf, &count, &files,
1828 EW_FILE|EW_SILENT) != OK)
1829 count = 0;
1830 }
1831
1832# ifdef FEAT_SPELL
1833 if (count == -1)
1834 {
1835 // Complete from active spelling. Skip "\<" in the pattern, we
1836 // don't use it as a RE.
1837 if (pat[0] == '\\' && pat[1] == '<')
1838 ptr = pat + 2;
1839 else
1840 ptr = pat;
1841 spell_dump_compl(ptr, regmatch.rm_ic, &dir, 0);
1842 }
1843 else
1844# endif
1845 if (count > 0) // avoid warning for using "files" uninit
1846 {
1847 ins_compl_files(count, files, thesaurus, flags,
glepnirf31cfa22025-03-06 21:59:13 +01001848 (cfc_has_mode() ? NULL : &regmatch), buf, &dir);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001849 if (flags != DICT_EXACT)
1850 FreeWild(count, files);
1851 }
1852 if (flags != 0)
1853 break;
1854 }
1855
1856theend:
1857 p_scs = save_p_scs;
1858 vim_regfree(regmatch.regprog);
1859 vim_free(buf);
1860}
1861
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001862/*
1863 * Add all the words in the line "*buf_arg" from the thesaurus file "fname"
1864 * skipping the word at 'skip_word'. Returns OK on success.
1865 */
1866 static int
zeertzjq5fb3aab2022-08-24 16:48:23 +01001867thesaurus_add_words_in_line(
glepnir19e1dd62025-05-08 22:50:38 +02001868 char_u *fname,
1869 char_u **buf_arg,
1870 int dir,
1871 char_u *skip_word)
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001872{
1873 int status = OK;
1874 char_u *ptr;
1875 char_u *wstart;
1876
1877 // Add the other matches on the line
1878 ptr = *buf_arg;
1879 while (!got_int)
1880 {
1881 // Find start of the next word. Skip white
1882 // space and punctuation.
1883 ptr = find_word_start(ptr);
1884 if (*ptr == NUL || *ptr == NL)
1885 break;
1886 wstart = ptr;
1887
1888 // Find end of the word.
1889 if (has_mbyte)
1890 // Japanese words may have characters in
1891 // different classes, only separate words
1892 // with single-byte non-word characters.
1893 while (*ptr != NUL)
1894 {
1895 int l = (*mb_ptr2len)(ptr);
1896
1897 if (l < 2 && !vim_iswordc(*ptr))
1898 break;
1899 ptr += l;
1900 }
1901 else
1902 ptr = find_word_end(ptr);
1903
1904 // Add the word. Skip the regexp match.
1905 if (wstart != skip_word)
1906 {
1907 status = ins_compl_add_infercase(wstart, (int)(ptr - wstart), p_ic,
glepnirf31cfa22025-03-06 21:59:13 +01001908 fname, dir, FALSE, 0);
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001909 if (status == FAIL)
1910 break;
1911 }
1912 }
1913
1914 *buf_arg = ptr;
1915 return status;
1916}
1917
1918/*
1919 * Process "count" dictionary/thesaurus "files" and add the text matching
1920 * "regmatch".
1921 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001922 static void
1923ins_compl_files(
1924 int count,
1925 char_u **files,
1926 int thesaurus,
1927 int flags,
1928 regmatch_T *regmatch,
1929 char_u *buf,
1930 int *dir)
1931{
1932 char_u *ptr;
1933 int i;
1934 FILE *fp;
1935 int add_r;
glepnirf31cfa22025-03-06 21:59:13 +01001936 char_u *leader = NULL;
1937 int leader_len = 0;
glepnir58760162025-03-13 21:39:51 +01001938 int in_fuzzy_collect = cfc_has_mode();
glepnirf31cfa22025-03-06 21:59:13 +01001939 int score = 0;
1940 int len = 0;
1941 char_u *line_end = NULL;
1942
1943 if (in_fuzzy_collect)
1944 {
1945 leader = ins_compl_leader();
Yegappan Lakshmanan7b6add02025-04-01 20:38:37 +02001946 leader_len = (int)ins_compl_leader_len();
glepnirf31cfa22025-03-06 21:59:13 +01001947 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001948
1949 for (i = 0; i < count && !got_int && !compl_interrupted; i++)
1950 {
1951 fp = mch_fopen((char *)files[i], "r"); // open dictionary file
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01001952 if (flags != DICT_EXACT && !shortmess(SHM_COMPLETIONSCAN))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001953 {
Bram Moolenaarcc233582020-12-12 13:32:07 +01001954 msg_hist_off = TRUE; // reset in msg_trunc_attr()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001955 vim_snprintf((char *)IObuff, IOSIZE,
1956 _("Scanning dictionary: %s"), (char *)files[i]);
1957 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
1958 }
1959
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001960 if (fp == NULL)
1961 continue;
1962
1963 // Read dictionary file line by line.
1964 // Check each line for a match.
1965 while (!got_int && !compl_interrupted && !vim_fgets(buf, LSIZE, fp))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001966 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001967 ptr = buf;
glepnirf31cfa22025-03-06 21:59:13 +01001968 if (regmatch != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001969 {
glepnirf31cfa22025-03-06 21:59:13 +01001970 while (vim_regexec(regmatch, buf, (colnr_T)(ptr - buf)))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001971 {
glepnirf31cfa22025-03-06 21:59:13 +01001972 ptr = regmatch->startp[0];
1973 ptr = ctrl_x_mode_line_or_eval() ? find_line_end(ptr)
1974 : find_word_end(ptr);
1975 add_r = ins_compl_add_infercase(regmatch->startp[0],
1976 (int)(ptr - regmatch->startp[0]),
1977 p_ic, files[i], *dir, FALSE, 0);
1978 if (thesaurus)
1979 {
1980 // For a thesaurus, add all the words in the line
1981 ptr = buf;
1982 add_r = thesaurus_add_words_in_line(files[i], &ptr, *dir,
1983 regmatch->startp[0]);
1984 }
1985 if (add_r == OK)
1986 // if dir was BACKWARD then honor it just once
1987 *dir = FORWARD;
1988 else if (add_r == FAIL)
1989 break;
1990 // avoid expensive call to vim_regexec() when at end
1991 // of line
1992 if (*ptr == '\n' || got_int)
1993 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001994 }
glepnirf31cfa22025-03-06 21:59:13 +01001995 }
1996 else if (in_fuzzy_collect && leader_len > 0)
1997 {
1998 line_end = find_line_end(ptr);
1999 while (ptr < line_end)
2000 {
2001 if (fuzzy_match_str_in_line(&ptr, leader, &len, NULL, &score))
2002 {
2003 char_u *end_ptr = ctrl_x_mode_line_or_eval()
2004 ? find_line_end(ptr) : find_word_end(ptr);
2005 add_r = ins_compl_add_infercase(ptr, (int)(end_ptr - ptr),
2006 p_ic, files[i], *dir, FALSE, score);
2007 if (add_r == FAIL)
2008 break;
2009 ptr = end_ptr; // start from next word
2010 if (compl_get_longest && ctrl_x_mode_normal()
2011 && compl_first_match->cp_next
2012 && score == compl_first_match->cp_next->cp_score)
2013 compl_num_bests++;
2014 }
glepnirf31cfa22025-03-06 21:59:13 +01002015 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002016 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002017 line_breakcheck();
2018 ins_compl_check_keys(50, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002019 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002020 fclose(fp);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002021 }
2022}
2023
2024/*
2025 * Find the start of the next word.
2026 * Returns a pointer to the first char of the word. Also stops at a NUL.
2027 */
2028 char_u *
2029find_word_start(char_u *ptr)
2030{
2031 if (has_mbyte)
glepnir19e1dd62025-05-08 22:50:38 +02002032 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002033 while (*ptr != NUL && *ptr != '\n' && mb_get_class(ptr) <= 1)
2034 ptr += (*mb_ptr2len)(ptr);
glepnir19e1dd62025-05-08 22:50:38 +02002035 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002036 else
glepnir19e1dd62025-05-08 22:50:38 +02002037 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002038 while (*ptr != NUL && *ptr != '\n' && !vim_iswordc(*ptr))
2039 ++ptr;
glepnir19e1dd62025-05-08 22:50:38 +02002040 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002041 return ptr;
2042}
2043
2044/*
2045 * Find the end of the word. Assumes it starts inside a word.
2046 * Returns a pointer to just after the word.
2047 */
2048 char_u *
2049find_word_end(char_u *ptr)
2050{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002051 if (has_mbyte)
2052 {
glepnir19e1dd62025-05-08 22:50:38 +02002053 int start_class = mb_get_class(ptr);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002054 if (start_class > 1)
2055 while (*ptr != NUL)
2056 {
2057 ptr += (*mb_ptr2len)(ptr);
2058 if (mb_get_class(ptr) != start_class)
2059 break;
2060 }
2061 }
2062 else
2063 while (vim_iswordc(*ptr))
2064 ++ptr;
2065 return ptr;
2066}
2067
2068/*
2069 * Find the end of the line, omitting CR and NL at the end.
2070 * Returns a pointer to just after the line.
2071 */
glepnirdd42b052025-03-08 16:52:55 +01002072 char_u *
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002073find_line_end(char_u *ptr)
2074{
glepnir19e1dd62025-05-08 22:50:38 +02002075 char_u *s = ptr + STRLEN(ptr);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002076 while (s > ptr && (s[-1] == CAR || s[-1] == NL))
2077 --s;
2078 return s;
2079}
2080
2081/*
Girish Palyacbe53192025-04-14 22:13:15 +02002082 * Free a completion item in the list
2083 */
2084 static void
2085ins_compl_item_free(compl_T *match)
2086{
Girish Palyacbe53192025-04-14 22:13:15 +02002087 VIM_CLEAR_STRING(match->cp_str);
2088 // several entries may use the same fname, free it just once.
2089 if (match->cp_flags & CP_FREE_FNAME)
2090 vim_free(match->cp_fname);
glepnir19e1dd62025-05-08 22:50:38 +02002091 for (int i = 0; i < CPT_COUNT; ++i)
Girish Palyacbe53192025-04-14 22:13:15 +02002092 vim_free(match->cp_text[i]);
2093#ifdef FEAT_EVAL
2094 clear_tv(&match->cp_user_data);
2095#endif
2096 vim_free(match);
2097}
2098
2099/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002100 * Free the list of completions
2101 */
2102 static void
2103ins_compl_free(void)
2104{
2105 compl_T *match;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002106
John Marriott5e6ea922024-11-23 14:01:57 +01002107 VIM_CLEAR_STRING(compl_pattern);
2108 VIM_CLEAR_STRING(compl_leader);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002109
2110 if (compl_first_match == NULL)
2111 return;
2112
2113 ins_compl_del_pum();
2114 pum_clear();
2115
2116 compl_curr_match = compl_first_match;
2117 do
2118 {
2119 match = compl_curr_match;
2120 compl_curr_match = compl_curr_match->cp_next;
Girish Palyacbe53192025-04-14 22:13:15 +02002121 ins_compl_item_free(match);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002122 } while (compl_curr_match != NULL && !is_first_match(compl_curr_match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002123 compl_first_match = compl_curr_match = NULL;
2124 compl_shown_match = NULL;
2125 compl_old_match = NULL;
2126}
2127
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002128/*
2129 * Reset/clear the completion state.
2130 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002131 void
2132ins_compl_clear(void)
2133{
2134 compl_cont_status = 0;
2135 compl_started = FALSE;
glepnirf31cfa22025-03-06 21:59:13 +01002136 compl_cfc_longest_ins = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002137 compl_matches = 0;
glepnir07f0dbe2025-02-18 20:27:30 +01002138 compl_selected_item = -1;
glepnir6a38aff2024-12-16 21:56:16 +01002139 compl_ins_end_col = 0;
glepnircf7f0122025-04-15 19:02:00 +02002140 compl_curr_win = NULL;
2141 compl_curr_buf = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002142 VIM_CLEAR_STRING(compl_pattern);
2143 VIM_CLEAR_STRING(compl_leader);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002144 edit_submode_extra = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002145 VIM_CLEAR_STRING(compl_orig_text);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002146 compl_enter_selects = FALSE;
Girish Palya0ac1eb32025-04-16 20:18:33 +02002147 cpt_sources_clear();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002148#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002149 // clear v:completed_item
2150 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002151#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002152}
2153
2154/*
2155 * Return TRUE when Insert completion is active.
2156 */
2157 int
2158ins_compl_active(void)
2159{
2160 return compl_started;
2161}
2162
2163/*
glepnir8d0bb6d2024-12-24 09:44:35 +01002164 * Return True when wp is the actual completion window
2165 */
2166 int
glepnircf7f0122025-04-15 19:02:00 +02002167ins_compl_win_active(win_T *wp)
glepnir8d0bb6d2024-12-24 09:44:35 +01002168{
glepnircf7f0122025-04-15 19:02:00 +02002169 return ins_compl_active() && wp == compl_curr_win
2170 && wp->w_buffer == compl_curr_buf;
glepnir8d0bb6d2024-12-24 09:44:35 +01002171}
2172
2173/*
Girish Palyacbe53192025-04-14 22:13:15 +02002174 * Selected one of the matches. When FALSE, the match was either edited or
2175 * using the longest common string.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002176 */
2177 int
2178ins_compl_used_match(void)
2179{
2180 return compl_used_match;
2181}
2182
2183/*
2184 * Initialize get longest common string.
2185 */
2186 void
2187ins_compl_init_get_longest(void)
2188{
2189 compl_get_longest = FALSE;
2190}
2191
2192/*
2193 * Returns TRUE when insert completion is interrupted.
2194 */
2195 int
2196ins_compl_interrupted(void)
2197{
2198 return compl_interrupted;
2199}
2200
2201/*
2202 * Returns TRUE if the <Enter> key selects a match in the completion popup
2203 * menu.
2204 */
2205 int
2206ins_compl_enter_selects(void)
2207{
2208 return compl_enter_selects;
2209}
2210
2211/*
2212 * Return the column where the text starts that is being completed
2213 */
2214 colnr_T
2215ins_compl_col(void)
2216{
2217 return compl_col;
2218}
2219
2220/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002221 * Return the length in bytes of the text being completed
2222 */
2223 int
2224ins_compl_len(void)
2225{
2226 return compl_length;
2227}
2228
2229/*
glepnir94a045e2025-03-01 16:12:23 +01002230 * Return TRUE when the 'completeopt' "preinsert" flag is in effect,
2231 * otherwise return FALSE.
glepniredd4ac32025-01-29 18:53:51 +01002232 */
2233 static int
2234ins_compl_has_preinsert(void)
2235{
glepnira2c55592025-02-28 17:43:42 +01002236 int cur_cot_flags = get_cot_flags();
glepnir94a045e2025-03-01 16:12:23 +01002237 return (cur_cot_flags & (COT_PREINSERT | COT_FUZZY | COT_MENUONE))
2238 == (COT_PREINSERT | COT_MENUONE);
glepniredd4ac32025-01-29 18:53:51 +01002239}
2240
2241/*
2242 * Returns TRUE if the pre-insert effect is valid and the cursor is within
2243 * the `compl_ins_end_col` range.
2244 */
2245 int
2246ins_compl_preinsert_effect(void)
2247{
2248 if (!ins_compl_has_preinsert())
2249 return FALSE;
2250
2251 return curwin->w_cursor.col < compl_ins_end_col;
2252}
2253
2254/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002255 * Delete one character before the cursor and show the subset of the matches
2256 * that match the word that is now before the cursor.
2257 * Returns the character to be used, NUL if the work is done and another char
2258 * to be got from the user.
2259 */
2260 int
2261ins_compl_bs(void)
2262{
2263 char_u *line;
2264 char_u *p;
2265
glepniredd4ac32025-01-29 18:53:51 +01002266 if (ins_compl_preinsert_effect())
2267 ins_compl_delete();
2268
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002269 line = ml_get_curline();
2270 p = line + curwin->w_cursor.col;
2271 MB_PTR_BACK(line, p);
2272
2273 // Stop completion when the whole word was deleted. For Omni completion
2274 // allow the word to be deleted, we won't match everything.
2275 // Respect the 'backspace' option.
2276 if ((int)(p - line) - (int)compl_col < 0
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002277 || ((int)(p - line) - (int)compl_col == 0 && !ctrl_x_mode_omni())
2278 || ctrl_x_mode_eval()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002279 || (!can_bs(BS_START) && (int)(p - line) - (int)compl_col
2280 - compl_length < 0))
2281 return K_BS;
2282
2283 // Deleted more than what was used to find matches or didn't finish
2284 // finding all matches: need to look for matches all over again.
2285 if (curwin->w_cursor.col <= compl_col + compl_length
2286 || ins_compl_need_restart())
2287 ins_compl_restart();
2288
John Marriott5e6ea922024-11-23 14:01:57 +01002289 VIM_CLEAR_STRING(compl_leader);
2290 compl_leader.length = (size_t)((p - line) - compl_col);
2291 compl_leader.string = vim_strnsave(line + compl_col, compl_leader.length);
2292 if (compl_leader.string == NULL)
2293 {
2294 compl_leader.length = 0;
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00002295 return K_BS;
John Marriott5e6ea922024-11-23 14:01:57 +01002296 }
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00002297
2298 ins_compl_new_leader();
2299 if (compl_shown_match != NULL)
2300 // Make sure current match is not a hidden item.
2301 compl_curr_match = compl_shown_match;
2302 return NUL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002303}
2304
2305/*
2306 * Return TRUE when we need to find matches again, ins_compl_restart() is to
2307 * be called.
2308 */
2309 static int
2310ins_compl_need_restart(void)
2311{
2312 // Return TRUE if we didn't complete finding matches or when the
2313 // 'completefunc' returned "always" in the "refresh" dictionary item.
2314 return compl_was_interrupted
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002315 || ((ctrl_x_mode_function() || ctrl_x_mode_omni())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002316 && compl_opt_refresh_always);
2317}
2318
2319/*
2320 * Called after changing "compl_leader".
2321 * Show the popup menu with a different set of matches.
2322 * May also search for matches again if the previous search was interrupted.
2323 */
2324 static void
2325ins_compl_new_leader(void)
2326{
2327 ins_compl_del_pum();
2328 ins_compl_delete();
glepnir6a38aff2024-12-16 21:56:16 +01002329 ins_compl_insert_bytes(compl_leader.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002330 compl_used_match = FALSE;
2331
2332 if (compl_started)
Girish Palyacbe53192025-04-14 22:13:15 +02002333 {
John Marriott5e6ea922024-11-23 14:01:57 +01002334 ins_compl_set_original_text(compl_leader.string, compl_leader.length);
Girish Palyacbe53192025-04-14 22:13:15 +02002335 if (is_cpt_func_refresh_always())
2336 cpt_compl_refresh();
2337 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002338 else
2339 {
2340#ifdef FEAT_SPELL
2341 spell_bad_len = 0; // need to redetect bad word
2342#endif
Bram Moolenaar32aa1022019-11-02 22:54:41 +01002343 // Matches were cleared, need to search for them now. Before drawing
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002344 // the popup menu display the changed text before the cursor. Set
2345 // "compl_restarting" to avoid that the first match is inserted.
2346 pum_call_update_screen();
2347#ifdef FEAT_GUI
2348 if (gui.in_use)
2349 {
2350 // Show the cursor after the match, not after the redrawn text.
2351 setcursor();
2352 out_flush_cursor(FALSE, FALSE);
2353 }
2354#endif
2355 compl_restarting = TRUE;
2356 if (ins_complete(Ctrl_N, TRUE) == FAIL)
2357 compl_cont_status = 0;
2358 compl_restarting = FALSE;
2359 }
2360
glepnir44180412025-02-20 22:09:48 +01002361 compl_enter_selects = !compl_used_match && compl_selected_item != -1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002362
2363 // Show the popup menu with a different set of matches.
2364 ins_compl_show_pum();
2365
2366 // Don't let Enter select the original text when there is no popup menu.
2367 if (compl_match_array == NULL)
2368 compl_enter_selects = FALSE;
glepniredd4ac32025-01-29 18:53:51 +01002369 else if (ins_compl_has_preinsert() && compl_leader.length > 0)
2370 ins_compl_insert(FALSE, TRUE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002371}
2372
2373/*
2374 * Return the length of the completion, from the completion start column to
2375 * the cursor column. Making sure it never goes below zero.
2376 */
2377 static int
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002378get_compl_len(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002379{
2380 int off = (int)curwin->w_cursor.col - (int)compl_col;
glepnir40891ba2025-02-10 22:18:00 +01002381 return MAX(0, off);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002382}
2383
2384/*
2385 * Append one character to the match leader. May reduce the number of
2386 * matches.
2387 */
2388 void
2389ins_compl_addleader(int c)
2390{
glepnir19e1dd62025-05-08 22:50:38 +02002391 int cc;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002392
glepniredd4ac32025-01-29 18:53:51 +01002393 if (ins_compl_preinsert_effect())
2394 ins_compl_delete();
2395
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002396 if (stop_arrow() == FAIL)
2397 return;
2398 if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)
2399 {
2400 char_u buf[MB_MAXBYTES + 1];
2401
2402 (*mb_char2bytes)(c, buf);
2403 buf[cc] = NUL;
2404 ins_char_bytes(buf, cc);
2405 if (compl_opt_refresh_always)
2406 AppendToRedobuff(buf);
2407 }
2408 else
2409 {
2410 ins_char(c);
2411 if (compl_opt_refresh_always)
2412 AppendCharToRedobuff(c);
2413 }
2414
2415 // If we didn't complete finding matches we must search again.
2416 if (ins_compl_need_restart())
2417 ins_compl_restart();
2418
2419 // When 'always' is set, don't reset compl_leader. While completing,
2420 // cursor doesn't point original position, changing compl_leader would
2421 // break redo.
2422 if (!compl_opt_refresh_always)
2423 {
John Marriott5e6ea922024-11-23 14:01:57 +01002424 VIM_CLEAR_STRING(compl_leader);
2425 compl_leader.length = (size_t)(curwin->w_cursor.col - compl_col);
2426 compl_leader.string = vim_strnsave(ml_get_curline() + compl_col,
2427 compl_leader.length);
2428 if (compl_leader.string == NULL)
2429 {
2430 compl_leader.length = 0;
2431 return;
2432 }
2433
2434 ins_compl_new_leader();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002435 }
2436}
2437
2438/*
2439 * Setup for finding completions again without leaving CTRL-X mode. Used when
2440 * BS or a key was typed while still searching for matches.
2441 */
2442 static void
2443ins_compl_restart(void)
2444{
2445 ins_compl_free();
2446 compl_started = FALSE;
2447 compl_matches = 0;
2448 compl_cont_status = 0;
2449 compl_cont_mode = 0;
Girish Palya0ac1eb32025-04-16 20:18:33 +02002450 cpt_sources_clear();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002451}
2452
2453/*
2454 * Set the first match, the original text.
2455 */
2456 static void
John Marriott5e6ea922024-11-23 14:01:57 +01002457ins_compl_set_original_text(char_u *str, size_t len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002458{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002459 // Replace the original text entry.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002460 // The CP_ORIGINAL_TEXT flag is either at the first item or might possibly
2461 // be at the last item for backward completion
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002462 if (match_at_original_text(compl_first_match)) // safety check
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002463 {
John Marriott5e6ea922024-11-23 14:01:57 +01002464 char_u *p = vim_strnsave(str, len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002465 if (p != NULL)
2466 {
John Marriott5e6ea922024-11-23 14:01:57 +01002467 VIM_CLEAR_STRING(compl_first_match->cp_str);
2468 compl_first_match->cp_str.string = p;
2469 compl_first_match->cp_str.length = len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002470 }
2471 }
2472 else if (compl_first_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002473 && match_at_original_text(compl_first_match->cp_prev))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002474 {
John Marriott5e6ea922024-11-23 14:01:57 +01002475 char_u *p = vim_strnsave(str, len);
2476 if (p != NULL)
2477 {
2478 VIM_CLEAR_STRING(compl_first_match->cp_prev->cp_str);
2479 compl_first_match->cp_prev->cp_str.string = p;
2480 compl_first_match->cp_prev->cp_str.length = len;
2481 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002482 }
2483}
2484
2485/*
2486 * Append one character to the match leader. May reduce the number of
2487 * matches.
2488 */
2489 void
2490ins_compl_addfrommatch(void)
2491{
2492 char_u *p;
2493 int len = (int)curwin->w_cursor.col - (int)compl_col;
2494 int c;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002495
John Marriott5e6ea922024-11-23 14:01:57 +01002496 p = compl_shown_match->cp_str.string;
2497 if ((int)compl_shown_match->cp_str.length <= len) // the match is too short
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002498 {
John Marriott5e6ea922024-11-23 14:01:57 +01002499 size_t plen;
2500 compl_T *cp;
2501
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002502 // When still at the original match use the first entry that matches
2503 // the leader.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002504 if (!match_at_original_text(compl_shown_match))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002505 return;
2506
2507 p = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002508 plen = 0;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002509 for (cp = compl_shown_match->cp_next; cp != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002510 && !is_first_match(cp); cp = cp->cp_next)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002511 {
John Marriott5e6ea922024-11-23 14:01:57 +01002512 if (compl_leader.string == NULL
2513 || ins_compl_equal(cp, compl_leader.string,
2514 (int)compl_leader.length))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002515 {
John Marriott5e6ea922024-11-23 14:01:57 +01002516 p = cp->cp_str.string;
2517 plen = cp->cp_str.length;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002518 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002519 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002520 }
John Marriott5e6ea922024-11-23 14:01:57 +01002521 if (p == NULL || (int)plen <= len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002522 return;
2523 }
2524 p += len;
2525 c = PTR2CHAR(p);
2526 ins_compl_addleader(c);
2527}
2528
2529/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002530 * Set the CTRL-X completion mode based on the key "c" typed after a CTRL-X.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002531 * Uses the global variables: ctrl_x_mode, edit_submode, edit_submode_pre,
2532 * compl_cont_mode and compl_cont_status.
2533 * Returns TRUE when the character is not to be inserted.
2534 */
2535 static int
2536set_ctrl_x_mode(int c)
2537{
2538 int retval = FALSE;
2539
2540 switch (c)
2541 {
2542 case Ctrl_E:
2543 case Ctrl_Y:
2544 // scroll the window one line up or down
2545 ctrl_x_mode = CTRL_X_SCROLL;
2546 if (!(State & REPLACE_FLAG))
2547 edit_submode = (char_u *)_(" (insert) Scroll (^E/^Y)");
2548 else
2549 edit_submode = (char_u *)_(" (replace) Scroll (^E/^Y)");
2550 edit_submode_pre = NULL;
2551 showmode();
2552 break;
2553 case Ctrl_L:
2554 // complete whole line
2555 ctrl_x_mode = CTRL_X_WHOLE_LINE;
2556 break;
2557 case Ctrl_F:
2558 // complete filenames
2559 ctrl_x_mode = CTRL_X_FILES;
2560 break;
2561 case Ctrl_K:
zeertzjq5fb3aab2022-08-24 16:48:23 +01002562 // complete words from a dictionary
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002563 ctrl_x_mode = CTRL_X_DICTIONARY;
2564 break;
2565 case Ctrl_R:
2566 // Register insertion without exiting CTRL-X mode
2567 // Simply allow ^R to happen without affecting ^X mode
2568 break;
2569 case Ctrl_T:
2570 // complete words from a thesaurus
2571 ctrl_x_mode = CTRL_X_THESAURUS;
2572 break;
2573#ifdef FEAT_COMPL_FUNC
2574 case Ctrl_U:
2575 // user defined completion
2576 ctrl_x_mode = CTRL_X_FUNCTION;
2577 break;
2578 case Ctrl_O:
2579 // omni completion
2580 ctrl_x_mode = CTRL_X_OMNI;
2581 break;
2582#endif
2583 case 's':
2584 case Ctrl_S:
2585 // complete spelling suggestions
2586 ctrl_x_mode = CTRL_X_SPELL;
2587#ifdef FEAT_SPELL
2588 ++emsg_off; // Avoid getting the E756 error twice.
2589 spell_back_to_badword();
2590 --emsg_off;
2591#endif
2592 break;
2593 case Ctrl_RSB:
2594 // complete tag names
2595 ctrl_x_mode = CTRL_X_TAGS;
2596 break;
2597#ifdef FEAT_FIND_ID
2598 case Ctrl_I:
2599 case K_S_TAB:
2600 // complete keywords from included files
2601 ctrl_x_mode = CTRL_X_PATH_PATTERNS;
2602 break;
2603 case Ctrl_D:
2604 // complete definitions from included files
2605 ctrl_x_mode = CTRL_X_PATH_DEFINES;
2606 break;
2607#endif
2608 case Ctrl_V:
2609 case Ctrl_Q:
2610 // complete vim commands
2611 ctrl_x_mode = CTRL_X_CMDLINE;
2612 break;
2613 case Ctrl_Z:
2614 // stop completion
2615 ctrl_x_mode = CTRL_X_NORMAL;
2616 edit_submode = NULL;
2617 showmode();
2618 retval = TRUE;
2619 break;
2620 case Ctrl_P:
2621 case Ctrl_N:
2622 // ^X^P means LOCAL expansion if nothing interrupted (eg we
2623 // just started ^X mode, or there were enough ^X's to cancel
2624 // the previous mode, say ^X^F^X^X^P or ^P^X^X^X^P, see below)
2625 // do normal expansion when interrupting a different mode (say
2626 // ^X^F^X^P or ^P^X^X^P, see below)
2627 // nothing changes if interrupting mode 0, (eg, the flag
2628 // doesn't change when going to ADDING mode -- Acevedo
2629 if (!(compl_cont_status & CONT_INTRPT))
2630 compl_cont_status |= CONT_LOCAL;
2631 else if (compl_cont_mode != 0)
2632 compl_cont_status &= ~CONT_LOCAL;
2633 // FALLTHROUGH
2634 default:
2635 // If we have typed at least 2 ^X's... for modes != 0, we set
2636 // compl_cont_status = 0 (eg, as if we had just started ^X
2637 // mode).
2638 // For mode 0, we set "compl_cont_mode" to an impossible
2639 // value, in both cases ^X^X can be used to restart the same
2640 // mode (avoiding ADDING mode).
2641 // Undocumented feature: In a mode != 0 ^X^P and ^X^X^P start
2642 // 'complete' and local ^P expansions respectively.
2643 // In mode 0 an extra ^X is needed since ^X^P goes to ADDING
2644 // mode -- Acevedo
2645 if (c == Ctrl_X)
2646 {
2647 if (compl_cont_mode != 0)
2648 compl_cont_status = 0;
2649 else
2650 compl_cont_mode = CTRL_X_NOT_DEFINED_YET;
2651 }
2652 ctrl_x_mode = CTRL_X_NORMAL;
2653 edit_submode = NULL;
2654 showmode();
2655 break;
2656 }
2657
2658 return retval;
2659}
2660
2661/*
glepnir1c5a1202024-12-04 20:27:34 +01002662 * Trigger CompleteDone event and adds relevant information to v:event
2663 */
2664 static void
2665trigger_complete_done_event(int mode UNUSED, char_u *word UNUSED)
2666{
2667#if defined(FEAT_EVAL)
2668 save_v_event_T save_v_event;
2669 dict_T *v_event = get_v_event(&save_v_event);
2670 char_u *mode_str = NULL;
2671
2672 mode = mode & ~CTRL_X_WANT_IDENT;
2673 if (ctrl_x_mode_names[mode])
2674 mode_str = (char_u *)ctrl_x_mode_names[mode];
2675
2676 (void)dict_add_string(v_event, "complete_word",
2677 word == NULL ? (char_u *)"" : word);
2678 (void)dict_add_string(v_event, "complete_type",
2679 mode_str != NULL ? mode_str : (char_u *)"");
2680
2681 dict_set_items_ro(v_event);
2682#endif
2683 ins_apply_autocmds(EVENT_COMPLETEDONE);
2684
2685#if defined(FEAT_EVAL)
2686 restore_v_event(v_event, &save_v_event);
2687#endif
2688}
2689
2690/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002691 * Stop insert completion mode
2692 */
2693 static int
2694ins_compl_stop(int c, int prev_mode, int retval)
2695{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002696 int want_cindent;
glepnir1c5a1202024-12-04 20:27:34 +01002697 char_u *word = NULL;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002698
glepnir84a75032025-03-15 09:59:22 +01002699 // Remove pre-inserted text when present.
zeertzjq13436812025-04-23 20:46:35 +02002700 if (ins_compl_preinsert_effect() && ins_compl_win_active(curwin))
glepnir84a75032025-03-15 09:59:22 +01002701 ins_compl_delete();
2702
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002703 // Get here when we have finished typing a sequence of ^N and
2704 // ^P or other completion characters in CTRL-X mode. Free up
2705 // memory that was used, and make sure we can redo the insert.
John Marriott5e6ea922024-11-23 14:01:57 +01002706 if (compl_curr_match != NULL || compl_leader.string != NULL || c == Ctrl_E)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002707 {
glepnir40891ba2025-02-10 22:18:00 +01002708 char_u *ptr = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002709
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002710 // If any of the original typed text has been changed, eg when
2711 // ignorecase is set, we must add back-spaces to the redo
2712 // buffer. We add as few as necessary to delete just the part
2713 // of the original text that has changed.
2714 // When using the longest match, edited the match or used
2715 // CTRL-E then don't use the current match.
2716 if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E)
John Marriott5e6ea922024-11-23 14:01:57 +01002717 ptr = compl_curr_match->cp_str.string;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002718 ins_compl_fixRedoBufForLeader(ptr);
2719 }
2720
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002721 want_cindent = (get_can_cindent() && cindent_on());
Bram Moolenaar8e145b82022-05-21 20:17:31 +01002722
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002723 // When completing whole lines: fix indent for 'cindent'.
2724 // Otherwise, break line if it's too long.
2725 if (compl_cont_mode == CTRL_X_WHOLE_LINE)
2726 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002727 // re-indent the current line
2728 if (want_cindent)
2729 {
2730 do_c_expr_indent();
2731 want_cindent = FALSE; // don't do it again
2732 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002733 }
2734 else
2735 {
2736 int prev_col = curwin->w_cursor.col;
2737
2738 // put the cursor on the last char, for 'tw' formatting
2739 if (prev_col > 0)
2740 dec_cursor();
2741 // only format when something was inserted
2742 if (!arrow_used && !ins_need_undo_get() && c != Ctrl_E)
2743 insertchar(NUL, 0, -1);
2744 if (prev_col > 0
2745 && ml_get_curline()[curwin->w_cursor.col] != NUL)
2746 inc_cursor();
2747 }
2748
2749 // If the popup menu is displayed pressing CTRL-Y means accepting
2750 // the selection without inserting anything. When
2751 // compl_enter_selects is set the Enter key does the same.
2752 if ((c == Ctrl_Y || (compl_enter_selects
2753 && (c == CAR || c == K_KENTER || c == NL)))
2754 && pum_visible())
glepnir1c5a1202024-12-04 20:27:34 +01002755 {
2756 word = vim_strsave(compl_shown_match->cp_str.string);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002757 retval = TRUE;
glepnir1c5a1202024-12-04 20:27:34 +01002758 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002759
2760 // CTRL-E means completion is Ended, go back to the typed text.
2761 // but only do this, if the Popup is still visible
2762 if (c == Ctrl_E)
2763 {
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002764 char_u *p = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002765 size_t plen = 0;
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002766
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002767 ins_compl_delete();
John Marriott5e6ea922024-11-23 14:01:57 +01002768 if (compl_leader.string != NULL)
2769 {
2770 p = compl_leader.string;
2771 plen = compl_leader.length;
2772 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002773 else if (compl_first_match != NULL)
John Marriott5e6ea922024-11-23 14:01:57 +01002774 {
2775 p = compl_orig_text.string;
2776 plen = compl_orig_text.length;
2777 }
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002778 if (p != NULL)
2779 {
2780 int compl_len = get_compl_len();
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002781
John Marriott5e6ea922024-11-23 14:01:57 +01002782 if ((int)plen > compl_len)
zeertzjqf25d8f92024-12-18 21:12:25 +01002783 ins_compl_insert_bytes(p + compl_len, (int)plen - compl_len);
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002784 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002785 retval = TRUE;
2786 }
2787
2788 auto_format(FALSE, TRUE);
2789
2790 // Trigger the CompleteDonePre event to give scripts a chance to
2791 // act upon the completion before clearing the info, and restore
2792 // ctrl_x_mode, so that complete_info() can be used.
2793 ctrl_x_mode = prev_mode;
2794 ins_apply_autocmds(EVENT_COMPLETEDONEPRE);
2795
2796 ins_compl_free();
2797 compl_started = FALSE;
2798 compl_matches = 0;
2799 if (!shortmess(SHM_COMPLETIONMENU))
2800 msg_clr_cmdline(); // necessary for "noshowmode"
2801 ctrl_x_mode = CTRL_X_NORMAL;
2802 compl_enter_selects = FALSE;
2803 if (edit_submode != NULL)
2804 {
2805 edit_submode = NULL;
2806 showmode();
2807 }
2808
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002809 if (c == Ctrl_C && cmdwin_type != 0)
2810 // Avoid the popup menu remains displayed when leaving the
2811 // command line window.
2812 update_screen(0);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002813 // Indent now if a key was typed that is in 'cinkeys'.
2814 if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0)))
2815 do_c_expr_indent();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002816 // Trigger the CompleteDone event to give scripts a chance to act
2817 // upon the end of completion.
glepnir1c5a1202024-12-04 20:27:34 +01002818 trigger_complete_done_event(prev_mode, word);
2819 vim_free(word);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002820
2821 return retval;
2822}
2823
2824/*
glepnircf7f0122025-04-15 19:02:00 +02002825 * Cancel completion.
2826 */
2827 int
2828ins_compl_cancel(void)
2829{
2830 return ins_compl_stop(' ', ctrl_x_mode, TRUE);
2831}
2832
2833/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002834 * Prepare for Insert mode completion, or stop it.
2835 * Called just after typing a character in Insert mode.
2836 * Returns TRUE when the character is not to be inserted;
2837 */
2838 int
2839ins_compl_prep(int c)
2840{
glepnir19e1dd62025-05-08 22:50:38 +02002841 int retval = FALSE;
2842 int prev_mode = ctrl_x_mode;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002843
2844 // Forget any previous 'special' messages if this is actually
2845 // a ^X mode key - bar ^R, in which case we wait to see what it gives us.
2846 if (c != Ctrl_R && vim_is_ctrl_x_key(c))
2847 edit_submode_extra = NULL;
2848
zeertzjq440d4cb2023-03-02 17:51:32 +00002849 // Ignore end of Select mode mapping and mouse scroll/movement.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002850 if (c == K_SELECT || c == K_MOUSEDOWN || c == K_MOUSEUP
zeertzjq440d4cb2023-03-02 17:51:32 +00002851 || c == K_MOUSELEFT || c == K_MOUSERIGHT || c == K_MOUSEMOVE
Bram Moolenaare32c3c42022-01-15 18:26:04 +00002852 || c == K_COMMAND || c == K_SCRIPT_COMMAND)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002853 return retval;
2854
Bram Moolenaar05ad5ff2019-11-30 22:48:27 +01002855#ifdef FEAT_PROP_POPUP
Bram Moolenaarf0bc15c2019-08-18 19:23:45 +02002856 // Ignore mouse events in a popup window
2857 if (is_mouse_key(c))
2858 {
2859 // Ignore drag and release events, the position does not need to be in
2860 // the popup and it may have just closed.
2861 if (c == K_LEFTRELEASE
2862 || c == K_LEFTRELEASE_NM
2863 || c == K_MIDDLERELEASE
2864 || c == K_RIGHTRELEASE
2865 || c == K_X1RELEASE
2866 || c == K_X2RELEASE
2867 || c == K_LEFTDRAG
2868 || c == K_MIDDLEDRAG
2869 || c == K_RIGHTDRAG
2870 || c == K_X1DRAG
2871 || c == K_X2DRAG)
2872 return retval;
2873 if (popup_visible)
2874 {
2875 int row = mouse_row;
2876 int col = mouse_col;
2877 win_T *wp = mouse_find_win(&row, &col, FIND_POPUP);
2878
2879 if (wp != NULL && WIN_IS_POPUP(wp))
2880 return retval;
2881 }
2882 }
2883#endif
2884
zeertzjqdca29d92021-08-31 19:12:51 +02002885 if (ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X && c != Ctrl_X)
2886 {
2887 if (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_Z || ins_compl_pum_key(c)
2888 || !vim_is_ctrl_x_key(c))
2889 {
2890 // Not starting another completion mode.
2891 ctrl_x_mode = CTRL_X_CMDLINE;
2892
2893 // CTRL-X CTRL-Z should stop completion without inserting anything
2894 if (c == Ctrl_Z)
2895 retval = TRUE;
2896 }
2897 else
2898 {
2899 ctrl_x_mode = CTRL_X_CMDLINE;
2900
2901 // Other CTRL-X keys first stop completion, then start another
2902 // completion mode.
2903 ins_compl_prep(' ');
2904 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
2905 }
2906 }
2907
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002908 // Set "compl_get_longest" when finding the first matches.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002909 if (ctrl_x_mode_not_defined_yet()
2910 || (ctrl_x_mode_normal() && !compl_started))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002911 {
zeertzjq529b9ad2024-06-05 20:27:06 +02002912 compl_get_longest = (get_cot_flags() & COT_LONGEST) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002913 compl_used_match = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002914 }
2915
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002916 if (ctrl_x_mode_not_defined_yet())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002917 // We have just typed CTRL-X and aren't quite sure which CTRL-X mode
2918 // it will be yet. Now we decide.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002919 retval = set_ctrl_x_mode(c);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002920 else if (ctrl_x_mode_not_default())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002921 {
2922 // We're already in CTRL-X mode, do we stay in it?
2923 if (!vim_is_ctrl_x_key(c))
2924 {
glepnir40891ba2025-02-10 22:18:00 +01002925 ctrl_x_mode = ctrl_x_mode_scroll() ? CTRL_X_NORMAL : CTRL_X_FINISHED;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002926 edit_submode = NULL;
2927 }
2928 showmode();
2929 }
2930
2931 if (compl_started || ctrl_x_mode == CTRL_X_FINISHED)
2932 {
2933 // Show error message from attempted keyword completion (probably
2934 // 'Pattern not found') until another key is hit, then go back to
2935 // showing what mode we are in.
2936 showmode();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002937 if ((ctrl_x_mode_normal() && c != Ctrl_N && c != Ctrl_P
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002938 && c != Ctrl_R && !ins_compl_pum_key(c))
2939 || ctrl_x_mode == CTRL_X_FINISHED)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002940 retval = ins_compl_stop(c, prev_mode, retval);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002941 }
2942 else if (ctrl_x_mode == CTRL_X_LOCAL_MSG)
2943 // Trigger the CompleteDone event to give scripts a chance to act
2944 // upon the (possibly failed) completion.
glepnir1c5a1202024-12-04 20:27:34 +01002945 trigger_complete_done_event(ctrl_x_mode, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002946
LemonBoy2bf52dd2022-04-09 18:17:34 +01002947 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01002948
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002949 // reset continue_* if we left expansion-mode, if we stay they'll be
2950 // (re)set properly in ins_complete()
2951 if (!vim_is_ctrl_x_key(c))
2952 {
2953 compl_cont_status = 0;
2954 compl_cont_mode = 0;
2955 }
2956
2957 return retval;
2958}
2959
2960/*
2961 * Fix the redo buffer for the completion leader replacing some of the typed
2962 * text. This inserts backspaces and appends the changed text.
2963 * "ptr" is the known leader text or NUL.
2964 */
2965 static void
2966ins_compl_fixRedoBufForLeader(char_u *ptr_arg)
2967{
John Marriott5e6ea922024-11-23 14:01:57 +01002968 int len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002969 char_u *p;
2970 char_u *ptr = ptr_arg;
2971
2972 if (ptr == NULL)
2973 {
John Marriott5e6ea922024-11-23 14:01:57 +01002974 if (compl_leader.string != NULL)
2975 ptr = compl_leader.string;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002976 else
2977 return; // nothing to do
2978 }
John Marriott5e6ea922024-11-23 14:01:57 +01002979 if (compl_orig_text.string != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002980 {
John Marriott5e6ea922024-11-23 14:01:57 +01002981 p = compl_orig_text.string;
glepnir40891ba2025-02-10 22:18:00 +01002982 // Find length of common prefix between original text and new completion
2983 while (p[len] != NUL && p[len] == ptr[len])
2984 len++;
2985 // Adjust length to not break inside a multi-byte character
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002986 if (len > 0)
2987 len -= (*mb_head_off)(p, p + len);
glepnir40891ba2025-02-10 22:18:00 +01002988 // Add backspace characters for each remaining character in
2989 // original text
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002990 for (p += len; *p != NUL; MB_PTR_ADV(p))
2991 AppendCharToRedobuff(K_BS);
2992 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002993 if (ptr != NULL)
2994 AppendToRedobuffLit(ptr + len, -1);
2995}
2996
2997/*
2998 * Loops through the list of windows, loaded-buffers or non-loaded-buffers
2999 * (depending on flag) starting from buf and looking for a non-scanned
3000 * buffer (other than curbuf). curbuf is special, if it is called with
3001 * buf=curbuf then it has to be the first call for a given flag/expansion.
3002 *
3003 * Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo
3004 */
3005 static buf_T *
3006ins_compl_next_buf(buf_T *buf, int flag)
3007{
glepnir19e1dd62025-05-08 22:50:38 +02003008 static win_T *wp = NULL;
3009 int skip_buffer;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003010
3011 if (flag == 'w') // just windows
3012 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003013 if (buf == curbuf || !win_valid(wp))
3014 // first call for this flag/expansion or window was closed
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003015 wp = curwin;
glepnir40891ba2025-02-10 22:18:00 +01003016
3017 while (TRUE)
3018 {
Hirohito Higashi355db992025-04-28 18:07:02 +02003019 // Move to next window (wrap to first window if at the end)
3020 wp = (wp->w_next != NULL) ? wp->w_next : firstwin;
3021 // Break if we're back at start or found an unscanned buffer
3022 if (wp == curwin || !wp->w_buffer->b_scanned)
3023 break;
glepnir40891ba2025-02-10 22:18:00 +01003024 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003025 buf = wp->w_buffer;
3026 }
3027 else
glepnir40891ba2025-02-10 22:18:00 +01003028 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003029 // 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U'
3030 // (unlisted buffers)
3031 // When completing whole lines skip unloaded buffers.
glepnir40891ba2025-02-10 22:18:00 +01003032 while (TRUE)
3033 {
3034 // Move to next buffer (wrap to first buffer if at the end)
3035 buf = (buf->b_next != NULL) ? buf->b_next : firstbuf;
3036 // Break if we're back at start buffer
3037 if (buf == curbuf)
3038 break;
3039
3040 // Check buffer conditions based on flag
3041 if (flag == 'U')
3042 skip_buffer = buf->b_p_bl;
3043 else
3044 skip_buffer = !buf->b_p_bl ||
3045 (buf->b_ml.ml_mfp == NULL) != (flag == 'u');
3046
3047 // Break if we found a buffer that matches our criteria
3048 if (!skip_buffer && !buf->b_scanned)
3049 break;
3050 }
3051 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003052 return buf;
3053}
3054
3055#ifdef FEAT_COMPL_FUNC
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003056
3057# ifdef FEAT_EVAL
3058static callback_T cfu_cb; // 'completefunc' callback function
3059static callback_T ofu_cb; // 'omnifunc' callback function
3060static callback_T tsrfu_cb; // 'thesaurusfunc' callback function
3061# endif
3062
3063/*
3064 * Copy a global callback function to a buffer local callback.
3065 */
3066 static void
3067copy_global_to_buflocal_cb(callback_T *globcb, callback_T *bufcb)
3068{
3069 free_callback(bufcb);
3070 if (globcb->cb_name != NULL && *globcb->cb_name != NUL)
3071 copy_callback(bufcb, globcb);
3072}
3073
3074/*
3075 * Parse the 'completefunc' option value and set the callback function.
3076 * Invoked when the 'completefunc' option is set. The option value can be a
3077 * name of a function (string), or function(<name>) or funcref(<name>) or a
3078 * lambda expression.
3079 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003080 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00003081did_set_completefunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003082{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003083 if (option_set_callback_func(curbuf->b_p_cfu, &cfu_cb) == FAIL)
3084 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003085
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003086 set_buflocal_cfu_callback(curbuf);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003087
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003088 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003089}
3090
3091/*
3092 * Copy the global 'completefunc' callback function to the buffer-local
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003093 * 'completefunc' callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003094 */
3095 void
3096set_buflocal_cfu_callback(buf_T *buf UNUSED)
3097{
3098# ifdef FEAT_EVAL
3099 copy_global_to_buflocal_cb(&cfu_cb, &buf->b_cfu_cb);
3100# endif
3101}
3102
3103/*
3104 * Parse the 'omnifunc' option value and set the callback function.
3105 * Invoked when the 'omnifunc' option is set. The option value can be a
3106 * name of a function (string), or function(<name>) or funcref(<name>) or a
3107 * lambda expression.
3108 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003109 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00003110did_set_omnifunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003111{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003112 if (option_set_callback_func(curbuf->b_p_ofu, &ofu_cb) == FAIL)
3113 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003114
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003115 set_buflocal_ofu_callback(curbuf);
3116 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003117}
3118
3119/*
3120 * Copy the global 'omnifunc' callback function to the buffer-local 'omnifunc'
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003121 * callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003122 */
3123 void
3124set_buflocal_ofu_callback(buf_T *buf UNUSED)
3125{
3126# ifdef FEAT_EVAL
3127 copy_global_to_buflocal_cb(&ofu_cb, &buf->b_ofu_cb);
3128# endif
3129}
3130
3131/*
3132 * Parse the 'thesaurusfunc' option value and set the callback function.
3133 * Invoked when the 'thesaurusfunc' option is set. The option value can be a
3134 * name of a function (string), or function(<name>) or funcref(<name>) or a
3135 * lambda expression.
3136 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003137 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00003138did_set_thesaurusfunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003139{
3140 int retval;
3141
zeertzjq6eda2692024-11-03 09:23:33 +01003142 if (args->os_flags & OPT_LOCAL)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003143 // buffer-local option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003144 retval = option_set_callback_func(curbuf->b_p_tsrfu,
3145 &curbuf->b_tsrfu_cb);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003146 else
3147 {
3148 // global option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003149 retval = option_set_callback_func(p_tsrfu, &tsrfu_cb);
zeertzjq6eda2692024-11-03 09:23:33 +01003150 // when using :set, free the local callback
3151 if (!(args->os_flags & OPT_GLOBAL))
3152 free_callback(&curbuf->b_tsrfu_cb);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003153 }
3154
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003155 return retval == FAIL ? e_invalid_argument : NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003156}
3157
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00003158/*
3159 * Mark the global 'completefunc' 'omnifunc' and 'thesaurusfunc' callbacks with
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003160 * "copyID" so that they are not garbage collected.
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00003161 */
3162 int
3163set_ref_in_insexpand_funcs(int copyID)
3164{
glepnir19e1dd62025-05-08 22:50:38 +02003165 int abort = set_ref_in_callback(&cfu_cb, copyID);
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00003166 abort = abort || set_ref_in_callback(&ofu_cb, copyID);
3167 abort = abort || set_ref_in_callback(&tsrfu_cb, copyID);
3168
3169 return abort;
3170}
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003171
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003172/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003173 * Get the user-defined completion function name for completion "type"
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003174 */
3175 static char_u *
3176get_complete_funcname(int type)
3177{
3178 switch (type)
3179 {
3180 case CTRL_X_FUNCTION:
3181 return curbuf->b_p_cfu;
3182 case CTRL_X_OMNI:
3183 return curbuf->b_p_ofu;
3184 case CTRL_X_THESAURUS:
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01003185 return *curbuf->b_p_tsrfu == NUL ? p_tsrfu : curbuf->b_p_tsrfu;
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003186 default:
3187 return (char_u *)"";
3188 }
3189}
3190
3191/*
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003192 * Get the callback to use for insert mode completion.
3193 */
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003194 static callback_T *
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003195get_insert_callback(int type)
3196{
3197 if (type == CTRL_X_FUNCTION)
3198 return &curbuf->b_cfu_cb;
3199 if (type == CTRL_X_OMNI)
3200 return &curbuf->b_ofu_cb;
3201 // CTRL_X_THESAURUS
3202 return (*curbuf->b_p_tsrfu != NUL) ? &curbuf->b_tsrfu_cb : &tsrfu_cb;
3203}
3204
3205/*
Yegappan Lakshmanan05e59e32021-12-01 10:30:07 +00003206 * Execute user defined complete function 'completefunc', 'omnifunc' or
3207 * 'thesaurusfunc', and get matches in "matches".
Girish Palyacbe53192025-04-14 22:13:15 +02003208 * "type" can be one of CTRL_X_OMNI, CTRL_X_FUNCTION, or CTRL_X_THESAURUS.
3209 * Callback function "cb" is set if triggered by a function in the 'cpt'
3210 * option; otherwise, it is NULL.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003211 */
3212 static void
Girish Palyacbe53192025-04-14 22:13:15 +02003213expand_by_function(int type, char_u *base, callback_T *cb)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003214{
3215 list_T *matchlist = NULL;
3216 dict_T *matchdict = NULL;
3217 typval_T args[3];
3218 char_u *funcname;
3219 pos_T pos;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003220 typval_T rettv;
3221 int save_State = State;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003222 int retval;
Girish Palyacbe53192025-04-14 22:13:15 +02003223 int is_cpt_function = (cb != NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003224
Girish Palyacbe53192025-04-14 22:13:15 +02003225 if (!is_cpt_function)
3226 {
3227 funcname = get_complete_funcname(type);
3228 if (*funcname == NUL)
3229 return;
3230 cb = get_insert_callback(type);
3231 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003232
3233 // Call 'completefunc' to obtain the list of matches.
3234 args[0].v_type = VAR_NUMBER;
3235 args[0].vval.v_number = 0;
3236 args[1].v_type = VAR_STRING;
3237 args[1].vval.v_string = base != NULL ? base : (char_u *)"";
3238 args[2].v_type = VAR_UNKNOWN;
3239
3240 pos = curwin->w_cursor;
Bram Moolenaar28976e22021-01-29 21:07:07 +01003241 // Lock the text to avoid weird things from happening. Also disallow
3242 // switching to another window, it should not be needed and may end up in
3243 // Insert mode in another buffer.
zeertzjqcfe45652022-05-27 17:26:55 +01003244 ++textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003245
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003246 retval = call_callback(cb, 0, &rettv, 2, args);
3247
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003248 // Call a function, which returns a list or dict.
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003249 if (retval == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003250 {
3251 switch (rettv.v_type)
3252 {
3253 case VAR_LIST:
3254 matchlist = rettv.vval.v_list;
3255 break;
3256 case VAR_DICT:
3257 matchdict = rettv.vval.v_dict;
3258 break;
3259 case VAR_SPECIAL:
3260 if (rettv.vval.v_number == VVAL_NONE)
3261 compl_opt_suppress_empty = TRUE;
3262 // FALLTHROUGH
3263 default:
3264 // TODO: Give error message?
3265 clear_tv(&rettv);
3266 break;
3267 }
3268 }
zeertzjqcfe45652022-05-27 17:26:55 +01003269 --textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003270
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003271 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02003272 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003273 validate_cursor();
3274 if (!EQUAL_POS(curwin->w_cursor, pos))
3275 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00003276 emsg(_(e_complete_function_deleted_text));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003277 goto theend;
3278 }
3279
3280 if (matchlist != NULL)
3281 ins_compl_add_list(matchlist);
3282 else if (matchdict != NULL)
3283 ins_compl_add_dict(matchdict);
3284
3285theend:
3286 // Restore State, it might have been changed.
3287 State = save_State;
3288
3289 if (matchdict != NULL)
3290 dict_unref(matchdict);
3291 if (matchlist != NULL)
3292 list_unref(matchlist);
3293}
3294#endif // FEAT_COMPL_FUNC
3295
3296#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL) || defined(PROTO)
glepnir38f99a12024-08-23 18:31:06 +02003297
3298 static inline int
3299get_user_highlight_attr(char_u *hlname)
3300{
3301 if (hlname != NULL && *hlname != NUL)
Hirohito Higashi355db992025-04-28 18:07:02 +02003302 return syn_name2attr(hlname);
glepnir38f99a12024-08-23 18:31:06 +02003303 return -1;
3304}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003305/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003306 * Add a match to the list of matches from a typeval_T.
3307 * If the given string is already in the list of completions, then return
3308 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
3309 * maybe because alloc() returns NULL, then FAIL is returned.
Bram Moolenaar440cf092021-04-03 20:13:30 +02003310 * When "fast" is TRUE use fast_breakcheck() instead of ui_breakcheck().
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003311 */
3312 static int
Bram Moolenaar440cf092021-04-03 20:13:30 +02003313ins_compl_add_tv(typval_T *tv, int dir, int fast)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003314{
3315 char_u *word;
3316 int dup = FALSE;
3317 int empty = FALSE;
Bram Moolenaar440cf092021-04-03 20:13:30 +02003318 int flags = fast ? CP_FAST : 0;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003319 char_u *(cptext[CPT_COUNT]);
Bram Moolenaar08928322020-01-04 14:32:48 +01003320 typval_T user_data;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003321 int status;
glepnir0fe17f82024-10-08 22:26:44 +02003322 char_u *user_abbr_hlname;
glepnir38f99a12024-08-23 18:31:06 +02003323 char_u *user_kind_hlname;
glepnir80b66202024-11-27 21:53:53 +01003324 int user_hl[2] = { -1, -1 };
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003325
Bram Moolenaar08928322020-01-04 14:32:48 +01003326 user_data.v_type = VAR_UNKNOWN;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003327 if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL)
3328 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01003329 word = dict_get_string(tv->vval.v_dict, "word", FALSE);
3330 cptext[CPT_ABBR] = dict_get_string(tv->vval.v_dict, "abbr", FALSE);
3331 cptext[CPT_MENU] = dict_get_string(tv->vval.v_dict, "menu", FALSE);
3332 cptext[CPT_KIND] = dict_get_string(tv->vval.v_dict, "kind", FALSE);
3333 cptext[CPT_INFO] = dict_get_string(tv->vval.v_dict, "info", FALSE);
glepnir38f99a12024-08-23 18:31:06 +02003334
glepnir0fe17f82024-10-08 22:26:44 +02003335 user_abbr_hlname = dict_get_string(tv->vval.v_dict, "abbr_hlgroup", FALSE);
glepnir80b66202024-11-27 21:53:53 +01003336 user_hl[0] = get_user_highlight_attr(user_abbr_hlname);
glepnir38f99a12024-08-23 18:31:06 +02003337
3338 user_kind_hlname = dict_get_string(tv->vval.v_dict, "kind_hlgroup", FALSE);
glepnir80b66202024-11-27 21:53:53 +01003339 user_hl[1] = get_user_highlight_attr(user_kind_hlname);
glepnir508e7852024-07-25 21:39:08 +02003340
Bram Moolenaard61efa52022-07-23 09:52:04 +01003341 dict_get_tv(tv->vval.v_dict, "user_data", &user_data);
3342 if (dict_get_string(tv->vval.v_dict, "icase", FALSE) != NULL
3343 && dict_get_number(tv->vval.v_dict, "icase"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003344 flags |= CP_ICASE;
Bram Moolenaard61efa52022-07-23 09:52:04 +01003345 if (dict_get_string(tv->vval.v_dict, "dup", FALSE) != NULL)
3346 dup = dict_get_number(tv->vval.v_dict, "dup");
3347 if (dict_get_string(tv->vval.v_dict, "empty", FALSE) != NULL)
3348 empty = dict_get_number(tv->vval.v_dict, "empty");
3349 if (dict_get_string(tv->vval.v_dict, "equal", FALSE) != NULL
3350 && dict_get_number(tv->vval.v_dict, "equal"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003351 flags |= CP_EQUAL;
3352 }
3353 else
3354 {
3355 word = tv_get_string_chk(tv);
Bram Moolenaara80faa82020-04-12 19:37:17 +02003356 CLEAR_FIELD(cptext);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003357 }
3358 if (word == NULL || (!empty && *word == NUL))
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003359 {
3360 clear_tv(&user_data);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003361 return FAIL;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003362 }
glepnir508e7852024-07-25 21:39:08 +02003363 status = ins_compl_add(word, -1, NULL, cptext,
glepnirf31cfa22025-03-06 21:59:13 +01003364 &user_data, dir, flags, dup, user_hl, 0);
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003365 if (status != OK)
3366 clear_tv(&user_data);
3367 return status;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003368}
3369
3370/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003371 * Add completions from a list.
3372 */
3373 static void
3374ins_compl_add_list(list_T *list)
3375{
3376 listitem_T *li;
3377 int dir = compl_direction;
3378
3379 // Go through the List with matches and add each of them.
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003380 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003381 FOR_ALL_LIST_ITEMS(list, li)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003382 {
Bram Moolenaar440cf092021-04-03 20:13:30 +02003383 if (ins_compl_add_tv(&li->li_tv, dir, TRUE) == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003384 // if dir was BACKWARD then honor it just once
3385 dir = FORWARD;
3386 else if (did_emsg)
3387 break;
3388 }
3389}
3390
3391/*
3392 * Add completions from a dict.
3393 */
3394 static void
3395ins_compl_add_dict(dict_T *dict)
3396{
3397 dictitem_T *di_refresh;
3398 dictitem_T *di_words;
3399
3400 // Check for optional "refresh" item.
3401 compl_opt_refresh_always = FALSE;
3402 di_refresh = dict_find(dict, (char_u *)"refresh", 7);
3403 if (di_refresh != NULL && di_refresh->di_tv.v_type == VAR_STRING)
3404 {
3405 char_u *v = di_refresh->di_tv.vval.v_string;
3406
3407 if (v != NULL && STRCMP(v, (char_u *)"always") == 0)
3408 compl_opt_refresh_always = TRUE;
3409 }
3410
3411 // Add completions from a "words" list.
3412 di_words = dict_find(dict, (char_u *)"words", 5);
3413 if (di_words != NULL && di_words->di_tv.v_type == VAR_LIST)
3414 ins_compl_add_list(di_words->di_tv.vval.v_list);
3415}
3416
3417/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003418 * Start completion for the complete() function.
3419 * "startcol" is where the matched text starts (1 is first column).
3420 * "list" is the list of matches.
3421 */
3422 static void
3423set_completion(colnr_T startcol, list_T *list)
3424{
3425 int save_w_wrow = curwin->w_wrow;
3426 int save_w_leftcol = curwin->w_leftcol;
3427 int flags = CP_ORIGINAL_TEXT;
zeertzjqaa925ee2024-06-09 18:24:05 +02003428 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02003429 int compl_longest = (cur_cot_flags & COT_LONGEST) != 0;
3430 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
3431 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003432
3433 // If already doing completions stop it.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003434 if (ctrl_x_mode_not_default())
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003435 ins_compl_prep(' ');
3436 ins_compl_clear();
3437 ins_compl_free();
bfredl87af60c2022-09-24 11:17:51 +01003438 compl_get_longest = compl_longest;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003439
3440 compl_direction = FORWARD;
3441 if (startcol > curwin->w_cursor.col)
3442 startcol = curwin->w_cursor.col;
3443 compl_col = startcol;
glepnir76bdb822025-02-08 19:04:51 +01003444 compl_lnum = curwin->w_cursor.lnum;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003445 compl_length = (int)curwin->w_cursor.col - (int)startcol;
3446 // compl_pattern doesn't need to be set
glepniredd4ac32025-01-29 18:53:51 +01003447 compl_orig_text.string = vim_strnsave(ml_get_curline() + compl_col,
3448 (size_t)compl_length);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003449 if (p_ic)
3450 flags |= CP_ICASE;
John Marriott5e6ea922024-11-23 14:01:57 +01003451 if (compl_orig_text.string == NULL)
3452 {
3453 compl_orig_text.length = 0;
3454 return;
3455 }
3456 compl_orig_text.length = (size_t)compl_length;
3457 if (ins_compl_add(compl_orig_text.string,
Hirohito Higashi355db992025-04-28 18:07:02 +02003458 (int)compl_orig_text.length, NULL, NULL, NULL, 0,
3459 flags | CP_FAST, FALSE, NULL, 0) != OK)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003460 return;
3461
3462 ctrl_x_mode = CTRL_X_EVAL;
3463
3464 ins_compl_add_list(list);
3465 compl_matches = ins_compl_make_cyclic();
3466 compl_started = TRUE;
3467 compl_used_match = TRUE;
3468 compl_cont_status = 0;
3469
3470 compl_curr_match = compl_first_match;
bfredl87af60c2022-09-24 11:17:51 +01003471 int no_select = compl_no_select || compl_longest;
3472 if (compl_no_insert || no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003473 {
3474 ins_complete(K_DOWN, FALSE);
bfredl87af60c2022-09-24 11:17:51 +01003475 if (no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003476 // Down/Up has no real effect.
3477 ins_complete(K_UP, FALSE);
3478 }
3479 else
3480 ins_complete(Ctrl_N, FALSE);
3481 compl_enter_selects = compl_no_insert;
3482
3483 // Lazily show the popup menu, unless we got interrupted.
3484 if (!compl_interrupted)
3485 show_pum(save_w_wrow, save_w_leftcol);
LemonBoy2bf52dd2022-04-09 18:17:34 +01003486 may_trigger_modechanged();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003487 out_flush();
3488}
3489
3490/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003491 * "complete()" function
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003492 */
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003493 void
3494f_complete(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003495{
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003496 if (in_vim9script()
3497 && (check_for_number_arg(argvars, 0) == FAIL
3498 || check_for_list_arg(argvars, 1) == FAIL))
3499 return;
3500
Bram Moolenaar24959102022-05-07 20:01:16 +01003501 if ((State & MODE_INSERT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003502 {
Bram Moolenaar677658a2022-01-05 16:09:06 +00003503 emsg(_(e_complete_can_only_be_used_in_insert_mode));
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003504 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003505 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003506
3507 // Check for undo allowed here, because if something was already inserted
3508 // the line was already saved for undo and this check isn't done.
3509 if (!undo_allowed())
3510 return;
3511
Bram Moolenaard83392a2022-09-01 12:22:46 +01003512 if (check_for_nonnull_list_arg(argvars, 1) != FAIL)
Bram Moolenaarff06f282020-04-21 22:01:14 +02003513 {
glepnir19e1dd62025-05-08 22:50:38 +02003514 int startcol = (int)tv_get_number_chk(&argvars[0], NULL);
Bram Moolenaarff06f282020-04-21 22:01:14 +02003515 if (startcol > 0)
3516 set_completion(startcol - 1, argvars[1].vval.v_list);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003517 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003518}
3519
3520/*
3521 * "complete_add()" function
3522 */
3523 void
3524f_complete_add(typval_T *argvars, typval_T *rettv)
3525{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003526 if (in_vim9script() && check_for_string_or_dict_arg(argvars, 0) == FAIL)
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003527 return;
3528
Bram Moolenaar440cf092021-04-03 20:13:30 +02003529 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0, FALSE);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003530}
3531
3532/*
3533 * "complete_check()" function
3534 */
3535 void
3536f_complete_check(typval_T *argvars UNUSED, typval_T *rettv)
3537{
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003538 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003539 RedrawingDisabled = 0;
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003540
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003541 ins_compl_check_keys(0, TRUE);
3542 rettv->vval.v_number = ins_compl_interrupted();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003543
3544 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003545}
3546
3547/*
glepnirbcd59952025-04-24 21:48:35 +02003548 * Add match item to the return list.
3549 * Returns FAIL if out of memory, OK otherwise.
3550 */
3551 static int
3552add_match_to_list(
3553 typval_T *rettv,
3554 char_u *str,
3555 int len,
3556 int pos)
3557{
3558 list_T *match;
3559 int ret;
3560
3561 match = list_alloc();
3562 if (match == NULL)
Hirohito Higashi355db992025-04-28 18:07:02 +02003563 return FAIL;
glepnirbcd59952025-04-24 21:48:35 +02003564
3565 if ((ret = list_append_number(match, pos + 1)) == FAIL
3566 || (ret = list_append_string(match, str, len)) == FAIL
3567 || (ret = list_append_list(rettv->vval.v_list, match)) == FAIL)
3568 {
Hirohito Higashi355db992025-04-28 18:07:02 +02003569 vim_free(match);
3570 return FAIL;
glepnirbcd59952025-04-24 21:48:35 +02003571 }
3572
3573 return OK;
3574}
3575
3576/*
3577 * "complete_match()" function
3578 */
3579 void
3580f_complete_match(typval_T *argvars, typval_T *rettv)
3581{
3582 linenr_T lnum;
3583 colnr_T col;
3584 char_u *line = NULL;
3585 char_u *ise = NULL;
3586 regmatch_T regmatch;
3587 char_u *before_cursor = NULL;
3588 char_u *cur_end = NULL;
glepnirbcd59952025-04-24 21:48:35 +02003589 int bytepos = 0;
3590 char_u part[MAXPATHL];
3591 int ret;
3592
3593 if (rettv_list_alloc(rettv) == FAIL)
3594 return;
3595
3596 ise = curbuf->b_p_ise[0] != NUL ? curbuf->b_p_ise : p_ise;
3597
3598 if (argvars[0].v_type == VAR_UNKNOWN)
3599 {
3600 lnum = curwin->w_cursor.lnum;
3601 col = curwin->w_cursor.col;
3602 }
3603 else if (argvars[1].v_type == VAR_UNKNOWN)
3604 {
3605 emsg(_(e_invalid_argument));
3606 return;
3607 }
3608 else
3609 {
3610 lnum = (linenr_T)tv_get_number(&argvars[0]);
3611 col = (colnr_T)tv_get_number(&argvars[1]);
3612 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
3613 {
3614 semsg(_(e_invalid_line_number_nr), lnum);
3615 return;
3616 }
3617 if (col < 1 || col > ml_get_buf_len(curbuf, lnum))
3618 {
3619 semsg(_(e_invalid_column_number_nr), col + 1);
3620 return;
3621 }
3622 }
3623
3624 line = ml_get_buf(curbuf, lnum, FALSE);
3625 if (line == NULL)
3626 return;
3627
3628 before_cursor = vim_strnsave(line, col);
3629 if (before_cursor == NULL)
3630 return;
3631
3632 if (ise == NULL || *ise == NUL)
3633 {
3634 regmatch.regprog = vim_regcomp((char_u *)"\\k\\+$", RE_MAGIC);
3635 if (regmatch.regprog != NULL)
3636 {
3637 if (vim_regexec_nl(&regmatch, before_cursor, (colnr_T)0))
3638 {
Christian Brabandt3accf042025-04-25 19:01:06 +02003639 char_u *trig = vim_strnsave(regmatch.startp[0],
glepnirbcd59952025-04-24 21:48:35 +02003640 regmatch.endp[0] - regmatch.startp[0]);
3641 if (trig == NULL)
3642 {
3643 vim_free(before_cursor);
Christian Brabandt3accf042025-04-25 19:01:06 +02003644 vim_regfree(regmatch.regprog);
glepnirbcd59952025-04-24 21:48:35 +02003645 return;
3646 }
3647
Christian Brabandt3accf042025-04-25 19:01:06 +02003648 bytepos = (int)(regmatch.startp[0] - before_cursor);
glepnirbcd59952025-04-24 21:48:35 +02003649 ret = add_match_to_list(rettv, trig, -1, bytepos);
3650 vim_free(trig);
3651 if (ret == FAIL)
3652 {
Christian Brabandt3accf042025-04-25 19:01:06 +02003653 vim_free(before_cursor);
glepnirbcd59952025-04-24 21:48:35 +02003654 vim_regfree(regmatch.regprog);
3655 return;
3656 }
3657 }
3658 vim_regfree(regmatch.regprog);
3659 }
3660 }
3661 else
3662 {
3663 char_u *p = ise;
3664 cur_end = before_cursor + (int)STRLEN(before_cursor);
3665
3666 while (*p != NUL)
3667 {
3668 int len = copy_option_part(&p, part, MAXPATHL, ",");
3669
3670 if (len > 0 && len <= col)
3671 {
3672 if (STRNCMP(cur_end - len, part, len) == 0)
3673 {
3674 bytepos = col - len;
3675 if (add_match_to_list(rettv, part, len, bytepos) == FAIL)
3676 {
3677 vim_free(before_cursor);
3678 return;
3679 }
3680 }
3681 }
3682 }
3683 }
3684
3685 vim_free(before_cursor);
3686}
3687
3688/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003689 * Return Insert completion mode name string
3690 */
3691 static char_u *
3692ins_compl_mode(void)
3693{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003694 if (ctrl_x_mode_not_defined_yet() || ctrl_x_mode_scroll() || compl_started)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003695 return (char_u *)ctrl_x_mode_names[ctrl_x_mode & ~CTRL_X_WANT_IDENT];
3696
3697 return (char_u *)"";
3698}
3699
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00003700/*
3701 * Assign the sequence number to all the completion matches which don't have
3702 * one assigned yet.
3703 */
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003704 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003705ins_compl_update_sequence_numbers(void)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003706{
3707 int number = 0;
3708 compl_T *match;
3709
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003710 if (compl_dir_forward())
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003711 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003712 // Search backwards for the first valid (!= -1) number.
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003713 // This should normally succeed already at the first loop
3714 // cycle, so it's fast!
3715 for (match = compl_curr_match->cp_prev; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003716 && !is_first_match(match); match = match->cp_prev)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003717 if (match->cp_number != -1)
3718 {
3719 number = match->cp_number;
3720 break;
3721 }
3722 if (match != NULL)
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003723 // go up and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003724 for (match = match->cp_next;
3725 match != NULL && match->cp_number == -1;
3726 match = match->cp_next)
3727 match->cp_number = ++number;
3728 }
3729 else // BACKWARD
3730 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003731 // Search forwards (upwards) for the first valid (!= -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003732 // number. This should normally succeed already at the
3733 // first loop cycle, so it's fast!
3734 for (match = compl_curr_match->cp_next; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003735 && !is_first_match(match); match = match->cp_next)
glepnir40891ba2025-02-10 22:18:00 +01003736 {
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003737 if (match->cp_number != -1)
3738 {
3739 number = match->cp_number;
3740 break;
3741 }
glepnir40891ba2025-02-10 22:18:00 +01003742 }
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003743 if (match != NULL)
glepnir40891ba2025-02-10 22:18:00 +01003744 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003745 // go down and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003746 for (match = match->cp_prev; match
3747 && match->cp_number == -1;
3748 match = match->cp_prev)
3749 match->cp_number = ++number;
glepnir40891ba2025-02-10 22:18:00 +01003750 }
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003751 }
3752}
3753
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003754/*
glepnir037b0282025-01-16 14:37:44 +01003755 * Fill the dict of complete_info
3756 */
3757 static void
3758fill_complete_info_dict(dict_T *di, compl_T *match, int add_match)
3759{
3760 dict_add_string(di, "word", match->cp_str.string);
3761 dict_add_string(di, "abbr", match->cp_text[CPT_ABBR]);
3762 dict_add_string(di, "menu", match->cp_text[CPT_MENU]);
3763 dict_add_string(di, "kind", match->cp_text[CPT_KIND]);
3764 dict_add_string(di, "info", match->cp_text[CPT_INFO]);
3765 if (add_match)
Hirohito Higashi355db992025-04-28 18:07:02 +02003766 dict_add_bool(di, "match", match->cp_in_match_array);
glepnir037b0282025-01-16 14:37:44 +01003767 if (match->cp_user_data.v_type == VAR_UNKNOWN)
Hirohito Higashi355db992025-04-28 18:07:02 +02003768 // Add an empty string for backwards compatibility
3769 dict_add_string(di, "user_data", (char_u *)"");
glepnir037b0282025-01-16 14:37:44 +01003770 else
Hirohito Higashi355db992025-04-28 18:07:02 +02003771 dict_add_tv(di, "user_data", &match->cp_user_data);
glepnir037b0282025-01-16 14:37:44 +01003772}
3773
3774/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003775 * Get complete information
3776 */
3777 static void
3778get_complete_info(list_T *what_list, dict_T *retdict)
3779{
3780 int ret = OK;
3781 listitem_T *item;
3782#define CI_WHAT_MODE 0x01
3783#define CI_WHAT_PUM_VISIBLE 0x02
3784#define CI_WHAT_ITEMS 0x04
3785#define CI_WHAT_SELECTED 0x08
glepnir037b0282025-01-16 14:37:44 +01003786#define CI_WHAT_COMPLETED 0x10
glepnird4088ed2024-12-31 10:55:22 +01003787#define CI_WHAT_MATCHES 0x20
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003788#define CI_WHAT_ALL 0xff
3789 int what_flag;
Girish Palya0ac1eb32025-04-16 20:18:33 +02003790 int compl_fuzzy_match = (get_cot_flags() & COT_FUZZY) != 0;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003791
3792 if (what_list == NULL)
glepnir037b0282025-01-16 14:37:44 +01003793 what_flag = CI_WHAT_ALL & ~(CI_WHAT_MATCHES | CI_WHAT_COMPLETED);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003794 else
3795 {
3796 what_flag = 0;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003797 CHECK_LIST_MATERIALIZE(what_list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003798 FOR_ALL_LIST_ITEMS(what_list, item)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003799 {
3800 char_u *what = tv_get_string(&item->li_tv);
3801
3802 if (STRCMP(what, "mode") == 0)
3803 what_flag |= CI_WHAT_MODE;
3804 else if (STRCMP(what, "pum_visible") == 0)
3805 what_flag |= CI_WHAT_PUM_VISIBLE;
3806 else if (STRCMP(what, "items") == 0)
3807 what_flag |= CI_WHAT_ITEMS;
3808 else if (STRCMP(what, "selected") == 0)
3809 what_flag |= CI_WHAT_SELECTED;
glepnir037b0282025-01-16 14:37:44 +01003810 else if (STRCMP(what, "completed") == 0)
3811 what_flag |= CI_WHAT_COMPLETED;
glepnird4088ed2024-12-31 10:55:22 +01003812 else if (STRCMP(what, "matches") == 0)
3813 what_flag |= CI_WHAT_MATCHES;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003814 }
3815 }
3816
3817 if (ret == OK && (what_flag & CI_WHAT_MODE))
3818 ret = dict_add_string(retdict, "mode", ins_compl_mode());
3819
3820 if (ret == OK && (what_flag & CI_WHAT_PUM_VISIBLE))
3821 ret = dict_add_number(retdict, "pum_visible", pum_visible());
3822
glepnir037b0282025-01-16 14:37:44 +01003823 if (ret == OK && (what_flag & (CI_WHAT_ITEMS | CI_WHAT_SELECTED
3824 | CI_WHAT_MATCHES | CI_WHAT_COMPLETED)))
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003825 {
Christian Brabandt9eb236f2024-03-21 20:12:59 +01003826 list_T *li = NULL;
Girish Palya8950bf72024-03-20 20:07:29 +01003827 dict_T *di;
3828 compl_T *match;
3829 int selected_idx = -1;
glepnird4088ed2024-12-31 10:55:22 +01003830 int has_items = what_flag & CI_WHAT_ITEMS;
3831 int has_matches = what_flag & CI_WHAT_MATCHES;
glepnir037b0282025-01-16 14:37:44 +01003832 int has_completed = what_flag & CI_WHAT_COMPLETED;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003833
glepnird4088ed2024-12-31 10:55:22 +01003834 if (has_items || has_matches)
Girish Palya8950bf72024-03-20 20:07:29 +01003835 {
3836 li = list_alloc();
3837 if (li == NULL)
3838 return;
glepnird4088ed2024-12-31 10:55:22 +01003839 ret = dict_add_list(retdict, (has_matches && !has_items)
3840 ? "matches" : "items", li);
Girish Palya8950bf72024-03-20 20:07:29 +01003841 }
3842 if (ret == OK && what_flag & CI_WHAT_SELECTED)
3843 if (compl_curr_match != NULL && compl_curr_match->cp_number == -1)
3844 ins_compl_update_sequence_numbers();
3845 if (ret == OK && compl_first_match != NULL)
3846 {
3847 int list_idx = 0;
3848 match = compl_first_match;
3849 do
3850 {
3851 if (!match_at_original_text(match))
3852 {
glepnird4088ed2024-12-31 10:55:22 +01003853 if (has_items
3854 || (has_matches && match->cp_in_match_array))
Girish Palya8950bf72024-03-20 20:07:29 +01003855 {
3856 di = dict_alloc();
3857 if (di == NULL)
3858 return;
3859 ret = list_append_dict(li, di);
3860 if (ret != OK)
3861 return;
glepnir037b0282025-01-16 14:37:44 +01003862 fill_complete_info_dict(di, match, has_matches && has_items);
Girish Palya8950bf72024-03-20 20:07:29 +01003863 }
glepnird4088ed2024-12-31 10:55:22 +01003864 if (compl_curr_match != NULL
3865 && compl_curr_match->cp_number == match->cp_number)
Girish Palya8950bf72024-03-20 20:07:29 +01003866 selected_idx = list_idx;
Girish Palya0ac1eb32025-04-16 20:18:33 +02003867 if (compl_fuzzy_match || match->cp_in_match_array)
3868 list_idx += 1;
Girish Palya8950bf72024-03-20 20:07:29 +01003869 }
3870 match = match->cp_next;
3871 }
3872 while (match != NULL && !is_first_match(match));
3873 }
3874 if (ret == OK && (what_flag & CI_WHAT_SELECTED))
3875 ret = dict_add_number(retdict, "selected", selected_idx);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003876
glepnir037b0282025-01-16 14:37:44 +01003877 if (ret == OK && selected_idx != -1 && has_completed)
3878 {
3879 di = dict_alloc();
3880 if (di == NULL)
3881 return;
3882 fill_complete_info_dict(di, compl_curr_match, FALSE);
3883 ret = dict_add_dict(retdict, "completed", di);
3884 }
Yegappan Lakshmanan6b085b92022-09-04 12:47:21 +01003885 }
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003886}
3887
3888/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003889 * "complete_info()" function
3890 */
3891 void
3892f_complete_info(typval_T *argvars, typval_T *rettv)
3893{
3894 list_T *what_list = NULL;
3895
Bram Moolenaar93a10962022-06-16 11:42:09 +01003896 if (rettv_dict_alloc(rettv) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003897 return;
3898
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003899 if (in_vim9script() && check_for_opt_list_arg(argvars, 0) == FAIL)
3900 return;
3901
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003902 if (argvars[0].v_type != VAR_UNKNOWN)
3903 {
Bram Moolenaard83392a2022-09-01 12:22:46 +01003904 if (check_for_list_arg(argvars, 0) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003905 return;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003906 what_list = argvars[0].vval.v_list;
3907 }
3908 get_complete_info(what_list, rettv->vval.v_dict);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003909}
3910#endif
3911
3912/*
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003913 * Returns TRUE when using a user-defined function for thesaurus completion.
3914 */
3915 static int
3916thesaurus_func_complete(int type UNUSED)
3917{
3918#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01003919 return type == CTRL_X_THESAURUS
3920 && (*curbuf->b_p_tsrfu != NUL || *p_tsrfu != NUL);
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003921#else
3922 return FALSE;
3923#endif
3924}
3925
3926/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003927 * Return value of process_next_cpt_value()
3928 */
3929enum
3930{
3931 INS_COMPL_CPT_OK = 1,
3932 INS_COMPL_CPT_CONT,
3933 INS_COMPL_CPT_END
3934};
3935
3936/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003937 * state information used for getting the next set of insert completion
3938 * matches.
3939 */
3940typedef struct
3941{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003942 char_u *e_cpt_copy; // copy of 'complete'
3943 char_u *e_cpt; // current entry in "e_cpt_copy"
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003944 buf_T *ins_buf; // buffer being scanned
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003945 pos_T *cur_match_pos; // current match position
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003946 pos_T prev_match_pos; // previous match position
3947 int set_match_pos; // save first_match_pos/last_match_pos
3948 pos_T first_match_pos; // first match position
3949 pos_T last_match_pos; // last match position
3950 int found_all; // found all matches of a certain type.
3951 char_u *dict; // dictionary file to search
3952 int dict_f; // "dict" is an exact file name or not
Girish Palyacbe53192025-04-14 22:13:15 +02003953 callback_T *func_cb; // callback of function in 'cpt' option
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003954} ins_compl_next_state_T;
3955
3956/*
3957 * Process the next 'complete' option value in st->e_cpt.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003958 *
3959 * If successful, the arguments are set as below:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003960 * st->cpt - pointer to the next option value in "st->cpt"
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003961 * compl_type_arg - type of insert mode completion to use
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003962 * st->found_all - all matches of this type are found
3963 * st->ins_buf - search for completions in this buffer
3964 * st->first_match_pos - position of the first completion match
3965 * st->last_match_pos - position of the last completion match
3966 * st->set_match_pos - TRUE if the first match position should be saved to
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01003967 * avoid loops after the search wraps around.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003968 * st->dict - name of the dictionary or thesaurus file to search
3969 * st->dict_f - flag specifying whether "dict" is an exact file name or not
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003970 *
3971 * Returns INS_COMPL_CPT_OK if the next value is processed successfully.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003972 * Returns INS_COMPL_CPT_CONT to skip the current completion source matching
3973 * the "st->e_cpt" option value and process the next matching source.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003974 * Returns INS_COMPL_CPT_END if all the values in "st->e_cpt" are processed.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003975 */
3976 static int
3977process_next_cpt_value(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003978 ins_compl_next_state_T *st,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003979 int *compl_type_arg,
glepnir8159fb12024-07-17 20:32:54 +02003980 pos_T *start_match_pos,
glepnir53b14572025-03-12 21:28:39 +01003981 int fuzzy_collect)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003982{
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003983 int compl_type = -1;
3984 int status = INS_COMPL_CPT_OK;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003985
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003986 st->found_all = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003987
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003988 while (*st->e_cpt == ',' || *st->e_cpt == ' ')
3989 st->e_cpt++;
3990
3991 if (*st->e_cpt == '.' && !curbuf->b_scanned)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003992 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003993 st->ins_buf = curbuf;
3994 st->first_match_pos = *start_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003995 // Move the cursor back one character so that ^N can match the
3996 // word immediately after the cursor.
glepnir53b14572025-03-12 21:28:39 +01003997 if (ctrl_x_mode_normal() && (!fuzzy_collect && dec(&st->first_match_pos) < 0))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003998 {
3999 // Move the cursor to after the last character in the
4000 // buffer, so that word at start of buffer is found
4001 // correctly.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004002 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count;
zeertzjq94b7c322024-03-12 21:50:32 +01004003 st->first_match_pos.col = ml_get_len(st->first_match_pos.lnum);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004004 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004005 st->last_match_pos = st->first_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004006 compl_type = 0;
4007
4008 // Remember the first match so that the loop stops when we
4009 // wrap and come back there a second time.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004010 st->set_match_pos = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004011 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004012 else if (vim_strchr((char_u *)"buwU", *st->e_cpt) != NULL
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004013 && (st->ins_buf = ins_compl_next_buf(
4014 st->ins_buf, *st->e_cpt)) != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004015 {
4016 // Scan a buffer, but not the current one.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004017 if (st->ins_buf->b_ml.ml_mfp != NULL) // loaded buffer
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004018 {
4019 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004020 st->first_match_pos.col = st->last_match_pos.col = 0;
4021 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count + 1;
4022 st->last_match_pos.lnum = 0;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004023 compl_type = 0;
4024 }
4025 else // unloaded buffer, scan like dictionary
4026 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004027 st->found_all = TRUE;
4028 if (st->ins_buf->b_fname == NULL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004029 {
4030 status = INS_COMPL_CPT_CONT;
4031 goto done;
4032 }
4033 compl_type = CTRL_X_DICTIONARY;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004034 st->dict = st->ins_buf->b_fname;
4035 st->dict_f = DICT_EXACT;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004036 }
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01004037 if (!shortmess(SHM_COMPLETIONSCAN))
4038 {
4039 msg_hist_off = TRUE; // reset in msg_trunc_attr()
4040 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning: %s"),
4041 st->ins_buf->b_fname == NULL
4042 ? buf_spname(st->ins_buf)
4043 : st->ins_buf->b_sfname == NULL
4044 ? st->ins_buf->b_fname
4045 : st->ins_buf->b_sfname);
4046 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
4047 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004048 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004049 else if (*st->e_cpt == NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004050 status = INS_COMPL_CPT_END;
4051 else
4052 {
4053 if (ctrl_x_mode_line_or_eval())
4054 compl_type = -1;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004055 else if (*st->e_cpt == 'k' || *st->e_cpt == 's')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004056 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004057 if (*st->e_cpt == 'k')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004058 compl_type = CTRL_X_DICTIONARY;
4059 else
4060 compl_type = CTRL_X_THESAURUS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004061 if (*++st->e_cpt != ',' && *st->e_cpt != NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004062 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004063 st->dict = st->e_cpt;
4064 st->dict_f = DICT_FIRST;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004065 }
4066 }
Girish Palyacbe53192025-04-14 22:13:15 +02004067#ifdef FEAT_COMPL_FUNC
4068 else if (*st->e_cpt == 'f' || *st->e_cpt == 'o')
4069 {
4070 compl_type = CTRL_X_FUNCTION;
4071 if (*st->e_cpt == 'o')
4072 st->func_cb = &curbuf->b_ofu_cb;
4073 else
4074 st->func_cb = (*++st->e_cpt != ',' && *st->e_cpt != NUL)
4075 ? get_cpt_func_callback(st->e_cpt) : &curbuf->b_cfu_cb;
4076 if (!st->func_cb)
4077 compl_type = -1;
4078 }
4079#endif
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004080#ifdef FEAT_FIND_ID
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004081 else if (*st->e_cpt == 'i')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004082 compl_type = CTRL_X_PATH_PATTERNS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004083 else if (*st->e_cpt == 'd')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004084 compl_type = CTRL_X_PATH_DEFINES;
4085#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004086 else if (*st->e_cpt == ']' || *st->e_cpt == 't')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004087 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004088 compl_type = CTRL_X_TAGS;
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01004089 if (!shortmess(SHM_COMPLETIONSCAN))
4090 {
4091 msg_hist_off = TRUE; // reset in msg_trunc_attr()
4092 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning tags."));
4093 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
4094 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004095 }
4096 else
4097 compl_type = -1;
4098
4099 // in any case e_cpt is advanced to the next entry
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004100 (void)copy_option_part(&st->e_cpt, IObuff, IOSIZE, ",");
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004101
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004102 st->found_all = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004103 if (compl_type == -1)
4104 status = INS_COMPL_CPT_CONT;
4105 }
4106
4107done:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004108 *compl_type_arg = compl_type;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004109 return status;
4110}
4111
4112#ifdef FEAT_FIND_ID
4113/*
4114 * Get the next set of identifiers or defines matching "compl_pattern" in
4115 * included files.
4116 */
4117 static void
4118get_next_include_file_completion(int compl_type)
4119{
John Marriott5e6ea922024-11-23 14:01:57 +01004120 find_pattern_in_path(compl_pattern.string, compl_direction,
4121 (int)compl_pattern.length, FALSE, FALSE,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004122 (compl_type == CTRL_X_PATH_DEFINES
4123 && !(compl_cont_status & CONT_SOL))
4124 ? FIND_DEFINE : FIND_ANY, 1L, ACTION_EXPAND,
Colin Kennedy21570352024-03-03 16:16:47 +01004125 (linenr_T)1, (linenr_T)MAXLNUM, FALSE);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004126}
4127#endif
4128
4129/*
4130 * Get the next set of words matching "compl_pattern" in dictionary or
4131 * thesaurus files.
4132 */
4133 static void
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004134get_next_dict_tsr_completion(int compl_type, char_u *dict, int dict_f)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004135{
4136#ifdef FEAT_COMPL_FUNC
4137 if (thesaurus_func_complete(compl_type))
Girish Palyacbe53192025-04-14 22:13:15 +02004138 expand_by_function(compl_type, compl_pattern.string, NULL);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004139 else
4140#endif
4141 ins_compl_dictionaries(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004142 dict != NULL ? dict
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004143 : (compl_type == CTRL_X_THESAURUS
4144 ? (*curbuf->b_p_tsr == NUL ? p_tsr : curbuf->b_p_tsr)
4145 : (*curbuf->b_p_dict == NUL ? p_dict : curbuf->b_p_dict)),
John Marriott5e6ea922024-11-23 14:01:57 +01004146 compl_pattern.string,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004147 dict != NULL ? dict_f : 0,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004148 compl_type == CTRL_X_THESAURUS);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004149}
4150
4151/*
4152 * Get the next set of tag names matching "compl_pattern".
4153 */
4154 static void
4155get_next_tag_completion(void)
4156{
4157 int save_p_ic;
4158 char_u **matches;
4159 int num_matches;
4160
4161 // set p_ic according to p_ic, p_scs and pat for find_tags().
4162 save_p_ic = p_ic;
John Marriott5e6ea922024-11-23 14:01:57 +01004163 p_ic = ignorecase(compl_pattern.string);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004164
4165 // Find up to TAG_MANY matches. Avoids that an enormous number
4166 // of matches is found when compl_pattern is empty
4167 g_tag_at_cursor = TRUE;
John Marriott5e6ea922024-11-23 14:01:57 +01004168 if (find_tags(compl_pattern.string, &num_matches, &matches,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004169 TAG_REGEXP | TAG_NAMES | TAG_NOIC | TAG_INS_COMP
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004170 | (ctrl_x_mode_not_default() ? TAG_VERBOSE : 0),
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004171 TAG_MANY, curbuf->b_ffname) == OK && num_matches > 0)
4172 ins_compl_add_matches(num_matches, matches, p_ic);
4173 g_tag_at_cursor = FALSE;
4174 p_ic = save_p_ic;
4175}
4176
4177/*
glepnir8159fb12024-07-17 20:32:54 +02004178 * Compare function for qsort
4179 */
glepnirf31cfa22025-03-06 21:59:13 +01004180 static int
4181compare_scores(const void *a, const void *b)
glepnir8159fb12024-07-17 20:32:54 +02004182{
4183 int idx_a = *(const int *)a;
4184 int idx_b = *(const int *)b;
4185 int score_a = compl_fuzzy_scores[idx_a];
4186 int score_b = compl_fuzzy_scores[idx_b];
zeertzjq58d70522024-08-31 17:05:39 +02004187 return score_a == score_b ? (idx_a == idx_b ? 0 : (idx_a < idx_b ? -1 : 1))
4188 : (score_a > score_b ? -1 : 1);
glepnir8159fb12024-07-17 20:32:54 +02004189}
4190
4191/*
glepnirf31cfa22025-03-06 21:59:13 +01004192 * insert prefix with redraw
4193 */
4194 static void
4195ins_compl_longest_insert(char_u *prefix)
4196{
4197 ins_compl_delete();
4198 ins_compl_insert_bytes(prefix + get_compl_len(), -1);
4199 ins_redraw(FALSE);
4200}
4201
4202/*
4203 * Calculate the longest common prefix among the best fuzzy matches
4204 * stored in compl_best_matches, and insert it as the longest.
4205 */
4206 static void
4207fuzzy_longest_match(void)
4208{
4209 char_u *prefix = NULL;
4210 int prefix_len = 0;
4211 int i = 0;
4212 int j = 0;
4213 char_u *match_str = NULL;
4214 char_u *prefix_ptr = NULL;
4215 char_u *match_ptr = NULL;
4216 char_u *leader = NULL;
4217 size_t leader_len = 0;
4218 compl_T *compl = NULL;
4219 int more_candidates = FALSE;
4220 compl_T *nn_compl = NULL;
4221
4222 if (compl_num_bests == 0)
Hirohito Higashi355db992025-04-28 18:07:02 +02004223 return;
glepnirf31cfa22025-03-06 21:59:13 +01004224
4225 nn_compl = compl_first_match->cp_next->cp_next;
4226 if (nn_compl && nn_compl != compl_first_match)
4227 more_candidates = TRUE;
4228
4229 compl = ctrl_x_mode_whole_line() ? compl_first_match
4230 : compl_first_match->cp_next;
4231 if (compl_num_bests == 1)
4232 {
4233 // no more candidates insert the match str
4234 if (!more_candidates)
4235 {
4236 ins_compl_longest_insert(compl->cp_str.string);
4237 compl_num_bests = 0;
4238 }
4239 compl_num_bests = 0;
4240 return;
4241 }
4242
4243 compl_best_matches = (compl_T **)alloc(compl_num_bests * sizeof(compl_T *));
4244 if (compl_best_matches == NULL)
Hirohito Higashi355db992025-04-28 18:07:02 +02004245 return;
glepnirf31cfa22025-03-06 21:59:13 +01004246 while (compl != NULL && i < compl_num_bests)
4247 {
Hirohito Higashi355db992025-04-28 18:07:02 +02004248 compl_best_matches[i] = compl;
4249 compl = compl->cp_next;
4250 i++;
glepnirf31cfa22025-03-06 21:59:13 +01004251 }
4252
4253 prefix = compl_best_matches[0]->cp_str.string;
zeertzjq4422de62025-03-07 19:06:02 +01004254 prefix_len = (int)compl_best_matches[0]->cp_str.length;
glepnirf31cfa22025-03-06 21:59:13 +01004255
4256 for (i = 1; i < compl_num_bests; i++)
4257 {
4258 match_str = compl_best_matches[i]->cp_str.string;
Hirohito Higashi355db992025-04-28 18:07:02 +02004259 prefix_ptr = prefix;
4260 match_ptr = match_str;
4261 j = 0;
glepnirf31cfa22025-03-06 21:59:13 +01004262
4263 while (j < prefix_len && *match_ptr != NUL && *prefix_ptr != NUL)
4264 {
4265 if (STRNCMP(prefix_ptr, match_ptr, mb_ptr2len(prefix_ptr)) != 0)
4266 break;
4267
4268 MB_PTR_ADV(prefix_ptr);
4269 MB_PTR_ADV(match_ptr);
4270 j++;
4271 }
4272
4273 if (j > 0)
4274 prefix_len = j;
4275 }
4276
4277 leader = ins_compl_leader();
zeertzjq4422de62025-03-07 19:06:02 +01004278 leader_len = ins_compl_leader_len();
glepnirf31cfa22025-03-06 21:59:13 +01004279
4280 // skip non-consecutive prefixes
zeertzjq4422de62025-03-07 19:06:02 +01004281 if (leader_len > 0 && STRNCMP(prefix, leader, leader_len) != 0)
glepnirf31cfa22025-03-06 21:59:13 +01004282 goto end;
4283
zeertzjq4422de62025-03-07 19:06:02 +01004284 prefix = vim_strnsave(prefix, prefix_len);
glepnirf31cfa22025-03-06 21:59:13 +01004285 if (prefix != NULL)
4286 {
4287 ins_compl_longest_insert(prefix);
4288 compl_cfc_longest_ins = TRUE;
4289 vim_free(prefix);
4290 }
4291
4292end:
4293 vim_free(compl_best_matches);
4294 compl_best_matches = NULL;
4295 compl_num_bests = 0;
4296}
4297
4298/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004299 * Get the next set of filename matching "compl_pattern".
4300 */
4301 static void
4302get_next_filename_completion(void)
4303{
4304 char_u **matches;
4305 int num_matches;
glepnir8159fb12024-07-17 20:32:54 +02004306 char_u *ptr;
4307 garray_T fuzzy_indices;
4308 int i;
4309 int score;
4310 char_u *leader = ins_compl_leader();
John Marriott5e6ea922024-11-23 14:01:57 +01004311 size_t leader_len = ins_compl_leader_len();;
glepnirf31cfa22025-03-06 21:59:13 +01004312 int in_fuzzy_collect = (cfc_has_mode() && leader_len > 0);
glepnir8159fb12024-07-17 20:32:54 +02004313 int *fuzzy_indices_data;
glepnir0be03e12024-07-19 16:45:05 +02004314 char_u *last_sep = NULL;
glepnirf31cfa22025-03-06 21:59:13 +01004315 int need_collect_bests = in_fuzzy_collect && compl_get_longest;
4316 int max_score = 0;
4317 int current_score = 0;
4318 int dir = compl_direction;
glepnir8159fb12024-07-17 20:32:54 +02004319
glepnirb9de1a02024-08-02 19:14:38 +02004320#ifdef BACKSLASH_IN_FILENAME
4321 char pathsep = (curbuf->b_p_csl[0] == 's') ?
4322 '/' : (curbuf->b_p_csl[0] == 'b') ? '\\' : PATHSEP;
4323#else
4324 char pathsep = PATHSEP;
4325#endif
4326
glepnirf31cfa22025-03-06 21:59:13 +01004327 if (in_fuzzy_collect)
glepnir8159fb12024-07-17 20:32:54 +02004328 {
glepnirb9de1a02024-08-02 19:14:38 +02004329#ifdef BACKSLASH_IN_FILENAME
4330 if (curbuf->b_p_csl[0] == 's')
4331 {
John Marriott5e6ea922024-11-23 14:01:57 +01004332 for (i = 0; i < (int)leader_len; i++)
glepnirb9de1a02024-08-02 19:14:38 +02004333 {
4334 if (leader[i] == '\\')
4335 leader[i] = '/';
4336 }
4337 }
4338 else if (curbuf->b_p_csl[0] == 'b')
4339 {
John Marriott5e6ea922024-11-23 14:01:57 +01004340 for (i = 0; i < (int)leader_len; i++)
glepnirb9de1a02024-08-02 19:14:38 +02004341 {
4342 if (leader[i] == '/')
4343 leader[i] = '\\';
4344 }
4345 }
4346#endif
4347 last_sep = vim_strrchr(leader, pathsep);
glepnir0be03e12024-07-19 16:45:05 +02004348 if (last_sep == NULL)
4349 {
4350 // No path separator or separator is the last character,
4351 // fuzzy match the whole leader
John Marriott5e6ea922024-11-23 14:01:57 +01004352 VIM_CLEAR_STRING(compl_pattern);
4353 compl_pattern.string = vim_strnsave((char_u *)"*", 1);
4354 if (compl_pattern.string == NULL)
4355 return;
4356 compl_pattern.length = 1;
glepnir0be03e12024-07-19 16:45:05 +02004357 }
4358 else if (*(last_sep + 1) == '\0')
glepnirf31cfa22025-03-06 21:59:13 +01004359 in_fuzzy_collect = FALSE;
glepnir0be03e12024-07-19 16:45:05 +02004360 else
4361 {
4362 // Split leader into path and file parts
4363 int path_len = last_sep - leader + 1;
John Marriott5e6ea922024-11-23 14:01:57 +01004364 char_u *path_with_wildcard;
4365
4366 path_with_wildcard = alloc(path_len + 2);
glepnir0be03e12024-07-19 16:45:05 +02004367 if (path_with_wildcard != NULL)
4368 {
John Marriott5e6ea922024-11-23 14:01:57 +01004369 vim_snprintf((char *)path_with_wildcard, path_len + 2, "%*.*s*", path_len, path_len, leader);
4370 VIM_CLEAR_STRING(compl_pattern);
4371 compl_pattern.string = path_with_wildcard;
4372 compl_pattern.length = path_len + 1;
glepnir0be03e12024-07-19 16:45:05 +02004373
4374 // Move leader to the file part
4375 leader = last_sep + 1;
John Marriott5e6ea922024-11-23 14:01:57 +01004376 leader_len -= path_len;
glepnir0be03e12024-07-19 16:45:05 +02004377 }
4378 }
glepnir8159fb12024-07-17 20:32:54 +02004379 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004380
John Marriott5e6ea922024-11-23 14:01:57 +01004381 if (expand_wildcards(1, &compl_pattern.string, &num_matches, &matches,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004382 EW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) != OK)
4383 return;
4384
4385 // May change home directory back to "~".
John Marriott5e6ea922024-11-23 14:01:57 +01004386 tilde_replace(compl_pattern.string, num_matches, matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004387#ifdef BACKSLASH_IN_FILENAME
4388 if (curbuf->b_p_csl[0] != NUL)
4389 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004390 for (i = 0; i < num_matches; ++i)
4391 {
glepnir8159fb12024-07-17 20:32:54 +02004392 ptr = matches[i];
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004393 while (*ptr != NUL)
4394 {
4395 if (curbuf->b_p_csl[0] == 's' && *ptr == '\\')
4396 *ptr = '/';
4397 else if (curbuf->b_p_csl[0] == 'b' && *ptr == '/')
4398 *ptr = '\\';
4399 ptr += (*mb_ptr2len)(ptr);
4400 }
4401 }
4402 }
4403#endif
glepnir8159fb12024-07-17 20:32:54 +02004404
glepnirf31cfa22025-03-06 21:59:13 +01004405 if (in_fuzzy_collect)
glepnir8159fb12024-07-17 20:32:54 +02004406 {
4407 ga_init2(&fuzzy_indices, sizeof(int), 10);
4408 compl_fuzzy_scores = (int *)alloc(sizeof(int) * num_matches);
4409
4410 for (i = 0; i < num_matches; i++)
4411 {
4412 ptr = matches[i];
4413 score = fuzzy_match_str(ptr, leader);
4414 if (score > 0)
4415 {
4416 if (ga_grow(&fuzzy_indices, 1) == OK)
4417 {
4418 ((int *)fuzzy_indices.ga_data)[fuzzy_indices.ga_len] = i;
4419 compl_fuzzy_scores[i] = score;
4420 fuzzy_indices.ga_len++;
4421 }
4422 }
4423 }
4424
Christian Brabandt220474d2024-07-20 13:26:44 +02004425 // prevent qsort from deref NULL pointer
4426 if (fuzzy_indices.ga_len > 0)
4427 {
glepnirf31cfa22025-03-06 21:59:13 +01004428 char_u *match = NULL;
Christian Brabandt220474d2024-07-20 13:26:44 +02004429 fuzzy_indices_data = (int *)fuzzy_indices.ga_data;
4430 qsort(fuzzy_indices_data, fuzzy_indices.ga_len, sizeof(int), compare_scores);
glepnir8159fb12024-07-17 20:32:54 +02004431
Christian Brabandt220474d2024-07-20 13:26:44 +02004432 for (i = 0; i < fuzzy_indices.ga_len; ++i)
glepnirf31cfa22025-03-06 21:59:13 +01004433 {
Hirohito Higashi355db992025-04-28 18:07:02 +02004434 match = matches[fuzzy_indices_data[i]];
glepnirf31cfa22025-03-06 21:59:13 +01004435 current_score = compl_fuzzy_scores[fuzzy_indices_data[i]];
4436 if (ins_compl_add(match, -1, NULL, NULL, NULL, dir,
Hirohito Higashi355db992025-04-28 18:07:02 +02004437 CP_FAST | ((p_fic || p_wic) ? CP_ICASE : 0),
4438 FALSE, NULL, current_score) == OK)
glepnirf31cfa22025-03-06 21:59:13 +01004439 dir = FORWARD;
4440
4441 if (need_collect_bests)
4442 {
4443 if (i == 0 || current_score == max_score)
4444 {
4445 compl_num_bests++;
4446 max_score = current_score;
4447 }
4448 }
4449 }
glepnir8159fb12024-07-17 20:32:54 +02004450
Christian Brabandt220474d2024-07-20 13:26:44 +02004451 FreeWild(num_matches, matches);
Christian Brabandt220474d2024-07-20 13:26:44 +02004452 }
glepnir6b6280c2024-07-27 16:25:45 +02004453 else if (leader_len > 0)
4454 {
4455 FreeWild(num_matches, matches);
4456 num_matches = 0;
4457 }
Christian Brabandt220474d2024-07-20 13:26:44 +02004458
glepnir8159fb12024-07-17 20:32:54 +02004459 vim_free(compl_fuzzy_scores);
4460 ga_clear(&fuzzy_indices);
glepnirf31cfa22025-03-06 21:59:13 +01004461
4462 if (compl_num_bests > 0 && compl_get_longest)
4463 fuzzy_longest_match();
4464 return;
glepnir8159fb12024-07-17 20:32:54 +02004465 }
4466
glepnir6b6280c2024-07-27 16:25:45 +02004467 if (num_matches > 0)
4468 ins_compl_add_matches(num_matches, matches, p_fic || p_wic);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004469}
4470
4471/*
4472 * Get the next set of command-line completions matching "compl_pattern".
4473 */
4474 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00004475get_next_cmdline_completion(void)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004476{
4477 char_u **matches;
4478 int num_matches;
4479
John Marriott5e6ea922024-11-23 14:01:57 +01004480 if (expand_cmdline(&compl_xp, compl_pattern.string,
4481 (int)compl_pattern.length, &num_matches, &matches) == EXPAND_OK)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004482 ins_compl_add_matches(num_matches, matches, FALSE);
4483}
4484
4485/*
4486 * Get the next set of spell suggestions matching "compl_pattern".
4487 */
4488 static void
4489get_next_spell_completion(linenr_T lnum UNUSED)
4490{
4491#ifdef FEAT_SPELL
4492 char_u **matches;
4493 int num_matches;
4494
John Marriott5e6ea922024-11-23 14:01:57 +01004495 num_matches = expand_spelling(lnum, compl_pattern.string, &matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004496 if (num_matches > 0)
4497 ins_compl_add_matches(num_matches, matches, p_ic);
Bram Moolenaar8e7cc6b2021-12-30 10:32:25 +00004498 else
4499 vim_free(matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004500#endif
4501}
4502
4503/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004504 * Return the next word or line from buffer "ins_buf" at position
4505 * "cur_match_pos" for completion. The length of the match is set in "len".
4506 */
4507 static char_u *
zeertzjq440d4cb2023-03-02 17:51:32 +00004508ins_compl_get_next_word_or_line(
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004509 buf_T *ins_buf, // buffer being scanned
4510 pos_T *cur_match_pos, // current match position
4511 int *match_len,
4512 int *cont_s_ipos) // next ^X<> will set initial_pos
4513{
4514 char_u *ptr;
4515 int len;
4516
4517 *match_len = 0;
4518 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum, FALSE) +
4519 cur_match_pos->col;
John Marriott5e6ea922024-11-23 14:01:57 +01004520 len = (int)ml_get_buf_len(ins_buf, cur_match_pos->lnum) - cur_match_pos->col;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004521 if (ctrl_x_mode_line_or_eval())
4522 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004523 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004524 {
4525 if (cur_match_pos->lnum >= ins_buf->b_ml.ml_line_count)
4526 return NULL;
4527 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
John Marriott5e6ea922024-11-23 14:01:57 +01004528 len = ml_get_buf_len(ins_buf, cur_match_pos->lnum + 1);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004529 if (!p_paste)
John Marriott5e6ea922024-11-23 14:01:57 +01004530 {
4531 char_u *tmp_ptr = ptr;
4532
4533 ptr = skipwhite(tmp_ptr);
4534 len -= (int)(ptr - tmp_ptr);
4535 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004536 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004537 }
4538 else
4539 {
4540 char_u *tmp_ptr = ptr;
4541
John Marriott5e6ea922024-11-23 14:01:57 +01004542 if (compl_status_adding() && compl_length <= len)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004543 {
4544 tmp_ptr += compl_length;
4545 // Skip if already inside a word.
4546 if (vim_iswordp(tmp_ptr))
4547 return NULL;
4548 // Find start of next word.
4549 tmp_ptr = find_word_start(tmp_ptr);
4550 }
4551 // Find end of this word.
4552 tmp_ptr = find_word_end(tmp_ptr);
4553 len = (int)(tmp_ptr - ptr);
4554
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004555 if (compl_status_adding() && len == compl_length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004556 {
4557 if (cur_match_pos->lnum < ins_buf->b_ml.ml_line_count)
4558 {
4559 // Try next line, if any. the new word will be
4560 // "join" as if the normal command "J" was used.
4561 // IOSIZE is always greater than
4562 // compl_length, so the next STRNCPY always
4563 // works -- Acevedo
4564 STRNCPY(IObuff, ptr, len);
4565 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
4566 tmp_ptr = ptr = skipwhite(ptr);
4567 // Find start of next word.
4568 tmp_ptr = find_word_start(tmp_ptr);
4569 // Find end of next word.
4570 tmp_ptr = find_word_end(tmp_ptr);
4571 if (tmp_ptr > ptr)
4572 {
4573 if (*ptr != ')' && IObuff[len - 1] != TAB)
4574 {
4575 if (IObuff[len - 1] != ' ')
4576 IObuff[len++] = ' ';
4577 // IObuf =~ "\k.* ", thus len >= 2
4578 if (p_js
4579 && (IObuff[len - 2] == '.'
4580 || (vim_strchr(p_cpo, CPO_JOINSP)
4581 == NULL
4582 && (IObuff[len - 2] == '?'
4583 || IObuff[len - 2] == '!'))))
4584 IObuff[len++] = ' ';
4585 }
4586 // copy as much as possible of the new word
4587 if (tmp_ptr - ptr >= IOSIZE - len)
4588 tmp_ptr = ptr + IOSIZE - len - 1;
4589 STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);
4590 len += (int)(tmp_ptr - ptr);
4591 *cont_s_ipos = TRUE;
4592 }
4593 IObuff[len] = NUL;
4594 ptr = IObuff;
4595 }
4596 if (len == compl_length)
4597 return NULL;
4598 }
4599 }
4600
4601 *match_len = len;
4602 return ptr;
4603}
4604
4605/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004606 * Get the next set of words matching "compl_pattern" for default completion(s)
4607 * (normal ^P/^N and ^X^L).
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004608 * Search for "compl_pattern" in the buffer "st->ins_buf" starting from the
4609 * position "st->start_pos" in the "compl_direction" direction. If
4610 * "st->set_match_pos" is TRUE, then set the "st->first_match_pos" and
4611 * "st->last_match_pos".
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004612 * Returns OK if a new next match is found, otherwise returns FAIL.
4613 */
4614 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004615get_next_default_completion(ins_compl_next_state_T *st, pos_T *start_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004616{
4617 int found_new_match = FAIL;
4618 int save_p_scs;
4619 int save_p_ws;
4620 int looped_around = FALSE;
glepnir8159fb12024-07-17 20:32:54 +02004621 char_u *ptr = NULL;
4622 int len = 0;
glepnirf31cfa22025-03-06 21:59:13 +01004623 int in_collect = (cfc_has_mode() && compl_length > 0);
glepnir8159fb12024-07-17 20:32:54 +02004624 char_u *leader = ins_compl_leader();
glepnirf31cfa22025-03-06 21:59:13 +01004625 int score = 0;
Girish Palyab1565882025-04-15 20:16:00 +02004626 int in_curbuf = st->ins_buf == curbuf;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004627
4628 // If 'infercase' is set, don't use 'smartcase' here
4629 save_p_scs = p_scs;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004630 if (st->ins_buf->b_p_inf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004631 p_scs = FALSE;
4632
4633 // Buffers other than curbuf are scanned from the beginning or the
4634 // end but never from the middle, thus setting nowrapscan in this
4635 // buffer is a good idea, on the other hand, we always set
4636 // wrapscan for curbuf to avoid missing matches -- Acevedo,Webb
4637 save_p_ws = p_ws;
Girish Palyab1565882025-04-15 20:16:00 +02004638 if (!in_curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004639 p_ws = FALSE;
glepnirf31cfa22025-03-06 21:59:13 +01004640 else if (*st->e_cpt == '.')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004641 p_ws = TRUE;
4642 looped_around = FALSE;
4643 for (;;)
4644 {
4645 int cont_s_ipos = FALSE;
4646
4647 ++msg_silent; // Don't want messages for wrapscan.
4648
glepnirf31cfa22025-03-06 21:59:13 +01004649 if (in_collect)
4650 {
Hirohito Higashi355db992025-04-28 18:07:02 +02004651 found_new_match = search_for_fuzzy_match(st->ins_buf,
glepnir8159fb12024-07-17 20:32:54 +02004652 st->cur_match_pos, leader, compl_direction,
glepnirf31cfa22025-03-06 21:59:13 +01004653 start_pos, &len, &ptr, &score);
4654 }
4655 // ctrl_x_mode_line_or_eval() || word-wise search that
4656 // has added a word that was at the beginning of the line
4657 else if (ctrl_x_mode_whole_line() || ctrl_x_mode_eval() || (compl_cont_status & CONT_SOL))
4658 found_new_match = search_for_exact_line(st->ins_buf,
4659 st->cur_match_pos, compl_direction, compl_pattern.string);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004660 else
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004661 found_new_match = searchit(NULL, st->ins_buf, st->cur_match_pos,
John Marriott5e6ea922024-11-23 14:01:57 +01004662 NULL, compl_direction, compl_pattern.string, (int)compl_pattern.length,
John Marriott8c85a2a2024-05-20 19:18:26 +02004663 1L, SEARCH_KEEP + SEARCH_NFMSG, RE_LAST, NULL);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004664 --msg_silent;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004665 if (!compl_started || st->set_match_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004666 {
4667 // set "compl_started" even on fail
4668 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004669 st->first_match_pos = *st->cur_match_pos;
4670 st->last_match_pos = *st->cur_match_pos;
4671 st->set_match_pos = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004672 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004673 else if (st->first_match_pos.lnum == st->last_match_pos.lnum
4674 && st->first_match_pos.col == st->last_match_pos.col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004675 {
4676 found_new_match = FAIL;
4677 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004678 else if (compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004679 && (st->prev_match_pos.lnum > st->cur_match_pos->lnum
4680 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
4681 && st->prev_match_pos.col >= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004682 {
4683 if (looped_around)
4684 found_new_match = FAIL;
4685 else
4686 looped_around = TRUE;
4687 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004688 else if (!compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004689 && (st->prev_match_pos.lnum < st->cur_match_pos->lnum
4690 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
4691 && st->prev_match_pos.col <= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004692 {
4693 if (looped_around)
4694 found_new_match = FAIL;
4695 else
4696 looped_around = TRUE;
4697 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004698 st->prev_match_pos = *st->cur_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004699 if (found_new_match == FAIL)
4700 break;
4701
4702 // when ADDING, the text before the cursor matches, skip it
Girish Palyab1565882025-04-15 20:16:00 +02004703 if (compl_status_adding() && in_curbuf
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004704 && start_pos->lnum == st->cur_match_pos->lnum
4705 && start_pos->col == st->cur_match_pos->col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004706 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004707
glepnirf31cfa22025-03-06 21:59:13 +01004708 if (!in_collect)
glepnir8159fb12024-07-17 20:32:54 +02004709 ptr = ins_compl_get_next_word_or_line(st->ins_buf, st->cur_match_pos,
4710 &len, &cont_s_ipos);
glepnirbfb4eea2025-01-31 15:28:29 +01004711 if (ptr == NULL || (ins_compl_has_preinsert() && STRCMP(ptr, compl_pattern.string) == 0))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004712 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004713
Girish Palyab1565882025-04-15 20:16:00 +02004714 if (is_nearest_active() && in_curbuf)
4715 {
4716 score = st->cur_match_pos->lnum - curwin->w_cursor.lnum;
4717 if (score < 0)
4718 score = -score;
4719 score++;
4720 }
4721
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004722 if (ins_compl_add_infercase(ptr, len, p_ic,
Girish Palyab1565882025-04-15 20:16:00 +02004723 in_curbuf ? NULL : st->ins_buf->b_sfname,
glepnirf31cfa22025-03-06 21:59:13 +01004724 0, cont_s_ipos, score) != NOTDONE)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004725 {
glepnirf31cfa22025-03-06 21:59:13 +01004726 if (in_collect && score == compl_first_match->cp_next->cp_score)
4727 compl_num_bests++;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004728 found_new_match = OK;
4729 break;
4730 }
4731 }
4732 p_scs = save_p_scs;
4733 p_ws = save_p_ws;
4734
4735 return found_new_match;
4736}
4737
4738/*
Girish Palyacbe53192025-04-14 22:13:15 +02004739 * Return the callback function associated with "funcname".
4740 */
4741#ifdef FEAT_COMPL_FUNC
4742 static callback_T *
4743get_cpt_func_callback(char_u *funcname)
4744{
4745 static callback_T cb;
4746 char_u buf[LSIZE];
4747 int slen;
4748
4749 slen = copy_option_part(&funcname, buf, LSIZE, ",");
4750 if (slen > 0 && option_set_callback_func(buf, &cb))
4751 return &cb;
4752 return NULL;
4753}
4754
4755/*
4756 * Retrieve new completion matches by invoking callback "cb".
4757 */
4758 static void
4759expand_cpt_function(callback_T *cb)
4760{
4761 // Re-insert the text removed by ins_compl_delete().
4762 ins_compl_insert_bytes(compl_orig_text.string + get_compl_len(), -1);
4763 // Get matches
4764 get_cpt_func_completion_matches(cb);
4765 // Undo insertion
4766 ins_compl_delete();
4767}
4768#endif
4769
4770/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004771 * get the next set of completion matches for "type".
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004772 * Returns TRUE if a new match is found. Otherwise returns FALSE.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004773 */
4774 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004775get_next_completion_match(int type, ins_compl_next_state_T *st, pos_T *ini)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004776{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004777 int found_new_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004778
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004779 switch (type)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004780 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004781 case -1:
4782 break;
4783#ifdef FEAT_FIND_ID
4784 case CTRL_X_PATH_PATTERNS:
4785 case CTRL_X_PATH_DEFINES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004786 get_next_include_file_completion(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004787 break;
4788#endif
4789
4790 case CTRL_X_DICTIONARY:
4791 case CTRL_X_THESAURUS:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004792 get_next_dict_tsr_completion(type, st->dict, st->dict_f);
4793 st->dict = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004794 break;
4795
4796 case CTRL_X_TAGS:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004797 get_next_tag_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004798 break;
4799
4800 case CTRL_X_FILES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004801 get_next_filename_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004802 break;
4803
4804 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +02004805 case CTRL_X_CMDLINE_CTRL_X:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004806 get_next_cmdline_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004807 break;
4808
4809#ifdef FEAT_COMPL_FUNC
4810 case CTRL_X_FUNCTION:
Girish Palyacbe53192025-04-14 22:13:15 +02004811 if (ctrl_x_mode_normal()) // Invoked by a func in 'cpt' option
4812 expand_cpt_function(st->func_cb);
4813 else
4814 expand_by_function(type, compl_pattern.string, NULL);
4815 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004816 case CTRL_X_OMNI:
Girish Palyacbe53192025-04-14 22:13:15 +02004817 expand_by_function(type, compl_pattern.string, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004818 break;
4819#endif
4820
4821 case CTRL_X_SPELL:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004822 get_next_spell_completion(st->first_match_pos.lnum);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004823 break;
4824
4825 default: // normal ^P/^N and ^X^L
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004826 found_new_match = get_next_default_completion(st, ini);
4827 if (found_new_match == FAIL && st->ins_buf == curbuf)
4828 st->found_all = TRUE;
4829 }
4830
4831 // check if compl_curr_match has changed, (e.g. other type of
4832 // expansion added something)
4833 if (type != 0 && compl_curr_match != compl_old_match)
4834 found_new_match = OK;
4835
4836 return found_new_match;
4837}
4838
4839/*
Girish Palya0ac1eb32025-04-16 20:18:33 +02004840 * Strips carets followed by numbers. This suffix typically represents the
4841 * max_matches setting.
4842 */
4843 static void
4844strip_caret_numbers_in_place(char_u *str)
4845{
4846 char_u *read = str, *write = str, *p;
4847
4848 if (str == NULL)
4849 return;
4850
4851 while (*read)
4852 {
4853 if (*read == '^')
4854 {
4855 p = read + 1;
4856 while (vim_isdigit(*p))
4857 p++;
4858 if ((*p == ',' || *p == '\0') && p != read + 1)
4859 {
4860 read = p;
4861 continue;
4862 }
4863 else
4864 *write++ = *read++;
4865 }
4866 else
4867 *write++ = *read++;
4868 }
4869 *write = '\0';
4870}
4871
4872/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004873 * Get the next expansion(s), using "compl_pattern".
4874 * The search starts at position "ini" in curbuf and in the direction
4875 * compl_direction.
4876 * When "compl_started" is FALSE start at that position, otherwise continue
4877 * where we stopped searching before.
4878 * This may return before finding all the matches.
4879 * Return the total number of matches or -1 if still unknown -- Acevedo
4880 */
4881 static int
4882ins_compl_get_exp(pos_T *ini)
4883{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004884 static ins_compl_next_state_T st;
4885 static int st_cleared = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004886 int i;
4887 int found_new_match;
4888 int type = ctrl_x_mode;
4889
4890 if (!compl_started)
4891 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004892 buf_T *buf;
4893
4894 FOR_ALL_BUFFERS(buf)
4895 buf->b_scanned = 0;
4896 if (!st_cleared)
4897 {
4898 CLEAR_FIELD(st);
4899 st_cleared = TRUE;
4900 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004901 st.found_all = FALSE;
4902 st.ins_buf = curbuf;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004903 vim_free(st.e_cpt_copy);
Christian Brabandtee17b6f2023-09-09 11:23:50 +02004904 // Make a copy of 'complete', in case the buffer is wiped out.
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004905 st.e_cpt_copy = vim_strsave((compl_cont_status & CONT_LOCAL)
4906 ? (char_u *)"." : curbuf->b_p_cpt);
Girish Palya0ac1eb32025-04-16 20:18:33 +02004907 strip_caret_numbers_in_place(st.e_cpt_copy);
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004908 st.e_cpt = st.e_cpt_copy == NULL ? (char_u *)"" : st.e_cpt_copy;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004909 st.last_match_pos = st.first_match_pos = *ini;
Girish Palyacbe53192025-04-14 22:13:15 +02004910
4911 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Girish Palya0ac1eb32025-04-16 20:18:33 +02004912 && !cpt_sources_init())
Girish Palyacbe53192025-04-14 22:13:15 +02004913 return FAIL;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004914 }
4915 else if (st.ins_buf != curbuf && !buf_valid(st.ins_buf))
4916 st.ins_buf = curbuf; // In case the buffer was wiped out.
4917
4918 compl_old_match = compl_curr_match; // remember the last current match
Christian Brabandt13032a42024-07-28 21:16:48 +02004919 st.cur_match_pos = (compl_dir_forward())
glepnir8159fb12024-07-17 20:32:54 +02004920 ? &st.last_match_pos : &st.first_match_pos;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004921
4922 // For ^N/^P loop over all the flags/windows/buffers in 'complete'.
Girish Palya0ac1eb32025-04-16 20:18:33 +02004923 for (cpt_sources_index = 0;;)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004924 {
4925 found_new_match = FAIL;
4926 st.set_match_pos = FALSE;
4927
4928 // For ^N/^P pick a new entry from e_cpt if compl_started is off,
4929 // or if found_all says this entry is done. For ^X^L only use the
4930 // entries from 'complete' that look in loaded buffers.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004931 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004932 && (!compl_started || st.found_all))
4933 {
glepnir53b14572025-03-12 21:28:39 +01004934 int status = process_next_cpt_value(&st, &type, ini, cfc_has_mode());
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004935
4936 if (status == INS_COMPL_CPT_END)
4937 break;
4938 if (status == INS_COMPL_CPT_CONT)
Girish Palyacbe53192025-04-14 22:13:15 +02004939 {
Girish Palya0ac1eb32025-04-16 20:18:33 +02004940 cpt_sources_index++;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004941 continue;
Girish Palyacbe53192025-04-14 22:13:15 +02004942 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004943 }
4944
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004945 // If complete() was called then compl_pattern has been reset. The
4946 // following won't work then, bail out.
John Marriott5e6ea922024-11-23 14:01:57 +01004947 if (compl_pattern.string == NULL)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004948 break;
4949
4950 // get the next set of completion matches
4951 found_new_match = get_next_completion_match(type, &st, ini);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004952
Girish Palyacbe53192025-04-14 22:13:15 +02004953 if (type > 0)
Girish Palya0ac1eb32025-04-16 20:18:33 +02004954 cpt_sources_index++;
Girish Palyacbe53192025-04-14 22:13:15 +02004955
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004956 // break the loop for specialized modes (use 'complete' just for the
4957 // generic ctrl_x_mode == CTRL_X_NORMAL) or when we've found a new
4958 // match
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004959 if ((ctrl_x_mode_not_default() && !ctrl_x_mode_line_or_eval())
4960 || found_new_match != FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004961 {
4962 if (got_int)
4963 break;
4964 // Fill the popup menu as soon as possible.
4965 if (type != -1)
4966 ins_compl_check_keys(0, FALSE);
4967
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004968 if ((ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004969 && !ctrl_x_mode_line_or_eval()) || compl_interrupted)
4970 break;
4971 compl_started = TRUE;
4972 }
4973 else
4974 {
4975 // Mark a buffer scanned when it has been scanned completely
Christian Brabandtee9166e2023-09-03 21:24:33 +02004976 if (buf_valid(st.ins_buf) && (type == 0 || type == CTRL_X_PATH_PATTERNS))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004977 st.ins_buf->b_scanned = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004978
4979 compl_started = FALSE;
4980 }
4981 }
Girish Palya0ac1eb32025-04-16 20:18:33 +02004982 cpt_sources_index = -1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004983 compl_started = TRUE;
4984
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004985 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004986 && *st.e_cpt == NUL) // Got to end of 'complete'
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004987 found_new_match = FAIL;
4988
4989 i = -1; // total of matches, unknown
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004990 if (found_new_match == FAIL || (ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004991 && !ctrl_x_mode_line_or_eval()))
4992 i = ins_compl_make_cyclic();
4993
glepnirf31cfa22025-03-06 21:59:13 +01004994 if (cfc_has_mode() && compl_get_longest && compl_num_bests > 0)
4995 fuzzy_longest_match();
4996
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004997 if (compl_old_match != NULL)
4998 {
4999 // If several matches were added (FORWARD) or the search failed and has
5000 // just been made cyclic then we have to move compl_curr_match to the
5001 // next or previous entry (if any) -- Acevedo
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005002 compl_curr_match = compl_dir_forward() ? compl_old_match->cp_next
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005003 : compl_old_match->cp_prev;
5004 if (compl_curr_match == NULL)
5005 compl_curr_match = compl_old_match;
5006 }
LemonBoy2bf52dd2022-04-09 18:17:34 +01005007 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01005008
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005009 return i;
5010}
5011
5012/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005013 * Update "compl_shown_match" to the actually shown match, it may differ when
5014 * "compl_leader" is used to omit some of the matches.
5015 */
5016 static void
5017ins_compl_update_shown_match(void)
5018{
5019 while (!ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01005020 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005021 && compl_shown_match->cp_next != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005022 && !is_first_match(compl_shown_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005023 compl_shown_match = compl_shown_match->cp_next;
5024
5025 // If we didn't find it searching forward, and compl_shows_dir is
5026 // backward, find the last match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005027 if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005028 && !ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01005029 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005030 && (compl_shown_match->cp_next == NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005031 || is_first_match(compl_shown_match->cp_next)))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005032 {
5033 while (!ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01005034 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005035 && compl_shown_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005036 && !is_first_match(compl_shown_match->cp_prev))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005037 compl_shown_match = compl_shown_match->cp_prev;
5038 }
5039}
5040
5041/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005042 * Delete the old text being completed.
5043 */
5044 void
5045ins_compl_delete(void)
5046{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005047 // In insert mode: Delete the typed part.
5048 // In replace mode: Put the old characters back, if any.
glepniredd4ac32025-01-29 18:53:51 +01005049 int col = compl_col + (compl_status_adding() ? compl_length : 0);
John Marriottf4b36412025-02-23 09:09:59 +01005050 string_T remaining = {NULL, 0};
glepnir76bdb822025-02-08 19:04:51 +01005051 int orig_col;
glepniredd4ac32025-01-29 18:53:51 +01005052 int has_preinsert = ins_compl_preinsert_effect();
5053 if (has_preinsert)
5054 {
Yegappan Lakshmanan7b6add02025-04-01 20:38:37 +02005055 col += (int)ins_compl_leader_len();
glepniredd4ac32025-01-29 18:53:51 +01005056 curwin->w_cursor.col = compl_ins_end_col;
5057 }
5058
glepnir76bdb822025-02-08 19:04:51 +01005059 if (curwin->w_cursor.lnum > compl_lnum)
5060 {
5061 if (curwin->w_cursor.col < ml_get_curline_len())
5062 {
John Marriottf4b36412025-02-23 09:09:59 +01005063 char_u *line = ml_get_cursor();
5064 remaining.length = ml_get_cursor_len();
5065 remaining.string = vim_strnsave(line, remaining.length);
5066 if (remaining.string == NULL)
glepnir76bdb822025-02-08 19:04:51 +01005067 return;
5068 }
5069 while (curwin->w_cursor.lnum > compl_lnum)
5070 {
5071 if (ml_delete(curwin->w_cursor.lnum) == FAIL)
5072 {
John Marriottf4b36412025-02-23 09:09:59 +01005073 if (remaining.string)
5074 vim_free(remaining.string);
glepnir76bdb822025-02-08 19:04:51 +01005075 return;
5076 }
zeertzjq060e6552025-02-21 20:06:26 +01005077 deleted_lines_mark(curwin->w_cursor.lnum, 1L);
glepnir76bdb822025-02-08 19:04:51 +01005078 curwin->w_cursor.lnum--;
5079 }
5080 // move cursor to end of line
5081 curwin->w_cursor.col = ml_get_curline_len();
5082 }
5083
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005084 if ((int)curwin->w_cursor.col > col)
5085 {
5086 if (stop_arrow() == FAIL)
glepnire3647c82025-02-10 21:16:32 +01005087 {
John Marriottf4b36412025-02-23 09:09:59 +01005088 if (remaining.string)
5089 vim_free(remaining.string);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005090 return;
glepnire3647c82025-02-10 21:16:32 +01005091 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005092 backspace_until_column(col);
zeertzjqf25d8f92024-12-18 21:12:25 +01005093 compl_ins_end_col = curwin->w_cursor.col;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005094 }
5095
John Marriottf4b36412025-02-23 09:09:59 +01005096 if (remaining.string != NULL)
glepnir76bdb822025-02-08 19:04:51 +01005097 {
5098 orig_col = curwin->w_cursor.col;
John Marriottf4b36412025-02-23 09:09:59 +01005099 ins_str(remaining.string, remaining.length);
glepnir76bdb822025-02-08 19:04:51 +01005100 curwin->w_cursor.col = orig_col;
John Marriottf4b36412025-02-23 09:09:59 +01005101 vim_free(remaining.string);
glepnir76bdb822025-02-08 19:04:51 +01005102 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005103 // TODO: is this sufficient for redrawing? Redrawing everything causes
5104 // flicker, thus we can't do that.
5105 changed_cline_bef_curs();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02005106#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005107 // clear v:completed_item
5108 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02005109#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005110}
5111
5112/*
glepnir76bdb822025-02-08 19:04:51 +01005113 * Insert a completion string that contains newlines.
5114 * The string is split and inserted line by line.
5115 */
5116 static void
5117ins_compl_expand_multiple(char_u *str)
5118{
5119 char_u *start = str;
5120 char_u *curr = str;
glepnir5090a1f2025-02-24 19:10:37 +01005121 int base_indent = get_indent();
glepnir76bdb822025-02-08 19:04:51 +01005122
5123 while (*curr != NUL)
5124 {
5125 if (*curr == '\n')
5126 {
5127 // Insert the text chunk before newline
5128 if (curr > start)
5129 ins_char_bytes(start, (int)(curr - start));
5130
5131 // Handle newline
glepnir5090a1f2025-02-24 19:10:37 +01005132 open_line(FORWARD, OPENLINE_KEEPTRAIL | OPENLINE_FORCE_INDENT, base_indent, NULL);
glepnir76bdb822025-02-08 19:04:51 +01005133 start = curr + 1;
5134 }
5135 curr++;
5136 }
5137
5138 // Handle remaining text after last newline (if any)
5139 if (curr > start)
5140 ins_char_bytes(start, (int)(curr - start));
5141
5142 compl_ins_end_col = curwin->w_cursor.col;
5143}
5144
5145/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005146 * Insert the new text being completed.
5147 * "in_compl_func" is TRUE when called from complete_check().
glepniredd4ac32025-01-29 18:53:51 +01005148 * "move_cursor" is used when 'completeopt' includes "preinsert" and when TRUE
5149 * cursor needs to move back from the inserted text to the compl_leader.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005150 */
5151 void
glepniredd4ac32025-01-29 18:53:51 +01005152ins_compl_insert(int in_compl_func, int move_cursor)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005153{
glepnir76bdb822025-02-08 19:04:51 +01005154 int compl_len = get_compl_len();
5155 int preinsert = ins_compl_has_preinsert();
5156 char_u *cp_str = compl_shown_match->cp_str.string;
5157 size_t cp_str_len = compl_shown_match->cp_str.length;
5158 size_t leader_len = ins_compl_leader_len();
5159 char_u *has_multiple = vim_strchr(cp_str, '\n');
Bram Moolenaar4b28ba32021-12-27 19:28:37 +00005160
5161 // Make sure we don't go over the end of the string, this can happen with
5162 // illegal bytes.
zeertzjq8297e2c2025-01-30 11:04:47 +01005163 if (compl_len < (int)cp_str_len)
glepniredd4ac32025-01-29 18:53:51 +01005164 {
glepnir76bdb822025-02-08 19:04:51 +01005165 if (has_multiple)
5166 ins_compl_expand_multiple(cp_str + compl_len);
5167 else
5168 {
5169 ins_compl_insert_bytes(cp_str + compl_len, -1);
5170 if (preinsert && move_cursor)
5171 curwin->w_cursor.col -= (colnr_T)(cp_str_len - leader_len);
5172 }
glepniredd4ac32025-01-29 18:53:51 +01005173 }
5174 if (match_at_original_text(compl_shown_match) || preinsert)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005175 compl_used_match = FALSE;
5176 else
5177 compl_used_match = TRUE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02005178#ifdef FEAT_EVAL
5179 {
5180 dict_T *dict = ins_compl_dict_alloc(compl_shown_match);
5181
5182 set_vim_var_dict(VV_COMPLETED_ITEM, dict);
5183 }
5184#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005185 if (!in_compl_func)
5186 compl_curr_match = compl_shown_match;
5187}
5188
5189/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005190 * show the file name for the completion match (if any). Truncate the file
5191 * name to avoid a wait for return.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005192 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005193 static void
5194ins_compl_show_filename(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005195{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005196 char *lead = _("match in file");
5197 int space = sc_col - vim_strsize((char_u *)lead) - 2;
5198 char_u *s;
5199 char_u *e;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005200
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005201 if (space <= 0)
5202 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005203
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005204 // We need the tail that fits. With double-byte encoding going
5205 // back from the end is very slow, thus go from the start and keep
5206 // the text that fits in "space" between "s" and "e".
5207 for (s = e = compl_shown_match->cp_fname; *e != NUL; MB_PTR_ADV(e))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005208 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005209 space -= ptr2cells(e);
5210 while (space < 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005211 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005212 space += ptr2cells(s);
5213 MB_PTR_ADV(s);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005214 }
5215 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005216 msg_hist_off = TRUE;
5217 vim_snprintf((char *)IObuff, IOSIZE, "%s %s%s", lead,
5218 s > compl_shown_match->cp_fname ? "<" : "", s);
5219 msg((char *)IObuff);
5220 msg_hist_off = FALSE;
5221 redraw_cmdline = FALSE; // don't overwrite!
5222}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005223
glepnirdca57fb2024-06-04 22:01:21 +02005224/*
zeertzjq551d8c32024-06-05 19:53:32 +02005225 * Find a completion item when 'completeopt' contains "fuzzy".
glepnirdca57fb2024-06-04 22:01:21 +02005226 */
glepnira218cc62024-06-03 19:32:39 +02005227 static compl_T *
5228find_comp_when_fuzzy(void)
5229{
5230 int score;
5231 char_u* str;
5232 int target_idx = -1;
5233 int is_forward = compl_shows_dir_forward();
5234 int is_backward = compl_shows_dir_backward();
5235 compl_T *comp = NULL;
5236
glepnir43eef882024-06-19 20:20:48 +02005237 if ((is_forward && compl_selected_item == compl_match_arraysize - 1)
glepnira218cc62024-06-03 19:32:39 +02005238 || (is_backward && compl_selected_item == 0))
glepnir3e50a282025-04-03 21:17:06 +02005239 return compl_first_match != compl_shown_match ?
5240 (is_forward ? compl_shown_match->cp_next : compl_first_match) :
glepnir65407ce2024-07-06 16:09:19 +02005241 (compl_first_match->cp_prev ? compl_first_match->cp_prev : NULL);
glepnira218cc62024-06-03 19:32:39 +02005242
5243 if (is_forward)
5244 target_idx = compl_selected_item + 1;
5245 else if (is_backward)
Hirohito Higashi355db992025-04-28 18:07:02 +02005246 target_idx = compl_selected_item == -1 ? compl_match_arraysize - 1
glepnirdca57fb2024-06-04 22:01:21 +02005247 : compl_selected_item - 1;
glepnira218cc62024-06-03 19:32:39 +02005248
5249 score = compl_match_array[target_idx].pum_score;
5250 str = compl_match_array[target_idx].pum_text;
5251
5252 comp = compl_first_match;
Hirohito Higashia4a00a72025-05-08 22:58:31 +02005253 do
5254 {
Hirohito Higashi355db992025-04-28 18:07:02 +02005255 if (comp->cp_score == score && (str == comp->cp_str.string || str == comp->cp_text[CPT_ABBR]))
5256 return comp;
5257 comp = comp->cp_next;
glepnira218cc62024-06-03 19:32:39 +02005258 } while (comp != NULL && !is_first_match(comp));
5259
5260 return NULL;
5261}
5262
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005263/*
Girish Palya0ac1eb32025-04-16 20:18:33 +02005264 * Find the appropriate completion item when 'complete' ('cpt') includes
5265 * a 'max_matches' postfix. In this case, we search for a match where
5266 * 'cp_in_match_array' is set, indicating that the match is also present
5267 * in 'compl_match_array'.
5268 */
5269 static compl_T *
5270find_comp_when_cpt_sources(void)
5271{
5272 int is_forward = compl_shows_dir_forward();
5273 compl_T *match = compl_shown_match;
5274
5275 do
5276 match = is_forward ? match->cp_next : match->cp_prev;
5277 while (match->cp_next && !match->cp_in_match_array
5278 && !match_at_original_text(match));
5279 return match;
5280}
5281
5282/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005283 * Find the next set of matches for completion. Repeat the completion "todo"
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005284 * times. The number of matches found is returned in 'num_matches'.
5285 *
5286 * If "allow_get_expansion" is TRUE, then ins_compl_get_exp() may be called to
5287 * get more completions. If it is FALSE, then do nothing when there are no more
5288 * completions in the given direction.
5289 *
5290 * If "advance" is TRUE, then completion will move to the first match.
5291 * Otherwise, the original text will be shown.
5292 *
5293 * Returns OK on success and -1 if the number of matches are unknown.
5294 */
5295 static int
5296find_next_completion_match(
5297 int allow_get_expansion,
5298 int todo, // repeat completion this many times
5299 int advance,
5300 int *num_matches)
5301{
5302 int found_end = FALSE;
5303 compl_T *found_compl = NULL;
zeertzjqaa925ee2024-06-09 18:24:05 +02005304 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02005305 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
5306 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Girish Palya0ac1eb32025-04-16 20:18:33 +02005307 int cpt_sources_active = compl_match_array && cpt_sources_array;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005308
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005309 while (--todo >= 0)
5310 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005311 if (compl_shows_dir_forward() && compl_shown_match->cp_next != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005312 {
Girish Palya0ac1eb32025-04-16 20:18:33 +02005313 if (compl_match_array != NULL && compl_fuzzy_match)
5314 compl_shown_match = find_comp_when_fuzzy();
5315 else if (cpt_sources_active)
5316 compl_shown_match = find_comp_when_cpt_sources();
5317 else
5318 compl_shown_match = compl_shown_match->cp_next;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005319 found_end = (compl_first_match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005320 && (is_first_match(compl_shown_match->cp_next)
5321 || is_first_match(compl_shown_match)));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005322 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005323 else if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005324 && compl_shown_match->cp_prev != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005325 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005326 found_end = is_first_match(compl_shown_match);
Girish Palya0ac1eb32025-04-16 20:18:33 +02005327 if (compl_match_array != NULL && compl_fuzzy_match)
5328 compl_shown_match = find_comp_when_fuzzy();
5329 else if (cpt_sources_active)
5330 compl_shown_match = find_comp_when_cpt_sources();
5331 else
5332 compl_shown_match = compl_shown_match->cp_prev;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005333 found_end |= is_first_match(compl_shown_match);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005334 }
5335 else
5336 {
5337 if (!allow_get_expansion)
5338 {
5339 if (advance)
5340 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005341 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005342 compl_pending -= todo + 1;
5343 else
5344 compl_pending += todo + 1;
5345 }
5346 return -1;
5347 }
5348
5349 if (!compl_no_select && advance)
5350 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005351 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005352 --compl_pending;
5353 else
5354 ++compl_pending;
5355 }
5356
5357 // Find matches.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005358 *num_matches = ins_compl_get_exp(&compl_startpos);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005359
5360 // handle any pending completions
5361 while (compl_pending != 0 && compl_direction == compl_shows_dir
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005362 && advance)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005363 {
5364 if (compl_pending > 0 && compl_shown_match->cp_next != NULL)
5365 {
5366 compl_shown_match = compl_shown_match->cp_next;
5367 --compl_pending;
5368 }
5369 if (compl_pending < 0 && compl_shown_match->cp_prev != NULL)
5370 {
5371 compl_shown_match = compl_shown_match->cp_prev;
5372 ++compl_pending;
5373 }
5374 else
5375 break;
5376 }
5377 found_end = FALSE;
5378 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005379 if (!match_at_original_text(compl_shown_match)
John Marriott5e6ea922024-11-23 14:01:57 +01005380 && compl_leader.string != NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005381 && !ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01005382 compl_leader.string, (int)compl_leader.length)
glepnira218cc62024-06-03 19:32:39 +02005383 && !(compl_fuzzy_match && compl_shown_match->cp_score > 0))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005384 ++todo;
5385 else
5386 // Remember a matching item.
5387 found_compl = compl_shown_match;
5388
5389 // Stop at the end of the list when we found a usable match.
5390 if (found_end)
5391 {
5392 if (found_compl != NULL)
5393 {
5394 compl_shown_match = found_compl;
5395 break;
5396 }
5397 todo = 1; // use first usable match after wrapping around
5398 }
5399 }
5400
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005401 return OK;
5402}
5403
5404/*
5405 * Fill in the next completion in the current direction.
5406 * If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to
5407 * get more completions. If it is FALSE, then we just do nothing when there
5408 * are no more completions in a given direction. The latter case is used when
5409 * we are still in the middle of finding completions, to allow browsing
5410 * through the ones found so far.
5411 * Return the total number of matches, or -1 if still unknown -- webb.
5412 *
5413 * compl_curr_match is currently being used by ins_compl_get_exp(), so we use
5414 * compl_shown_match here.
5415 *
5416 * Note that this function may be called recursively once only. First with
5417 * "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn
5418 * calls this function with "allow_get_expansion" FALSE.
5419 */
5420 static int
5421ins_compl_next(
5422 int allow_get_expansion,
5423 int count, // repeat completion this many times; should
5424 // be at least 1
5425 int insert_match, // Insert the newly selected match
5426 int in_compl_func) // called from complete_check()
5427{
5428 int num_matches = -1;
5429 int todo = count;
5430 int advance;
5431 int started = compl_started;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005432 buf_T *orig_curbuf = curbuf;
zeertzjqaa925ee2024-06-09 18:24:05 +02005433 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02005434 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
5435 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
glepniredd4ac32025-01-29 18:53:51 +01005436 int compl_preinsert = ins_compl_has_preinsert();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005437
5438 // When user complete function return -1 for findstart which is next
5439 // time of 'always', compl_shown_match become NULL.
5440 if (compl_shown_match == NULL)
5441 return -1;
5442
John Marriott5e6ea922024-11-23 14:01:57 +01005443 if (compl_leader.string != NULL
glepnira218cc62024-06-03 19:32:39 +02005444 && !match_at_original_text(compl_shown_match)
5445 && !compl_fuzzy_match)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005446 // Update "compl_shown_match" to the actually shown match
5447 ins_compl_update_shown_match();
5448
5449 if (allow_get_expansion && insert_match
nwounkn2e3cd522023-10-17 11:05:38 +02005450 && (!compl_get_longest || compl_used_match))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005451 // Delete old text to be replaced
5452 ins_compl_delete();
5453
5454 // When finding the longest common text we stick at the original text,
5455 // don't let CTRL-N or CTRL-P move to the first match.
5456 advance = count != 1 || !allow_get_expansion || !compl_get_longest;
5457
5458 // When restarting the search don't insert the first match either.
5459 if (compl_restarting)
5460 {
5461 advance = FALSE;
5462 compl_restarting = FALSE;
5463 }
5464
5465 // Repeat this for when <PageUp> or <PageDown> is typed. But don't wrap
5466 // around.
5467 if (find_next_completion_match(allow_get_expansion, todo, advance,
5468 &num_matches) == -1)
5469 return -1;
5470
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005471 if (curbuf != orig_curbuf)
5472 {
5473 // In case some completion function switched buffer, don't want to
5474 // insert the completion elsewhere.
5475 return -1;
5476 }
5477
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005478 // Insert the text of the new completion, or the compl_leader.
glepniredd4ac32025-01-29 18:53:51 +01005479 if (compl_no_insert && !started && !compl_preinsert)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005480 {
glepnir6a38aff2024-12-16 21:56:16 +01005481 ins_compl_insert_bytes(compl_orig_text.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005482 compl_used_match = FALSE;
5483 }
5484 else if (insert_match)
5485 {
5486 if (!compl_get_longest || compl_used_match)
glepniredd4ac32025-01-29 18:53:51 +01005487 ins_compl_insert(in_compl_func, TRUE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005488 else
glepnir6a38aff2024-12-16 21:56:16 +01005489 ins_compl_insert_bytes(compl_leader.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005490 }
5491 else
5492 compl_used_match = FALSE;
5493
5494 if (!allow_get_expansion)
5495 {
5496 // may undisplay the popup menu first
5497 ins_compl_upd_pum();
5498
5499 if (pum_enough_matches())
5500 // Will display the popup menu, don't redraw yet to avoid flicker.
5501 pum_call_update_screen();
5502 else
5503 // Not showing the popup menu yet, redraw to show the user what was
5504 // inserted.
5505 update_screen(0);
5506
5507 // display the updated popup menu
5508 ins_compl_show_pum();
5509#ifdef FEAT_GUI
5510 if (gui.in_use)
5511 {
5512 // Show the cursor after the match, not after the redrawn text.
5513 setcursor();
5514 out_flush_cursor(FALSE, FALSE);
5515 }
5516#endif
5517
5518 // Delete old text to be replaced, since we're still searching and
5519 // don't want to match ourselves!
5520 ins_compl_delete();
5521 }
5522
5523 // Enter will select a match when the match wasn't inserted and the popup
5524 // menu is visible.
5525 if (compl_no_insert && !started)
5526 compl_enter_selects = TRUE;
5527 else
5528 compl_enter_selects = !insert_match && compl_match_array != NULL;
5529
5530 // Show the file name for the match (if any)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005531 if (compl_shown_match->cp_fname != NULL)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005532 ins_compl_show_filename();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005533
5534 return num_matches;
5535}
5536
5537/*
5538 * Call this while finding completions, to check whether the user has hit a key
5539 * that should change the currently displayed completion, or exit completion
5540 * mode. Also, when compl_pending is not zero, show a completion as soon as
5541 * possible. -- webb
5542 * "frequency" specifies out of how many calls we actually check.
5543 * "in_compl_func" is TRUE when called from complete_check(), don't set
5544 * compl_curr_match.
5545 */
5546 void
5547ins_compl_check_keys(int frequency, int in_compl_func)
5548{
5549 static int count = 0;
5550 int c;
5551
5552 // Don't check when reading keys from a script, :normal or feedkeys().
5553 // That would break the test scripts. But do check for keys when called
5554 // from complete_check().
5555 if (!in_compl_func && (using_script() || ex_normal_busy))
5556 return;
5557
5558 // Only do this at regular intervals
5559 if (++count < frequency)
5560 return;
5561 count = 0;
5562
5563 // Check for a typed key. Do use mappings, otherwise vim_is_ctrl_x_key()
5564 // can't do its work correctly.
5565 c = vpeekc_any();
5566 if (c != NUL)
5567 {
5568 if (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R)
5569 {
5570 c = safe_vgetc(); // Eat the character
5571 compl_shows_dir = ins_compl_key2dir(c);
5572 (void)ins_compl_next(FALSE, ins_compl_key2count(c),
5573 c != K_UP && c != K_DOWN, in_compl_func);
5574 }
5575 else
5576 {
5577 // Need to get the character to have KeyTyped set. We'll put it
5578 // back with vungetc() below. But skip K_IGNORE.
5579 c = safe_vgetc();
5580 if (c != K_IGNORE)
5581 {
5582 // Don't interrupt completion when the character wasn't typed,
5583 // e.g., when doing @q to replay keys.
5584 if (c != Ctrl_R && KeyTyped)
5585 compl_interrupted = TRUE;
5586
5587 vungetc(c);
5588 }
5589 }
5590 }
zeertzjq529b9ad2024-06-05 20:27:06 +02005591 if (compl_pending != 0 && !got_int && !(cot_flags & COT_NOINSERT))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005592 {
5593 int todo = compl_pending > 0 ? compl_pending : -compl_pending;
5594
5595 compl_pending = 0;
5596 (void)ins_compl_next(FALSE, todo, TRUE, in_compl_func);
5597 }
5598}
5599
5600/*
5601 * Decide the direction of Insert mode complete from the key typed.
5602 * Returns BACKWARD or FORWARD.
5603 */
5604 static int
5605ins_compl_key2dir(int c)
5606{
5607 if (c == Ctrl_P || c == Ctrl_L
5608 || c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP || c == K_UP)
5609 return BACKWARD;
5610 return FORWARD;
5611}
5612
5613/*
5614 * Return TRUE for keys that are used for completion only when the popup menu
5615 * is visible.
5616 */
5617 static int
5618ins_compl_pum_key(int c)
5619{
5620 return pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP
5621 || c == K_PAGEDOWN || c == K_KPAGEDOWN || c == K_S_DOWN
5622 || c == K_UP || c == K_DOWN);
5623}
5624
5625/*
5626 * Decide the number of completions to move forward.
5627 * Returns 1 for most keys, height of the popup menu for page-up/down keys.
5628 */
5629 static int
5630ins_compl_key2count(int c)
5631{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005632 if (ins_compl_pum_key(c) && c != K_UP && c != K_DOWN)
5633 {
glepnir19e1dd62025-05-08 22:50:38 +02005634 int h = pum_get_height();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005635 if (h > 3)
5636 h -= 2; // keep some context
5637 return h;
5638 }
5639 return 1;
5640}
5641
5642/*
5643 * Return TRUE if completion with "c" should insert the match, FALSE if only
5644 * to change the currently selected completion.
5645 */
5646 static int
5647ins_compl_use_match(int c)
5648{
5649 switch (c)
5650 {
5651 case K_UP:
5652 case K_DOWN:
5653 case K_PAGEDOWN:
5654 case K_KPAGEDOWN:
5655 case K_S_DOWN:
5656 case K_PAGEUP:
5657 case K_KPAGEUP:
5658 case K_S_UP:
5659 return FALSE;
5660 }
5661 return TRUE;
5662}
5663
5664/*
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005665 * Get the pattern, column and length for normal completion (CTRL-N CTRL-P
5666 * completion)
John Marriott5e6ea922024-11-23 14:01:57 +01005667 * Sets the global variables: compl_col, compl_length and compl_pattern.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005668 * Uses the global variables: compl_cont_status and ctrl_x_mode
5669 */
5670 static int
5671get_normal_compl_info(char_u *line, int startcol, colnr_T curs_col)
5672{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005673 if ((compl_cont_status & CONT_SOL) || ctrl_x_mode_path_defines())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005674 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005675 if (!compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005676 {
5677 while (--startcol >= 0 && vim_isIDc(line[startcol]))
5678 ;
5679 compl_col += ++startcol;
5680 compl_length = curs_col - startcol;
5681 }
5682 if (p_ic)
John Marriott8c85a2a2024-05-20 19:18:26 +02005683 {
John Marriott5e6ea922024-11-23 14:01:57 +01005684 compl_pattern.string = str_foldcase(line + compl_col,
5685 compl_length, NULL, 0);
5686 if (compl_pattern.string == NULL)
5687 {
5688 compl_pattern.length = 0;
5689 return FAIL;
5690 }
5691 compl_pattern.length = STRLEN(compl_pattern.string);
5692 }
5693 else
5694 {
5695 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5696 if (compl_pattern.string == NULL)
5697 {
5698 compl_pattern.length = 0;
5699 return FAIL;
5700 }
5701 compl_pattern.length = (size_t)compl_length;
John Marriott8c85a2a2024-05-20 19:18:26 +02005702 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005703 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005704 else if (compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005705 {
5706 char_u *prefix = (char_u *)"\\<";
John Marriott8c85a2a2024-05-20 19:18:26 +02005707 size_t prefixlen = STRLEN_LITERAL("\\<");
John Marriott5e6ea922024-11-23 14:01:57 +01005708 size_t n;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005709
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005710 if (!vim_iswordp(line + compl_col)
5711 || (compl_col > 0
5712 && (vim_iswordp(mb_prevptr(line, line + compl_col)))))
John Marriott8c85a2a2024-05-20 19:18:26 +02005713 {
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005714 prefix = (char_u *)"";
John Marriott8c85a2a2024-05-20 19:18:26 +02005715 prefixlen = 0;
5716 }
John Marriott5e6ea922024-11-23 14:01:57 +01005717
5718 // we need up to 2 extra chars for the prefix
5719 n = quote_meta(NULL, line + compl_col, compl_length) + prefixlen;
5720 compl_pattern.string = alloc(n);
5721 if (compl_pattern.string == NULL)
5722 {
5723 compl_pattern.length = 0;
5724 return FAIL;
5725 }
5726 STRCPY((char *)compl_pattern.string, prefix);
5727 (void)quote_meta(compl_pattern.string + prefixlen,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005728 line + compl_col, compl_length);
John Marriott5e6ea922024-11-23 14:01:57 +01005729 compl_pattern.length = n - 1;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005730 }
5731 else if (--startcol < 0
5732 || !vim_iswordp(mb_prevptr(line, line + startcol + 1)))
5733 {
John Marriott5e6ea922024-11-23 14:01:57 +01005734 size_t len = STRLEN_LITERAL("\\<\\k\\k");
5735
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005736 // Match any word of at least two chars
John Marriott5e6ea922024-11-23 14:01:57 +01005737 compl_pattern.string = vim_strnsave((char_u *)"\\<\\k\\k", len);
5738 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005739 {
John Marriott5e6ea922024-11-23 14:01:57 +01005740 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005741 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005742 }
John Marriott5e6ea922024-11-23 14:01:57 +01005743 compl_pattern.length = len;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005744 compl_col += curs_col;
5745 compl_length = 0;
5746 }
5747 else
5748 {
5749 // Search the point of change class of multibyte character
5750 // or not a word single byte character backward.
5751 if (has_mbyte)
5752 {
5753 int base_class;
5754 int head_off;
5755
5756 startcol -= (*mb_head_off)(line, line + startcol);
5757 base_class = mb_get_class(line + startcol);
5758 while (--startcol >= 0)
5759 {
5760 head_off = (*mb_head_off)(line, line + startcol);
5761 if (base_class != mb_get_class(line + startcol
5762 - head_off))
5763 break;
5764 startcol -= head_off;
5765 }
5766 }
5767 else
glepnir19e1dd62025-05-08 22:50:38 +02005768 {
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005769 while (--startcol >= 0 && vim_iswordc(line[startcol]))
5770 ;
glepnir19e1dd62025-05-08 22:50:38 +02005771 }
5772
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005773 compl_col += ++startcol;
5774 compl_length = (int)curs_col - startcol;
5775 if (compl_length == 1)
5776 {
5777 // Only match word with at least two chars -- webb
5778 // there's no need to call quote_meta,
5779 // alloc(7) is enough -- Acevedo
John Marriott5e6ea922024-11-23 14:01:57 +01005780 compl_pattern.string = alloc(7);
5781 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005782 {
John Marriott5e6ea922024-11-23 14:01:57 +01005783 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005784 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005785 }
John Marriott5e6ea922024-11-23 14:01:57 +01005786 STRCPY((char *)compl_pattern.string, "\\<");
5787 (void)quote_meta(compl_pattern.string + 2, line + compl_col, 1);
5788 STRCAT((char *)compl_pattern.string, "\\k");
5789 compl_pattern.length = STRLEN(compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005790 }
5791 else
5792 {
John Marriott5e6ea922024-11-23 14:01:57 +01005793 size_t n = quote_meta(NULL, line + compl_col, compl_length) + 2;
5794
5795 compl_pattern.string = alloc(n);
5796 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005797 {
John Marriott5e6ea922024-11-23 14:01:57 +01005798 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005799 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005800 }
John Marriott5e6ea922024-11-23 14:01:57 +01005801 STRCPY((char *)compl_pattern.string, "\\<");
5802 (void)quote_meta(compl_pattern.string + 2, line + compl_col,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005803 compl_length);
John Marriott5e6ea922024-11-23 14:01:57 +01005804 compl_pattern.length = n - 1;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005805 }
5806 }
5807
5808 return OK;
5809}
5810
5811/*
5812 * Get the pattern, column and length for whole line completion or for the
5813 * complete() function.
5814 * Sets the global variables: compl_col, compl_length and compl_pattern.
5815 */
5816 static int
5817get_wholeline_compl_info(char_u *line, colnr_T curs_col)
5818{
5819 compl_col = (colnr_T)getwhitecols(line);
5820 compl_length = (int)curs_col - (int)compl_col;
5821 if (compl_length < 0) // cursor in indent: empty pattern
5822 compl_length = 0;
5823 if (p_ic)
John Marriott8c85a2a2024-05-20 19:18:26 +02005824 {
John Marriott5e6ea922024-11-23 14:01:57 +01005825 compl_pattern.string = str_foldcase(line + compl_col, compl_length,
5826 NULL, 0);
5827 if (compl_pattern.string == NULL)
5828 {
5829 compl_pattern.length = 0;
5830 return FAIL;
5831 }
5832 compl_pattern.length = STRLEN(compl_pattern.string);
John Marriott8c85a2a2024-05-20 19:18:26 +02005833 }
John Marriott5e6ea922024-11-23 14:01:57 +01005834 else
5835 {
5836 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5837 if (compl_pattern.string == NULL)
5838 {
5839 compl_pattern.length = 0;
5840 return FAIL;
5841 }
5842 compl_pattern.length = (size_t)compl_length;
5843 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005844
5845 return OK;
5846}
5847
5848/*
5849 * Get the pattern, column and length for filename completion.
5850 * Sets the global variables: compl_col, compl_length and compl_pattern.
5851 */
5852 static int
5853get_filename_compl_info(char_u *line, int startcol, colnr_T curs_col)
5854{
5855 // Go back to just before the first filename character.
5856 if (startcol > 0)
5857 {
5858 char_u *p = line + startcol;
5859
5860 MB_PTR_BACK(line, p);
5861 while (p > line && vim_isfilec(PTR2CHAR(p)))
5862 MB_PTR_BACK(line, p);
5863 if (p == line && vim_isfilec(PTR2CHAR(p)))
5864 startcol = 0;
5865 else
5866 startcol = (int)(p - line) + 1;
5867 }
5868
5869 compl_col += startcol;
5870 compl_length = (int)curs_col - startcol;
John Marriott5e6ea922024-11-23 14:01:57 +01005871 compl_pattern.string = addstar(line + compl_col, compl_length, EXPAND_FILES);
5872 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005873 {
John Marriott5e6ea922024-11-23 14:01:57 +01005874 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005875 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005876 }
5877
John Marriott5e6ea922024-11-23 14:01:57 +01005878 compl_pattern.length = STRLEN(compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005879
5880 return OK;
5881}
5882
5883/*
5884 * Get the pattern, column and length for command-line completion.
5885 * Sets the global variables: compl_col, compl_length and compl_pattern.
5886 */
5887 static int
5888get_cmdline_compl_info(char_u *line, colnr_T curs_col)
5889{
John Marriott5e6ea922024-11-23 14:01:57 +01005890 compl_pattern.string = vim_strnsave(line, curs_col);
5891 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005892 {
John Marriott5e6ea922024-11-23 14:01:57 +01005893 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005894 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005895 }
John Marriott5e6ea922024-11-23 14:01:57 +01005896 compl_pattern.length = curs_col;
5897 set_cmd_context(&compl_xp, compl_pattern.string,
5898 (int)compl_pattern.length, curs_col, FALSE);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005899 if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL
5900 || compl_xp.xp_context == EXPAND_NOTHING)
5901 // No completion possible, use an empty pattern to get a
5902 // "pattern not found" message.
5903 compl_col = curs_col;
5904 else
John Marriott5e6ea922024-11-23 14:01:57 +01005905 compl_col = (int)(compl_xp.xp_pattern - compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005906 compl_length = curs_col - compl_col;
5907
5908 return OK;
5909}
5910
5911/*
5912 * Get the pattern, column and length for user defined completion ('omnifunc',
5913 * 'completefunc' and 'thesaurusfunc')
5914 * Sets the global variables: compl_col, compl_length and compl_pattern.
5915 * Uses the global variable: spell_bad_len
Girish Palyacbe53192025-04-14 22:13:15 +02005916 * Callback function "cb" is set if triggered by a function in the 'cpt'
5917 * option; otherwise, it is NULL.
5918 * "startcol", when not NULL, contains the column returned by function.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005919 */
5920 static int
glepnir19e1dd62025-05-08 22:50:38 +02005921get_userdefined_compl_info(
5922 colnr_T curs_col UNUSED,
5923 callback_T *cb UNUSED,
5924 int *startcol UNUSED)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005925{
5926 int ret = FAIL;
5927
5928#ifdef FEAT_COMPL_FUNC
5929 // Call user defined function 'completefunc' with "a:findstart"
5930 // set to 1 to obtain the length of text to use for completion.
glepnir19e1dd62025-05-08 22:50:38 +02005931 char_u *line = NULL;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005932 typval_T args[3];
5933 int col;
glepnir19e1dd62025-05-08 22:50:38 +02005934 char_u *funcname = NULL;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005935 pos_T pos;
5936 int save_State = State;
Girish Palyacbe53192025-04-14 22:13:15 +02005937 int len;
glepnir19e1dd62025-05-08 22:50:38 +02005938 string_T *compl_pat = NULL;
Girish Palyacbe53192025-04-14 22:13:15 +02005939 int is_cpt_function = (cb != NULL);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005940
Girish Palyacbe53192025-04-14 22:13:15 +02005941 if (!is_cpt_function)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005942 {
Girish Palyacbe53192025-04-14 22:13:15 +02005943 // Call 'completefunc' or 'omnifunc' or 'thesaurusfunc' and get pattern
5944 // length as a string
5945 funcname = get_complete_funcname(ctrl_x_mode);
5946 if (*funcname == NUL)
5947 {
5948 semsg(_(e_option_str_is_not_set), ctrl_x_mode_function()
5949 ? "completefunc" : "omnifunc");
5950 return FAIL;
5951 }
5952 cb = get_insert_callback(ctrl_x_mode);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005953 }
5954
5955 args[0].v_type = VAR_NUMBER;
5956 args[0].vval.v_number = 1;
5957 args[1].v_type = VAR_STRING;
5958 args[1].vval.v_string = (char_u *)"";
5959 args[2].v_type = VAR_UNKNOWN;
5960 pos = curwin->w_cursor;
zeertzjqcfe45652022-05-27 17:26:55 +01005961 ++textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005962 col = call_callback_retnr(cb, 2, args);
zeertzjqcfe45652022-05-27 17:26:55 +01005963 --textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005964
5965 State = save_State;
5966 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02005967 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005968 validate_cursor();
5969 if (!EQUAL_POS(curwin->w_cursor, pos))
5970 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00005971 emsg(_(e_complete_function_deleted_text));
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005972 return FAIL;
5973 }
5974
Girish Palyacbe53192025-04-14 22:13:15 +02005975 if (startcol != NULL)
5976 *startcol = col;
5977
LemonBoy9bcb9ca2022-05-26 15:23:26 +01005978 // Return value -2 means the user complete function wants to cancel the
5979 // complete without an error, do the same if the function did not execute
5980 // successfully.
5981 if (col == -2 || aborting())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005982 return FAIL;
glepnir19e1dd62025-05-08 22:50:38 +02005983
LemonBoy9bcb9ca2022-05-26 15:23:26 +01005984 // Return value -3 does the same as -2 and leaves CTRL-X mode.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005985 if (col == -3)
5986 {
Girish Palyacbe53192025-04-14 22:13:15 +02005987 if (is_cpt_function)
5988 return FAIL;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005989 ctrl_x_mode = CTRL_X_NORMAL;
5990 edit_submode = NULL;
5991 if (!shortmess(SHM_COMPLETIONMENU))
5992 msg_clr_cmdline();
5993 return FAIL;
5994 }
5995
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00005996 // Reset extended parameters of completion, when starting new
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005997 // completion.
5998 compl_opt_refresh_always = FALSE;
5999 compl_opt_suppress_empty = FALSE;
6000
Girish Palyacbe53192025-04-14 22:13:15 +02006001 if (col < 0 || col > curs_col)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006002 col = curs_col;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006003
6004 // Setup variables for completion. Need to obtain "line" again,
6005 // it may have become invalid.
6006 line = ml_get(curwin->w_cursor.lnum);
Girish Palyacbe53192025-04-14 22:13:15 +02006007 len = curs_col - col;
6008 compl_pat = is_cpt_function ? &cpt_compl_pattern : &compl_pattern;
6009 compl_pat->string = vim_strnsave(line + col, (size_t)len);
6010 if (compl_pat->string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02006011 {
Girish Palyacbe53192025-04-14 22:13:15 +02006012 compl_pat->length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006013 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02006014 }
Girish Palyacbe53192025-04-14 22:13:15 +02006015 compl_pat->length = (size_t)compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006016
Girish Palyacbe53192025-04-14 22:13:15 +02006017 if (!is_cpt_function)
6018 {
6019 compl_col = col;
6020 compl_length = len;
6021 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006022 ret = OK;
6023#endif
6024
6025 return ret;
6026}
6027
6028/*
6029 * Get the pattern, column and length for spell completion.
6030 * Sets the global variables: compl_col, compl_length and compl_pattern.
6031 * Uses the global variable: spell_bad_len
6032 */
6033 static int
6034get_spell_compl_info(int startcol UNUSED, colnr_T curs_col UNUSED)
6035{
6036 int ret = FAIL;
6037#ifdef FEAT_SPELL
glepnir19e1dd62025-05-08 22:50:38 +02006038 char_u *line = NULL;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006039
6040 if (spell_bad_len > 0)
6041 compl_col = curs_col - spell_bad_len;
6042 else
6043 compl_col = spell_word_start(startcol);
glepnir19e1dd62025-05-08 22:50:38 +02006044
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006045 if (compl_col >= (colnr_T)startcol)
6046 {
6047 compl_length = 0;
6048 compl_col = curs_col;
6049 }
6050 else
6051 {
6052 spell_expand_check_cap(compl_col);
6053 compl_length = (int)curs_col - compl_col;
6054 }
6055 // Need to obtain "line" again, it may have become invalid.
6056 line = ml_get(curwin->w_cursor.lnum);
John Marriott5e6ea922024-11-23 14:01:57 +01006057 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
6058 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02006059 {
John Marriott5e6ea922024-11-23 14:01:57 +01006060 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006061 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02006062 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006063
John Marriott5e6ea922024-11-23 14:01:57 +01006064 compl_pattern.length = (size_t)compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006065 ret = OK;
6066#endif
6067
6068 return ret;
6069}
6070
6071/*
6072 * Get the completion pattern, column and length.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006073 * "startcol" - start column number of the completion pattern/text
6074 * "cur_col" - current cursor column
6075 * On return, "line_invalid" is set to TRUE, if the current line may have
6076 * become invalid and needs to be fetched again.
6077 * Returns OK on success.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006078 */
6079 static int
6080compl_get_info(char_u *line, int startcol, colnr_T curs_col, int *line_invalid)
6081{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006082 if (ctrl_x_mode_normal()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006083 || (ctrl_x_mode & CTRL_X_WANT_IDENT
6084 && !thesaurus_func_complete(ctrl_x_mode)))
6085 {
6086 return get_normal_compl_info(line, startcol, curs_col);
6087 }
6088 else if (ctrl_x_mode_line_or_eval())
6089 {
6090 return get_wholeline_compl_info(line, curs_col);
6091 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006092 else if (ctrl_x_mode_files())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006093 {
6094 return get_filename_compl_info(line, startcol, curs_col);
6095 }
6096 else if (ctrl_x_mode == CTRL_X_CMDLINE)
6097 {
6098 return get_cmdline_compl_info(line, curs_col);
6099 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006100 else if (ctrl_x_mode_function() || ctrl_x_mode_omni()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006101 || thesaurus_func_complete(ctrl_x_mode))
6102 {
Girish Palyacbe53192025-04-14 22:13:15 +02006103 if (get_userdefined_compl_info(curs_col, NULL, NULL) != OK)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006104 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006105 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006106 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006107 else if (ctrl_x_mode_spell())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006108 {
6109 if (get_spell_compl_info(startcol, curs_col) == FAIL)
6110 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006111 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006112 }
6113 else
6114 {
6115 internal_error("ins_complete()");
6116 return FAIL;
6117 }
6118
6119 return OK;
6120}
6121
6122/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006123 * Continue an interrupted completion mode search in "line".
6124 *
6125 * If this same ctrl_x_mode has been interrupted use the text from
6126 * "compl_startpos" to the cursor as a pattern to add a new word instead of
6127 * expand the one before the cursor, in word-wise if "compl_startpos" is not in
6128 * the same line as the cursor then fix it (the line has been split because it
6129 * was longer than 'tw'). if SOL is set then skip the previous pattern, a word
6130 * at the beginning of the line has been inserted, we'll look for that.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006131 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006132 static void
6133ins_compl_continue_search(char_u *line)
6134{
6135 // it is a continued search
6136 compl_cont_status &= ~CONT_INTRPT; // remove INTRPT
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006137 if (ctrl_x_mode_normal() || ctrl_x_mode_path_patterns()
6138 || ctrl_x_mode_path_defines())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006139 {
6140 if (compl_startpos.lnum != curwin->w_cursor.lnum)
6141 {
6142 // line (probably) wrapped, set compl_startpos to the
6143 // first non_blank in the line, if it is not a wordchar
6144 // include it to get a better pattern, but then we don't
6145 // want the "\\<" prefix, check it below
6146 compl_col = (colnr_T)getwhitecols(line);
6147 compl_startpos.col = compl_col;
6148 compl_startpos.lnum = curwin->w_cursor.lnum;
6149 compl_cont_status &= ~CONT_SOL; // clear SOL if present
6150 }
6151 else
6152 {
6153 // S_IPOS was set when we inserted a word that was at the
6154 // beginning of the line, which means that we'll go to SOL
6155 // mode but first we need to redefine compl_startpos
6156 if (compl_cont_status & CONT_S_IPOS)
6157 {
6158 compl_cont_status |= CONT_SOL;
6159 compl_startpos.col = (colnr_T)(skipwhite(
6160 line + compl_length
6161 + compl_startpos.col) - line);
6162 }
6163 compl_col = compl_startpos.col;
6164 }
6165 compl_length = curwin->w_cursor.col - (int)compl_col;
6166 // IObuff is used to add a "word from the next line" would we
6167 // have enough space? just being paranoid
6168#define MIN_SPACE 75
6169 if (compl_length > (IOSIZE - MIN_SPACE))
6170 {
6171 compl_cont_status &= ~CONT_SOL;
6172 compl_length = (IOSIZE - MIN_SPACE);
6173 compl_col = curwin->w_cursor.col - compl_length;
6174 }
6175 compl_cont_status |= CONT_ADDING | CONT_N_ADDS;
6176 if (compl_length < 1)
6177 compl_cont_status &= CONT_LOCAL;
6178 }
6179 else if (ctrl_x_mode_line_or_eval())
6180 compl_cont_status = CONT_ADDING | CONT_N_ADDS;
6181 else
6182 compl_cont_status = 0;
6183}
6184
6185/*
6186 * start insert mode completion
6187 */
6188 static int
6189ins_compl_start(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006190{
glepnir19e1dd62025-05-08 22:50:38 +02006191 char_u *line = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006192 int startcol = 0; // column where searched text starts
6193 colnr_T curs_col; // cursor column
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006194 int line_invalid = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006195 int save_did_ai = did_ai;
Bram Moolenaard9eefe32019-04-06 14:22:21 +02006196 int flags = CP_ORIGINAL_TEXT;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006197
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006198 // First time we hit ^N or ^P (in a row, I mean)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006199 did_ai = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006200 did_si = FALSE;
6201 can_si = FALSE;
6202 can_si_back = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006203 if (stop_arrow() == FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006204 return FAIL;
6205
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006206 line = ml_get(curwin->w_cursor.lnum);
6207 curs_col = curwin->w_cursor.col;
6208 compl_pending = 0;
glepnir76bdb822025-02-08 19:04:51 +01006209 compl_lnum = curwin->w_cursor.lnum;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006210
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006211 if ((compl_cont_status & CONT_INTRPT) == CONT_INTRPT
6212 && compl_cont_mode == ctrl_x_mode)
6213 // this same ctrl-x_mode was interrupted previously. Continue the
6214 // completion.
6215 ins_compl_continue_search(line);
6216 else
6217 compl_cont_status &= CONT_LOCAL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006218
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006219 if (!compl_status_adding()) // normal expansion
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006220 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006221 compl_cont_mode = ctrl_x_mode;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006222 if (ctrl_x_mode_not_default())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006223 // Remove LOCAL if ctrl_x_mode != CTRL_X_NORMAL
6224 compl_cont_status = 0;
6225 compl_cont_status |= CONT_N_ADDS;
6226 compl_startpos = curwin->w_cursor;
6227 startcol = (int)curs_col;
6228 compl_col = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006229 }
6230
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006231 // Work out completion pattern and original text -- webb
6232 if (compl_get_info(line, startcol, curs_col, &line_invalid) == FAIL)
6233 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006234 if (ctrl_x_mode_function() || ctrl_x_mode_omni()
6235 || thesaurus_func_complete(ctrl_x_mode))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006236 // restore did_ai, so that adding comment leader works
6237 did_ai = save_did_ai;
6238 return FAIL;
6239 }
6240 // If "line" was changed while getting completion info get it again.
6241 if (line_invalid)
6242 line = ml_get(curwin->w_cursor.lnum);
6243
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006244 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006245 {
6246 edit_submode_pre = (char_u *)_(" Adding");
6247 if (ctrl_x_mode_line_or_eval())
6248 {
6249 // Insert a new line, keep indentation but ignore 'comments'.
6250 char_u *old = curbuf->b_p_com;
6251
6252 curbuf->b_p_com = (char_u *)"";
6253 compl_startpos.lnum = curwin->w_cursor.lnum;
6254 compl_startpos.col = compl_col;
6255 ins_eol('\r');
6256 curbuf->b_p_com = old;
6257 compl_length = 0;
6258 compl_col = curwin->w_cursor.col;
glepnir76bdb822025-02-08 19:04:51 +01006259 compl_lnum = curwin->w_cursor.lnum;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006260 }
glepnircfe502c2025-04-17 20:17:53 +02006261 else if (ctrl_x_mode_normal() && cfc_has_mode())
glepnir7cfe6932024-09-15 20:06:28 +02006262 {
6263 compl_startpos = curwin->w_cursor;
6264 compl_cont_status &= CONT_S_IPOS;
6265 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006266 }
6267 else
6268 {
6269 edit_submode_pre = NULL;
6270 compl_startpos.col = compl_col;
6271 }
6272
6273 if (compl_cont_status & CONT_LOCAL)
6274 edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]);
6275 else
6276 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
6277
6278 // If any of the original typed text has been changed we need to fix
6279 // the redo buffer.
6280 ins_compl_fixRedoBufForLeader(NULL);
6281
6282 // Always add completion for the original text.
John Marriott5e6ea922024-11-23 14:01:57 +01006283 VIM_CLEAR_STRING(compl_orig_text);
6284 compl_orig_text.length = (size_t)compl_length;
6285 compl_orig_text.string = vim_strnsave(line + compl_col, (size_t)compl_length);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006286 if (p_ic)
6287 flags |= CP_ICASE;
zeertzjq4422de62025-03-07 19:06:02 +01006288 if (compl_orig_text.string == NULL
6289 || ins_compl_add(compl_orig_text.string,
6290 (int)compl_orig_text.length,
6291 NULL, NULL, NULL, 0, flags, FALSE, NULL, 0) != OK)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006292 {
John Marriott5e6ea922024-11-23 14:01:57 +01006293 VIM_CLEAR_STRING(compl_pattern);
6294 VIM_CLEAR_STRING(compl_orig_text);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006295 return FAIL;
6296 }
6297
6298 // showmode might reset the internal line pointers, so it must
6299 // be called before line = ml_get(), or when this address is no
6300 // longer needed. -- Acevedo.
6301 edit_submode_extra = (char_u *)_("-- Searching...");
6302 edit_submode_highl = HLF_COUNT;
6303 showmode();
6304 edit_submode_extra = NULL;
6305 out_flush();
6306
6307 return OK;
6308}
6309
6310/*
6311 * display the completion status message
6312 */
6313 static void
6314ins_compl_show_statusmsg(void)
6315{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006316 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006317 if (is_first_match(compl_first_match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006318 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006319 edit_submode_extra = compl_status_adding() && compl_length > 1
Bram Moolenaarb53a1902022-11-15 13:57:38 +00006320 ? (char_u *)_("Hit end of paragraph")
6321 : (char_u *)_("Pattern not found");
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006322 edit_submode_highl = HLF_E;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006323 }
6324
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006325 if (edit_submode_extra == NULL)
6326 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006327 if (match_at_original_text(compl_curr_match))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006328 {
6329 edit_submode_extra = (char_u *)_("Back at original");
6330 edit_submode_highl = HLF_W;
6331 }
6332 else if (compl_cont_status & CONT_S_IPOS)
6333 {
6334 edit_submode_extra = (char_u *)_("Word from other line");
6335 edit_submode_highl = HLF_COUNT;
6336 }
6337 else if (compl_curr_match->cp_next == compl_curr_match->cp_prev)
6338 {
6339 edit_submode_extra = (char_u *)_("The only match");
6340 edit_submode_highl = HLF_COUNT;
Bram Moolenaarf9d51352020-10-26 19:22:42 +01006341 compl_curr_match->cp_number = 1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006342 }
6343 else
6344 {
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01006345#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006346 // Update completion sequence number when needed.
6347 if (compl_curr_match->cp_number == -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01006348 ins_compl_update_sequence_numbers();
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01006349#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006350 // The match should always have a sequence number now, this is
6351 // just a safety check.
6352 if (compl_curr_match->cp_number != -1)
6353 {
6354 // Space for 10 text chars. + 2x10-digit no.s = 31.
6355 // Translations may need more than twice that.
6356 static char_u match_ref[81];
6357
6358 if (compl_matches > 0)
6359 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006360 _("match %d of %d"),
6361 compl_curr_match->cp_number, compl_matches);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006362 else
6363 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006364 _("match %d"),
6365 compl_curr_match->cp_number);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006366 edit_submode_extra = match_ref;
6367 edit_submode_highl = HLF_R;
6368 if (dollar_vcol >= 0)
6369 curs_columns(FALSE);
6370 }
6371 }
6372 }
6373
6374 // Show a message about what (completion) mode we're in.
6375 if (!compl_opt_suppress_empty)
6376 {
6377 showmode();
6378 if (!shortmess(SHM_COMPLETIONMENU))
6379 {
6380 if (edit_submode_extra != NULL)
6381 {
6382 if (!p_smd)
Bram Moolenaarcc233582020-12-12 13:32:07 +01006383 {
6384 msg_hist_off = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006385 msg_attr((char *)edit_submode_extra,
6386 edit_submode_highl < HLF_COUNT
6387 ? HL_ATTR(edit_submode_highl) : 0);
Bram Moolenaarcc233582020-12-12 13:32:07 +01006388 msg_hist_off = FALSE;
6389 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006390 }
6391 else
6392 msg_clr_cmdline(); // necessary for "noshowmode"
6393 }
6394 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006395}
6396
6397/*
6398 * Do Insert mode completion.
6399 * Called when character "c" was typed, which has a meaning for completion.
6400 * Returns OK if completion was done, FAIL if something failed (out of mem).
6401 */
6402 int
6403ins_complete(int c, int enable_pum)
6404{
6405 int n;
6406 int save_w_wrow;
6407 int save_w_leftcol;
6408 int insert_match;
6409
6410 compl_direction = ins_compl_key2dir(c);
6411 insert_match = ins_compl_use_match(c);
6412
6413 if (!compl_started)
6414 {
6415 if (ins_compl_start() == FAIL)
6416 return FAIL;
6417 }
6418 else if (insert_match && stop_arrow() == FAIL)
6419 return FAIL;
6420
glepnircf7f0122025-04-15 19:02:00 +02006421 compl_curr_win = curwin;
6422 compl_curr_buf = curwin->w_buffer;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006423 compl_shown_match = compl_curr_match;
6424 compl_shows_dir = compl_direction;
6425
6426 // Find next match (and following matches).
6427 save_w_wrow = curwin->w_wrow;
6428 save_w_leftcol = curwin->w_leftcol;
6429 n = ins_compl_next(TRUE, ins_compl_key2count(c), insert_match, FALSE);
6430
6431 // may undisplay the popup menu
6432 ins_compl_upd_pum();
6433
6434 if (n > 1) // all matches have been found
6435 compl_matches = n;
6436 compl_curr_match = compl_shown_match;
6437 compl_direction = compl_shows_dir;
6438
6439 // Eat the ESC that vgetc() returns after a CTRL-C to avoid leaving Insert
6440 // mode.
6441 if (got_int && !global_busy)
6442 {
6443 (void)vgetc();
6444 got_int = FALSE;
6445 }
6446
6447 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006448 if (is_first_match(compl_first_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006449 {
6450 // remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,
6451 // because we couldn't expand anything at first place, but if we used
6452 // ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word
6453 // (such as M in M'exico) if not tried already. -- Acevedo
6454 if (compl_length > 1
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006455 || compl_status_adding()
6456 || (ctrl_x_mode_not_default()
6457 && !ctrl_x_mode_path_patterns()
6458 && !ctrl_x_mode_path_defines()))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006459 compl_cont_status &= ~CONT_N_ADDS;
6460 }
6461
6462 if (compl_curr_match->cp_flags & CP_CONT_S_IPOS)
6463 compl_cont_status |= CONT_S_IPOS;
6464 else
6465 compl_cont_status &= ~CONT_S_IPOS;
6466
6467 ins_compl_show_statusmsg();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006468
6469 // Show the popup menu, unless we got interrupted.
6470 if (enable_pum && !compl_interrupted)
6471 show_pum(save_w_wrow, save_w_leftcol);
6472
6473 compl_was_interrupted = compl_interrupted;
6474 compl_interrupted = FALSE;
6475
6476 return OK;
6477}
6478
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00006479/*
6480 * Remove (if needed) and show the popup menu
6481 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006482 static void
6483show_pum(int prev_w_wrow, int prev_w_leftcol)
6484{
6485 // RedrawingDisabled may be set when invoked through complete().
Bram Moolenaar79cdf022023-05-20 14:07:00 +01006486 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006487 RedrawingDisabled = 0;
6488
6489 // If the cursor moved or the display scrolled we need to remove the pum
6490 // first.
6491 setcursor();
6492 if (prev_w_wrow != curwin->w_wrow || prev_w_leftcol != curwin->w_leftcol)
6493 ins_compl_del_pum();
6494
6495 ins_compl_show_pum();
6496 setcursor();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01006497
6498 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006499}
6500
6501/*
6502 * Looks in the first "len" chars. of "src" for search-metachars.
6503 * If dest is not NULL the chars. are copied there quoting (with
6504 * a backslash) the metachars, and dest would be NUL terminated.
6505 * Returns the length (needed) of dest
6506 */
6507 static unsigned
6508quote_meta(char_u *dest, char_u *src, int len)
6509{
6510 unsigned m = (unsigned)len + 1; // one extra for the NUL
6511
6512 for ( ; --len >= 0; src++)
6513 {
6514 switch (*src)
6515 {
6516 case '.':
6517 case '*':
6518 case '[':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006519 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006520 break;
6521 // FALLTHROUGH
6522 case '~':
Bram Moolenaarf4e20992020-12-21 19:59:08 +01006523 if (!magic_isset()) // quote these only if magic is set
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006524 break;
6525 // FALLTHROUGH
6526 case '\\':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006527 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006528 break;
6529 // FALLTHROUGH
6530 case '^': // currently it's not needed.
6531 case '$':
6532 m++;
6533 if (dest != NULL)
6534 *dest++ = '\\';
6535 break;
6536 }
6537 if (dest != NULL)
6538 *dest++ = *src;
6539 // Copy remaining bytes of a multibyte character.
6540 if (has_mbyte)
6541 {
glepnir19e1dd62025-05-08 22:50:38 +02006542 int mb_len = (*mb_ptr2len)(src) - 1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006543 if (mb_len > 0 && len >= mb_len)
glepnir19e1dd62025-05-08 22:50:38 +02006544 for (int i = 0; i < mb_len; ++i)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006545 {
6546 --len;
6547 ++src;
6548 if (dest != NULL)
6549 *dest++ = *src;
6550 }
6551 }
6552 }
6553 if (dest != NULL)
6554 *dest = NUL;
6555
6556 return m;
6557}
6558
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006559#if defined(EXITFREE) || defined(PROTO)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006560 void
6561free_insexpand_stuff(void)
6562{
John Marriott5e6ea922024-11-23 14:01:57 +01006563 VIM_CLEAR_STRING(compl_orig_text);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00006564# ifdef FEAT_EVAL
6565 free_callback(&cfu_cb);
6566 free_callback(&ofu_cb);
6567 free_callback(&tsrfu_cb);
6568# endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006569}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006570#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006571
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006572#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006573/*
6574 * Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly
6575 * spelled word, if there is one.
6576 */
6577 static void
6578spell_back_to_badword(void)
6579{
6580 pos_T tpos = curwin->w_cursor;
6581
Christ van Willegen - van Noort8e4c4c72024-05-17 18:49:27 +02006582 spell_bad_len = spell_move_to(curwin, BACKWARD, SMT_ALL, TRUE, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006583 if (curwin->w_cursor.col != tpos.col)
6584 start_arrow(&tpos);
6585}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006586#endif
Girish Palyacbe53192025-04-14 22:13:15 +02006587
6588/*
6589 * Reset the info associated with completion sources.
6590 */
6591 static void
Girish Palya0ac1eb32025-04-16 20:18:33 +02006592cpt_sources_clear(void)
Girish Palyacbe53192025-04-14 22:13:15 +02006593{
Girish Palya0ac1eb32025-04-16 20:18:33 +02006594 VIM_CLEAR(cpt_sources_array);
6595 cpt_sources_index = -1;
6596 cpt_sources_count = 0;
Girish Palyacbe53192025-04-14 22:13:15 +02006597}
6598
6599/*
6600 * Initialize the info associated with completion sources.
6601 */
6602 static int
Girish Palya0ac1eb32025-04-16 20:18:33 +02006603cpt_sources_init(void)
Girish Palyacbe53192025-04-14 22:13:15 +02006604{
Girish Palya0ac1eb32025-04-16 20:18:33 +02006605 char_u buf[LSIZE];
6606 int slen;
Girish Palyacbe53192025-04-14 22:13:15 +02006607 int count = 0;
Girish Palya0ac1eb32025-04-16 20:18:33 +02006608 char_u *p;
Girish Palyacbe53192025-04-14 22:13:15 +02006609
Girish Palya0ac1eb32025-04-16 20:18:33 +02006610 for (p = curbuf->b_p_cpt; *p;)
Girish Palyacbe53192025-04-14 22:13:15 +02006611 {
6612 while (*p == ',' || *p == ' ') // Skip delimiters
6613 p++;
6614 if (*p) // If not end of string, count this segment
6615 {
Girish Palya0ac1eb32025-04-16 20:18:33 +02006616 (void)copy_option_part(&p, buf, LSIZE, ","); // Advance p
Girish Palyacbe53192025-04-14 22:13:15 +02006617 count++;
Girish Palyacbe53192025-04-14 22:13:15 +02006618 }
6619 }
Girish Palya0ac1eb32025-04-16 20:18:33 +02006620 cpt_sources_clear();
6621 cpt_sources_count = count;
Girish Palyacbe53192025-04-14 22:13:15 +02006622 if (count > 0)
6623 {
Girish Palya0ac1eb32025-04-16 20:18:33 +02006624 cpt_sources_array = ALLOC_CLEAR_MULT(cpt_source_T, count);
6625 if (cpt_sources_array == NULL)
Girish Palyacbe53192025-04-14 22:13:15 +02006626 {
Girish Palya0ac1eb32025-04-16 20:18:33 +02006627 cpt_sources_count = 0;
Girish Palyacbe53192025-04-14 22:13:15 +02006628 return FAIL;
6629 }
Girish Palya0ac1eb32025-04-16 20:18:33 +02006630 count = 0;
6631 for (p = curbuf->b_p_cpt; *p;)
6632 {
6633 while (*p == ',' || *p == ' ') // Skip delimiters
6634 p++;
6635 if (*p) // If not end of string, count this segment
6636 {
6637 char_u *t;
6638
6639 vim_memset(buf, 0, LSIZE);
6640 slen = copy_option_part(&p, buf, LSIZE, ","); // Advance p
6641 if (slen > 0 && (t = vim_strchr(buf, '^')) != NULL)
6642 cpt_sources_array[count].max_matches = atoi((char *)t + 1);
6643 count++;
6644 }
6645 }
Girish Palyacbe53192025-04-14 22:13:15 +02006646 }
6647 return OK;
6648}
6649
6650/*
6651 * Return TRUE if any of the completion sources have 'refresh' set to 'always'.
6652 */
6653 static int
6654is_cpt_func_refresh_always(void)
6655{
6656#ifdef FEAT_COMPL_FUNC
glepnir19e1dd62025-05-08 22:50:38 +02006657 for (int i = 0; i < cpt_sources_count; i++)
Girish Palya0ac1eb32025-04-16 20:18:33 +02006658 if (cpt_sources_array[i].refresh_always)
Girish Palyacbe53192025-04-14 22:13:15 +02006659 return TRUE;
6660#endif
6661 return FALSE;
6662}
6663
6664/*
6665 * Make the completion list non-cyclic.
6666 */
6667#ifdef FEAT_COMPL_FUNC
6668 static void
6669ins_compl_make_linear(void)
6670{
6671 compl_T *m;
6672
6673 if (compl_first_match == NULL || compl_first_match->cp_prev == NULL)
6674 return;
6675 m = compl_first_match->cp_prev;
6676 m->cp_next = NULL;
6677 compl_first_match->cp_prev = NULL;
6678}
6679#endif
6680
6681/*
6682 * Remove the matches linked to the current completion source (as indicated by
Girish Palya0ac1eb32025-04-16 20:18:33 +02006683 * cpt_sources_index) from the completion list.
Girish Palyacbe53192025-04-14 22:13:15 +02006684 */
6685#ifdef FEAT_COMPL_FUNC
6686 static compl_T *
6687remove_old_matches(void)
6688{
6689 compl_T *sublist_start = NULL, *sublist_end = NULL, *insert_at = NULL;
6690 compl_T *current, *next;
Girish Palya0ac1eb32025-04-16 20:18:33 +02006691 int compl_shown_removed = FALSE;
6692 int forward = (compl_first_match->cp_cpt_source_idx < 0);
6693
6694 compl_direction = forward ? FORWARD : BACKWARD;
6695 compl_shows_dir = compl_direction;
Girish Palyacbe53192025-04-14 22:13:15 +02006696
6697 // Identify the sublist of old matches that needs removal
6698 for (current = compl_first_match; current != NULL; current = current->cp_next)
6699 {
Girish Palya0ac1eb32025-04-16 20:18:33 +02006700 if (current->cp_cpt_source_idx < cpt_sources_index &&
6701 (forward || (!forward && !insert_at)))
Girish Palyacbe53192025-04-14 22:13:15 +02006702 insert_at = current;
6703
Girish Palya0ac1eb32025-04-16 20:18:33 +02006704 if (current->cp_cpt_source_idx == cpt_sources_index)
Girish Palyacbe53192025-04-14 22:13:15 +02006705 {
6706 if (!sublist_start)
6707 sublist_start = current;
6708 sublist_end = current;
6709 if (!compl_shown_removed && compl_shown_match == current)
6710 compl_shown_removed = TRUE;
6711 }
6712
Girish Palya0ac1eb32025-04-16 20:18:33 +02006713 if ((forward && current->cp_cpt_source_idx > cpt_sources_index)
6714 || (!forward && insert_at))
Girish Palyacbe53192025-04-14 22:13:15 +02006715 break;
6716 }
6717
6718 // Re-assign compl_shown_match if necessary
6719 if (compl_shown_removed)
6720 {
6721 if (forward)
6722 compl_shown_match = compl_first_match;
6723 else
6724 { // Last node will have the prefix that is being completed
Girish Palya0ac1eb32025-04-16 20:18:33 +02006725 for (current = compl_first_match; current->cp_next != NULL;
6726 current = current->cp_next)
Girish Palyacbe53192025-04-14 22:13:15 +02006727 ;
6728 compl_shown_match = current;
6729 }
6730 }
6731
6732 if (!sublist_start) // No nodes to remove
6733 return insert_at;
6734
6735 // Update links to remove sublist
6736 if (sublist_start->cp_prev)
6737 sublist_start->cp_prev->cp_next = sublist_end->cp_next;
6738 else
6739 compl_first_match = sublist_end->cp_next;
6740
6741 if (sublist_end->cp_next)
6742 sublist_end->cp_next->cp_prev = sublist_start->cp_prev;
6743
6744 // Free all nodes in the sublist
6745 sublist_end->cp_next = NULL;
6746 for (current = sublist_start; current != NULL; current = next)
6747 {
6748 next = current->cp_next;
6749 ins_compl_item_free(current);
6750 }
6751
6752 return insert_at;
6753}
6754#endif
6755
6756/*
6757 * Retrieve completion matches using the callback function "cb" and store the
6758 * 'refresh:always' flag.
6759 */
6760#ifdef FEAT_COMPL_FUNC
6761 static void
6762get_cpt_func_completion_matches(callback_T *cb UNUSED)
6763{
glepnir19e1dd62025-05-08 22:50:38 +02006764 int ret;
6765 int startcol;
Girish Palyacbe53192025-04-14 22:13:15 +02006766
6767 VIM_CLEAR_STRING(cpt_compl_pattern);
6768 ret = get_userdefined_compl_info(curwin->w_cursor.col, cb, &startcol);
6769 if (ret == FAIL && startcol == -3)
Girish Palya0ac1eb32025-04-16 20:18:33 +02006770 cpt_sources_array[cpt_sources_index].refresh_always = FALSE;
Girish Palyacbe53192025-04-14 22:13:15 +02006771 else if (ret == OK)
6772 {
6773 expand_by_function(0, cpt_compl_pattern.string, cb);
Girish Palya0ac1eb32025-04-16 20:18:33 +02006774 cpt_sources_array[cpt_sources_index].refresh_always =
6775 compl_opt_refresh_always;
Girish Palyacbe53192025-04-14 22:13:15 +02006776 compl_opt_refresh_always = FALSE;
6777 }
6778}
6779#endif
6780
6781/*
6782 * Retrieve completion matches from functions in the 'cpt' option where the
6783 * 'refresh:always' flag is set.
6784 */
6785 static void
6786cpt_compl_refresh(void)
6787{
6788#ifdef FEAT_COMPL_FUNC
6789 char_u *cpt;
6790 char_u *p;
Christian Brabandtd2079cf2025-04-15 18:10:26 +02006791 callback_T *cb = NULL;
Girish Palyacbe53192025-04-14 22:13:15 +02006792
6793 // Make the completion list linear (non-cyclic)
6794 ins_compl_make_linear();
6795 // Make a copy of 'cpt' in case the buffer gets wiped out
6796 cpt = vim_strsave(curbuf->b_p_cpt);
Girish Palya0ac1eb32025-04-16 20:18:33 +02006797 strip_caret_numbers_in_place(cpt);
Girish Palyacbe53192025-04-14 22:13:15 +02006798
Girish Palya0ac1eb32025-04-16 20:18:33 +02006799 cpt_sources_index = 0;
6800 for (p = cpt; *p; cpt_sources_index++)
Girish Palyacbe53192025-04-14 22:13:15 +02006801 {
6802 while (*p == ',' || *p == ' ') // Skip delimiters
6803 p++;
6804
Girish Palya0ac1eb32025-04-16 20:18:33 +02006805 if (cpt_sources_array[cpt_sources_index].refresh_always)
Girish Palyacbe53192025-04-14 22:13:15 +02006806 {
6807 if (*p == 'o')
6808 cb = &curbuf->b_ofu_cb;
6809 else if (*p == 'f')
6810 cb = (*(p + 1) != ',' && *(p + 1) != NUL)
6811 ? get_cpt_func_callback(p + 1) : &curbuf->b_cfu_cb;
6812 if (cb)
6813 {
6814 compl_curr_match = remove_old_matches();
6815 get_cpt_func_completion_matches(cb);
6816 }
6817 }
6818
6819 copy_option_part(&p, IObuff, IOSIZE, ","); // Advance p
6820 }
Girish Palya0ac1eb32025-04-16 20:18:33 +02006821 cpt_sources_index = -1;
Girish Palyacbe53192025-04-14 22:13:15 +02006822
6823 vim_free(cpt);
6824 // Make the list cyclic
6825 compl_matches = ins_compl_make_cyclic();
6826#endif
6827}