blob: 5f5a5b90579c6b9972adcafc66521e5df3c003df [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 {
glepnir8d0e42b2025-05-12 20:28:28 +02003668 int len = 0;
3669 if (*p == ',' && *(p+1) == ' ' && (*(p+2) == ',' || *(p+2) == NUL))
3670 {
3671 part[0] = ' ';
3672 len = 1;
3673 p++;
3674 }
3675 else
3676 len = copy_option_part(&p, part, MAXPATHL, ",");
glepnirbcd59952025-04-24 21:48:35 +02003677
3678 if (len > 0 && len <= col)
3679 {
3680 if (STRNCMP(cur_end - len, part, len) == 0)
3681 {
3682 bytepos = col - len;
3683 if (add_match_to_list(rettv, part, len, bytepos) == FAIL)
3684 {
3685 vim_free(before_cursor);
3686 return;
3687 }
3688 }
3689 }
3690 }
3691 }
3692
3693 vim_free(before_cursor);
3694}
3695
3696/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003697 * Return Insert completion mode name string
3698 */
3699 static char_u *
3700ins_compl_mode(void)
3701{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003702 if (ctrl_x_mode_not_defined_yet() || ctrl_x_mode_scroll() || compl_started)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003703 return (char_u *)ctrl_x_mode_names[ctrl_x_mode & ~CTRL_X_WANT_IDENT];
3704
3705 return (char_u *)"";
3706}
3707
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00003708/*
3709 * Assign the sequence number to all the completion matches which don't have
3710 * one assigned yet.
3711 */
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003712 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003713ins_compl_update_sequence_numbers(void)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003714{
3715 int number = 0;
3716 compl_T *match;
3717
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003718 if (compl_dir_forward())
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003719 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003720 // Search backwards for the first valid (!= -1) number.
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003721 // This should normally succeed already at the first loop
3722 // cycle, so it's fast!
3723 for (match = compl_curr_match->cp_prev; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003724 && !is_first_match(match); match = match->cp_prev)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003725 if (match->cp_number != -1)
3726 {
3727 number = match->cp_number;
3728 break;
3729 }
3730 if (match != NULL)
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003731 // go up and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003732 for (match = match->cp_next;
3733 match != NULL && match->cp_number == -1;
3734 match = match->cp_next)
3735 match->cp_number = ++number;
3736 }
3737 else // BACKWARD
3738 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003739 // Search forwards (upwards) for the first valid (!= -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003740 // number. This should normally succeed already at the
3741 // first loop cycle, so it's fast!
3742 for (match = compl_curr_match->cp_next; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003743 && !is_first_match(match); match = match->cp_next)
glepnir40891ba2025-02-10 22:18:00 +01003744 {
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003745 if (match->cp_number != -1)
3746 {
3747 number = match->cp_number;
3748 break;
3749 }
glepnir40891ba2025-02-10 22:18:00 +01003750 }
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003751 if (match != NULL)
glepnir40891ba2025-02-10 22:18:00 +01003752 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003753 // go down and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003754 for (match = match->cp_prev; match
3755 && match->cp_number == -1;
3756 match = match->cp_prev)
3757 match->cp_number = ++number;
glepnir40891ba2025-02-10 22:18:00 +01003758 }
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003759 }
3760}
3761
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003762/*
glepnir037b0282025-01-16 14:37:44 +01003763 * Fill the dict of complete_info
3764 */
3765 static void
3766fill_complete_info_dict(dict_T *di, compl_T *match, int add_match)
3767{
3768 dict_add_string(di, "word", match->cp_str.string);
3769 dict_add_string(di, "abbr", match->cp_text[CPT_ABBR]);
3770 dict_add_string(di, "menu", match->cp_text[CPT_MENU]);
3771 dict_add_string(di, "kind", match->cp_text[CPT_KIND]);
3772 dict_add_string(di, "info", match->cp_text[CPT_INFO]);
3773 if (add_match)
Hirohito Higashi355db992025-04-28 18:07:02 +02003774 dict_add_bool(di, "match", match->cp_in_match_array);
glepnir037b0282025-01-16 14:37:44 +01003775 if (match->cp_user_data.v_type == VAR_UNKNOWN)
Hirohito Higashi355db992025-04-28 18:07:02 +02003776 // Add an empty string for backwards compatibility
3777 dict_add_string(di, "user_data", (char_u *)"");
glepnir037b0282025-01-16 14:37:44 +01003778 else
Hirohito Higashi355db992025-04-28 18:07:02 +02003779 dict_add_tv(di, "user_data", &match->cp_user_data);
glepnir037b0282025-01-16 14:37:44 +01003780}
3781
3782/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003783 * Get complete information
3784 */
3785 static void
3786get_complete_info(list_T *what_list, dict_T *retdict)
3787{
3788 int ret = OK;
3789 listitem_T *item;
3790#define CI_WHAT_MODE 0x01
3791#define CI_WHAT_PUM_VISIBLE 0x02
3792#define CI_WHAT_ITEMS 0x04
3793#define CI_WHAT_SELECTED 0x08
glepnir037b0282025-01-16 14:37:44 +01003794#define CI_WHAT_COMPLETED 0x10
glepnird4088ed2024-12-31 10:55:22 +01003795#define CI_WHAT_MATCHES 0x20
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003796#define CI_WHAT_ALL 0xff
3797 int what_flag;
Girish Palya0ac1eb32025-04-16 20:18:33 +02003798 int compl_fuzzy_match = (get_cot_flags() & COT_FUZZY) != 0;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003799
3800 if (what_list == NULL)
glepnir037b0282025-01-16 14:37:44 +01003801 what_flag = CI_WHAT_ALL & ~(CI_WHAT_MATCHES | CI_WHAT_COMPLETED);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003802 else
3803 {
3804 what_flag = 0;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003805 CHECK_LIST_MATERIALIZE(what_list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003806 FOR_ALL_LIST_ITEMS(what_list, item)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003807 {
3808 char_u *what = tv_get_string(&item->li_tv);
3809
3810 if (STRCMP(what, "mode") == 0)
3811 what_flag |= CI_WHAT_MODE;
3812 else if (STRCMP(what, "pum_visible") == 0)
3813 what_flag |= CI_WHAT_PUM_VISIBLE;
3814 else if (STRCMP(what, "items") == 0)
3815 what_flag |= CI_WHAT_ITEMS;
3816 else if (STRCMP(what, "selected") == 0)
3817 what_flag |= CI_WHAT_SELECTED;
glepnir037b0282025-01-16 14:37:44 +01003818 else if (STRCMP(what, "completed") == 0)
3819 what_flag |= CI_WHAT_COMPLETED;
glepnird4088ed2024-12-31 10:55:22 +01003820 else if (STRCMP(what, "matches") == 0)
3821 what_flag |= CI_WHAT_MATCHES;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003822 }
3823 }
3824
3825 if (ret == OK && (what_flag & CI_WHAT_MODE))
3826 ret = dict_add_string(retdict, "mode", ins_compl_mode());
3827
3828 if (ret == OK && (what_flag & CI_WHAT_PUM_VISIBLE))
3829 ret = dict_add_number(retdict, "pum_visible", pum_visible());
3830
glepnir037b0282025-01-16 14:37:44 +01003831 if (ret == OK && (what_flag & (CI_WHAT_ITEMS | CI_WHAT_SELECTED
3832 | CI_WHAT_MATCHES | CI_WHAT_COMPLETED)))
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003833 {
Christian Brabandt9eb236f2024-03-21 20:12:59 +01003834 list_T *li = NULL;
Girish Palya8950bf72024-03-20 20:07:29 +01003835 dict_T *di;
3836 compl_T *match;
3837 int selected_idx = -1;
glepnird4088ed2024-12-31 10:55:22 +01003838 int has_items = what_flag & CI_WHAT_ITEMS;
3839 int has_matches = what_flag & CI_WHAT_MATCHES;
glepnir037b0282025-01-16 14:37:44 +01003840 int has_completed = what_flag & CI_WHAT_COMPLETED;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003841
glepnird4088ed2024-12-31 10:55:22 +01003842 if (has_items || has_matches)
Girish Palya8950bf72024-03-20 20:07:29 +01003843 {
3844 li = list_alloc();
3845 if (li == NULL)
3846 return;
glepnird4088ed2024-12-31 10:55:22 +01003847 ret = dict_add_list(retdict, (has_matches && !has_items)
3848 ? "matches" : "items", li);
Girish Palya8950bf72024-03-20 20:07:29 +01003849 }
3850 if (ret == OK && what_flag & CI_WHAT_SELECTED)
3851 if (compl_curr_match != NULL && compl_curr_match->cp_number == -1)
3852 ins_compl_update_sequence_numbers();
3853 if (ret == OK && compl_first_match != NULL)
3854 {
3855 int list_idx = 0;
3856 match = compl_first_match;
3857 do
3858 {
3859 if (!match_at_original_text(match))
3860 {
glepnird4088ed2024-12-31 10:55:22 +01003861 if (has_items
3862 || (has_matches && match->cp_in_match_array))
Girish Palya8950bf72024-03-20 20:07:29 +01003863 {
3864 di = dict_alloc();
3865 if (di == NULL)
3866 return;
3867 ret = list_append_dict(li, di);
3868 if (ret != OK)
3869 return;
glepnir037b0282025-01-16 14:37:44 +01003870 fill_complete_info_dict(di, match, has_matches && has_items);
Girish Palya8950bf72024-03-20 20:07:29 +01003871 }
glepnird4088ed2024-12-31 10:55:22 +01003872 if (compl_curr_match != NULL
3873 && compl_curr_match->cp_number == match->cp_number)
Girish Palya8950bf72024-03-20 20:07:29 +01003874 selected_idx = list_idx;
Girish Palya0ac1eb32025-04-16 20:18:33 +02003875 if (compl_fuzzy_match || match->cp_in_match_array)
3876 list_idx += 1;
Girish Palya8950bf72024-03-20 20:07:29 +01003877 }
3878 match = match->cp_next;
3879 }
3880 while (match != NULL && !is_first_match(match));
3881 }
3882 if (ret == OK && (what_flag & CI_WHAT_SELECTED))
3883 ret = dict_add_number(retdict, "selected", selected_idx);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003884
glepnir037b0282025-01-16 14:37:44 +01003885 if (ret == OK && selected_idx != -1 && has_completed)
3886 {
3887 di = dict_alloc();
3888 if (di == NULL)
3889 return;
3890 fill_complete_info_dict(di, compl_curr_match, FALSE);
3891 ret = dict_add_dict(retdict, "completed", di);
3892 }
Yegappan Lakshmanan6b085b92022-09-04 12:47:21 +01003893 }
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003894}
3895
3896/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003897 * "complete_info()" function
3898 */
3899 void
3900f_complete_info(typval_T *argvars, typval_T *rettv)
3901{
3902 list_T *what_list = NULL;
3903
Bram Moolenaar93a10962022-06-16 11:42:09 +01003904 if (rettv_dict_alloc(rettv) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003905 return;
3906
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003907 if (in_vim9script() && check_for_opt_list_arg(argvars, 0) == FAIL)
3908 return;
3909
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003910 if (argvars[0].v_type != VAR_UNKNOWN)
3911 {
Bram Moolenaard83392a2022-09-01 12:22:46 +01003912 if (check_for_list_arg(argvars, 0) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003913 return;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003914 what_list = argvars[0].vval.v_list;
3915 }
3916 get_complete_info(what_list, rettv->vval.v_dict);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003917}
3918#endif
3919
3920/*
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003921 * Returns TRUE when using a user-defined function for thesaurus completion.
3922 */
3923 static int
3924thesaurus_func_complete(int type UNUSED)
3925{
3926#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01003927 return type == CTRL_X_THESAURUS
3928 && (*curbuf->b_p_tsrfu != NUL || *p_tsrfu != NUL);
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003929#else
3930 return FALSE;
3931#endif
3932}
3933
3934/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003935 * Return value of process_next_cpt_value()
3936 */
3937enum
3938{
3939 INS_COMPL_CPT_OK = 1,
3940 INS_COMPL_CPT_CONT,
3941 INS_COMPL_CPT_END
3942};
3943
3944/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003945 * state information used for getting the next set of insert completion
3946 * matches.
3947 */
3948typedef struct
3949{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003950 char_u *e_cpt_copy; // copy of 'complete'
3951 char_u *e_cpt; // current entry in "e_cpt_copy"
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003952 buf_T *ins_buf; // buffer being scanned
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003953 pos_T *cur_match_pos; // current match position
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003954 pos_T prev_match_pos; // previous match position
3955 int set_match_pos; // save first_match_pos/last_match_pos
3956 pos_T first_match_pos; // first match position
3957 pos_T last_match_pos; // last match position
3958 int found_all; // found all matches of a certain type.
3959 char_u *dict; // dictionary file to search
3960 int dict_f; // "dict" is an exact file name or not
Girish Palyacbe53192025-04-14 22:13:15 +02003961 callback_T *func_cb; // callback of function in 'cpt' option
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003962} ins_compl_next_state_T;
3963
3964/*
3965 * Process the next 'complete' option value in st->e_cpt.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003966 *
3967 * If successful, the arguments are set as below:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003968 * st->cpt - pointer to the next option value in "st->cpt"
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003969 * compl_type_arg - type of insert mode completion to use
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003970 * st->found_all - all matches of this type are found
3971 * st->ins_buf - search for completions in this buffer
3972 * st->first_match_pos - position of the first completion match
3973 * st->last_match_pos - position of the last completion match
3974 * st->set_match_pos - TRUE if the first match position should be saved to
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01003975 * avoid loops after the search wraps around.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003976 * st->dict - name of the dictionary or thesaurus file to search
3977 * st->dict_f - flag specifying whether "dict" is an exact file name or not
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003978 *
3979 * Returns INS_COMPL_CPT_OK if the next value is processed successfully.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003980 * Returns INS_COMPL_CPT_CONT to skip the current completion source matching
3981 * the "st->e_cpt" option value and process the next matching source.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003982 * Returns INS_COMPL_CPT_END if all the values in "st->e_cpt" are processed.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003983 */
3984 static int
3985process_next_cpt_value(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003986 ins_compl_next_state_T *st,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003987 int *compl_type_arg,
glepnir8159fb12024-07-17 20:32:54 +02003988 pos_T *start_match_pos,
glepnir53b14572025-03-12 21:28:39 +01003989 int fuzzy_collect)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003990{
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003991 int compl_type = -1;
3992 int status = INS_COMPL_CPT_OK;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003993
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003994 st->found_all = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003995
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003996 while (*st->e_cpt == ',' || *st->e_cpt == ' ')
3997 st->e_cpt++;
3998
3999 if (*st->e_cpt == '.' && !curbuf->b_scanned)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004000 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004001 st->ins_buf = curbuf;
4002 st->first_match_pos = *start_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004003 // Move the cursor back one character so that ^N can match the
4004 // word immediately after the cursor.
glepnir53b14572025-03-12 21:28:39 +01004005 if (ctrl_x_mode_normal() && (!fuzzy_collect && dec(&st->first_match_pos) < 0))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004006 {
4007 // Move the cursor to after the last character in the
4008 // buffer, so that word at start of buffer is found
4009 // correctly.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004010 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count;
zeertzjq94b7c322024-03-12 21:50:32 +01004011 st->first_match_pos.col = ml_get_len(st->first_match_pos.lnum);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004012 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004013 st->last_match_pos = st->first_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004014 compl_type = 0;
4015
4016 // Remember the first match so that the loop stops when we
4017 // wrap and come back there a second time.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004018 st->set_match_pos = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004019 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004020 else if (vim_strchr((char_u *)"buwU", *st->e_cpt) != NULL
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004021 && (st->ins_buf = ins_compl_next_buf(
4022 st->ins_buf, *st->e_cpt)) != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004023 {
4024 // Scan a buffer, but not the current one.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004025 if (st->ins_buf->b_ml.ml_mfp != NULL) // loaded buffer
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004026 {
4027 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004028 st->first_match_pos.col = st->last_match_pos.col = 0;
4029 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count + 1;
4030 st->last_match_pos.lnum = 0;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004031 compl_type = 0;
4032 }
4033 else // unloaded buffer, scan like dictionary
4034 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004035 st->found_all = TRUE;
4036 if (st->ins_buf->b_fname == NULL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004037 {
4038 status = INS_COMPL_CPT_CONT;
4039 goto done;
4040 }
4041 compl_type = CTRL_X_DICTIONARY;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004042 st->dict = st->ins_buf->b_fname;
4043 st->dict_f = DICT_EXACT;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004044 }
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01004045 if (!shortmess(SHM_COMPLETIONSCAN))
4046 {
4047 msg_hist_off = TRUE; // reset in msg_trunc_attr()
4048 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning: %s"),
4049 st->ins_buf->b_fname == NULL
4050 ? buf_spname(st->ins_buf)
4051 : st->ins_buf->b_sfname == NULL
4052 ? st->ins_buf->b_fname
4053 : st->ins_buf->b_sfname);
4054 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
4055 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004056 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004057 else if (*st->e_cpt == NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004058 status = INS_COMPL_CPT_END;
4059 else
4060 {
4061 if (ctrl_x_mode_line_or_eval())
4062 compl_type = -1;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004063 else if (*st->e_cpt == 'k' || *st->e_cpt == 's')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004064 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004065 if (*st->e_cpt == 'k')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004066 compl_type = CTRL_X_DICTIONARY;
4067 else
4068 compl_type = CTRL_X_THESAURUS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004069 if (*++st->e_cpt != ',' && *st->e_cpt != NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004070 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004071 st->dict = st->e_cpt;
4072 st->dict_f = DICT_FIRST;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004073 }
4074 }
Girish Palyacbe53192025-04-14 22:13:15 +02004075#ifdef FEAT_COMPL_FUNC
4076 else if (*st->e_cpt == 'f' || *st->e_cpt == 'o')
4077 {
4078 compl_type = CTRL_X_FUNCTION;
4079 if (*st->e_cpt == 'o')
4080 st->func_cb = &curbuf->b_ofu_cb;
4081 else
4082 st->func_cb = (*++st->e_cpt != ',' && *st->e_cpt != NUL)
4083 ? get_cpt_func_callback(st->e_cpt) : &curbuf->b_cfu_cb;
4084 if (!st->func_cb)
4085 compl_type = -1;
4086 }
4087#endif
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004088#ifdef FEAT_FIND_ID
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004089 else if (*st->e_cpt == 'i')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004090 compl_type = CTRL_X_PATH_PATTERNS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004091 else if (*st->e_cpt == 'd')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004092 compl_type = CTRL_X_PATH_DEFINES;
4093#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004094 else if (*st->e_cpt == ']' || *st->e_cpt == 't')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004095 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004096 compl_type = CTRL_X_TAGS;
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01004097 if (!shortmess(SHM_COMPLETIONSCAN))
4098 {
4099 msg_hist_off = TRUE; // reset in msg_trunc_attr()
4100 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning tags."));
4101 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
4102 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004103 }
4104 else
4105 compl_type = -1;
4106
4107 // in any case e_cpt is advanced to the next entry
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004108 (void)copy_option_part(&st->e_cpt, IObuff, IOSIZE, ",");
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004109
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004110 st->found_all = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004111 if (compl_type == -1)
4112 status = INS_COMPL_CPT_CONT;
4113 }
4114
4115done:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004116 *compl_type_arg = compl_type;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004117 return status;
4118}
4119
4120#ifdef FEAT_FIND_ID
4121/*
4122 * Get the next set of identifiers or defines matching "compl_pattern" in
4123 * included files.
4124 */
4125 static void
4126get_next_include_file_completion(int compl_type)
4127{
John Marriott5e6ea922024-11-23 14:01:57 +01004128 find_pattern_in_path(compl_pattern.string, compl_direction,
4129 (int)compl_pattern.length, FALSE, FALSE,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004130 (compl_type == CTRL_X_PATH_DEFINES
4131 && !(compl_cont_status & CONT_SOL))
4132 ? FIND_DEFINE : FIND_ANY, 1L, ACTION_EXPAND,
Colin Kennedy21570352024-03-03 16:16:47 +01004133 (linenr_T)1, (linenr_T)MAXLNUM, FALSE);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004134}
4135#endif
4136
4137/*
4138 * Get the next set of words matching "compl_pattern" in dictionary or
4139 * thesaurus files.
4140 */
4141 static void
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004142get_next_dict_tsr_completion(int compl_type, char_u *dict, int dict_f)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004143{
4144#ifdef FEAT_COMPL_FUNC
4145 if (thesaurus_func_complete(compl_type))
Girish Palyacbe53192025-04-14 22:13:15 +02004146 expand_by_function(compl_type, compl_pattern.string, NULL);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004147 else
4148#endif
4149 ins_compl_dictionaries(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004150 dict != NULL ? dict
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004151 : (compl_type == CTRL_X_THESAURUS
4152 ? (*curbuf->b_p_tsr == NUL ? p_tsr : curbuf->b_p_tsr)
4153 : (*curbuf->b_p_dict == NUL ? p_dict : curbuf->b_p_dict)),
John Marriott5e6ea922024-11-23 14:01:57 +01004154 compl_pattern.string,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004155 dict != NULL ? dict_f : 0,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004156 compl_type == CTRL_X_THESAURUS);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004157}
4158
4159/*
4160 * Get the next set of tag names matching "compl_pattern".
4161 */
4162 static void
4163get_next_tag_completion(void)
4164{
4165 int save_p_ic;
4166 char_u **matches;
4167 int num_matches;
4168
4169 // set p_ic according to p_ic, p_scs and pat for find_tags().
4170 save_p_ic = p_ic;
John Marriott5e6ea922024-11-23 14:01:57 +01004171 p_ic = ignorecase(compl_pattern.string);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004172
4173 // Find up to TAG_MANY matches. Avoids that an enormous number
4174 // of matches is found when compl_pattern is empty
4175 g_tag_at_cursor = TRUE;
John Marriott5e6ea922024-11-23 14:01:57 +01004176 if (find_tags(compl_pattern.string, &num_matches, &matches,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004177 TAG_REGEXP | TAG_NAMES | TAG_NOIC | TAG_INS_COMP
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004178 | (ctrl_x_mode_not_default() ? TAG_VERBOSE : 0),
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004179 TAG_MANY, curbuf->b_ffname) == OK && num_matches > 0)
4180 ins_compl_add_matches(num_matches, matches, p_ic);
4181 g_tag_at_cursor = FALSE;
4182 p_ic = save_p_ic;
4183}
4184
4185/*
glepnir8159fb12024-07-17 20:32:54 +02004186 * Compare function for qsort
4187 */
glepnirf31cfa22025-03-06 21:59:13 +01004188 static int
4189compare_scores(const void *a, const void *b)
glepnir8159fb12024-07-17 20:32:54 +02004190{
4191 int idx_a = *(const int *)a;
4192 int idx_b = *(const int *)b;
4193 int score_a = compl_fuzzy_scores[idx_a];
4194 int score_b = compl_fuzzy_scores[idx_b];
zeertzjq58d70522024-08-31 17:05:39 +02004195 return score_a == score_b ? (idx_a == idx_b ? 0 : (idx_a < idx_b ? -1 : 1))
4196 : (score_a > score_b ? -1 : 1);
glepnir8159fb12024-07-17 20:32:54 +02004197}
4198
4199/*
glepnirf31cfa22025-03-06 21:59:13 +01004200 * insert prefix with redraw
4201 */
4202 static void
4203ins_compl_longest_insert(char_u *prefix)
4204{
4205 ins_compl_delete();
4206 ins_compl_insert_bytes(prefix + get_compl_len(), -1);
4207 ins_redraw(FALSE);
4208}
4209
4210/*
4211 * Calculate the longest common prefix among the best fuzzy matches
4212 * stored in compl_best_matches, and insert it as the longest.
4213 */
4214 static void
4215fuzzy_longest_match(void)
4216{
4217 char_u *prefix = NULL;
4218 int prefix_len = 0;
4219 int i = 0;
4220 int j = 0;
4221 char_u *match_str = NULL;
4222 char_u *prefix_ptr = NULL;
4223 char_u *match_ptr = NULL;
4224 char_u *leader = NULL;
4225 size_t leader_len = 0;
4226 compl_T *compl = NULL;
4227 int more_candidates = FALSE;
4228 compl_T *nn_compl = NULL;
4229
4230 if (compl_num_bests == 0)
Hirohito Higashi355db992025-04-28 18:07:02 +02004231 return;
glepnirf31cfa22025-03-06 21:59:13 +01004232
4233 nn_compl = compl_first_match->cp_next->cp_next;
4234 if (nn_compl && nn_compl != compl_first_match)
4235 more_candidates = TRUE;
4236
4237 compl = ctrl_x_mode_whole_line() ? compl_first_match
4238 : compl_first_match->cp_next;
4239 if (compl_num_bests == 1)
4240 {
4241 // no more candidates insert the match str
4242 if (!more_candidates)
4243 {
4244 ins_compl_longest_insert(compl->cp_str.string);
4245 compl_num_bests = 0;
4246 }
4247 compl_num_bests = 0;
4248 return;
4249 }
4250
4251 compl_best_matches = (compl_T **)alloc(compl_num_bests * sizeof(compl_T *));
4252 if (compl_best_matches == NULL)
Hirohito Higashi355db992025-04-28 18:07:02 +02004253 return;
glepnirf31cfa22025-03-06 21:59:13 +01004254 while (compl != NULL && i < compl_num_bests)
4255 {
Hirohito Higashi355db992025-04-28 18:07:02 +02004256 compl_best_matches[i] = compl;
4257 compl = compl->cp_next;
4258 i++;
glepnirf31cfa22025-03-06 21:59:13 +01004259 }
4260
4261 prefix = compl_best_matches[0]->cp_str.string;
zeertzjq4422de62025-03-07 19:06:02 +01004262 prefix_len = (int)compl_best_matches[0]->cp_str.length;
glepnirf31cfa22025-03-06 21:59:13 +01004263
4264 for (i = 1; i < compl_num_bests; i++)
4265 {
4266 match_str = compl_best_matches[i]->cp_str.string;
Hirohito Higashi355db992025-04-28 18:07:02 +02004267 prefix_ptr = prefix;
4268 match_ptr = match_str;
4269 j = 0;
glepnirf31cfa22025-03-06 21:59:13 +01004270
4271 while (j < prefix_len && *match_ptr != NUL && *prefix_ptr != NUL)
4272 {
4273 if (STRNCMP(prefix_ptr, match_ptr, mb_ptr2len(prefix_ptr)) != 0)
4274 break;
4275
4276 MB_PTR_ADV(prefix_ptr);
4277 MB_PTR_ADV(match_ptr);
4278 j++;
4279 }
4280
4281 if (j > 0)
4282 prefix_len = j;
4283 }
4284
4285 leader = ins_compl_leader();
zeertzjq4422de62025-03-07 19:06:02 +01004286 leader_len = ins_compl_leader_len();
glepnirf31cfa22025-03-06 21:59:13 +01004287
4288 // skip non-consecutive prefixes
zeertzjq4422de62025-03-07 19:06:02 +01004289 if (leader_len > 0 && STRNCMP(prefix, leader, leader_len) != 0)
glepnirf31cfa22025-03-06 21:59:13 +01004290 goto end;
4291
zeertzjq4422de62025-03-07 19:06:02 +01004292 prefix = vim_strnsave(prefix, prefix_len);
glepnirf31cfa22025-03-06 21:59:13 +01004293 if (prefix != NULL)
4294 {
4295 ins_compl_longest_insert(prefix);
4296 compl_cfc_longest_ins = TRUE;
4297 vim_free(prefix);
4298 }
4299
4300end:
4301 vim_free(compl_best_matches);
4302 compl_best_matches = NULL;
4303 compl_num_bests = 0;
4304}
4305
4306/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004307 * Get the next set of filename matching "compl_pattern".
4308 */
4309 static void
4310get_next_filename_completion(void)
4311{
4312 char_u **matches;
4313 int num_matches;
glepnir8159fb12024-07-17 20:32:54 +02004314 char_u *ptr;
4315 garray_T fuzzy_indices;
4316 int i;
4317 int score;
4318 char_u *leader = ins_compl_leader();
John Marriott5e6ea922024-11-23 14:01:57 +01004319 size_t leader_len = ins_compl_leader_len();;
glepnirf31cfa22025-03-06 21:59:13 +01004320 int in_fuzzy_collect = (cfc_has_mode() && leader_len > 0);
glepnir8159fb12024-07-17 20:32:54 +02004321 int *fuzzy_indices_data;
glepnir0be03e12024-07-19 16:45:05 +02004322 char_u *last_sep = NULL;
glepnirf31cfa22025-03-06 21:59:13 +01004323 int need_collect_bests = in_fuzzy_collect && compl_get_longest;
4324 int max_score = 0;
4325 int current_score = 0;
4326 int dir = compl_direction;
glepnir8159fb12024-07-17 20:32:54 +02004327
glepnirb9de1a02024-08-02 19:14:38 +02004328#ifdef BACKSLASH_IN_FILENAME
4329 char pathsep = (curbuf->b_p_csl[0] == 's') ?
4330 '/' : (curbuf->b_p_csl[0] == 'b') ? '\\' : PATHSEP;
4331#else
4332 char pathsep = PATHSEP;
4333#endif
4334
glepnirf31cfa22025-03-06 21:59:13 +01004335 if (in_fuzzy_collect)
glepnir8159fb12024-07-17 20:32:54 +02004336 {
glepnirb9de1a02024-08-02 19:14:38 +02004337#ifdef BACKSLASH_IN_FILENAME
4338 if (curbuf->b_p_csl[0] == 's')
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 else if (curbuf->b_p_csl[0] == 'b')
4347 {
John Marriott5e6ea922024-11-23 14:01:57 +01004348 for (i = 0; i < (int)leader_len; i++)
glepnirb9de1a02024-08-02 19:14:38 +02004349 {
4350 if (leader[i] == '/')
4351 leader[i] = '\\';
4352 }
4353 }
4354#endif
4355 last_sep = vim_strrchr(leader, pathsep);
glepnir0be03e12024-07-19 16:45:05 +02004356 if (last_sep == NULL)
4357 {
4358 // No path separator or separator is the last character,
4359 // fuzzy match the whole leader
John Marriott5e6ea922024-11-23 14:01:57 +01004360 VIM_CLEAR_STRING(compl_pattern);
4361 compl_pattern.string = vim_strnsave((char_u *)"*", 1);
4362 if (compl_pattern.string == NULL)
4363 return;
4364 compl_pattern.length = 1;
glepnir0be03e12024-07-19 16:45:05 +02004365 }
4366 else if (*(last_sep + 1) == '\0')
glepnirf31cfa22025-03-06 21:59:13 +01004367 in_fuzzy_collect = FALSE;
glepnir0be03e12024-07-19 16:45:05 +02004368 else
4369 {
4370 // Split leader into path and file parts
4371 int path_len = last_sep - leader + 1;
John Marriott5e6ea922024-11-23 14:01:57 +01004372 char_u *path_with_wildcard;
4373
4374 path_with_wildcard = alloc(path_len + 2);
glepnir0be03e12024-07-19 16:45:05 +02004375 if (path_with_wildcard != NULL)
4376 {
John Marriott5e6ea922024-11-23 14:01:57 +01004377 vim_snprintf((char *)path_with_wildcard, path_len + 2, "%*.*s*", path_len, path_len, leader);
4378 VIM_CLEAR_STRING(compl_pattern);
4379 compl_pattern.string = path_with_wildcard;
4380 compl_pattern.length = path_len + 1;
glepnir0be03e12024-07-19 16:45:05 +02004381
4382 // Move leader to the file part
4383 leader = last_sep + 1;
John Marriott5e6ea922024-11-23 14:01:57 +01004384 leader_len -= path_len;
glepnir0be03e12024-07-19 16:45:05 +02004385 }
4386 }
glepnir8159fb12024-07-17 20:32:54 +02004387 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004388
John Marriott5e6ea922024-11-23 14:01:57 +01004389 if (expand_wildcards(1, &compl_pattern.string, &num_matches, &matches,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004390 EW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) != OK)
4391 return;
4392
4393 // May change home directory back to "~".
John Marriott5e6ea922024-11-23 14:01:57 +01004394 tilde_replace(compl_pattern.string, num_matches, matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004395#ifdef BACKSLASH_IN_FILENAME
4396 if (curbuf->b_p_csl[0] != NUL)
4397 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004398 for (i = 0; i < num_matches; ++i)
4399 {
glepnir8159fb12024-07-17 20:32:54 +02004400 ptr = matches[i];
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004401 while (*ptr != NUL)
4402 {
4403 if (curbuf->b_p_csl[0] == 's' && *ptr == '\\')
4404 *ptr = '/';
4405 else if (curbuf->b_p_csl[0] == 'b' && *ptr == '/')
4406 *ptr = '\\';
4407 ptr += (*mb_ptr2len)(ptr);
4408 }
4409 }
4410 }
4411#endif
glepnir8159fb12024-07-17 20:32:54 +02004412
glepnirf31cfa22025-03-06 21:59:13 +01004413 if (in_fuzzy_collect)
glepnir8159fb12024-07-17 20:32:54 +02004414 {
4415 ga_init2(&fuzzy_indices, sizeof(int), 10);
4416 compl_fuzzy_scores = (int *)alloc(sizeof(int) * num_matches);
4417
4418 for (i = 0; i < num_matches; i++)
4419 {
4420 ptr = matches[i];
4421 score = fuzzy_match_str(ptr, leader);
4422 if (score > 0)
4423 {
4424 if (ga_grow(&fuzzy_indices, 1) == OK)
4425 {
4426 ((int *)fuzzy_indices.ga_data)[fuzzy_indices.ga_len] = i;
4427 compl_fuzzy_scores[i] = score;
4428 fuzzy_indices.ga_len++;
4429 }
4430 }
4431 }
4432
Christian Brabandt220474d2024-07-20 13:26:44 +02004433 // prevent qsort from deref NULL pointer
4434 if (fuzzy_indices.ga_len > 0)
4435 {
glepnirf31cfa22025-03-06 21:59:13 +01004436 char_u *match = NULL;
Christian Brabandt220474d2024-07-20 13:26:44 +02004437 fuzzy_indices_data = (int *)fuzzy_indices.ga_data;
4438 qsort(fuzzy_indices_data, fuzzy_indices.ga_len, sizeof(int), compare_scores);
glepnir8159fb12024-07-17 20:32:54 +02004439
Christian Brabandt220474d2024-07-20 13:26:44 +02004440 for (i = 0; i < fuzzy_indices.ga_len; ++i)
glepnirf31cfa22025-03-06 21:59:13 +01004441 {
Hirohito Higashi355db992025-04-28 18:07:02 +02004442 match = matches[fuzzy_indices_data[i]];
glepnirf31cfa22025-03-06 21:59:13 +01004443 current_score = compl_fuzzy_scores[fuzzy_indices_data[i]];
4444 if (ins_compl_add(match, -1, NULL, NULL, NULL, dir,
Hirohito Higashi355db992025-04-28 18:07:02 +02004445 CP_FAST | ((p_fic || p_wic) ? CP_ICASE : 0),
4446 FALSE, NULL, current_score) == OK)
glepnirf31cfa22025-03-06 21:59:13 +01004447 dir = FORWARD;
4448
4449 if (need_collect_bests)
4450 {
4451 if (i == 0 || current_score == max_score)
4452 {
4453 compl_num_bests++;
4454 max_score = current_score;
4455 }
4456 }
4457 }
glepnir8159fb12024-07-17 20:32:54 +02004458
Christian Brabandt220474d2024-07-20 13:26:44 +02004459 FreeWild(num_matches, matches);
Christian Brabandt220474d2024-07-20 13:26:44 +02004460 }
glepnir6b6280c2024-07-27 16:25:45 +02004461 else if (leader_len > 0)
4462 {
4463 FreeWild(num_matches, matches);
4464 num_matches = 0;
4465 }
Christian Brabandt220474d2024-07-20 13:26:44 +02004466
glepnir8159fb12024-07-17 20:32:54 +02004467 vim_free(compl_fuzzy_scores);
4468 ga_clear(&fuzzy_indices);
glepnirf31cfa22025-03-06 21:59:13 +01004469
4470 if (compl_num_bests > 0 && compl_get_longest)
4471 fuzzy_longest_match();
4472 return;
glepnir8159fb12024-07-17 20:32:54 +02004473 }
4474
glepnir6b6280c2024-07-27 16:25:45 +02004475 if (num_matches > 0)
4476 ins_compl_add_matches(num_matches, matches, p_fic || p_wic);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004477}
4478
4479/*
4480 * Get the next set of command-line completions matching "compl_pattern".
4481 */
4482 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00004483get_next_cmdline_completion(void)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004484{
4485 char_u **matches;
4486 int num_matches;
4487
John Marriott5e6ea922024-11-23 14:01:57 +01004488 if (expand_cmdline(&compl_xp, compl_pattern.string,
4489 (int)compl_pattern.length, &num_matches, &matches) == EXPAND_OK)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004490 ins_compl_add_matches(num_matches, matches, FALSE);
4491}
4492
4493/*
4494 * Get the next set of spell suggestions matching "compl_pattern".
4495 */
4496 static void
4497get_next_spell_completion(linenr_T lnum UNUSED)
4498{
4499#ifdef FEAT_SPELL
4500 char_u **matches;
4501 int num_matches;
4502
John Marriott5e6ea922024-11-23 14:01:57 +01004503 num_matches = expand_spelling(lnum, compl_pattern.string, &matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004504 if (num_matches > 0)
4505 ins_compl_add_matches(num_matches, matches, p_ic);
Bram Moolenaar8e7cc6b2021-12-30 10:32:25 +00004506 else
4507 vim_free(matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004508#endif
4509}
4510
4511/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004512 * Return the next word or line from buffer "ins_buf" at position
4513 * "cur_match_pos" for completion. The length of the match is set in "len".
4514 */
4515 static char_u *
zeertzjq440d4cb2023-03-02 17:51:32 +00004516ins_compl_get_next_word_or_line(
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004517 buf_T *ins_buf, // buffer being scanned
4518 pos_T *cur_match_pos, // current match position
4519 int *match_len,
4520 int *cont_s_ipos) // next ^X<> will set initial_pos
4521{
4522 char_u *ptr;
4523 int len;
4524
4525 *match_len = 0;
4526 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum, FALSE) +
4527 cur_match_pos->col;
John Marriott5e6ea922024-11-23 14:01:57 +01004528 len = (int)ml_get_buf_len(ins_buf, cur_match_pos->lnum) - cur_match_pos->col;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004529 if (ctrl_x_mode_line_or_eval())
4530 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004531 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004532 {
4533 if (cur_match_pos->lnum >= ins_buf->b_ml.ml_line_count)
4534 return NULL;
4535 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
John Marriott5e6ea922024-11-23 14:01:57 +01004536 len = ml_get_buf_len(ins_buf, cur_match_pos->lnum + 1);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004537 if (!p_paste)
John Marriott5e6ea922024-11-23 14:01:57 +01004538 {
4539 char_u *tmp_ptr = ptr;
4540
4541 ptr = skipwhite(tmp_ptr);
4542 len -= (int)(ptr - tmp_ptr);
4543 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004544 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004545 }
4546 else
4547 {
4548 char_u *tmp_ptr = ptr;
4549
John Marriott5e6ea922024-11-23 14:01:57 +01004550 if (compl_status_adding() && compl_length <= len)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004551 {
4552 tmp_ptr += compl_length;
4553 // Skip if already inside a word.
4554 if (vim_iswordp(tmp_ptr))
4555 return NULL;
4556 // Find start of next word.
4557 tmp_ptr = find_word_start(tmp_ptr);
4558 }
4559 // Find end of this word.
4560 tmp_ptr = find_word_end(tmp_ptr);
4561 len = (int)(tmp_ptr - ptr);
4562
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004563 if (compl_status_adding() && len == compl_length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004564 {
4565 if (cur_match_pos->lnum < ins_buf->b_ml.ml_line_count)
4566 {
4567 // Try next line, if any. the new word will be
4568 // "join" as if the normal command "J" was used.
4569 // IOSIZE is always greater than
4570 // compl_length, so the next STRNCPY always
4571 // works -- Acevedo
4572 STRNCPY(IObuff, ptr, len);
4573 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
4574 tmp_ptr = ptr = skipwhite(ptr);
4575 // Find start of next word.
4576 tmp_ptr = find_word_start(tmp_ptr);
4577 // Find end of next word.
4578 tmp_ptr = find_word_end(tmp_ptr);
4579 if (tmp_ptr > ptr)
4580 {
4581 if (*ptr != ')' && IObuff[len - 1] != TAB)
4582 {
4583 if (IObuff[len - 1] != ' ')
4584 IObuff[len++] = ' ';
4585 // IObuf =~ "\k.* ", thus len >= 2
4586 if (p_js
4587 && (IObuff[len - 2] == '.'
4588 || (vim_strchr(p_cpo, CPO_JOINSP)
4589 == NULL
4590 && (IObuff[len - 2] == '?'
4591 || IObuff[len - 2] == '!'))))
4592 IObuff[len++] = ' ';
4593 }
4594 // copy as much as possible of the new word
4595 if (tmp_ptr - ptr >= IOSIZE - len)
4596 tmp_ptr = ptr + IOSIZE - len - 1;
4597 STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);
4598 len += (int)(tmp_ptr - ptr);
4599 *cont_s_ipos = TRUE;
4600 }
4601 IObuff[len] = NUL;
4602 ptr = IObuff;
4603 }
4604 if (len == compl_length)
4605 return NULL;
4606 }
4607 }
4608
4609 *match_len = len;
4610 return ptr;
4611}
4612
4613/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004614 * Get the next set of words matching "compl_pattern" for default completion(s)
4615 * (normal ^P/^N and ^X^L).
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004616 * Search for "compl_pattern" in the buffer "st->ins_buf" starting from the
4617 * position "st->start_pos" in the "compl_direction" direction. If
4618 * "st->set_match_pos" is TRUE, then set the "st->first_match_pos" and
4619 * "st->last_match_pos".
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004620 * Returns OK if a new next match is found, otherwise returns FAIL.
4621 */
4622 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004623get_next_default_completion(ins_compl_next_state_T *st, pos_T *start_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004624{
4625 int found_new_match = FAIL;
4626 int save_p_scs;
4627 int save_p_ws;
4628 int looped_around = FALSE;
glepnir8159fb12024-07-17 20:32:54 +02004629 char_u *ptr = NULL;
4630 int len = 0;
glepnirf31cfa22025-03-06 21:59:13 +01004631 int in_collect = (cfc_has_mode() && compl_length > 0);
glepnir8159fb12024-07-17 20:32:54 +02004632 char_u *leader = ins_compl_leader();
glepnirf31cfa22025-03-06 21:59:13 +01004633 int score = 0;
Girish Palyab1565882025-04-15 20:16:00 +02004634 int in_curbuf = st->ins_buf == curbuf;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004635
4636 // If 'infercase' is set, don't use 'smartcase' here
4637 save_p_scs = p_scs;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004638 if (st->ins_buf->b_p_inf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004639 p_scs = FALSE;
4640
4641 // Buffers other than curbuf are scanned from the beginning or the
4642 // end but never from the middle, thus setting nowrapscan in this
4643 // buffer is a good idea, on the other hand, we always set
4644 // wrapscan for curbuf to avoid missing matches -- Acevedo,Webb
4645 save_p_ws = p_ws;
Girish Palyab1565882025-04-15 20:16:00 +02004646 if (!in_curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004647 p_ws = FALSE;
glepnirf31cfa22025-03-06 21:59:13 +01004648 else if (*st->e_cpt == '.')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004649 p_ws = TRUE;
4650 looped_around = FALSE;
4651 for (;;)
4652 {
4653 int cont_s_ipos = FALSE;
4654
4655 ++msg_silent; // Don't want messages for wrapscan.
4656
glepnirf31cfa22025-03-06 21:59:13 +01004657 if (in_collect)
4658 {
Hirohito Higashi355db992025-04-28 18:07:02 +02004659 found_new_match = search_for_fuzzy_match(st->ins_buf,
glepnir8159fb12024-07-17 20:32:54 +02004660 st->cur_match_pos, leader, compl_direction,
glepnirf31cfa22025-03-06 21:59:13 +01004661 start_pos, &len, &ptr, &score);
4662 }
4663 // ctrl_x_mode_line_or_eval() || word-wise search that
4664 // has added a word that was at the beginning of the line
4665 else if (ctrl_x_mode_whole_line() || ctrl_x_mode_eval() || (compl_cont_status & CONT_SOL))
4666 found_new_match = search_for_exact_line(st->ins_buf,
4667 st->cur_match_pos, compl_direction, compl_pattern.string);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004668 else
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004669 found_new_match = searchit(NULL, st->ins_buf, st->cur_match_pos,
John Marriott5e6ea922024-11-23 14:01:57 +01004670 NULL, compl_direction, compl_pattern.string, (int)compl_pattern.length,
John Marriott8c85a2a2024-05-20 19:18:26 +02004671 1L, SEARCH_KEEP + SEARCH_NFMSG, RE_LAST, NULL);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004672 --msg_silent;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004673 if (!compl_started || st->set_match_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004674 {
4675 // set "compl_started" even on fail
4676 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004677 st->first_match_pos = *st->cur_match_pos;
4678 st->last_match_pos = *st->cur_match_pos;
4679 st->set_match_pos = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004680 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004681 else if (st->first_match_pos.lnum == st->last_match_pos.lnum
4682 && st->first_match_pos.col == st->last_match_pos.col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004683 {
4684 found_new_match = FAIL;
4685 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004686 else if (compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004687 && (st->prev_match_pos.lnum > st->cur_match_pos->lnum
4688 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
4689 && st->prev_match_pos.col >= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004690 {
4691 if (looped_around)
4692 found_new_match = FAIL;
4693 else
4694 looped_around = TRUE;
4695 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004696 else if (!compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004697 && (st->prev_match_pos.lnum < st->cur_match_pos->lnum
4698 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
4699 && st->prev_match_pos.col <= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004700 {
4701 if (looped_around)
4702 found_new_match = FAIL;
4703 else
4704 looped_around = TRUE;
4705 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004706 st->prev_match_pos = *st->cur_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004707 if (found_new_match == FAIL)
4708 break;
4709
4710 // when ADDING, the text before the cursor matches, skip it
Girish Palyab1565882025-04-15 20:16:00 +02004711 if (compl_status_adding() && in_curbuf
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004712 && start_pos->lnum == st->cur_match_pos->lnum
4713 && start_pos->col == st->cur_match_pos->col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004714 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004715
glepnirf31cfa22025-03-06 21:59:13 +01004716 if (!in_collect)
glepnir8159fb12024-07-17 20:32:54 +02004717 ptr = ins_compl_get_next_word_or_line(st->ins_buf, st->cur_match_pos,
4718 &len, &cont_s_ipos);
glepnirbfb4eea2025-01-31 15:28:29 +01004719 if (ptr == NULL || (ins_compl_has_preinsert() && STRCMP(ptr, compl_pattern.string) == 0))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004720 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004721
Girish Palyab1565882025-04-15 20:16:00 +02004722 if (is_nearest_active() && in_curbuf)
4723 {
4724 score = st->cur_match_pos->lnum - curwin->w_cursor.lnum;
4725 if (score < 0)
4726 score = -score;
4727 score++;
4728 }
4729
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004730 if (ins_compl_add_infercase(ptr, len, p_ic,
Girish Palyab1565882025-04-15 20:16:00 +02004731 in_curbuf ? NULL : st->ins_buf->b_sfname,
glepnirf31cfa22025-03-06 21:59:13 +01004732 0, cont_s_ipos, score) != NOTDONE)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004733 {
glepnirf31cfa22025-03-06 21:59:13 +01004734 if (in_collect && score == compl_first_match->cp_next->cp_score)
4735 compl_num_bests++;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004736 found_new_match = OK;
4737 break;
4738 }
4739 }
4740 p_scs = save_p_scs;
4741 p_ws = save_p_ws;
4742
4743 return found_new_match;
4744}
4745
4746/*
Girish Palyacbe53192025-04-14 22:13:15 +02004747 * Return the callback function associated with "funcname".
4748 */
4749#ifdef FEAT_COMPL_FUNC
4750 static callback_T *
4751get_cpt_func_callback(char_u *funcname)
4752{
4753 static callback_T cb;
4754 char_u buf[LSIZE];
4755 int slen;
4756
4757 slen = copy_option_part(&funcname, buf, LSIZE, ",");
4758 if (slen > 0 && option_set_callback_func(buf, &cb))
4759 return &cb;
4760 return NULL;
4761}
4762
4763/*
4764 * Retrieve new completion matches by invoking callback "cb".
4765 */
4766 static void
4767expand_cpt_function(callback_T *cb)
4768{
4769 // Re-insert the text removed by ins_compl_delete().
4770 ins_compl_insert_bytes(compl_orig_text.string + get_compl_len(), -1);
4771 // Get matches
4772 get_cpt_func_completion_matches(cb);
4773 // Undo insertion
4774 ins_compl_delete();
4775}
4776#endif
4777
4778/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004779 * get the next set of completion matches for "type".
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004780 * Returns TRUE if a new match is found. Otherwise returns FALSE.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004781 */
4782 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004783get_next_completion_match(int type, ins_compl_next_state_T *st, pos_T *ini)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004784{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004785 int found_new_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004786
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004787 switch (type)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004788 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004789 case -1:
4790 break;
4791#ifdef FEAT_FIND_ID
4792 case CTRL_X_PATH_PATTERNS:
4793 case CTRL_X_PATH_DEFINES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004794 get_next_include_file_completion(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004795 break;
4796#endif
4797
4798 case CTRL_X_DICTIONARY:
4799 case CTRL_X_THESAURUS:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004800 get_next_dict_tsr_completion(type, st->dict, st->dict_f);
4801 st->dict = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004802 break;
4803
4804 case CTRL_X_TAGS:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004805 get_next_tag_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004806 break;
4807
4808 case CTRL_X_FILES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004809 get_next_filename_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004810 break;
4811
4812 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +02004813 case CTRL_X_CMDLINE_CTRL_X:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004814 get_next_cmdline_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004815 break;
4816
4817#ifdef FEAT_COMPL_FUNC
4818 case CTRL_X_FUNCTION:
Girish Palyacbe53192025-04-14 22:13:15 +02004819 if (ctrl_x_mode_normal()) // Invoked by a func in 'cpt' option
4820 expand_cpt_function(st->func_cb);
4821 else
4822 expand_by_function(type, compl_pattern.string, NULL);
4823 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004824 case CTRL_X_OMNI:
Girish Palyacbe53192025-04-14 22:13:15 +02004825 expand_by_function(type, compl_pattern.string, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004826 break;
4827#endif
4828
4829 case CTRL_X_SPELL:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004830 get_next_spell_completion(st->first_match_pos.lnum);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004831 break;
4832
4833 default: // normal ^P/^N and ^X^L
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004834 found_new_match = get_next_default_completion(st, ini);
4835 if (found_new_match == FAIL && st->ins_buf == curbuf)
4836 st->found_all = TRUE;
4837 }
4838
4839 // check if compl_curr_match has changed, (e.g. other type of
4840 // expansion added something)
4841 if (type != 0 && compl_curr_match != compl_old_match)
4842 found_new_match = OK;
4843
4844 return found_new_match;
4845}
4846
4847/*
Girish Palya0ac1eb32025-04-16 20:18:33 +02004848 * Strips carets followed by numbers. This suffix typically represents the
4849 * max_matches setting.
4850 */
4851 static void
4852strip_caret_numbers_in_place(char_u *str)
4853{
4854 char_u *read = str, *write = str, *p;
4855
4856 if (str == NULL)
4857 return;
4858
4859 while (*read)
4860 {
4861 if (*read == '^')
4862 {
4863 p = read + 1;
4864 while (vim_isdigit(*p))
4865 p++;
4866 if ((*p == ',' || *p == '\0') && p != read + 1)
4867 {
4868 read = p;
4869 continue;
4870 }
4871 else
4872 *write++ = *read++;
4873 }
4874 else
4875 *write++ = *read++;
4876 }
4877 *write = '\0';
4878}
4879
4880/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004881 * Get the next expansion(s), using "compl_pattern".
4882 * The search starts at position "ini" in curbuf and in the direction
4883 * compl_direction.
4884 * When "compl_started" is FALSE start at that position, otherwise continue
4885 * where we stopped searching before.
4886 * This may return before finding all the matches.
4887 * Return the total number of matches or -1 if still unknown -- Acevedo
4888 */
4889 static int
4890ins_compl_get_exp(pos_T *ini)
4891{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004892 static ins_compl_next_state_T st;
4893 static int st_cleared = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004894 int i;
4895 int found_new_match;
4896 int type = ctrl_x_mode;
4897
4898 if (!compl_started)
4899 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004900 buf_T *buf;
4901
4902 FOR_ALL_BUFFERS(buf)
4903 buf->b_scanned = 0;
4904 if (!st_cleared)
4905 {
4906 CLEAR_FIELD(st);
4907 st_cleared = TRUE;
4908 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004909 st.found_all = FALSE;
4910 st.ins_buf = curbuf;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004911 vim_free(st.e_cpt_copy);
Christian Brabandtee17b6f2023-09-09 11:23:50 +02004912 // Make a copy of 'complete', in case the buffer is wiped out.
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004913 st.e_cpt_copy = vim_strsave((compl_cont_status & CONT_LOCAL)
4914 ? (char_u *)"." : curbuf->b_p_cpt);
Girish Palya0ac1eb32025-04-16 20:18:33 +02004915 strip_caret_numbers_in_place(st.e_cpt_copy);
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004916 st.e_cpt = st.e_cpt_copy == NULL ? (char_u *)"" : st.e_cpt_copy;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004917 st.last_match_pos = st.first_match_pos = *ini;
Girish Palyacbe53192025-04-14 22:13:15 +02004918
4919 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Girish Palya0ac1eb32025-04-16 20:18:33 +02004920 && !cpt_sources_init())
Girish Palyacbe53192025-04-14 22:13:15 +02004921 return FAIL;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004922 }
4923 else if (st.ins_buf != curbuf && !buf_valid(st.ins_buf))
4924 st.ins_buf = curbuf; // In case the buffer was wiped out.
4925
4926 compl_old_match = compl_curr_match; // remember the last current match
Christian Brabandt13032a42024-07-28 21:16:48 +02004927 st.cur_match_pos = (compl_dir_forward())
glepnir8159fb12024-07-17 20:32:54 +02004928 ? &st.last_match_pos : &st.first_match_pos;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004929
4930 // For ^N/^P loop over all the flags/windows/buffers in 'complete'.
Girish Palya0ac1eb32025-04-16 20:18:33 +02004931 for (cpt_sources_index = 0;;)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004932 {
4933 found_new_match = FAIL;
4934 st.set_match_pos = FALSE;
4935
4936 // For ^N/^P pick a new entry from e_cpt if compl_started is off,
4937 // or if found_all says this entry is done. For ^X^L only use the
4938 // entries from 'complete' that look in loaded buffers.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004939 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004940 && (!compl_started || st.found_all))
4941 {
glepnir53b14572025-03-12 21:28:39 +01004942 int status = process_next_cpt_value(&st, &type, ini, cfc_has_mode());
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004943
4944 if (status == INS_COMPL_CPT_END)
4945 break;
4946 if (status == INS_COMPL_CPT_CONT)
Girish Palyacbe53192025-04-14 22:13:15 +02004947 {
Girish Palya0ac1eb32025-04-16 20:18:33 +02004948 cpt_sources_index++;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004949 continue;
Girish Palyacbe53192025-04-14 22:13:15 +02004950 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004951 }
4952
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004953 // If complete() was called then compl_pattern has been reset. The
4954 // following won't work then, bail out.
John Marriott5e6ea922024-11-23 14:01:57 +01004955 if (compl_pattern.string == NULL)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004956 break;
4957
4958 // get the next set of completion matches
4959 found_new_match = get_next_completion_match(type, &st, ini);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004960
Girish Palyacbe53192025-04-14 22:13:15 +02004961 if (type > 0)
Girish Palya0ac1eb32025-04-16 20:18:33 +02004962 cpt_sources_index++;
Girish Palyacbe53192025-04-14 22:13:15 +02004963
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004964 // break the loop for specialized modes (use 'complete' just for the
4965 // generic ctrl_x_mode == CTRL_X_NORMAL) or when we've found a new
4966 // match
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004967 if ((ctrl_x_mode_not_default() && !ctrl_x_mode_line_or_eval())
4968 || found_new_match != FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004969 {
4970 if (got_int)
4971 break;
4972 // Fill the popup menu as soon as possible.
4973 if (type != -1)
4974 ins_compl_check_keys(0, FALSE);
4975
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004976 if ((ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004977 && !ctrl_x_mode_line_or_eval()) || compl_interrupted)
4978 break;
4979 compl_started = TRUE;
4980 }
4981 else
4982 {
4983 // Mark a buffer scanned when it has been scanned completely
Christian Brabandtee9166e2023-09-03 21:24:33 +02004984 if (buf_valid(st.ins_buf) && (type == 0 || type == CTRL_X_PATH_PATTERNS))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004985 st.ins_buf->b_scanned = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004986
4987 compl_started = FALSE;
4988 }
4989 }
Girish Palya0ac1eb32025-04-16 20:18:33 +02004990 cpt_sources_index = -1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004991 compl_started = TRUE;
4992
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004993 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004994 && *st.e_cpt == NUL) // Got to end of 'complete'
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004995 found_new_match = FAIL;
4996
4997 i = -1; // total of matches, unknown
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004998 if (found_new_match == FAIL || (ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004999 && !ctrl_x_mode_line_or_eval()))
5000 i = ins_compl_make_cyclic();
5001
glepnirf31cfa22025-03-06 21:59:13 +01005002 if (cfc_has_mode() && compl_get_longest && compl_num_bests > 0)
5003 fuzzy_longest_match();
5004
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005005 if (compl_old_match != NULL)
5006 {
5007 // If several matches were added (FORWARD) or the search failed and has
5008 // just been made cyclic then we have to move compl_curr_match to the
5009 // next or previous entry (if any) -- Acevedo
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005010 compl_curr_match = compl_dir_forward() ? compl_old_match->cp_next
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005011 : compl_old_match->cp_prev;
5012 if (compl_curr_match == NULL)
5013 compl_curr_match = compl_old_match;
5014 }
LemonBoy2bf52dd2022-04-09 18:17:34 +01005015 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01005016
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005017 return i;
5018}
5019
5020/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005021 * Update "compl_shown_match" to the actually shown match, it may differ when
5022 * "compl_leader" is used to omit some of the matches.
5023 */
5024 static void
5025ins_compl_update_shown_match(void)
5026{
5027 while (!ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01005028 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005029 && compl_shown_match->cp_next != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005030 && !is_first_match(compl_shown_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005031 compl_shown_match = compl_shown_match->cp_next;
5032
5033 // If we didn't find it searching forward, and compl_shows_dir is
5034 // backward, find the last match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005035 if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005036 && !ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01005037 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005038 && (compl_shown_match->cp_next == NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005039 || is_first_match(compl_shown_match->cp_next)))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005040 {
5041 while (!ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01005042 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005043 && compl_shown_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005044 && !is_first_match(compl_shown_match->cp_prev))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005045 compl_shown_match = compl_shown_match->cp_prev;
5046 }
5047}
5048
5049/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005050 * Delete the old text being completed.
5051 */
5052 void
5053ins_compl_delete(void)
5054{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005055 // In insert mode: Delete the typed part.
5056 // In replace mode: Put the old characters back, if any.
glepniredd4ac32025-01-29 18:53:51 +01005057 int col = compl_col + (compl_status_adding() ? compl_length : 0);
John Marriottf4b36412025-02-23 09:09:59 +01005058 string_T remaining = {NULL, 0};
glepnir76bdb822025-02-08 19:04:51 +01005059 int orig_col;
glepniredd4ac32025-01-29 18:53:51 +01005060 int has_preinsert = ins_compl_preinsert_effect();
5061 if (has_preinsert)
5062 {
Yegappan Lakshmanan7b6add02025-04-01 20:38:37 +02005063 col += (int)ins_compl_leader_len();
glepniredd4ac32025-01-29 18:53:51 +01005064 curwin->w_cursor.col = compl_ins_end_col;
5065 }
5066
glepnir76bdb822025-02-08 19:04:51 +01005067 if (curwin->w_cursor.lnum > compl_lnum)
5068 {
5069 if (curwin->w_cursor.col < ml_get_curline_len())
5070 {
John Marriottf4b36412025-02-23 09:09:59 +01005071 char_u *line = ml_get_cursor();
5072 remaining.length = ml_get_cursor_len();
5073 remaining.string = vim_strnsave(line, remaining.length);
5074 if (remaining.string == NULL)
glepnir76bdb822025-02-08 19:04:51 +01005075 return;
5076 }
5077 while (curwin->w_cursor.lnum > compl_lnum)
5078 {
5079 if (ml_delete(curwin->w_cursor.lnum) == FAIL)
5080 {
John Marriottf4b36412025-02-23 09:09:59 +01005081 if (remaining.string)
5082 vim_free(remaining.string);
glepnir76bdb822025-02-08 19:04:51 +01005083 return;
5084 }
zeertzjq060e6552025-02-21 20:06:26 +01005085 deleted_lines_mark(curwin->w_cursor.lnum, 1L);
glepnir76bdb822025-02-08 19:04:51 +01005086 curwin->w_cursor.lnum--;
5087 }
5088 // move cursor to end of line
5089 curwin->w_cursor.col = ml_get_curline_len();
5090 }
5091
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005092 if ((int)curwin->w_cursor.col > col)
5093 {
5094 if (stop_arrow() == FAIL)
glepnire3647c82025-02-10 21:16:32 +01005095 {
John Marriottf4b36412025-02-23 09:09:59 +01005096 if (remaining.string)
5097 vim_free(remaining.string);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005098 return;
glepnire3647c82025-02-10 21:16:32 +01005099 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005100 backspace_until_column(col);
zeertzjqf25d8f92024-12-18 21:12:25 +01005101 compl_ins_end_col = curwin->w_cursor.col;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005102 }
5103
John Marriottf4b36412025-02-23 09:09:59 +01005104 if (remaining.string != NULL)
glepnir76bdb822025-02-08 19:04:51 +01005105 {
5106 orig_col = curwin->w_cursor.col;
John Marriottf4b36412025-02-23 09:09:59 +01005107 ins_str(remaining.string, remaining.length);
glepnir76bdb822025-02-08 19:04:51 +01005108 curwin->w_cursor.col = orig_col;
John Marriottf4b36412025-02-23 09:09:59 +01005109 vim_free(remaining.string);
glepnir76bdb822025-02-08 19:04:51 +01005110 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005111 // TODO: is this sufficient for redrawing? Redrawing everything causes
5112 // flicker, thus we can't do that.
5113 changed_cline_bef_curs();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02005114#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005115 // clear v:completed_item
5116 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02005117#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005118}
5119
5120/*
glepnir76bdb822025-02-08 19:04:51 +01005121 * Insert a completion string that contains newlines.
5122 * The string is split and inserted line by line.
5123 */
5124 static void
5125ins_compl_expand_multiple(char_u *str)
5126{
5127 char_u *start = str;
5128 char_u *curr = str;
glepnir5090a1f2025-02-24 19:10:37 +01005129 int base_indent = get_indent();
glepnir76bdb822025-02-08 19:04:51 +01005130
5131 while (*curr != NUL)
5132 {
5133 if (*curr == '\n')
5134 {
5135 // Insert the text chunk before newline
5136 if (curr > start)
5137 ins_char_bytes(start, (int)(curr - start));
5138
5139 // Handle newline
glepnir5090a1f2025-02-24 19:10:37 +01005140 open_line(FORWARD, OPENLINE_KEEPTRAIL | OPENLINE_FORCE_INDENT, base_indent, NULL);
glepnir76bdb822025-02-08 19:04:51 +01005141 start = curr + 1;
5142 }
5143 curr++;
5144 }
5145
5146 // Handle remaining text after last newline (if any)
5147 if (curr > start)
5148 ins_char_bytes(start, (int)(curr - start));
5149
5150 compl_ins_end_col = curwin->w_cursor.col;
5151}
5152
5153/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005154 * Insert the new text being completed.
5155 * "in_compl_func" is TRUE when called from complete_check().
glepniredd4ac32025-01-29 18:53:51 +01005156 * "move_cursor" is used when 'completeopt' includes "preinsert" and when TRUE
5157 * cursor needs to move back from the inserted text to the compl_leader.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005158 */
5159 void
glepniredd4ac32025-01-29 18:53:51 +01005160ins_compl_insert(int in_compl_func, int move_cursor)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005161{
glepnir76bdb822025-02-08 19:04:51 +01005162 int compl_len = get_compl_len();
5163 int preinsert = ins_compl_has_preinsert();
5164 char_u *cp_str = compl_shown_match->cp_str.string;
5165 size_t cp_str_len = compl_shown_match->cp_str.length;
5166 size_t leader_len = ins_compl_leader_len();
5167 char_u *has_multiple = vim_strchr(cp_str, '\n');
Bram Moolenaar4b28ba32021-12-27 19:28:37 +00005168
5169 // Make sure we don't go over the end of the string, this can happen with
5170 // illegal bytes.
zeertzjq8297e2c2025-01-30 11:04:47 +01005171 if (compl_len < (int)cp_str_len)
glepniredd4ac32025-01-29 18:53:51 +01005172 {
glepnir76bdb822025-02-08 19:04:51 +01005173 if (has_multiple)
5174 ins_compl_expand_multiple(cp_str + compl_len);
5175 else
5176 {
5177 ins_compl_insert_bytes(cp_str + compl_len, -1);
5178 if (preinsert && move_cursor)
5179 curwin->w_cursor.col -= (colnr_T)(cp_str_len - leader_len);
5180 }
glepniredd4ac32025-01-29 18:53:51 +01005181 }
5182 if (match_at_original_text(compl_shown_match) || preinsert)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005183 compl_used_match = FALSE;
5184 else
5185 compl_used_match = TRUE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02005186#ifdef FEAT_EVAL
5187 {
5188 dict_T *dict = ins_compl_dict_alloc(compl_shown_match);
5189
5190 set_vim_var_dict(VV_COMPLETED_ITEM, dict);
5191 }
5192#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005193 if (!in_compl_func)
5194 compl_curr_match = compl_shown_match;
5195}
5196
5197/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005198 * show the file name for the completion match (if any). Truncate the file
5199 * name to avoid a wait for return.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005200 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005201 static void
5202ins_compl_show_filename(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005203{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005204 char *lead = _("match in file");
5205 int space = sc_col - vim_strsize((char_u *)lead) - 2;
5206 char_u *s;
5207 char_u *e;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005208
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005209 if (space <= 0)
5210 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005211
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005212 // We need the tail that fits. With double-byte encoding going
5213 // back from the end is very slow, thus go from the start and keep
5214 // the text that fits in "space" between "s" and "e".
5215 for (s = e = compl_shown_match->cp_fname; *e != NUL; MB_PTR_ADV(e))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005216 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005217 space -= ptr2cells(e);
5218 while (space < 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005219 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005220 space += ptr2cells(s);
5221 MB_PTR_ADV(s);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005222 }
5223 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005224 msg_hist_off = TRUE;
5225 vim_snprintf((char *)IObuff, IOSIZE, "%s %s%s", lead,
5226 s > compl_shown_match->cp_fname ? "<" : "", s);
5227 msg((char *)IObuff);
5228 msg_hist_off = FALSE;
5229 redraw_cmdline = FALSE; // don't overwrite!
5230}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005231
glepnirdca57fb2024-06-04 22:01:21 +02005232/*
zeertzjq551d8c32024-06-05 19:53:32 +02005233 * Find a completion item when 'completeopt' contains "fuzzy".
glepnirdca57fb2024-06-04 22:01:21 +02005234 */
glepnira218cc62024-06-03 19:32:39 +02005235 static compl_T *
5236find_comp_when_fuzzy(void)
5237{
5238 int score;
5239 char_u* str;
5240 int target_idx = -1;
5241 int is_forward = compl_shows_dir_forward();
5242 int is_backward = compl_shows_dir_backward();
5243 compl_T *comp = NULL;
5244
glepnir43eef882024-06-19 20:20:48 +02005245 if ((is_forward && compl_selected_item == compl_match_arraysize - 1)
glepnira218cc62024-06-03 19:32:39 +02005246 || (is_backward && compl_selected_item == 0))
glepnir5a18ccf2025-05-11 13:48:33 +02005247 return match_at_original_text(compl_first_match)
5248 ? compl_first_match : compl_first_match->cp_prev;
glepnira218cc62024-06-03 19:32:39 +02005249
5250 if (is_forward)
5251 target_idx = compl_selected_item + 1;
5252 else if (is_backward)
Hirohito Higashi355db992025-04-28 18:07:02 +02005253 target_idx = compl_selected_item == -1 ? compl_match_arraysize - 1
glepnirdca57fb2024-06-04 22:01:21 +02005254 : compl_selected_item - 1;
glepnira218cc62024-06-03 19:32:39 +02005255
5256 score = compl_match_array[target_idx].pum_score;
5257 str = compl_match_array[target_idx].pum_text;
5258
5259 comp = compl_first_match;
Hirohito Higashia4a00a72025-05-08 22:58:31 +02005260 do
5261 {
Hirohito Higashi355db992025-04-28 18:07:02 +02005262 if (comp->cp_score == score && (str == comp->cp_str.string || str == comp->cp_text[CPT_ABBR]))
5263 return comp;
5264 comp = comp->cp_next;
glepnira218cc62024-06-03 19:32:39 +02005265 } while (comp != NULL && !is_first_match(comp));
5266
5267 return NULL;
5268}
5269
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005270/*
Girish Palya0ac1eb32025-04-16 20:18:33 +02005271 * Find the appropriate completion item when 'complete' ('cpt') includes
5272 * a 'max_matches' postfix. In this case, we search for a match where
5273 * 'cp_in_match_array' is set, indicating that the match is also present
5274 * in 'compl_match_array'.
5275 */
5276 static compl_T *
5277find_comp_when_cpt_sources(void)
5278{
5279 int is_forward = compl_shows_dir_forward();
5280 compl_T *match = compl_shown_match;
5281
5282 do
5283 match = is_forward ? match->cp_next : match->cp_prev;
5284 while (match->cp_next && !match->cp_in_match_array
5285 && !match_at_original_text(match));
5286 return match;
5287}
5288
5289/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005290 * Find the next set of matches for completion. Repeat the completion "todo"
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005291 * times. The number of matches found is returned in 'num_matches'.
5292 *
5293 * If "allow_get_expansion" is TRUE, then ins_compl_get_exp() may be called to
5294 * get more completions. If it is FALSE, then do nothing when there are no more
5295 * completions in the given direction.
5296 *
5297 * If "advance" is TRUE, then completion will move to the first match.
5298 * Otherwise, the original text will be shown.
5299 *
5300 * Returns OK on success and -1 if the number of matches are unknown.
5301 */
5302 static int
5303find_next_completion_match(
5304 int allow_get_expansion,
5305 int todo, // repeat completion this many times
5306 int advance,
5307 int *num_matches)
5308{
5309 int found_end = FALSE;
5310 compl_T *found_compl = NULL;
zeertzjqaa925ee2024-06-09 18:24:05 +02005311 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02005312 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
5313 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Girish Palya0ac1eb32025-04-16 20:18:33 +02005314 int cpt_sources_active = compl_match_array && cpt_sources_array;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005315
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005316 while (--todo >= 0)
5317 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005318 if (compl_shows_dir_forward() && compl_shown_match->cp_next != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005319 {
Girish Palya0ac1eb32025-04-16 20:18:33 +02005320 if (compl_match_array != NULL && compl_fuzzy_match)
5321 compl_shown_match = find_comp_when_fuzzy();
5322 else if (cpt_sources_active)
5323 compl_shown_match = find_comp_when_cpt_sources();
5324 else
5325 compl_shown_match = compl_shown_match->cp_next;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005326 found_end = (compl_first_match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005327 && (is_first_match(compl_shown_match->cp_next)
5328 || is_first_match(compl_shown_match)));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005329 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005330 else if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005331 && compl_shown_match->cp_prev != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005332 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005333 found_end = is_first_match(compl_shown_match);
Girish Palya0ac1eb32025-04-16 20:18:33 +02005334 if (compl_match_array != NULL && compl_fuzzy_match)
5335 compl_shown_match = find_comp_when_fuzzy();
5336 else if (cpt_sources_active)
5337 compl_shown_match = find_comp_when_cpt_sources();
5338 else
5339 compl_shown_match = compl_shown_match->cp_prev;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005340 found_end |= is_first_match(compl_shown_match);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005341 }
5342 else
5343 {
5344 if (!allow_get_expansion)
5345 {
5346 if (advance)
5347 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005348 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005349 compl_pending -= todo + 1;
5350 else
5351 compl_pending += todo + 1;
5352 }
5353 return -1;
5354 }
5355
5356 if (!compl_no_select && advance)
5357 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005358 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005359 --compl_pending;
5360 else
5361 ++compl_pending;
5362 }
5363
5364 // Find matches.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005365 *num_matches = ins_compl_get_exp(&compl_startpos);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005366
5367 // handle any pending completions
5368 while (compl_pending != 0 && compl_direction == compl_shows_dir
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005369 && advance)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005370 {
5371 if (compl_pending > 0 && compl_shown_match->cp_next != NULL)
5372 {
5373 compl_shown_match = compl_shown_match->cp_next;
5374 --compl_pending;
5375 }
5376 if (compl_pending < 0 && compl_shown_match->cp_prev != NULL)
5377 {
5378 compl_shown_match = compl_shown_match->cp_prev;
5379 ++compl_pending;
5380 }
5381 else
5382 break;
5383 }
5384 found_end = FALSE;
5385 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005386 if (!match_at_original_text(compl_shown_match)
John Marriott5e6ea922024-11-23 14:01:57 +01005387 && compl_leader.string != NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005388 && !ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01005389 compl_leader.string, (int)compl_leader.length)
glepnira218cc62024-06-03 19:32:39 +02005390 && !(compl_fuzzy_match && compl_shown_match->cp_score > 0))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005391 ++todo;
5392 else
5393 // Remember a matching item.
5394 found_compl = compl_shown_match;
5395
5396 // Stop at the end of the list when we found a usable match.
5397 if (found_end)
5398 {
5399 if (found_compl != NULL)
5400 {
5401 compl_shown_match = found_compl;
5402 break;
5403 }
5404 todo = 1; // use first usable match after wrapping around
5405 }
5406 }
5407
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005408 return OK;
5409}
5410
5411/*
5412 * Fill in the next completion in the current direction.
5413 * If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to
5414 * get more completions. If it is FALSE, then we just do nothing when there
5415 * are no more completions in a given direction. The latter case is used when
5416 * we are still in the middle of finding completions, to allow browsing
5417 * through the ones found so far.
5418 * Return the total number of matches, or -1 if still unknown -- webb.
5419 *
5420 * compl_curr_match is currently being used by ins_compl_get_exp(), so we use
5421 * compl_shown_match here.
5422 *
5423 * Note that this function may be called recursively once only. First with
5424 * "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn
5425 * calls this function with "allow_get_expansion" FALSE.
5426 */
5427 static int
5428ins_compl_next(
5429 int allow_get_expansion,
5430 int count, // repeat completion this many times; should
5431 // be at least 1
5432 int insert_match, // Insert the newly selected match
5433 int in_compl_func) // called from complete_check()
5434{
5435 int num_matches = -1;
5436 int todo = count;
5437 int advance;
5438 int started = compl_started;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005439 buf_T *orig_curbuf = curbuf;
zeertzjqaa925ee2024-06-09 18:24:05 +02005440 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02005441 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
5442 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
glepniredd4ac32025-01-29 18:53:51 +01005443 int compl_preinsert = ins_compl_has_preinsert();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005444
5445 // When user complete function return -1 for findstart which is next
5446 // time of 'always', compl_shown_match become NULL.
5447 if (compl_shown_match == NULL)
5448 return -1;
5449
John Marriott5e6ea922024-11-23 14:01:57 +01005450 if (compl_leader.string != NULL
glepnira218cc62024-06-03 19:32:39 +02005451 && !match_at_original_text(compl_shown_match)
5452 && !compl_fuzzy_match)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005453 // Update "compl_shown_match" to the actually shown match
5454 ins_compl_update_shown_match();
5455
5456 if (allow_get_expansion && insert_match
nwounkn2e3cd522023-10-17 11:05:38 +02005457 && (!compl_get_longest || compl_used_match))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005458 // Delete old text to be replaced
5459 ins_compl_delete();
5460
5461 // When finding the longest common text we stick at the original text,
5462 // don't let CTRL-N or CTRL-P move to the first match.
5463 advance = count != 1 || !allow_get_expansion || !compl_get_longest;
5464
5465 // When restarting the search don't insert the first match either.
5466 if (compl_restarting)
5467 {
5468 advance = FALSE;
5469 compl_restarting = FALSE;
5470 }
5471
5472 // Repeat this for when <PageUp> or <PageDown> is typed. But don't wrap
5473 // around.
5474 if (find_next_completion_match(allow_get_expansion, todo, advance,
5475 &num_matches) == -1)
5476 return -1;
5477
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005478 if (curbuf != orig_curbuf)
5479 {
5480 // In case some completion function switched buffer, don't want to
5481 // insert the completion elsewhere.
5482 return -1;
5483 }
5484
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005485 // Insert the text of the new completion, or the compl_leader.
glepniredd4ac32025-01-29 18:53:51 +01005486 if (compl_no_insert && !started && !compl_preinsert)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005487 {
glepnir6a38aff2024-12-16 21:56:16 +01005488 ins_compl_insert_bytes(compl_orig_text.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005489 compl_used_match = FALSE;
5490 }
5491 else if (insert_match)
5492 {
5493 if (!compl_get_longest || compl_used_match)
glepniredd4ac32025-01-29 18:53:51 +01005494 ins_compl_insert(in_compl_func, TRUE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005495 else
glepnir6a38aff2024-12-16 21:56:16 +01005496 ins_compl_insert_bytes(compl_leader.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005497 }
5498 else
5499 compl_used_match = FALSE;
5500
5501 if (!allow_get_expansion)
5502 {
5503 // may undisplay the popup menu first
5504 ins_compl_upd_pum();
5505
5506 if (pum_enough_matches())
5507 // Will display the popup menu, don't redraw yet to avoid flicker.
5508 pum_call_update_screen();
5509 else
5510 // Not showing the popup menu yet, redraw to show the user what was
5511 // inserted.
5512 update_screen(0);
5513
5514 // display the updated popup menu
5515 ins_compl_show_pum();
5516#ifdef FEAT_GUI
5517 if (gui.in_use)
5518 {
5519 // Show the cursor after the match, not after the redrawn text.
5520 setcursor();
5521 out_flush_cursor(FALSE, FALSE);
5522 }
5523#endif
5524
5525 // Delete old text to be replaced, since we're still searching and
5526 // don't want to match ourselves!
5527 ins_compl_delete();
5528 }
5529
5530 // Enter will select a match when the match wasn't inserted and the popup
5531 // menu is visible.
5532 if (compl_no_insert && !started)
5533 compl_enter_selects = TRUE;
5534 else
5535 compl_enter_selects = !insert_match && compl_match_array != NULL;
5536
5537 // Show the file name for the match (if any)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005538 if (compl_shown_match->cp_fname != NULL)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005539 ins_compl_show_filename();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005540
5541 return num_matches;
5542}
5543
5544/*
5545 * Call this while finding completions, to check whether the user has hit a key
5546 * that should change the currently displayed completion, or exit completion
5547 * mode. Also, when compl_pending is not zero, show a completion as soon as
5548 * possible. -- webb
5549 * "frequency" specifies out of how many calls we actually check.
5550 * "in_compl_func" is TRUE when called from complete_check(), don't set
5551 * compl_curr_match.
5552 */
5553 void
5554ins_compl_check_keys(int frequency, int in_compl_func)
5555{
5556 static int count = 0;
5557 int c;
5558
5559 // Don't check when reading keys from a script, :normal or feedkeys().
5560 // That would break the test scripts. But do check for keys when called
5561 // from complete_check().
5562 if (!in_compl_func && (using_script() || ex_normal_busy))
5563 return;
5564
5565 // Only do this at regular intervals
5566 if (++count < frequency)
5567 return;
5568 count = 0;
5569
5570 // Check for a typed key. Do use mappings, otherwise vim_is_ctrl_x_key()
5571 // can't do its work correctly.
5572 c = vpeekc_any();
5573 if (c != NUL)
5574 {
5575 if (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R)
5576 {
5577 c = safe_vgetc(); // Eat the character
5578 compl_shows_dir = ins_compl_key2dir(c);
5579 (void)ins_compl_next(FALSE, ins_compl_key2count(c),
5580 c != K_UP && c != K_DOWN, in_compl_func);
5581 }
5582 else
5583 {
5584 // Need to get the character to have KeyTyped set. We'll put it
5585 // back with vungetc() below. But skip K_IGNORE.
5586 c = safe_vgetc();
5587 if (c != K_IGNORE)
5588 {
5589 // Don't interrupt completion when the character wasn't typed,
5590 // e.g., when doing @q to replay keys.
5591 if (c != Ctrl_R && KeyTyped)
5592 compl_interrupted = TRUE;
5593
5594 vungetc(c);
5595 }
5596 }
5597 }
zeertzjq529b9ad2024-06-05 20:27:06 +02005598 if (compl_pending != 0 && !got_int && !(cot_flags & COT_NOINSERT))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005599 {
5600 int todo = compl_pending > 0 ? compl_pending : -compl_pending;
5601
5602 compl_pending = 0;
5603 (void)ins_compl_next(FALSE, todo, TRUE, in_compl_func);
5604 }
5605}
5606
5607/*
5608 * Decide the direction of Insert mode complete from the key typed.
5609 * Returns BACKWARD or FORWARD.
5610 */
5611 static int
5612ins_compl_key2dir(int c)
5613{
5614 if (c == Ctrl_P || c == Ctrl_L
5615 || c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP || c == K_UP)
5616 return BACKWARD;
5617 return FORWARD;
5618}
5619
5620/*
5621 * Return TRUE for keys that are used for completion only when the popup menu
5622 * is visible.
5623 */
5624 static int
5625ins_compl_pum_key(int c)
5626{
5627 return pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP
5628 || c == K_PAGEDOWN || c == K_KPAGEDOWN || c == K_S_DOWN
5629 || c == K_UP || c == K_DOWN);
5630}
5631
5632/*
5633 * Decide the number of completions to move forward.
5634 * Returns 1 for most keys, height of the popup menu for page-up/down keys.
5635 */
5636 static int
5637ins_compl_key2count(int c)
5638{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005639 if (ins_compl_pum_key(c) && c != K_UP && c != K_DOWN)
5640 {
glepnir19e1dd62025-05-08 22:50:38 +02005641 int h = pum_get_height();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005642 if (h > 3)
5643 h -= 2; // keep some context
5644 return h;
5645 }
5646 return 1;
5647}
5648
5649/*
5650 * Return TRUE if completion with "c" should insert the match, FALSE if only
5651 * to change the currently selected completion.
5652 */
5653 static int
5654ins_compl_use_match(int c)
5655{
5656 switch (c)
5657 {
5658 case K_UP:
5659 case K_DOWN:
5660 case K_PAGEDOWN:
5661 case K_KPAGEDOWN:
5662 case K_S_DOWN:
5663 case K_PAGEUP:
5664 case K_KPAGEUP:
5665 case K_S_UP:
5666 return FALSE;
5667 }
5668 return TRUE;
5669}
5670
5671/*
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005672 * Get the pattern, column and length for normal completion (CTRL-N CTRL-P
5673 * completion)
John Marriott5e6ea922024-11-23 14:01:57 +01005674 * Sets the global variables: compl_col, compl_length and compl_pattern.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005675 * Uses the global variables: compl_cont_status and ctrl_x_mode
5676 */
5677 static int
5678get_normal_compl_info(char_u *line, int startcol, colnr_T curs_col)
5679{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005680 if ((compl_cont_status & CONT_SOL) || ctrl_x_mode_path_defines())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005681 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005682 if (!compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005683 {
5684 while (--startcol >= 0 && vim_isIDc(line[startcol]))
5685 ;
5686 compl_col += ++startcol;
5687 compl_length = curs_col - startcol;
5688 }
5689 if (p_ic)
John Marriott8c85a2a2024-05-20 19:18:26 +02005690 {
John Marriott5e6ea922024-11-23 14:01:57 +01005691 compl_pattern.string = str_foldcase(line + compl_col,
5692 compl_length, NULL, 0);
5693 if (compl_pattern.string == NULL)
5694 {
5695 compl_pattern.length = 0;
5696 return FAIL;
5697 }
5698 compl_pattern.length = STRLEN(compl_pattern.string);
5699 }
5700 else
5701 {
5702 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5703 if (compl_pattern.string == NULL)
5704 {
5705 compl_pattern.length = 0;
5706 return FAIL;
5707 }
5708 compl_pattern.length = (size_t)compl_length;
John Marriott8c85a2a2024-05-20 19:18:26 +02005709 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005710 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005711 else if (compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005712 {
5713 char_u *prefix = (char_u *)"\\<";
John Marriott8c85a2a2024-05-20 19:18:26 +02005714 size_t prefixlen = STRLEN_LITERAL("\\<");
John Marriott5e6ea922024-11-23 14:01:57 +01005715 size_t n;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005716
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005717 if (!vim_iswordp(line + compl_col)
5718 || (compl_col > 0
5719 && (vim_iswordp(mb_prevptr(line, line + compl_col)))))
John Marriott8c85a2a2024-05-20 19:18:26 +02005720 {
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005721 prefix = (char_u *)"";
John Marriott8c85a2a2024-05-20 19:18:26 +02005722 prefixlen = 0;
5723 }
John Marriott5e6ea922024-11-23 14:01:57 +01005724
5725 // we need up to 2 extra chars for the prefix
5726 n = quote_meta(NULL, line + compl_col, compl_length) + prefixlen;
5727 compl_pattern.string = alloc(n);
5728 if (compl_pattern.string == NULL)
5729 {
5730 compl_pattern.length = 0;
5731 return FAIL;
5732 }
5733 STRCPY((char *)compl_pattern.string, prefix);
5734 (void)quote_meta(compl_pattern.string + prefixlen,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005735 line + compl_col, compl_length);
John Marriott5e6ea922024-11-23 14:01:57 +01005736 compl_pattern.length = n - 1;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005737 }
5738 else if (--startcol < 0
5739 || !vim_iswordp(mb_prevptr(line, line + startcol + 1)))
5740 {
John Marriott5e6ea922024-11-23 14:01:57 +01005741 size_t len = STRLEN_LITERAL("\\<\\k\\k");
5742
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005743 // Match any word of at least two chars
John Marriott5e6ea922024-11-23 14:01:57 +01005744 compl_pattern.string = vim_strnsave((char_u *)"\\<\\k\\k", len);
5745 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005746 {
John Marriott5e6ea922024-11-23 14:01:57 +01005747 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005748 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005749 }
John Marriott5e6ea922024-11-23 14:01:57 +01005750 compl_pattern.length = len;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005751 compl_col += curs_col;
5752 compl_length = 0;
5753 }
5754 else
5755 {
5756 // Search the point of change class of multibyte character
5757 // or not a word single byte character backward.
5758 if (has_mbyte)
5759 {
5760 int base_class;
5761 int head_off;
5762
5763 startcol -= (*mb_head_off)(line, line + startcol);
5764 base_class = mb_get_class(line + startcol);
5765 while (--startcol >= 0)
5766 {
5767 head_off = (*mb_head_off)(line, line + startcol);
5768 if (base_class != mb_get_class(line + startcol
5769 - head_off))
5770 break;
5771 startcol -= head_off;
5772 }
5773 }
5774 else
glepnir19e1dd62025-05-08 22:50:38 +02005775 {
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005776 while (--startcol >= 0 && vim_iswordc(line[startcol]))
5777 ;
glepnir19e1dd62025-05-08 22:50:38 +02005778 }
5779
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005780 compl_col += ++startcol;
5781 compl_length = (int)curs_col - startcol;
5782 if (compl_length == 1)
5783 {
5784 // Only match word with at least two chars -- webb
5785 // there's no need to call quote_meta,
5786 // alloc(7) is enough -- Acevedo
John Marriott5e6ea922024-11-23 14:01:57 +01005787 compl_pattern.string = alloc(7);
5788 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005789 {
John Marriott5e6ea922024-11-23 14:01:57 +01005790 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005791 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005792 }
John Marriott5e6ea922024-11-23 14:01:57 +01005793 STRCPY((char *)compl_pattern.string, "\\<");
5794 (void)quote_meta(compl_pattern.string + 2, line + compl_col, 1);
5795 STRCAT((char *)compl_pattern.string, "\\k");
5796 compl_pattern.length = STRLEN(compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005797 }
5798 else
5799 {
John Marriott5e6ea922024-11-23 14:01:57 +01005800 size_t n = quote_meta(NULL, line + compl_col, compl_length) + 2;
5801
5802 compl_pattern.string = alloc(n);
5803 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005804 {
John Marriott5e6ea922024-11-23 14:01:57 +01005805 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005806 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005807 }
John Marriott5e6ea922024-11-23 14:01:57 +01005808 STRCPY((char *)compl_pattern.string, "\\<");
5809 (void)quote_meta(compl_pattern.string + 2, line + compl_col,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005810 compl_length);
John Marriott5e6ea922024-11-23 14:01:57 +01005811 compl_pattern.length = n - 1;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005812 }
5813 }
5814
5815 return OK;
5816}
5817
5818/*
5819 * Get the pattern, column and length for whole line completion or for the
5820 * complete() function.
5821 * Sets the global variables: compl_col, compl_length and compl_pattern.
5822 */
5823 static int
5824get_wholeline_compl_info(char_u *line, colnr_T curs_col)
5825{
5826 compl_col = (colnr_T)getwhitecols(line);
5827 compl_length = (int)curs_col - (int)compl_col;
5828 if (compl_length < 0) // cursor in indent: empty pattern
5829 compl_length = 0;
5830 if (p_ic)
John Marriott8c85a2a2024-05-20 19:18:26 +02005831 {
John Marriott5e6ea922024-11-23 14:01:57 +01005832 compl_pattern.string = str_foldcase(line + compl_col, compl_length,
5833 NULL, 0);
5834 if (compl_pattern.string == NULL)
5835 {
5836 compl_pattern.length = 0;
5837 return FAIL;
5838 }
5839 compl_pattern.length = STRLEN(compl_pattern.string);
John Marriott8c85a2a2024-05-20 19:18:26 +02005840 }
John Marriott5e6ea922024-11-23 14:01:57 +01005841 else
5842 {
5843 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5844 if (compl_pattern.string == NULL)
5845 {
5846 compl_pattern.length = 0;
5847 return FAIL;
5848 }
5849 compl_pattern.length = (size_t)compl_length;
5850 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005851
5852 return OK;
5853}
5854
5855/*
5856 * Get the pattern, column and length for filename completion.
5857 * Sets the global variables: compl_col, compl_length and compl_pattern.
5858 */
5859 static int
5860get_filename_compl_info(char_u *line, int startcol, colnr_T curs_col)
5861{
5862 // Go back to just before the first filename character.
5863 if (startcol > 0)
5864 {
5865 char_u *p = line + startcol;
5866
5867 MB_PTR_BACK(line, p);
5868 while (p > line && vim_isfilec(PTR2CHAR(p)))
5869 MB_PTR_BACK(line, p);
5870 if (p == line && vim_isfilec(PTR2CHAR(p)))
5871 startcol = 0;
5872 else
5873 startcol = (int)(p - line) + 1;
5874 }
5875
5876 compl_col += startcol;
5877 compl_length = (int)curs_col - startcol;
John Marriott5e6ea922024-11-23 14:01:57 +01005878 compl_pattern.string = addstar(line + compl_col, compl_length, EXPAND_FILES);
5879 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005880 {
John Marriott5e6ea922024-11-23 14:01:57 +01005881 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005882 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005883 }
5884
John Marriott5e6ea922024-11-23 14:01:57 +01005885 compl_pattern.length = STRLEN(compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005886
5887 return OK;
5888}
5889
5890/*
5891 * Get the pattern, column and length for command-line completion.
5892 * Sets the global variables: compl_col, compl_length and compl_pattern.
5893 */
5894 static int
5895get_cmdline_compl_info(char_u *line, colnr_T curs_col)
5896{
John Marriott5e6ea922024-11-23 14:01:57 +01005897 compl_pattern.string = vim_strnsave(line, curs_col);
5898 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005899 {
John Marriott5e6ea922024-11-23 14:01:57 +01005900 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005901 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005902 }
John Marriott5e6ea922024-11-23 14:01:57 +01005903 compl_pattern.length = curs_col;
5904 set_cmd_context(&compl_xp, compl_pattern.string,
5905 (int)compl_pattern.length, curs_col, FALSE);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005906 if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL
5907 || compl_xp.xp_context == EXPAND_NOTHING)
5908 // No completion possible, use an empty pattern to get a
5909 // "pattern not found" message.
5910 compl_col = curs_col;
5911 else
John Marriott5e6ea922024-11-23 14:01:57 +01005912 compl_col = (int)(compl_xp.xp_pattern - compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005913 compl_length = curs_col - compl_col;
5914
5915 return OK;
5916}
5917
5918/*
5919 * Get the pattern, column and length for user defined completion ('omnifunc',
5920 * 'completefunc' and 'thesaurusfunc')
5921 * Sets the global variables: compl_col, compl_length and compl_pattern.
5922 * Uses the global variable: spell_bad_len
Girish Palyacbe53192025-04-14 22:13:15 +02005923 * Callback function "cb" is set if triggered by a function in the 'cpt'
5924 * option; otherwise, it is NULL.
5925 * "startcol", when not NULL, contains the column returned by function.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005926 */
5927 static int
glepnir19e1dd62025-05-08 22:50:38 +02005928get_userdefined_compl_info(
5929 colnr_T curs_col UNUSED,
5930 callback_T *cb UNUSED,
5931 int *startcol UNUSED)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005932{
5933 int ret = FAIL;
5934
5935#ifdef FEAT_COMPL_FUNC
5936 // Call user defined function 'completefunc' with "a:findstart"
5937 // set to 1 to obtain the length of text to use for completion.
glepnir19e1dd62025-05-08 22:50:38 +02005938 char_u *line = NULL;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005939 typval_T args[3];
5940 int col;
glepnir19e1dd62025-05-08 22:50:38 +02005941 char_u *funcname = NULL;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005942 pos_T pos;
5943 int save_State = State;
Girish Palyacbe53192025-04-14 22:13:15 +02005944 int len;
glepnir19e1dd62025-05-08 22:50:38 +02005945 string_T *compl_pat = NULL;
Girish Palyacbe53192025-04-14 22:13:15 +02005946 int is_cpt_function = (cb != NULL);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005947
Girish Palyacbe53192025-04-14 22:13:15 +02005948 if (!is_cpt_function)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005949 {
Girish Palyacbe53192025-04-14 22:13:15 +02005950 // Call 'completefunc' or 'omnifunc' or 'thesaurusfunc' and get pattern
5951 // length as a string
5952 funcname = get_complete_funcname(ctrl_x_mode);
5953 if (*funcname == NUL)
5954 {
5955 semsg(_(e_option_str_is_not_set), ctrl_x_mode_function()
5956 ? "completefunc" : "omnifunc");
5957 return FAIL;
5958 }
5959 cb = get_insert_callback(ctrl_x_mode);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005960 }
5961
5962 args[0].v_type = VAR_NUMBER;
5963 args[0].vval.v_number = 1;
5964 args[1].v_type = VAR_STRING;
5965 args[1].vval.v_string = (char_u *)"";
5966 args[2].v_type = VAR_UNKNOWN;
5967 pos = curwin->w_cursor;
zeertzjqcfe45652022-05-27 17:26:55 +01005968 ++textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005969 col = call_callback_retnr(cb, 2, args);
zeertzjqcfe45652022-05-27 17:26:55 +01005970 --textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005971
5972 State = save_State;
5973 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02005974 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005975 validate_cursor();
5976 if (!EQUAL_POS(curwin->w_cursor, pos))
5977 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00005978 emsg(_(e_complete_function_deleted_text));
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005979 return FAIL;
5980 }
5981
Girish Palyacbe53192025-04-14 22:13:15 +02005982 if (startcol != NULL)
5983 *startcol = col;
5984
LemonBoy9bcb9ca2022-05-26 15:23:26 +01005985 // Return value -2 means the user complete function wants to cancel the
5986 // complete without an error, do the same if the function did not execute
5987 // successfully.
5988 if (col == -2 || aborting())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005989 return FAIL;
glepnir19e1dd62025-05-08 22:50:38 +02005990
LemonBoy9bcb9ca2022-05-26 15:23:26 +01005991 // Return value -3 does the same as -2 and leaves CTRL-X mode.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005992 if (col == -3)
5993 {
Girish Palyacbe53192025-04-14 22:13:15 +02005994 if (is_cpt_function)
5995 return FAIL;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005996 ctrl_x_mode = CTRL_X_NORMAL;
5997 edit_submode = NULL;
5998 if (!shortmess(SHM_COMPLETIONMENU))
5999 msg_clr_cmdline();
6000 return FAIL;
6001 }
6002
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00006003 // Reset extended parameters of completion, when starting new
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006004 // completion.
6005 compl_opt_refresh_always = FALSE;
6006 compl_opt_suppress_empty = FALSE;
6007
Girish Palyacbe53192025-04-14 22:13:15 +02006008 if (col < 0 || col > curs_col)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006009 col = curs_col;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006010
6011 // Setup variables for completion. Need to obtain "line" again,
6012 // it may have become invalid.
6013 line = ml_get(curwin->w_cursor.lnum);
Girish Palyacbe53192025-04-14 22:13:15 +02006014 len = curs_col - col;
6015 compl_pat = is_cpt_function ? &cpt_compl_pattern : &compl_pattern;
6016 compl_pat->string = vim_strnsave(line + col, (size_t)len);
6017 if (compl_pat->string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02006018 {
Girish Palyacbe53192025-04-14 22:13:15 +02006019 compl_pat->length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006020 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02006021 }
Girish Palyacbe53192025-04-14 22:13:15 +02006022 compl_pat->length = (size_t)compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006023
Girish Palyacbe53192025-04-14 22:13:15 +02006024 if (!is_cpt_function)
6025 {
6026 compl_col = col;
6027 compl_length = len;
6028 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006029 ret = OK;
6030#endif
6031
6032 return ret;
6033}
6034
6035/*
6036 * Get the pattern, column and length for spell completion.
6037 * Sets the global variables: compl_col, compl_length and compl_pattern.
6038 * Uses the global variable: spell_bad_len
6039 */
6040 static int
6041get_spell_compl_info(int startcol UNUSED, colnr_T curs_col UNUSED)
6042{
6043 int ret = FAIL;
6044#ifdef FEAT_SPELL
glepnir19e1dd62025-05-08 22:50:38 +02006045 char_u *line = NULL;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006046
6047 if (spell_bad_len > 0)
6048 compl_col = curs_col - spell_bad_len;
6049 else
6050 compl_col = spell_word_start(startcol);
glepnir19e1dd62025-05-08 22:50:38 +02006051
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006052 if (compl_col >= (colnr_T)startcol)
6053 {
6054 compl_length = 0;
6055 compl_col = curs_col;
6056 }
6057 else
6058 {
6059 spell_expand_check_cap(compl_col);
6060 compl_length = (int)curs_col - compl_col;
6061 }
6062 // Need to obtain "line" again, it may have become invalid.
6063 line = ml_get(curwin->w_cursor.lnum);
John Marriott5e6ea922024-11-23 14:01:57 +01006064 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
6065 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02006066 {
John Marriott5e6ea922024-11-23 14:01:57 +01006067 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006068 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02006069 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006070
John Marriott5e6ea922024-11-23 14:01:57 +01006071 compl_pattern.length = (size_t)compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006072 ret = OK;
6073#endif
6074
6075 return ret;
6076}
6077
6078/*
6079 * Get the completion pattern, column and length.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006080 * "startcol" - start column number of the completion pattern/text
6081 * "cur_col" - current cursor column
6082 * On return, "line_invalid" is set to TRUE, if the current line may have
6083 * become invalid and needs to be fetched again.
6084 * Returns OK on success.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006085 */
6086 static int
6087compl_get_info(char_u *line, int startcol, colnr_T curs_col, int *line_invalid)
6088{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006089 if (ctrl_x_mode_normal()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006090 || (ctrl_x_mode & CTRL_X_WANT_IDENT
6091 && !thesaurus_func_complete(ctrl_x_mode)))
6092 {
6093 return get_normal_compl_info(line, startcol, curs_col);
6094 }
6095 else if (ctrl_x_mode_line_or_eval())
6096 {
6097 return get_wholeline_compl_info(line, curs_col);
6098 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006099 else if (ctrl_x_mode_files())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006100 {
6101 return get_filename_compl_info(line, startcol, curs_col);
6102 }
6103 else if (ctrl_x_mode == CTRL_X_CMDLINE)
6104 {
6105 return get_cmdline_compl_info(line, curs_col);
6106 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006107 else if (ctrl_x_mode_function() || ctrl_x_mode_omni()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006108 || thesaurus_func_complete(ctrl_x_mode))
6109 {
Girish Palyacbe53192025-04-14 22:13:15 +02006110 if (get_userdefined_compl_info(curs_col, NULL, NULL) != OK)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006111 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006112 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006113 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006114 else if (ctrl_x_mode_spell())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006115 {
6116 if (get_spell_compl_info(startcol, curs_col) == FAIL)
6117 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006118 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006119 }
6120 else
6121 {
6122 internal_error("ins_complete()");
6123 return FAIL;
6124 }
6125
6126 return OK;
6127}
6128
6129/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006130 * Continue an interrupted completion mode search in "line".
6131 *
6132 * If this same ctrl_x_mode has been interrupted use the text from
6133 * "compl_startpos" to the cursor as a pattern to add a new word instead of
6134 * expand the one before the cursor, in word-wise if "compl_startpos" is not in
6135 * the same line as the cursor then fix it (the line has been split because it
6136 * was longer than 'tw'). if SOL is set then skip the previous pattern, a word
6137 * at the beginning of the line has been inserted, we'll look for that.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006138 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006139 static void
6140ins_compl_continue_search(char_u *line)
6141{
6142 // it is a continued search
6143 compl_cont_status &= ~CONT_INTRPT; // remove INTRPT
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006144 if (ctrl_x_mode_normal() || ctrl_x_mode_path_patterns()
6145 || ctrl_x_mode_path_defines())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006146 {
6147 if (compl_startpos.lnum != curwin->w_cursor.lnum)
6148 {
6149 // line (probably) wrapped, set compl_startpos to the
6150 // first non_blank in the line, if it is not a wordchar
6151 // include it to get a better pattern, but then we don't
6152 // want the "\\<" prefix, check it below
6153 compl_col = (colnr_T)getwhitecols(line);
6154 compl_startpos.col = compl_col;
6155 compl_startpos.lnum = curwin->w_cursor.lnum;
6156 compl_cont_status &= ~CONT_SOL; // clear SOL if present
6157 }
6158 else
6159 {
6160 // S_IPOS was set when we inserted a word that was at the
6161 // beginning of the line, which means that we'll go to SOL
6162 // mode but first we need to redefine compl_startpos
6163 if (compl_cont_status & CONT_S_IPOS)
6164 {
6165 compl_cont_status |= CONT_SOL;
6166 compl_startpos.col = (colnr_T)(skipwhite(
6167 line + compl_length
6168 + compl_startpos.col) - line);
6169 }
6170 compl_col = compl_startpos.col;
6171 }
6172 compl_length = curwin->w_cursor.col - (int)compl_col;
6173 // IObuff is used to add a "word from the next line" would we
6174 // have enough space? just being paranoid
6175#define MIN_SPACE 75
6176 if (compl_length > (IOSIZE - MIN_SPACE))
6177 {
6178 compl_cont_status &= ~CONT_SOL;
6179 compl_length = (IOSIZE - MIN_SPACE);
6180 compl_col = curwin->w_cursor.col - compl_length;
6181 }
6182 compl_cont_status |= CONT_ADDING | CONT_N_ADDS;
6183 if (compl_length < 1)
6184 compl_cont_status &= CONT_LOCAL;
6185 }
6186 else if (ctrl_x_mode_line_or_eval())
6187 compl_cont_status = CONT_ADDING | CONT_N_ADDS;
6188 else
6189 compl_cont_status = 0;
6190}
6191
6192/*
6193 * start insert mode completion
6194 */
6195 static int
6196ins_compl_start(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006197{
glepnir19e1dd62025-05-08 22:50:38 +02006198 char_u *line = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006199 int startcol = 0; // column where searched text starts
6200 colnr_T curs_col; // cursor column
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006201 int line_invalid = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006202 int save_did_ai = did_ai;
Bram Moolenaard9eefe32019-04-06 14:22:21 +02006203 int flags = CP_ORIGINAL_TEXT;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006204
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006205 // First time we hit ^N or ^P (in a row, I mean)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006206 did_ai = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006207 did_si = FALSE;
6208 can_si = FALSE;
6209 can_si_back = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006210 if (stop_arrow() == FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006211 return FAIL;
6212
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006213 line = ml_get(curwin->w_cursor.lnum);
6214 curs_col = curwin->w_cursor.col;
6215 compl_pending = 0;
glepnir76bdb822025-02-08 19:04:51 +01006216 compl_lnum = curwin->w_cursor.lnum;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006217
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006218 if ((compl_cont_status & CONT_INTRPT) == CONT_INTRPT
6219 && compl_cont_mode == ctrl_x_mode)
6220 // this same ctrl-x_mode was interrupted previously. Continue the
6221 // completion.
6222 ins_compl_continue_search(line);
6223 else
6224 compl_cont_status &= CONT_LOCAL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006225
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006226 if (!compl_status_adding()) // normal expansion
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006227 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006228 compl_cont_mode = ctrl_x_mode;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006229 if (ctrl_x_mode_not_default())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006230 // Remove LOCAL if ctrl_x_mode != CTRL_X_NORMAL
6231 compl_cont_status = 0;
6232 compl_cont_status |= CONT_N_ADDS;
6233 compl_startpos = curwin->w_cursor;
6234 startcol = (int)curs_col;
6235 compl_col = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006236 }
6237
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006238 // Work out completion pattern and original text -- webb
6239 if (compl_get_info(line, startcol, curs_col, &line_invalid) == FAIL)
6240 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006241 if (ctrl_x_mode_function() || ctrl_x_mode_omni()
6242 || thesaurus_func_complete(ctrl_x_mode))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006243 // restore did_ai, so that adding comment leader works
6244 did_ai = save_did_ai;
6245 return FAIL;
6246 }
6247 // If "line" was changed while getting completion info get it again.
6248 if (line_invalid)
6249 line = ml_get(curwin->w_cursor.lnum);
6250
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006251 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006252 {
6253 edit_submode_pre = (char_u *)_(" Adding");
6254 if (ctrl_x_mode_line_or_eval())
6255 {
6256 // Insert a new line, keep indentation but ignore 'comments'.
6257 char_u *old = curbuf->b_p_com;
6258
6259 curbuf->b_p_com = (char_u *)"";
6260 compl_startpos.lnum = curwin->w_cursor.lnum;
6261 compl_startpos.col = compl_col;
6262 ins_eol('\r');
6263 curbuf->b_p_com = old;
6264 compl_length = 0;
6265 compl_col = curwin->w_cursor.col;
glepnir76bdb822025-02-08 19:04:51 +01006266 compl_lnum = curwin->w_cursor.lnum;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006267 }
glepnircfe502c2025-04-17 20:17:53 +02006268 else if (ctrl_x_mode_normal() && cfc_has_mode())
glepnir7cfe6932024-09-15 20:06:28 +02006269 {
6270 compl_startpos = curwin->w_cursor;
6271 compl_cont_status &= CONT_S_IPOS;
6272 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006273 }
6274 else
6275 {
6276 edit_submode_pre = NULL;
6277 compl_startpos.col = compl_col;
6278 }
6279
6280 if (compl_cont_status & CONT_LOCAL)
6281 edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]);
6282 else
6283 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
6284
6285 // If any of the original typed text has been changed we need to fix
6286 // the redo buffer.
6287 ins_compl_fixRedoBufForLeader(NULL);
6288
6289 // Always add completion for the original text.
John Marriott5e6ea922024-11-23 14:01:57 +01006290 VIM_CLEAR_STRING(compl_orig_text);
6291 compl_orig_text.length = (size_t)compl_length;
6292 compl_orig_text.string = vim_strnsave(line + compl_col, (size_t)compl_length);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006293 if (p_ic)
6294 flags |= CP_ICASE;
zeertzjq4422de62025-03-07 19:06:02 +01006295 if (compl_orig_text.string == NULL
6296 || ins_compl_add(compl_orig_text.string,
6297 (int)compl_orig_text.length,
6298 NULL, NULL, NULL, 0, flags, FALSE, NULL, 0) != OK)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006299 {
John Marriott5e6ea922024-11-23 14:01:57 +01006300 VIM_CLEAR_STRING(compl_pattern);
6301 VIM_CLEAR_STRING(compl_orig_text);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006302 return FAIL;
6303 }
6304
6305 // showmode might reset the internal line pointers, so it must
6306 // be called before line = ml_get(), or when this address is no
6307 // longer needed. -- Acevedo.
6308 edit_submode_extra = (char_u *)_("-- Searching...");
6309 edit_submode_highl = HLF_COUNT;
6310 showmode();
6311 edit_submode_extra = NULL;
6312 out_flush();
6313
6314 return OK;
6315}
6316
6317/*
6318 * display the completion status message
6319 */
6320 static void
6321ins_compl_show_statusmsg(void)
6322{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006323 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006324 if (is_first_match(compl_first_match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006325 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006326 edit_submode_extra = compl_status_adding() && compl_length > 1
Bram Moolenaarb53a1902022-11-15 13:57:38 +00006327 ? (char_u *)_("Hit end of paragraph")
6328 : (char_u *)_("Pattern not found");
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006329 edit_submode_highl = HLF_E;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006330 }
6331
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006332 if (edit_submode_extra == NULL)
6333 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006334 if (match_at_original_text(compl_curr_match))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006335 {
6336 edit_submode_extra = (char_u *)_("Back at original");
6337 edit_submode_highl = HLF_W;
6338 }
6339 else if (compl_cont_status & CONT_S_IPOS)
6340 {
6341 edit_submode_extra = (char_u *)_("Word from other line");
6342 edit_submode_highl = HLF_COUNT;
6343 }
6344 else if (compl_curr_match->cp_next == compl_curr_match->cp_prev)
6345 {
6346 edit_submode_extra = (char_u *)_("The only match");
6347 edit_submode_highl = HLF_COUNT;
Bram Moolenaarf9d51352020-10-26 19:22:42 +01006348 compl_curr_match->cp_number = 1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006349 }
6350 else
6351 {
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01006352#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006353 // Update completion sequence number when needed.
6354 if (compl_curr_match->cp_number == -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01006355 ins_compl_update_sequence_numbers();
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01006356#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006357 // The match should always have a sequence number now, this is
6358 // just a safety check.
6359 if (compl_curr_match->cp_number != -1)
6360 {
6361 // Space for 10 text chars. + 2x10-digit no.s = 31.
6362 // Translations may need more than twice that.
6363 static char_u match_ref[81];
6364
6365 if (compl_matches > 0)
6366 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006367 _("match %d of %d"),
6368 compl_curr_match->cp_number, compl_matches);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006369 else
6370 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006371 _("match %d"),
6372 compl_curr_match->cp_number);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006373 edit_submode_extra = match_ref;
6374 edit_submode_highl = HLF_R;
6375 if (dollar_vcol >= 0)
6376 curs_columns(FALSE);
6377 }
6378 }
6379 }
6380
6381 // Show a message about what (completion) mode we're in.
6382 if (!compl_opt_suppress_empty)
6383 {
6384 showmode();
6385 if (!shortmess(SHM_COMPLETIONMENU))
6386 {
6387 if (edit_submode_extra != NULL)
6388 {
6389 if (!p_smd)
Bram Moolenaarcc233582020-12-12 13:32:07 +01006390 {
6391 msg_hist_off = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006392 msg_attr((char *)edit_submode_extra,
6393 edit_submode_highl < HLF_COUNT
6394 ? HL_ATTR(edit_submode_highl) : 0);
Bram Moolenaarcc233582020-12-12 13:32:07 +01006395 msg_hist_off = FALSE;
6396 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006397 }
6398 else
6399 msg_clr_cmdline(); // necessary for "noshowmode"
6400 }
6401 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006402}
6403
6404/*
6405 * Do Insert mode completion.
6406 * Called when character "c" was typed, which has a meaning for completion.
6407 * Returns OK if completion was done, FAIL if something failed (out of mem).
6408 */
6409 int
6410ins_complete(int c, int enable_pum)
6411{
6412 int n;
6413 int save_w_wrow;
6414 int save_w_leftcol;
6415 int insert_match;
6416
6417 compl_direction = ins_compl_key2dir(c);
6418 insert_match = ins_compl_use_match(c);
6419
6420 if (!compl_started)
6421 {
6422 if (ins_compl_start() == FAIL)
6423 return FAIL;
6424 }
6425 else if (insert_match && stop_arrow() == FAIL)
6426 return FAIL;
6427
glepnircf7f0122025-04-15 19:02:00 +02006428 compl_curr_win = curwin;
6429 compl_curr_buf = curwin->w_buffer;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006430 compl_shown_match = compl_curr_match;
6431 compl_shows_dir = compl_direction;
6432
6433 // Find next match (and following matches).
6434 save_w_wrow = curwin->w_wrow;
6435 save_w_leftcol = curwin->w_leftcol;
6436 n = ins_compl_next(TRUE, ins_compl_key2count(c), insert_match, FALSE);
6437
6438 // may undisplay the popup menu
6439 ins_compl_upd_pum();
6440
6441 if (n > 1) // all matches have been found
6442 compl_matches = n;
6443 compl_curr_match = compl_shown_match;
6444 compl_direction = compl_shows_dir;
6445
6446 // Eat the ESC that vgetc() returns after a CTRL-C to avoid leaving Insert
6447 // mode.
6448 if (got_int && !global_busy)
6449 {
6450 (void)vgetc();
6451 got_int = FALSE;
6452 }
6453
6454 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006455 if (is_first_match(compl_first_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006456 {
6457 // remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,
6458 // because we couldn't expand anything at first place, but if we used
6459 // ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word
6460 // (such as M in M'exico) if not tried already. -- Acevedo
6461 if (compl_length > 1
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006462 || compl_status_adding()
6463 || (ctrl_x_mode_not_default()
6464 && !ctrl_x_mode_path_patterns()
6465 && !ctrl_x_mode_path_defines()))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006466 compl_cont_status &= ~CONT_N_ADDS;
6467 }
6468
6469 if (compl_curr_match->cp_flags & CP_CONT_S_IPOS)
6470 compl_cont_status |= CONT_S_IPOS;
6471 else
6472 compl_cont_status &= ~CONT_S_IPOS;
6473
6474 ins_compl_show_statusmsg();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006475
6476 // Show the popup menu, unless we got interrupted.
6477 if (enable_pum && !compl_interrupted)
6478 show_pum(save_w_wrow, save_w_leftcol);
6479
6480 compl_was_interrupted = compl_interrupted;
6481 compl_interrupted = FALSE;
6482
6483 return OK;
6484}
6485
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00006486/*
6487 * Remove (if needed) and show the popup menu
6488 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006489 static void
6490show_pum(int prev_w_wrow, int prev_w_leftcol)
6491{
6492 // RedrawingDisabled may be set when invoked through complete().
Bram Moolenaar79cdf022023-05-20 14:07:00 +01006493 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006494 RedrawingDisabled = 0;
6495
6496 // If the cursor moved or the display scrolled we need to remove the pum
6497 // first.
6498 setcursor();
6499 if (prev_w_wrow != curwin->w_wrow || prev_w_leftcol != curwin->w_leftcol)
6500 ins_compl_del_pum();
6501
6502 ins_compl_show_pum();
6503 setcursor();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01006504
6505 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006506}
6507
6508/*
6509 * Looks in the first "len" chars. of "src" for search-metachars.
6510 * If dest is not NULL the chars. are copied there quoting (with
6511 * a backslash) the metachars, and dest would be NUL terminated.
6512 * Returns the length (needed) of dest
6513 */
6514 static unsigned
6515quote_meta(char_u *dest, char_u *src, int len)
6516{
6517 unsigned m = (unsigned)len + 1; // one extra for the NUL
6518
6519 for ( ; --len >= 0; src++)
6520 {
6521 switch (*src)
6522 {
6523 case '.':
6524 case '*':
6525 case '[':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006526 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006527 break;
6528 // FALLTHROUGH
6529 case '~':
Bram Moolenaarf4e20992020-12-21 19:59:08 +01006530 if (!magic_isset()) // quote these only if magic is set
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006531 break;
6532 // FALLTHROUGH
6533 case '\\':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006534 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006535 break;
6536 // FALLTHROUGH
6537 case '^': // currently it's not needed.
6538 case '$':
6539 m++;
6540 if (dest != NULL)
6541 *dest++ = '\\';
6542 break;
6543 }
6544 if (dest != NULL)
6545 *dest++ = *src;
6546 // Copy remaining bytes of a multibyte character.
6547 if (has_mbyte)
6548 {
glepnir19e1dd62025-05-08 22:50:38 +02006549 int mb_len = (*mb_ptr2len)(src) - 1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006550 if (mb_len > 0 && len >= mb_len)
glepnir19e1dd62025-05-08 22:50:38 +02006551 for (int i = 0; i < mb_len; ++i)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006552 {
6553 --len;
6554 ++src;
6555 if (dest != NULL)
6556 *dest++ = *src;
6557 }
6558 }
6559 }
6560 if (dest != NULL)
6561 *dest = NUL;
6562
6563 return m;
6564}
6565
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006566#if defined(EXITFREE) || defined(PROTO)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006567 void
6568free_insexpand_stuff(void)
6569{
John Marriott5e6ea922024-11-23 14:01:57 +01006570 VIM_CLEAR_STRING(compl_orig_text);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00006571# ifdef FEAT_EVAL
6572 free_callback(&cfu_cb);
6573 free_callback(&ofu_cb);
6574 free_callback(&tsrfu_cb);
6575# endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006576}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006577#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006578
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006579#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006580/*
6581 * Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly
6582 * spelled word, if there is one.
6583 */
6584 static void
6585spell_back_to_badword(void)
6586{
6587 pos_T tpos = curwin->w_cursor;
6588
Christ van Willegen - van Noort8e4c4c72024-05-17 18:49:27 +02006589 spell_bad_len = spell_move_to(curwin, BACKWARD, SMT_ALL, TRUE, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006590 if (curwin->w_cursor.col != tpos.col)
6591 start_arrow(&tpos);
6592}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006593#endif
Girish Palyacbe53192025-04-14 22:13:15 +02006594
6595/*
6596 * Reset the info associated with completion sources.
6597 */
6598 static void
Girish Palya0ac1eb32025-04-16 20:18:33 +02006599cpt_sources_clear(void)
Girish Palyacbe53192025-04-14 22:13:15 +02006600{
Girish Palya0ac1eb32025-04-16 20:18:33 +02006601 VIM_CLEAR(cpt_sources_array);
6602 cpt_sources_index = -1;
6603 cpt_sources_count = 0;
Girish Palyacbe53192025-04-14 22:13:15 +02006604}
6605
6606/*
6607 * Initialize the info associated with completion sources.
6608 */
6609 static int
Girish Palya0ac1eb32025-04-16 20:18:33 +02006610cpt_sources_init(void)
Girish Palyacbe53192025-04-14 22:13:15 +02006611{
Girish Palya0ac1eb32025-04-16 20:18:33 +02006612 char_u buf[LSIZE];
6613 int slen;
Girish Palyacbe53192025-04-14 22:13:15 +02006614 int count = 0;
Girish Palya0ac1eb32025-04-16 20:18:33 +02006615 char_u *p;
Girish Palyacbe53192025-04-14 22:13:15 +02006616
Girish Palya0ac1eb32025-04-16 20:18:33 +02006617 for (p = curbuf->b_p_cpt; *p;)
Girish Palyacbe53192025-04-14 22:13:15 +02006618 {
6619 while (*p == ',' || *p == ' ') // Skip delimiters
6620 p++;
6621 if (*p) // If not end of string, count this segment
6622 {
Girish Palya0ac1eb32025-04-16 20:18:33 +02006623 (void)copy_option_part(&p, buf, LSIZE, ","); // Advance p
Girish Palyacbe53192025-04-14 22:13:15 +02006624 count++;
Girish Palyacbe53192025-04-14 22:13:15 +02006625 }
6626 }
Girish Palya0ac1eb32025-04-16 20:18:33 +02006627 cpt_sources_clear();
6628 cpt_sources_count = count;
Girish Palyacbe53192025-04-14 22:13:15 +02006629 if (count > 0)
6630 {
Girish Palya0ac1eb32025-04-16 20:18:33 +02006631 cpt_sources_array = ALLOC_CLEAR_MULT(cpt_source_T, count);
6632 if (cpt_sources_array == NULL)
Girish Palyacbe53192025-04-14 22:13:15 +02006633 {
Girish Palya0ac1eb32025-04-16 20:18:33 +02006634 cpt_sources_count = 0;
Girish Palyacbe53192025-04-14 22:13:15 +02006635 return FAIL;
6636 }
Girish Palya0ac1eb32025-04-16 20:18:33 +02006637 count = 0;
6638 for (p = curbuf->b_p_cpt; *p;)
6639 {
6640 while (*p == ',' || *p == ' ') // Skip delimiters
6641 p++;
6642 if (*p) // If not end of string, count this segment
6643 {
6644 char_u *t;
6645
6646 vim_memset(buf, 0, LSIZE);
6647 slen = copy_option_part(&p, buf, LSIZE, ","); // Advance p
6648 if (slen > 0 && (t = vim_strchr(buf, '^')) != NULL)
6649 cpt_sources_array[count].max_matches = atoi((char *)t + 1);
6650 count++;
6651 }
6652 }
Girish Palyacbe53192025-04-14 22:13:15 +02006653 }
6654 return OK;
6655}
6656
6657/*
6658 * Return TRUE if any of the completion sources have 'refresh' set to 'always'.
6659 */
6660 static int
6661is_cpt_func_refresh_always(void)
6662{
6663#ifdef FEAT_COMPL_FUNC
glepnir19e1dd62025-05-08 22:50:38 +02006664 for (int i = 0; i < cpt_sources_count; i++)
Girish Palya0ac1eb32025-04-16 20:18:33 +02006665 if (cpt_sources_array[i].refresh_always)
Girish Palyacbe53192025-04-14 22:13:15 +02006666 return TRUE;
6667#endif
6668 return FALSE;
6669}
6670
6671/*
6672 * Make the completion list non-cyclic.
6673 */
6674#ifdef FEAT_COMPL_FUNC
6675 static void
6676ins_compl_make_linear(void)
6677{
6678 compl_T *m;
6679
6680 if (compl_first_match == NULL || compl_first_match->cp_prev == NULL)
6681 return;
6682 m = compl_first_match->cp_prev;
6683 m->cp_next = NULL;
6684 compl_first_match->cp_prev = NULL;
6685}
6686#endif
6687
6688/*
6689 * Remove the matches linked to the current completion source (as indicated by
Girish Palya0ac1eb32025-04-16 20:18:33 +02006690 * cpt_sources_index) from the completion list.
Girish Palyacbe53192025-04-14 22:13:15 +02006691 */
6692#ifdef FEAT_COMPL_FUNC
6693 static compl_T *
6694remove_old_matches(void)
6695{
6696 compl_T *sublist_start = NULL, *sublist_end = NULL, *insert_at = NULL;
6697 compl_T *current, *next;
Girish Palya0ac1eb32025-04-16 20:18:33 +02006698 int compl_shown_removed = FALSE;
6699 int forward = (compl_first_match->cp_cpt_source_idx < 0);
6700
6701 compl_direction = forward ? FORWARD : BACKWARD;
6702 compl_shows_dir = compl_direction;
Girish Palyacbe53192025-04-14 22:13:15 +02006703
6704 // Identify the sublist of old matches that needs removal
6705 for (current = compl_first_match; current != NULL; current = current->cp_next)
6706 {
Girish Palya0ac1eb32025-04-16 20:18:33 +02006707 if (current->cp_cpt_source_idx < cpt_sources_index &&
6708 (forward || (!forward && !insert_at)))
Girish Palyacbe53192025-04-14 22:13:15 +02006709 insert_at = current;
6710
Girish Palya0ac1eb32025-04-16 20:18:33 +02006711 if (current->cp_cpt_source_idx == cpt_sources_index)
Girish Palyacbe53192025-04-14 22:13:15 +02006712 {
6713 if (!sublist_start)
6714 sublist_start = current;
6715 sublist_end = current;
6716 if (!compl_shown_removed && compl_shown_match == current)
6717 compl_shown_removed = TRUE;
6718 }
6719
Girish Palya0ac1eb32025-04-16 20:18:33 +02006720 if ((forward && current->cp_cpt_source_idx > cpt_sources_index)
6721 || (!forward && insert_at))
Girish Palyacbe53192025-04-14 22:13:15 +02006722 break;
6723 }
6724
6725 // Re-assign compl_shown_match if necessary
6726 if (compl_shown_removed)
6727 {
6728 if (forward)
6729 compl_shown_match = compl_first_match;
6730 else
6731 { // Last node will have the prefix that is being completed
Girish Palya0ac1eb32025-04-16 20:18:33 +02006732 for (current = compl_first_match; current->cp_next != NULL;
6733 current = current->cp_next)
Girish Palyacbe53192025-04-14 22:13:15 +02006734 ;
6735 compl_shown_match = current;
6736 }
6737 }
6738
6739 if (!sublist_start) // No nodes to remove
6740 return insert_at;
6741
6742 // Update links to remove sublist
6743 if (sublist_start->cp_prev)
6744 sublist_start->cp_prev->cp_next = sublist_end->cp_next;
6745 else
6746 compl_first_match = sublist_end->cp_next;
6747
6748 if (sublist_end->cp_next)
6749 sublist_end->cp_next->cp_prev = sublist_start->cp_prev;
6750
6751 // Free all nodes in the sublist
6752 sublist_end->cp_next = NULL;
6753 for (current = sublist_start; current != NULL; current = next)
6754 {
6755 next = current->cp_next;
6756 ins_compl_item_free(current);
6757 }
6758
6759 return insert_at;
6760}
6761#endif
6762
6763/*
6764 * Retrieve completion matches using the callback function "cb" and store the
6765 * 'refresh:always' flag.
6766 */
6767#ifdef FEAT_COMPL_FUNC
6768 static void
6769get_cpt_func_completion_matches(callback_T *cb UNUSED)
6770{
glepnir19e1dd62025-05-08 22:50:38 +02006771 int ret;
6772 int startcol;
Girish Palyacbe53192025-04-14 22:13:15 +02006773
6774 VIM_CLEAR_STRING(cpt_compl_pattern);
6775 ret = get_userdefined_compl_info(curwin->w_cursor.col, cb, &startcol);
6776 if (ret == FAIL && startcol == -3)
Girish Palya0ac1eb32025-04-16 20:18:33 +02006777 cpt_sources_array[cpt_sources_index].refresh_always = FALSE;
Girish Palyacbe53192025-04-14 22:13:15 +02006778 else if (ret == OK)
6779 {
6780 expand_by_function(0, cpt_compl_pattern.string, cb);
Girish Palya0ac1eb32025-04-16 20:18:33 +02006781 cpt_sources_array[cpt_sources_index].refresh_always =
6782 compl_opt_refresh_always;
Girish Palyacbe53192025-04-14 22:13:15 +02006783 compl_opt_refresh_always = FALSE;
6784 }
6785}
6786#endif
6787
6788/*
6789 * Retrieve completion matches from functions in the 'cpt' option where the
6790 * 'refresh:always' flag is set.
6791 */
6792 static void
6793cpt_compl_refresh(void)
6794{
6795#ifdef FEAT_COMPL_FUNC
6796 char_u *cpt;
6797 char_u *p;
Christian Brabandtd2079cf2025-04-15 18:10:26 +02006798 callback_T *cb = NULL;
Girish Palyacbe53192025-04-14 22:13:15 +02006799
6800 // Make the completion list linear (non-cyclic)
6801 ins_compl_make_linear();
6802 // Make a copy of 'cpt' in case the buffer gets wiped out
6803 cpt = vim_strsave(curbuf->b_p_cpt);
Girish Palya0ac1eb32025-04-16 20:18:33 +02006804 strip_caret_numbers_in_place(cpt);
Girish Palyacbe53192025-04-14 22:13:15 +02006805
Girish Palya0ac1eb32025-04-16 20:18:33 +02006806 cpt_sources_index = 0;
6807 for (p = cpt; *p; cpt_sources_index++)
Girish Palyacbe53192025-04-14 22:13:15 +02006808 {
6809 while (*p == ',' || *p == ' ') // Skip delimiters
6810 p++;
6811
Girish Palya0ac1eb32025-04-16 20:18:33 +02006812 if (cpt_sources_array[cpt_sources_index].refresh_always)
Girish Palyacbe53192025-04-14 22:13:15 +02006813 {
6814 if (*p == 'o')
6815 cb = &curbuf->b_ofu_cb;
6816 else if (*p == 'f')
6817 cb = (*(p + 1) != ',' && *(p + 1) != NUL)
6818 ? get_cpt_func_callback(p + 1) : &curbuf->b_cfu_cb;
6819 if (cb)
6820 {
6821 compl_curr_match = remove_old_matches();
6822 get_cpt_func_completion_matches(cb);
6823 }
6824 }
6825
6826 copy_option_part(&p, IObuff, IOSIZE, ","); // Advance p
6827 }
Girish Palya0ac1eb32025-04-16 20:18:33 +02006828 cpt_sources_index = -1;
Girish Palyacbe53192025-04-14 22:13:15 +02006829
6830 vim_free(cpt);
6831 // Make the list cyclic
6832 compl_matches = ins_compl_make_cyclic();
6833#endif
6834}